router.c 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965
  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-2008, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /* $Id$ */
  7. const char router_c_id[] =
  8. "$Id$";
  9. #define ROUTER_PRIVATE
  10. #include "or.h"
  11. /**
  12. * \file router.c
  13. * \brief OR functionality, including key maintenance, generating
  14. * and uploading server descriptors, retrying OR connections.
  15. **/
  16. extern long stats_n_seconds_working;
  17. /************************************************************/
  18. /*****
  19. * Key management: ORs only.
  20. *****/
  21. /** Private keys for this OR. There is also an SSL key managed by tortls.c.
  22. */
  23. static tor_mutex_t *key_lock=NULL;
  24. static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
  25. /** Current private onionskin decryption key: used to decode CREATE cells. */
  26. static crypto_pk_env_t *onionkey=NULL;
  27. /** Previous private onionskin decription key: used to decode CREATE cells
  28. * generated by clients that have an older version of our descriptor. */
  29. static crypto_pk_env_t *lastonionkey=NULL;
  30. /** Private "identity key": used to sign directory info and TLS
  31. * certificates. Never changes. */
  32. static crypto_pk_env_t *identitykey=NULL;
  33. /** Digest of identitykey. */
  34. static char identitykey_digest[DIGEST_LEN];
  35. /** Signing key used for v3 directory material; only set for authorities. */
  36. static crypto_pk_env_t *authority_signing_key = NULL;
  37. /** Key certificate to authenticate v3 directory material; only set for
  38. * authorities. */
  39. static authority_cert_t *authority_key_certificate = NULL;
  40. /* (Note that v3 authorities also have a separate "authority identity key",
  41. * but this key is never actually loaded by the Tor process. Instead, it's
  42. * used by tor-gencert to sign new signing keys and make new key
  43. * certificates. */
  44. /** Replace the current onion key with <b>k</b>. Does not affect lastonionkey;
  45. * to update onionkey correctly, call rotate_onion_key().
  46. */
  47. static void
  48. set_onion_key(crypto_pk_env_t *k)
  49. {
  50. tor_mutex_acquire(key_lock);
  51. onionkey = k;
  52. onionkey_set_at = time(NULL);
  53. tor_mutex_release(key_lock);
  54. mark_my_descriptor_dirty();
  55. }
  56. /** Return the current onion key. Requires that the onion key has been
  57. * loaded or generated. */
  58. crypto_pk_env_t *
  59. get_onion_key(void)
  60. {
  61. tor_assert(onionkey);
  62. return onionkey;
  63. }
  64. /** Store a copy of the current onion key into *<b>key</b>, and a copy
  65. * of the most recent onion key into *<b>last</b>.
  66. */
  67. void
  68. dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
  69. {
  70. tor_assert(key);
  71. tor_assert(last);
  72. tor_mutex_acquire(key_lock);
  73. tor_assert(onionkey);
  74. *key = crypto_pk_dup_key(onionkey);
  75. if (lastonionkey)
  76. *last = crypto_pk_dup_key(lastonionkey);
  77. else
  78. *last = NULL;
  79. tor_mutex_release(key_lock);
  80. }
  81. /** Return the time when the onion key was last set. This is either the time
  82. * when the process launched, or the time of the most recent key rotation since
  83. * the process launched.
  84. */
  85. time_t
  86. get_onion_key_set_at(void)
  87. {
  88. return onionkey_set_at;
  89. }
  90. /** Set the current identity key to k.
  91. */
  92. void
  93. set_identity_key(crypto_pk_env_t *k)
  94. {
  95. if (identitykey)
  96. crypto_free_pk_env(identitykey);
  97. identitykey = k;
  98. crypto_pk_get_digest(identitykey, identitykey_digest);
  99. }
  100. /** Returns the current identity key; requires that the identity key has been
  101. * set.
  102. */
  103. crypto_pk_env_t *
  104. get_identity_key(void)
  105. {
  106. tor_assert(identitykey);
  107. return identitykey;
  108. }
  109. /** Return true iff the identity key has been set. */
  110. int
  111. identity_key_is_set(void)
  112. {
  113. return identitykey != NULL;
  114. }
  115. /** Return the key certificate for this v3 (voting) authority, or NULL
  116. * if we have no such certificate. */
  117. authority_cert_t *
  118. get_my_v3_authority_cert(void)
  119. {
  120. return authority_key_certificate;
  121. }
  122. /** Return the v3 signing key for this v3 (voting) authority, or NULL
  123. * if we have no such key. */
  124. crypto_pk_env_t *
  125. get_my_v3_authority_signing_key(void)
  126. {
  127. return authority_signing_key;
  128. }
  129. /** Replace the previous onion key with the current onion key, and generate
  130. * a new previous onion key. Immediately after calling this function,
  131. * the OR should:
  132. * - schedule all previous cpuworkers to shut down _after_ processing
  133. * pending work. (This will cause fresh cpuworkers to be generated.)
  134. * - generate and upload a fresh routerinfo.
  135. */
  136. void
  137. rotate_onion_key(void)
  138. {
  139. char *fname, *fname_prev;
  140. crypto_pk_env_t *prkey;
  141. or_state_t *state = get_or_state();
  142. time_t now;
  143. fname = get_datadir_fname2("keys", "secret_onion_key");
  144. fname_prev = get_datadir_fname2("keys", "secret_onion_key.old");
  145. if (!(prkey = crypto_new_pk_env())) {
  146. log_err(LD_GENERAL,"Error constructing rotated onion key");
  147. goto error;
  148. }
  149. if (crypto_pk_generate_key(prkey)) {
  150. log_err(LD_BUG,"Error generating onion key");
  151. goto error;
  152. }
  153. if (file_status(fname) == FN_FILE) {
  154. if (replace_file(fname, fname_prev))
  155. goto error;
  156. }
  157. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  158. log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
  159. goto error;
  160. }
  161. log_info(LD_GENERAL, "Rotating onion key");
  162. tor_mutex_acquire(key_lock);
  163. if (lastonionkey)
  164. crypto_free_pk_env(lastonionkey);
  165. lastonionkey = onionkey;
  166. onionkey = prkey;
  167. now = time(NULL);
  168. state->LastRotatedOnionKey = onionkey_set_at = now;
  169. tor_mutex_release(key_lock);
  170. mark_my_descriptor_dirty();
  171. or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
  172. goto done;
  173. error:
  174. log_warn(LD_GENERAL, "Couldn't rotate onion key.");
  175. if (prkey)
  176. crypto_free_pk_env(prkey);
  177. done:
  178. tor_free(fname);
  179. tor_free(fname_prev);
  180. }
  181. /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
  182. * and <b>generate</b> is true, create a new RSA key and save it in
  183. * <b>fname</b>. Return the read/created key, or NULL on error. Log all
  184. * errors at level <b>severity</b>.
  185. */
  186. crypto_pk_env_t *
  187. init_key_from_file(const char *fname, int generate, int severity)
  188. {
  189. crypto_pk_env_t *prkey = NULL;
  190. FILE *file = NULL;
  191. if (!(prkey = crypto_new_pk_env())) {
  192. log(severity, LD_GENERAL,"Error constructing key");
  193. goto error;
  194. }
  195. switch (file_status(fname)) {
  196. case FN_DIR:
  197. case FN_ERROR:
  198. log(severity, LD_FS,"Can't read key from \"%s\"", fname);
  199. goto error;
  200. case FN_NOENT:
  201. if (generate) {
  202. log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
  203. fname);
  204. if (crypto_pk_generate_key(prkey)) {
  205. log(severity, LD_GENERAL,"Error generating onion key");
  206. goto error;
  207. }
  208. if (crypto_pk_check_key(prkey) <= 0) {
  209. log(severity, LD_GENERAL,"Generated key seems invalid");
  210. goto error;
  211. }
  212. log_info(LD_GENERAL, "Generated key seems valid");
  213. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  214. log(severity, LD_FS,
  215. "Couldn't write generated key to \"%s\".", fname);
  216. goto error;
  217. }
  218. } else {
  219. log_info(LD_GENERAL, "No key found in \"%s\"", fname);
  220. }
  221. return prkey;
  222. case FN_FILE:
  223. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  224. log(severity, LD_GENERAL,"Error loading private key.");
  225. goto error;
  226. }
  227. return prkey;
  228. default:
  229. tor_assert(0);
  230. }
  231. error:
  232. if (prkey)
  233. crypto_free_pk_env(prkey);
  234. if (file)
  235. fclose(file);
  236. return NULL;
  237. }
  238. /** Load the v3 (voting) authority signing key and certificate, if they are
  239. * present. Return -1 if anything is missing, mismatched, or unloadable;
  240. * return 0 on success. */
  241. static int
  242. init_v3_authority_keys(void)
  243. {
  244. char *fname = NULL, *cert = NULL;
  245. const char *eos = NULL;
  246. crypto_pk_env_t *signing_key = NULL;
  247. authority_cert_t *parsed = NULL;
  248. int r = -1;
  249. fname = get_datadir_fname2("keys", "authority_signing_key");
  250. signing_key = init_key_from_file(fname, 0, LOG_INFO);
  251. if (!signing_key) {
  252. log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
  253. goto done;
  254. }
  255. tor_free(fname);
  256. fname = get_datadir_fname2("keys", "authority_certificate");
  257. cert = read_file_to_str(fname, 0, NULL);
  258. if (!cert) {
  259. log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
  260. fname);
  261. goto done;
  262. }
  263. parsed = authority_cert_parse_from_string(cert, &eos);
  264. if (!parsed) {
  265. log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
  266. goto done;
  267. }
  268. if (crypto_pk_cmp_keys(signing_key, parsed->signing_key) != 0) {
  269. log_warn(LD_DIR, "Stored signing key does not match signing key in "
  270. "certificate");
  271. goto done;
  272. }
  273. parsed->cache_info.signed_descriptor_body = cert;
  274. parsed->cache_info.signed_descriptor_len = eos-cert;
  275. cert = NULL;
  276. /* Free old values... */
  277. if (authority_key_certificate)
  278. authority_cert_free(authority_key_certificate);
  279. if (authority_signing_key)
  280. crypto_free_pk_env(authority_signing_key);
  281. /* ...and replace them. */
  282. authority_key_certificate = parsed;
  283. authority_signing_key = signing_key;
  284. parsed = NULL;
  285. signing_key = NULL;
  286. r = 0;
  287. done:
  288. tor_free(fname);
  289. tor_free(cert);
  290. if (signing_key)
  291. crypto_free_pk_env(signing_key);
  292. if (parsed)
  293. authority_cert_free(parsed);
  294. return r;
  295. }
  296. /** If we're a v3 authority, check whether we have a certificate that's
  297. * likely to expire soon. Warn if we do, but not too often. */
  298. void
  299. v3_authority_check_key_expiry(void)
  300. {
  301. time_t now, expires;
  302. static time_t last_warned = 0;
  303. int badness, time_left, warn_interval;
  304. if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
  305. return;
  306. now = time(NULL);
  307. expires = authority_key_certificate->expires;
  308. time_left = (int)( expires - now );
  309. if (time_left <= 0) {
  310. badness = LOG_ERR;
  311. warn_interval = 60*60;
  312. } else if (time_left <= 24*60*60) {
  313. badness = LOG_WARN;
  314. warn_interval = 60*60;
  315. } else if (time_left <= 24*60*60*7) {
  316. badness = LOG_WARN;
  317. warn_interval = 24*60*60;
  318. } else if (time_left <= 24*60*60*30) {
  319. badness = LOG_WARN;
  320. warn_interval = 24*60*60*5;
  321. } else {
  322. return;
  323. }
  324. if (last_warned + warn_interval > now)
  325. return;
  326. if (time_left <= 0) {
  327. log(badness, LD_DIR, "Your v3 authority certificate has expired."
  328. " Generate a new one NOW.");
  329. } else if (time_left <= 24*60*60) {
  330. log(badness, LD_DIR, "Your v3 authority certificate expires in %d hours;"
  331. " Generate a new one NOW.", time_left/(60*60));
  332. } else {
  333. log(badness, LD_DIR, "Your v3 authority certificate expires in %d days;"
  334. " Generate a new one soon.", time_left/(24*60*60));
  335. }
  336. last_warned = now;
  337. }
  338. /** Initialize all OR private keys, and the TLS context, as necessary.
  339. * On OPs, this only initializes the tls context. Return 0 on success,
  340. * or -1 if Tor should die.
  341. */
  342. int
  343. init_keys(void)
  344. {
  345. char *keydir;
  346. char fingerprint[FINGERPRINT_LEN+1];
  347. /*nickname<space>fp\n\0 */
  348. char fingerprint_line[MAX_NICKNAME_LEN+FINGERPRINT_LEN+3];
  349. const char *mydesc;
  350. crypto_pk_env_t *prkey;
  351. char digest[20];
  352. char v3_digest[20];
  353. char *cp;
  354. or_options_t *options = get_options();
  355. authority_type_t type;
  356. time_t now = time(NULL);
  357. trusted_dir_server_t *ds;
  358. int v3_digest_set = 0;
  359. authority_cert_t *cert = NULL;
  360. if (!key_lock)
  361. key_lock = tor_mutex_new();
  362. /* OP's don't need persistent keys; just make up an identity and
  363. * initialize the TLS context. */
  364. if (!server_mode(options)) {
  365. if (!(prkey = crypto_new_pk_env()))
  366. return -1;
  367. if (crypto_pk_generate_key(prkey)) {
  368. crypto_free_pk_env(prkey);
  369. return -1;
  370. }
  371. set_identity_key(prkey);
  372. /* Create a TLS context; default the client nickname to "client". */
  373. if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME) < 0) {
  374. log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
  375. return -1;
  376. }
  377. return 0;
  378. }
  379. /* Make sure DataDirectory exists, and is private. */
  380. if (check_private_dir(options->DataDirectory, CPD_CREATE)) {
  381. return -1;
  382. }
  383. /* Check the key directory. */
  384. keydir = get_datadir_fname("keys");
  385. if (check_private_dir(keydir, CPD_CREATE)) {
  386. tor_free(keydir);
  387. return -1;
  388. }
  389. tor_free(keydir);
  390. /* 1a. Read v3 directory authority key/cert information. */
  391. memset(v3_digest, 0, sizeof(v3_digest));
  392. if (authdir_mode_v3(options)) {
  393. if (init_v3_authority_keys()<0) {
  394. log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
  395. "were unable to load our v3 authority keys and certificate! "
  396. "Use tor-gencert to generate them. Dying.");
  397. return -1;
  398. }
  399. cert = get_my_v3_authority_cert();
  400. if (cert) {
  401. crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
  402. v3_digest);
  403. v3_digest_set = 1;
  404. }
  405. }
  406. /* 1. Read identity key. Make it if none is found. */
  407. keydir = get_datadir_fname2("keys", "secret_id_key");
  408. log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
  409. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  410. tor_free(keydir);
  411. if (!prkey) return -1;
  412. set_identity_key(prkey);
  413. /* 2. Read onion key. Make it if none is found. */
  414. keydir = get_datadir_fname2("keys", "secret_onion_key");
  415. log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
  416. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  417. tor_free(keydir);
  418. if (!prkey) return -1;
  419. set_onion_key(prkey);
  420. if (options->command == CMD_RUN_TOR) {
  421. /* only mess with the state file if we're actually running Tor */
  422. or_state_t *state = get_or_state();
  423. if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
  424. /* We allow for some parsing slop, but we don't want to risk accepting
  425. * values in the distant future. If we did, we might never rotate the
  426. * onion key. */
  427. onionkey_set_at = state->LastRotatedOnionKey;
  428. } else {
  429. /* We have no LastRotatedOnionKey set; either we just created the key
  430. * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
  431. * start the clock ticking now so that we will eventually rotate it even
  432. * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
  433. state->LastRotatedOnionKey = onionkey_set_at = now;
  434. or_state_mark_dirty(state, options->AvoidDiskWrites ?
  435. time(NULL)+3600 : 0);
  436. }
  437. }
  438. keydir = get_datadir_fname2("keys", "secret_onion_key.old");
  439. if (!lastonionkey && file_status(keydir) == FN_FILE) {
  440. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  441. if (prkey)
  442. lastonionkey = prkey;
  443. }
  444. tor_free(keydir);
  445. /* 3. Initialize link key and TLS context. */
  446. if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME) < 0) {
  447. log_err(LD_GENERAL,"Error initializing TLS context");
  448. return -1;
  449. }
  450. /* 4. Build our router descriptor. */
  451. /* Must be called after keys are initialized. */
  452. mydesc = router_get_my_descriptor();
  453. if (authdir_mode(options)) {
  454. const char *m;
  455. routerinfo_t *ri;
  456. /* We need to add our own fingerprint so it gets recognized. */
  457. if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
  458. log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
  459. return -1;
  460. }
  461. if (mydesc) {
  462. ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL);
  463. if (!ri) {
  464. log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
  465. return -1;
  466. }
  467. if (dirserv_add_descriptor(ri, &m) < 0) {
  468. log_err(LD_GENERAL,"Unable to add own descriptor to directory: %s",
  469. m?m:"<unknown error>");
  470. return -1;
  471. }
  472. }
  473. }
  474. /* 5. Dump fingerprint to 'fingerprint' */
  475. keydir = get_datadir_fname("fingerprint");
  476. log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
  477. if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 1)<0) {
  478. log_err(LD_GENERAL,"Error computing fingerprint");
  479. tor_free(keydir);
  480. return -1;
  481. }
  482. tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
  483. if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
  484. "%s %s\n",options->Nickname, fingerprint) < 0) {
  485. log_err(LD_GENERAL,"Error writing fingerprint line");
  486. tor_free(keydir);
  487. return -1;
  488. }
  489. /* Check whether we need to write the fingerprint file. */
  490. cp = NULL;
  491. if (file_status(keydir) == FN_FILE)
  492. cp = read_file_to_str(keydir, 0, NULL);
  493. if (!cp || strcmp(cp, fingerprint_line)) {
  494. if (write_str_to_file(keydir, fingerprint_line, 0)) {
  495. log_err(LD_FS, "Error writing fingerprint line to file");
  496. tor_free(keydir);
  497. return -1;
  498. }
  499. }
  500. tor_free(cp);
  501. tor_free(keydir);
  502. log(LOG_NOTICE, LD_GENERAL,
  503. "Your Tor server's identity key fingerprint is '%s %s'",
  504. options->Nickname, fingerprint);
  505. if (!authdir_mode(options))
  506. return 0;
  507. /* 6. [authdirserver only] load approved-routers file */
  508. if (dirserv_load_fingerprint_file() < 0) {
  509. log_err(LD_GENERAL,"Error loading fingerprints");
  510. return -1;
  511. }
  512. /* 6b. [authdirserver only] add own key to approved directories. */
  513. crypto_pk_get_digest(get_identity_key(), digest);
  514. type = ((options->V1AuthoritativeDir ? V1_AUTHORITY : NO_AUTHORITY) |
  515. (options->V2AuthoritativeDir ? V2_AUTHORITY : NO_AUTHORITY) |
  516. (options->V3AuthoritativeDir ? V3_AUTHORITY : NO_AUTHORITY) |
  517. (options->BridgeAuthoritativeDir ? BRIDGE_AUTHORITY : NO_AUTHORITY) |
  518. (options->HSAuthoritativeDir ? HIDSERV_AUTHORITY : NO_AUTHORITY));
  519. ds = router_get_trusteddirserver_by_digest(digest);
  520. if (!ds) {
  521. ds = add_trusted_dir_server(options->Nickname, NULL,
  522. (uint16_t)options->DirPort,
  523. (uint16_t)options->ORPort,
  524. digest,
  525. v3_digest,
  526. type);
  527. if (!ds) {
  528. log_err(LD_GENERAL,"We want to be a directory authority, but we "
  529. "couldn't add ourselves to the authority list. Failing.");
  530. return -1;
  531. }
  532. }
  533. if (ds->type != type) {
  534. log_warn(LD_DIR, "Configured authority type does not match authority "
  535. "type in DirServer list. Adjusting. (%d v %d)",
  536. type, ds->type);
  537. ds->type = type;
  538. }
  539. if (v3_digest_set && (ds->type & V3_AUTHORITY) &&
  540. memcmp(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
  541. log_warn(LD_DIR, "V3 identity key does not match identity declared in "
  542. "DirServer line. Adjusting.");
  543. memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
  544. }
  545. if (cert) { /* add my own cert to the list of known certs */
  546. log_info(LD_DIR, "adding my own v3 cert");
  547. if (trusted_dirs_load_certs_from_string(
  548. cert->cache_info.signed_descriptor_body, 0, 0)<0) {
  549. log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
  550. return -1;
  551. }
  552. }
  553. return 0; /* success */
  554. }
  555. /* Keep track of whether we should upload our server descriptor,
  556. * and what type of server we are.
  557. */
  558. /** Whether we can reach our ORPort from the outside. */
  559. static int can_reach_or_port = 0;
  560. /** Whether we can reach our DirPort from the outside. */
  561. static int can_reach_dir_port = 0;
  562. /** Forget what we have learned about our reachability status. */
  563. void
  564. router_reset_reachability(void)
  565. {
  566. can_reach_or_port = can_reach_dir_port = 0;
  567. }
  568. /** Return 1 if ORPort is known reachable; else return 0. */
  569. int
  570. check_whether_orport_reachable(void)
  571. {
  572. or_options_t *options = get_options();
  573. return options->AssumeReachable ||
  574. can_reach_or_port;
  575. }
  576. /** Return 1 if we don't have a dirport configured, or if it's reachable. */
  577. int
  578. check_whether_dirport_reachable(void)
  579. {
  580. or_options_t *options = get_options();
  581. return !options->DirPort ||
  582. options->AssumeReachable ||
  583. we_are_hibernating() ||
  584. can_reach_dir_port;
  585. }
  586. /** Look at a variety of factors, and return 0 if we don't want to
  587. * advertise the fact that we have a DirPort open. Else return the
  588. * DirPort we want to advertise.
  589. *
  590. * Log a helpful message if we change our mind about whether to publish
  591. * a DirPort.
  592. */
  593. static int
  594. decide_to_advertise_dirport(or_options_t *options, uint16_t dir_port)
  595. {
  596. static int advertising=1; /* start out assuming we will advertise */
  597. int new_choice=1;
  598. const char *reason = NULL;
  599. /* Section one: reasons to publish or not publish that aren't
  600. * worth mentioning to the user, either because they're obvious
  601. * or because they're normal behavior. */
  602. if (!dir_port) /* short circuit the rest of the function */
  603. return 0;
  604. if (authdir_mode(options)) /* always publish */
  605. return dir_port;
  606. if (we_are_hibernating())
  607. return 0;
  608. if (!check_whether_dirport_reachable())
  609. return 0;
  610. /* Section two: reasons to publish or not publish that the user
  611. * might find surprising. These are generally config options that
  612. * make us choose not to publish. */
  613. if (accounting_is_enabled(options)) {
  614. /* if we might potentially hibernate */
  615. new_choice = 0;
  616. reason = "AccountingMax enabled";
  617. #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
  618. } else if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT ||
  619. (options->RelayBandwidthRate > 0 &&
  620. options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT)) {
  621. /* if we're advertising a small amount */
  622. new_choice = 0;
  623. reason = "BandwidthRate under 50KB";
  624. }
  625. if (advertising != new_choice) {
  626. if (new_choice == 1) {
  627. log(LOG_NOTICE, LD_DIR, "Advertising DirPort as %d", dir_port);
  628. } else {
  629. tor_assert(reason);
  630. log(LOG_NOTICE, LD_DIR, "Not advertising DirPort (Reason: %s)", reason);
  631. }
  632. advertising = new_choice;
  633. }
  634. return advertising ? dir_port : 0;
  635. }
  636. /** Some time has passed, or we just got new directory information.
  637. * See if we currently believe our ORPort or DirPort to be
  638. * unreachable. If so, launch a new test for it.
  639. *
  640. * For ORPort, we simply try making a circuit that ends at ourselves.
  641. * Success is noticed in onionskin_answer().
  642. *
  643. * For DirPort, we make a connection via Tor to our DirPort and ask
  644. * for our own server descriptor.
  645. * Success is noticed in connection_dir_client_reached_eof().
  646. */
  647. void
  648. consider_testing_reachability(int test_or, int test_dir)
  649. {
  650. routerinfo_t *me = router_get_my_routerinfo();
  651. int orport_reachable = check_whether_orport_reachable();
  652. if (!me)
  653. return;
  654. if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
  655. log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
  656. !orport_reachable ? "reachability" : "bandwidth",
  657. me->address, me->or_port);
  658. circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me,
  659. CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
  660. control_event_server_status(LOG_NOTICE,
  661. "CHECKING_REACHABILITY ORADDRESS=%s:%d",
  662. me->address, me->or_port);
  663. }
  664. if (test_dir && !check_whether_dirport_reachable() &&
  665. !connection_get_by_type_addr_port_purpose(
  666. CONN_TYPE_DIR, me->addr, me->dir_port,
  667. DIR_PURPOSE_FETCH_SERVERDESC)) {
  668. /* ask myself, via tor, for my server descriptor. */
  669. directory_initiate_command(me->address, me->addr,
  670. me->or_port, me->dir_port,
  671. 0, me->cache_info.identity_digest,
  672. DIR_PURPOSE_FETCH_SERVERDESC,
  673. ROUTER_PURPOSE_GENERAL,
  674. 1, "authority.z", NULL, 0, 0);
  675. control_event_server_status(LOG_NOTICE,
  676. "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
  677. me->address, me->dir_port);
  678. }
  679. }
  680. /** Annotate that we found our ORPort reachable. */
  681. void
  682. router_orport_found_reachable(void)
  683. {
  684. if (!can_reach_or_port) {
  685. routerinfo_t *me = router_get_my_routerinfo();
  686. log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
  687. "the outside. Excellent.%s",
  688. get_options()->_PublishServerDescriptor != NO_AUTHORITY ?
  689. " Publishing server descriptor." : "");
  690. can_reach_or_port = 1;
  691. mark_my_descriptor_dirty();
  692. if (!me)
  693. return;
  694. control_event_server_status(LOG_NOTICE,
  695. "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
  696. me->address, me->or_port);
  697. }
  698. }
  699. /** Annotate that we found our DirPort reachable. */
  700. void
  701. router_dirport_found_reachable(void)
  702. {
  703. if (!can_reach_dir_port) {
  704. routerinfo_t *me = router_get_my_routerinfo();
  705. log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
  706. "from the outside. Excellent.");
  707. can_reach_dir_port = 1;
  708. if (!me || decide_to_advertise_dirport(get_options(), me->dir_port))
  709. mark_my_descriptor_dirty();
  710. if (!me)
  711. return;
  712. control_event_server_status(LOG_NOTICE,
  713. "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
  714. me->address, me->dir_port);
  715. }
  716. }
  717. /** We have enough testing circuits open. Send a bunch of "drop"
  718. * cells down each of them, to exercise our bandwidth. */
  719. void
  720. router_perform_bandwidth_test(int num_circs, time_t now)
  721. {
  722. int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
  723. int max_cells = num_cells < CIRCWINDOW_START ?
  724. num_cells : CIRCWINDOW_START;
  725. int cells_per_circuit = max_cells / num_circs;
  726. origin_circuit_t *circ = NULL;
  727. log_notice(LD_OR,"Performing bandwidth self-test...done.");
  728. while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
  729. CIRCUIT_PURPOSE_TESTING))) {
  730. /* dump cells_per_circuit drop cells onto this circ */
  731. int i = cells_per_circuit;
  732. if (circ->_base.state != CIRCUIT_STATE_OPEN)
  733. continue;
  734. circ->_base.timestamp_dirty = now;
  735. while (i-- > 0) {
  736. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  737. RELAY_COMMAND_DROP,
  738. NULL, 0, circ->cpath->prev)<0) {
  739. return; /* stop if error */
  740. }
  741. }
  742. }
  743. }
  744. /** Return true iff we believe ourselves to be an authoritative
  745. * directory server.
  746. */
  747. int
  748. authdir_mode(or_options_t *options)
  749. {
  750. return options->AuthoritativeDir != 0;
  751. }
  752. /** Return true iff we believe ourselves to be a v1 authoritative
  753. * directory server.
  754. */
  755. int
  756. authdir_mode_v1(or_options_t *options)
  757. {
  758. return authdir_mode(options) && options->V1AuthoritativeDir != 0;
  759. }
  760. /** Return true iff we believe ourselves to be a v2 authoritative
  761. * directory server.
  762. */
  763. int
  764. authdir_mode_v2(or_options_t *options)
  765. {
  766. return authdir_mode(options) && options->V2AuthoritativeDir != 0;
  767. }
  768. /** Return true iff we believe ourselves to be a v3 authoritative
  769. * directory server.
  770. */
  771. int
  772. authdir_mode_v3(or_options_t *options)
  773. {
  774. return authdir_mode(options) && options->V3AuthoritativeDir != 0;
  775. }
  776. /** Return true iff we are a v1, v2, or v3 directory authority. */
  777. int
  778. authdir_mode_any_main(or_options_t *options)
  779. {
  780. return options->V1AuthoritativeDir ||
  781. options->V2AuthoritativeDir ||
  782. options->V3AuthoritativeDir;
  783. }
  784. /** Return true if we believe ourselves to be any kind of
  785. * authoritative directory beyond just a hidserv authority. */
  786. int
  787. authdir_mode_any_nonhidserv(or_options_t *options)
  788. {
  789. return options->BridgeAuthoritativeDir ||
  790. authdir_mode_any_main(options);
  791. }
  792. /** Return true iff we are an authoritative directory server that is
  793. * authoritative about receiving and serving descriptors of type
  794. * <b>purpose</b> its dirport. Use -1 for "any purpose". */
  795. int
  796. authdir_mode_handles_descs(or_options_t *options, int purpose)
  797. {
  798. if (purpose < 0)
  799. return authdir_mode_any_nonhidserv(options);
  800. else if (purpose == ROUTER_PURPOSE_GENERAL)
  801. return authdir_mode_any_main(options);
  802. else if (purpose == ROUTER_PURPOSE_BRIDGE)
  803. return (options->BridgeAuthoritativeDir);
  804. else
  805. return 0;
  806. }
  807. /** Return true iff we are an authoritative directory server that
  808. * publishes its own network statuses.
  809. */
  810. int
  811. authdir_mode_publishes_statuses(or_options_t *options)
  812. {
  813. if (authdir_mode_bridge(options))
  814. return 0;
  815. return authdir_mode_any_nonhidserv(options);
  816. }
  817. /** Return true iff we are an authoritative directory server that
  818. * tests reachability of the descriptors it learns about.
  819. */
  820. int
  821. authdir_mode_tests_reachability(or_options_t *options)
  822. {
  823. return authdir_mode_handles_descs(options, -1);
  824. }
  825. /** Return true iff we believe ourselves to be a bridge authoritative
  826. * directory server.
  827. */
  828. int
  829. authdir_mode_bridge(or_options_t *options)
  830. {
  831. return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
  832. }
  833. /** Return true iff we once tried to stay connected to all ORs at once.
  834. * FFFF this function, and the notion of staying connected to ORs, is
  835. * nearly obsolete. One day there will be a proposal for getting rid of
  836. * it.
  837. */
  838. int
  839. clique_mode(or_options_t *options)
  840. {
  841. return authdir_mode_tests_reachability(options);
  842. }
  843. /** Return true iff we are trying to be a server.
  844. */
  845. int
  846. server_mode(or_options_t *options)
  847. {
  848. if (options->ClientOnly) return 0;
  849. return (options->ORPort != 0 || options->ORListenAddress);
  850. }
  851. /** Remember if we've advertised ourselves to the dirservers. */
  852. static int server_is_advertised=0;
  853. /** Return true iff we have published our descriptor lately.
  854. */
  855. int
  856. advertised_server_mode(void)
  857. {
  858. return server_is_advertised;
  859. }
  860. /**
  861. * Called with a boolean: set whether we have recently published our
  862. * descriptor.
  863. */
  864. static void
  865. set_server_advertised(int s)
  866. {
  867. server_is_advertised = s;
  868. }
  869. /** Return true iff we are trying to be a socks proxy. */
  870. int
  871. proxy_mode(or_options_t *options)
  872. {
  873. return (options->SocksPort != 0 || options->SocksListenAddress ||
  874. options->TransPort != 0 || options->TransListenAddress ||
  875. options->NatdPort != 0 || options->NatdListenAddress ||
  876. options->DNSPort != 0 || options->DNSListenAddress);
  877. }
  878. /** Decide if we're a publishable server. We are a publishable server if:
  879. * - We don't have the ClientOnly option set
  880. * and
  881. * - We have the PublishServerDescriptor option set to non-empty
  882. * and
  883. * - We have ORPort set
  884. * and
  885. * - We believe we are reachable from the outside; or
  886. * - We are an authoritative directory server.
  887. */
  888. static int
  889. decide_if_publishable_server(void)
  890. {
  891. or_options_t *options = get_options();
  892. if (options->ClientOnly)
  893. return 0;
  894. if (options->_PublishServerDescriptor == NO_AUTHORITY)
  895. return 0;
  896. if (!server_mode(options))
  897. return 0;
  898. if (authdir_mode(options))
  899. return 1;
  900. return check_whether_orport_reachable();
  901. }
  902. /** Initiate server descriptor upload as reasonable (if server is publishable,
  903. * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
  904. *
  905. * We need to rebuild the descriptor if it's dirty even if we're not
  906. * uploading, because our reachability testing *uses* our descriptor to
  907. * determine what IP address and ports to test.
  908. */
  909. void
  910. consider_publishable_server(int force)
  911. {
  912. int rebuilt;
  913. if (!server_mode(get_options()))
  914. return;
  915. rebuilt = router_rebuild_descriptor(0);
  916. if (decide_if_publishable_server()) {
  917. set_server_advertised(1);
  918. if (rebuilt == 0)
  919. router_upload_dir_desc_to_dirservers(force);
  920. } else {
  921. set_server_advertised(0);
  922. }
  923. }
  924. /*
  925. * Clique maintenance -- to be phased out.
  926. */
  927. /** Return true iff we believe this OR tries to keep connections open
  928. * to all other ORs. */
  929. int
  930. router_is_clique_mode(routerinfo_t *router)
  931. {
  932. if (router_digest_is_trusted_dir(router->cache_info.identity_digest))
  933. return 1;
  934. return 0;
  935. }
  936. /*
  937. * OR descriptor generation.
  938. */
  939. /** My routerinfo. */
  940. static routerinfo_t *desc_routerinfo = NULL;
  941. /** My extrainfo */
  942. static extrainfo_t *desc_extrainfo = NULL;
  943. /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
  944. * now. */
  945. static time_t desc_clean_since = 0;
  946. /** Boolean: do we need to regenerate the above? */
  947. static int desc_needs_upload = 0;
  948. /** OR only: If <b>force</b> is true, or we haven't uploaded this
  949. * descriptor successfully yet, try to upload our signed descriptor to
  950. * all the directory servers we know about.
  951. */
  952. void
  953. router_upload_dir_desc_to_dirservers(int force)
  954. {
  955. routerinfo_t *ri;
  956. extrainfo_t *ei;
  957. char *msg;
  958. size_t desc_len, extra_len = 0, total_len;
  959. authority_type_t auth = get_options()->_PublishServerDescriptor;
  960. ri = router_get_my_routerinfo();
  961. if (!ri) {
  962. log_info(LD_GENERAL, "No descriptor; skipping upload");
  963. return;
  964. }
  965. ei = router_get_my_extrainfo();
  966. if (auth == NO_AUTHORITY)
  967. return;
  968. if (!force && !desc_needs_upload)
  969. return;
  970. desc_needs_upload = 0;
  971. desc_len = ri->cache_info.signed_descriptor_len;
  972. extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
  973. total_len = desc_len + extra_len + 1;
  974. msg = tor_malloc(total_len);
  975. memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
  976. if (ei) {
  977. memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
  978. }
  979. msg[desc_len+extra_len] = 0;
  980. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
  981. (auth & BRIDGE_AUTHORITY) ?
  982. ROUTER_PURPOSE_BRIDGE :
  983. ROUTER_PURPOSE_GENERAL,
  984. auth, msg, desc_len, extra_len);
  985. tor_free(msg);
  986. }
  987. /** OR only: Check whether my exit policy says to allow connection to
  988. * conn. Return 0 if we accept; non-0 if we reject.
  989. */
  990. int
  991. router_compare_to_my_exit_policy(edge_connection_t *conn)
  992. {
  993. if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
  994. return -1;
  995. /* make sure it's resolved to something. this way we can't get a
  996. 'maybe' below. */
  997. if (!conn->_base.addr)
  998. return -1;
  999. return compare_addr_to_addr_policy(conn->_base.addr, conn->_base.port,
  1000. desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
  1001. }
  1002. /** Return true iff I'm a server and <b>digest</b> is equal to
  1003. * my identity digest. */
  1004. int
  1005. router_digest_is_me(const char *digest)
  1006. {
  1007. return identitykey && !memcmp(identitykey_digest, digest, DIGEST_LEN);
  1008. }
  1009. /** Return true iff I'm a server and <b>digest</b> is equal to
  1010. * my identity digest. */
  1011. int
  1012. router_extrainfo_digest_is_me(const char *digest)
  1013. {
  1014. extrainfo_t *ei = router_get_my_extrainfo();
  1015. if (!ei)
  1016. return 0;
  1017. return !memcmp(digest,
  1018. ei->cache_info.signed_descriptor_digest,
  1019. DIGEST_LEN);
  1020. }
  1021. /** A wrapper around router_digest_is_me(). */
  1022. int
  1023. router_is_me(routerinfo_t *router)
  1024. {
  1025. return router_digest_is_me(router->cache_info.identity_digest);
  1026. }
  1027. /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
  1028. int
  1029. router_fingerprint_is_me(const char *fp)
  1030. {
  1031. char digest[DIGEST_LEN];
  1032. if (strlen(fp) == HEX_DIGEST_LEN &&
  1033. base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
  1034. return router_digest_is_me(digest);
  1035. return 0;
  1036. }
  1037. /** Return a routerinfo for this OR, rebuilding a fresh one if
  1038. * necessary. Return NULL on error, or if called on an OP. */
  1039. routerinfo_t *
  1040. router_get_my_routerinfo(void)
  1041. {
  1042. if (!server_mode(get_options()))
  1043. return NULL;
  1044. if (router_rebuild_descriptor(0))
  1045. return NULL;
  1046. return desc_routerinfo;
  1047. }
  1048. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  1049. * one if necessary. Return NULL on error.
  1050. */
  1051. const char *
  1052. router_get_my_descriptor(void)
  1053. {
  1054. const char *body;
  1055. if (!router_get_my_routerinfo())
  1056. return NULL;
  1057. /* Make sure this is nul-terminated. */
  1058. tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
  1059. body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
  1060. tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
  1061. log_debug(LD_GENERAL,"my desc is '%s'", body);
  1062. return body;
  1063. }
  1064. /* Return the extrainfo document for this OR, or NULL if we have none.
  1065. * Rebuilt it (and the server descriptor) if necessary. */
  1066. extrainfo_t *
  1067. router_get_my_extrainfo(void)
  1068. {
  1069. if (!server_mode(get_options()))
  1070. return NULL;
  1071. if (router_rebuild_descriptor(0))
  1072. return NULL;
  1073. return desc_extrainfo;
  1074. }
  1075. /** A list of nicknames that we've warned about including in our family
  1076. * declaration verbatim rather than as digests. */
  1077. static smartlist_t *warned_nonexistent_family = NULL;
  1078. static int router_guess_address_from_dir_headers(uint32_t *guess);
  1079. /** Make a current best guess at our address, either because
  1080. * it's configured in torrc, or because we've learned it from
  1081. * dirserver headers. Place the answer in *<b>addr</b> and return
  1082. * 0 on success, else return -1 if we have no guess. */
  1083. int
  1084. router_pick_published_address(or_options_t *options, uint32_t *addr)
  1085. {
  1086. if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
  1087. log_info(LD_CONFIG, "Could not determine our address locally. "
  1088. "Checking if directory headers provide any hints.");
  1089. if (router_guess_address_from_dir_headers(addr) < 0) {
  1090. log_info(LD_CONFIG, "No hints from directory headers either. "
  1091. "Will try again later.");
  1092. return -1;
  1093. }
  1094. }
  1095. return 0;
  1096. }
  1097. /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
  1098. * routerinfo, signed server descriptor, and extra-info document for this OR.
  1099. * Return 0 on success, -1 on temporary error.
  1100. */
  1101. int
  1102. router_rebuild_descriptor(int force)
  1103. {
  1104. routerinfo_t *ri;
  1105. extrainfo_t *ei;
  1106. uint32_t addr;
  1107. char platform[256];
  1108. int hibernating = we_are_hibernating();
  1109. or_options_t *options = get_options();
  1110. if (desc_clean_since && !force)
  1111. return 0;
  1112. if (router_pick_published_address(options, &addr) < 0) {
  1113. /* Stop trying to rebuild our descriptor every second. We'll
  1114. * learn that it's time to try again when server_has_changed_ip()
  1115. * marks it dirty. */
  1116. desc_clean_since = time(NULL);
  1117. return -1;
  1118. }
  1119. ri = tor_malloc_zero(sizeof(routerinfo_t));
  1120. ri->cache_info.routerlist_index = -1;
  1121. ri->address = tor_dup_addr(addr);
  1122. ri->nickname = tor_strdup(options->Nickname);
  1123. ri->addr = addr;
  1124. ri->or_port = options->ORPort;
  1125. ri->dir_port = options->DirPort;
  1126. ri->cache_info.published_on = time(NULL);
  1127. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
  1128. * main thread */
  1129. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  1130. if (crypto_pk_get_digest(ri->identity_pkey,
  1131. ri->cache_info.identity_digest)<0) {
  1132. routerinfo_free(ri);
  1133. return -1;
  1134. }
  1135. get_platform_str(platform, sizeof(platform));
  1136. ri->platform = tor_strdup(platform);
  1137. /* compute ri->bandwidthrate as the min of various options */
  1138. ri->bandwidthrate = (int)options->BandwidthRate;
  1139. if (ri->bandwidthrate > options->MaxAdvertisedBandwidth)
  1140. ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
  1141. if (options->RelayBandwidthRate > 0 &&
  1142. ri->bandwidthrate > options->RelayBandwidthRate)
  1143. ri->bandwidthrate = (int)options->RelayBandwidthRate;
  1144. /* and compute ri->bandwidthburst similarly */
  1145. ri->bandwidthburst = (int)options->BandwidthBurst;
  1146. if (options->RelayBandwidthBurst > 0 &&
  1147. ri->bandwidthburst > options->RelayBandwidthBurst)
  1148. ri->bandwidthburst = (int)options->RelayBandwidthBurst;
  1149. ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
  1150. policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
  1151. options->ExitPolicyRejectPrivate,
  1152. ri->address);
  1153. if (desc_routerinfo) { /* inherit values */
  1154. ri->is_valid = desc_routerinfo->is_valid;
  1155. ri->is_running = desc_routerinfo->is_running;
  1156. ri->is_named = desc_routerinfo->is_named;
  1157. }
  1158. if (authdir_mode(options))
  1159. ri->is_valid = ri->is_named = 1; /* believe in yourself */
  1160. if (options->MyFamily) {
  1161. smartlist_t *family;
  1162. if (!warned_nonexistent_family)
  1163. warned_nonexistent_family = smartlist_create();
  1164. family = smartlist_create();
  1165. ri->declared_family = smartlist_create();
  1166. smartlist_split_string(family, options->MyFamily, ",",
  1167. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1168. SMARTLIST_FOREACH(family, char *, name,
  1169. {
  1170. routerinfo_t *member;
  1171. if (!strcasecmp(name, options->Nickname))
  1172. member = ri;
  1173. else
  1174. member = router_get_by_nickname(name, 1);
  1175. if (!member) {
  1176. int is_legal = is_legal_nickname_or_hexdigest(name);
  1177. if (!smartlist_string_isin(warned_nonexistent_family, name) &&
  1178. !is_legal_hexdigest(name)) {
  1179. if (is_legal)
  1180. log_warn(LD_CONFIG,
  1181. "I have no descriptor for the router named \"%s\" in my "
  1182. "declared family; I'll use the nickname as is, but "
  1183. "this may confuse clients.", name);
  1184. else
  1185. log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
  1186. "declared family, but that isn't a legal nickname. "
  1187. "Skipping it.", escaped(name));
  1188. smartlist_add(warned_nonexistent_family, tor_strdup(name));
  1189. }
  1190. if (is_legal) {
  1191. smartlist_add(ri->declared_family, name);
  1192. name = NULL;
  1193. }
  1194. } else if (router_is_me(member)) {
  1195. /* Don't list ourself in our own family; that's redundant */
  1196. } else {
  1197. char *fp = tor_malloc(HEX_DIGEST_LEN+2);
  1198. fp[0] = '$';
  1199. base16_encode(fp+1,HEX_DIGEST_LEN+1,
  1200. member->cache_info.identity_digest, DIGEST_LEN);
  1201. smartlist_add(ri->declared_family, fp);
  1202. if (smartlist_string_isin(warned_nonexistent_family, name))
  1203. smartlist_string_remove(warned_nonexistent_family, name);
  1204. }
  1205. tor_free(name);
  1206. });
  1207. /* remove duplicates from the list */
  1208. smartlist_sort_strings(ri->declared_family);
  1209. smartlist_uniq_strings(ri->declared_family);
  1210. smartlist_free(family);
  1211. }
  1212. /* Now generate the extrainfo. */
  1213. ei = tor_malloc_zero(sizeof(extrainfo_t));
  1214. ei->cache_info.is_extrainfo = 1;
  1215. strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
  1216. ei->cache_info.published_on = ri->cache_info.published_on;
  1217. memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
  1218. DIGEST_LEN);
  1219. ei->cache_info.signed_descriptor_body = tor_malloc(8192);
  1220. if (extrainfo_dump_to_string(ei->cache_info.signed_descriptor_body, 8192,
  1221. ei, get_identity_key()) < 0) {
  1222. log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
  1223. extrainfo_free(ei);
  1224. return -1;
  1225. }
  1226. ei->cache_info.signed_descriptor_len =
  1227. strlen(ei->cache_info.signed_descriptor_body);
  1228. router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
  1229. ei->cache_info.signed_descriptor_digest);
  1230. /* Now finish the router descriptor. */
  1231. memcpy(ri->cache_info.extra_info_digest,
  1232. ei->cache_info.signed_descriptor_digest,
  1233. DIGEST_LEN);
  1234. ri->cache_info.signed_descriptor_body = tor_malloc(8192);
  1235. if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
  1236. ri, get_identity_key())<0) {
  1237. log_warn(LD_BUG, "Couldn't generate router descriptor.");
  1238. return -1;
  1239. }
  1240. ri->cache_info.signed_descriptor_len =
  1241. strlen(ri->cache_info.signed_descriptor_body);
  1242. ri->purpose =
  1243. options->BridgeRelay ? ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
  1244. if (!options->BridgeRelay) {
  1245. ri->cache_info.send_unencrypted = 1;
  1246. ei->cache_info.send_unencrypted = 1;
  1247. }
  1248. router_get_router_hash(ri->cache_info.signed_descriptor_body,
  1249. ri->cache_info.signed_descriptor_digest);
  1250. tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei, NULL, NULL));
  1251. if (desc_routerinfo)
  1252. routerinfo_free(desc_routerinfo);
  1253. desc_routerinfo = ri;
  1254. if (desc_extrainfo)
  1255. extrainfo_free(desc_extrainfo);
  1256. desc_extrainfo = ei;
  1257. desc_clean_since = time(NULL);
  1258. desc_needs_upload = 1;
  1259. control_event_my_descriptor_changed();
  1260. return 0;
  1261. }
  1262. /** Mark descriptor out of date if it's older than <b>when</b> */
  1263. void
  1264. mark_my_descriptor_dirty_if_older_than(time_t when)
  1265. {
  1266. if (desc_clean_since < when)
  1267. mark_my_descriptor_dirty();
  1268. }
  1269. /** Call when the current descriptor is out of date. */
  1270. void
  1271. mark_my_descriptor_dirty(void)
  1272. {
  1273. desc_clean_since = 0;
  1274. }
  1275. /** How frequently will we republish our descriptor because of large (factor
  1276. * of 2) shifts in estimated bandwidth? */
  1277. #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
  1278. /** Check whether bandwidth has changed a lot since the last time we announced
  1279. * bandwidth. If so, mark our descriptor dirty. */
  1280. void
  1281. check_descriptor_bandwidth_changed(time_t now)
  1282. {
  1283. static time_t last_changed = 0;
  1284. uint64_t prev, cur;
  1285. if (!desc_routerinfo)
  1286. return;
  1287. prev = desc_routerinfo->bandwidthcapacity;
  1288. cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
  1289. if ((prev != cur && (!prev || !cur)) ||
  1290. cur > prev*2 ||
  1291. cur < prev/2) {
  1292. if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
  1293. log_info(LD_GENERAL,
  1294. "Measured bandwidth has changed; rebuilding descriptor.");
  1295. mark_my_descriptor_dirty();
  1296. last_changed = now;
  1297. }
  1298. }
  1299. }
  1300. /** Note at log level severity that our best guess of address has changed from
  1301. * <b>prev</b> to <b>cur</b>. */
  1302. static void
  1303. log_addr_has_changed(int severity, uint32_t prev, uint32_t cur)
  1304. {
  1305. char addrbuf_prev[INET_NTOA_BUF_LEN];
  1306. char addrbuf_cur[INET_NTOA_BUF_LEN];
  1307. struct in_addr in_prev;
  1308. struct in_addr in_cur;
  1309. in_prev.s_addr = htonl(prev);
  1310. tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
  1311. in_cur.s_addr = htonl(cur);
  1312. tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
  1313. if (prev)
  1314. log_fn(severity, LD_GENERAL,
  1315. "Our IP Address has changed from %s to %s; "
  1316. "rebuilding descriptor.",
  1317. addrbuf_prev, addrbuf_cur);
  1318. else
  1319. log_notice(LD_GENERAL,
  1320. "Guessed our IP address as %s.",
  1321. addrbuf_cur);
  1322. }
  1323. /** Check whether our own address as defined by the Address configuration
  1324. * has changed. This is for routers that get their address from a service
  1325. * like dyndns. If our address has changed, mark our descriptor dirty. */
  1326. void
  1327. check_descriptor_ipaddress_changed(time_t now)
  1328. {
  1329. uint32_t prev, cur;
  1330. or_options_t *options = get_options();
  1331. (void) now;
  1332. if (!desc_routerinfo)
  1333. return;
  1334. prev = desc_routerinfo->addr;
  1335. if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
  1336. log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
  1337. return;
  1338. }
  1339. if (prev != cur) {
  1340. log_addr_has_changed(LOG_INFO, prev, cur);
  1341. ip_address_changed(0);
  1342. }
  1343. }
  1344. /** The most recently guessed value of our IP address, based on directory
  1345. * headers. */
  1346. static uint32_t last_guessed_ip = 0;
  1347. /** A directory server <b>d_conn</b> told us our IP address is
  1348. * <b>suggestion</b>.
  1349. * If this address is different from the one we think we are now, and
  1350. * if our computer doesn't actually know its IP address, then switch. */
  1351. void
  1352. router_new_address_suggestion(const char *suggestion,
  1353. const dir_connection_t *d_conn)
  1354. {
  1355. uint32_t addr, cur = 0;
  1356. struct in_addr in;
  1357. or_options_t *options = get_options();
  1358. /* first, learn what the IP address actually is */
  1359. if (!tor_inet_aton(suggestion, &in)) {
  1360. log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
  1361. escaped(suggestion));
  1362. return;
  1363. }
  1364. addr = ntohl(in.s_addr);
  1365. log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
  1366. if (!server_mode(options)) {
  1367. last_guessed_ip = addr; /* store it in case we need it later */
  1368. return;
  1369. }
  1370. if (resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
  1371. /* We're all set -- we already know our address. Great. */
  1372. last_guessed_ip = cur; /* store it in case we need it later */
  1373. return;
  1374. }
  1375. if (is_internal_IP(addr, 0)) {
  1376. /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
  1377. return;
  1378. }
  1379. if (addr == d_conn->_base.addr) {
  1380. /* Don't believe anybody who says our IP is their IP. */
  1381. log_debug(LD_DIR, "A directory server told us our IP address is %s, "
  1382. "but he's just reporting his own IP address. Ignoring.",
  1383. suggestion);
  1384. return;
  1385. }
  1386. /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
  1387. * us an answer different from what we had the last time we managed to
  1388. * resolve it. */
  1389. if (last_guessed_ip != addr) {
  1390. control_event_server_status(LOG_NOTICE,
  1391. "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
  1392. suggestion);
  1393. log_addr_has_changed(LOG_NOTICE, last_guessed_ip, addr);
  1394. ip_address_changed(0);
  1395. last_guessed_ip = addr; /* router_rebuild_descriptor() will fetch it */
  1396. }
  1397. }
  1398. /** We failed to resolve our address locally, but we'd like to build
  1399. * a descriptor and publish / test reachability. If we have a guess
  1400. * about our address based on directory headers, answer it and return
  1401. * 0; else return -1. */
  1402. static int
  1403. router_guess_address_from_dir_headers(uint32_t *guess)
  1404. {
  1405. if (last_guessed_ip) {
  1406. *guess = last_guessed_ip;
  1407. return 0;
  1408. }
  1409. return -1;
  1410. }
  1411. extern const char tor_svn_revision[]; /* from main.c */
  1412. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  1413. * string describing the version of Tor and the operating system we're
  1414. * currently running on.
  1415. */
  1416. void
  1417. get_platform_str(char *platform, size_t len)
  1418. {
  1419. tor_snprintf(platform, len, "Tor %s on %s", get_version(), get_uname());
  1420. }
  1421. /* XXX need to audit this thing and count fenceposts. maybe
  1422. * refactor so we don't have to keep asking if we're
  1423. * near the end of maxlen?
  1424. */
  1425. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1426. /** OR only: Given a routerinfo for this router, and an identity key to sign
  1427. * with, encode the routerinfo as a signed server descriptor and write the
  1428. * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
  1429. * failure, and the number of bytes used on success.
  1430. */
  1431. int
  1432. router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
  1433. crypto_pk_env_t *ident_key)
  1434. {
  1435. char *onion_pkey; /* Onion key, PEM-encoded. */
  1436. char *identity_pkey; /* Identity key, PEM-encoded. */
  1437. char digest[DIGEST_LEN];
  1438. char published[ISO_TIME_LEN+1];
  1439. char fingerprint[FINGERPRINT_LEN+1];
  1440. char extra_info_digest[HEX_DIGEST_LEN+1];
  1441. size_t onion_pkeylen, identity_pkeylen;
  1442. size_t written;
  1443. int result=0;
  1444. addr_policy_t *tmpe;
  1445. char *family_line;
  1446. or_options_t *options = get_options();
  1447. /* Make sure the identity key matches the one in the routerinfo. */
  1448. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  1449. log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
  1450. "match router's public key!");
  1451. return -1;
  1452. }
  1453. /* record our fingerprint, so we can include it in the descriptor */
  1454. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
  1455. log_err(LD_BUG,"Error computing fingerprint");
  1456. return -1;
  1457. }
  1458. /* PEM-encode the onion key */
  1459. if (crypto_pk_write_public_key_to_string(router->onion_pkey,
  1460. &onion_pkey,&onion_pkeylen)<0) {
  1461. log_warn(LD_BUG,"write onion_pkey to string failed!");
  1462. return -1;
  1463. }
  1464. /* PEM-encode the identity key key */
  1465. if (crypto_pk_write_public_key_to_string(router->identity_pkey,
  1466. &identity_pkey,&identity_pkeylen)<0) {
  1467. log_warn(LD_BUG,"write identity_pkey to string failed!");
  1468. tor_free(onion_pkey);
  1469. return -1;
  1470. }
  1471. /* Encode the publication time. */
  1472. format_iso_time(published, router->cache_info.published_on);
  1473. if (router->declared_family && smartlist_len(router->declared_family)) {
  1474. size_t n;
  1475. char *family = smartlist_join_strings(router->declared_family, " ", 0, &n);
  1476. n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
  1477. family_line = tor_malloc(n);
  1478. tor_snprintf(family_line, n, "family %s\n", family);
  1479. tor_free(family);
  1480. } else {
  1481. family_line = tor_strdup("");
  1482. }
  1483. base16_encode(extra_info_digest, sizeof(extra_info_digest),
  1484. router->cache_info.extra_info_digest, DIGEST_LEN);
  1485. /* Generate the easy portion of the router descriptor. */
  1486. result = tor_snprintf(s, maxlen,
  1487. "router %s %s %d 0 %d\n"
  1488. "platform %s\n"
  1489. "opt protocols Link 1 2 Circuit 1\n"
  1490. "published %s\n"
  1491. "opt fingerprint %s\n"
  1492. "uptime %ld\n"
  1493. "bandwidth %d %d %d\n"
  1494. "opt extra-info-digest %s\n%s"
  1495. "onion-key\n%s"
  1496. "signing-key\n%s"
  1497. "%s%s%s",
  1498. router->nickname,
  1499. router->address,
  1500. router->or_port,
  1501. decide_to_advertise_dirport(options, router->dir_port),
  1502. router->platform,
  1503. published,
  1504. fingerprint,
  1505. stats_n_seconds_working,
  1506. (int) router->bandwidthrate,
  1507. (int) router->bandwidthburst,
  1508. (int) router->bandwidthcapacity,
  1509. extra_info_digest,
  1510. options->DownloadExtraInfo ? "opt caches-extra-info\n" : "",
  1511. onion_pkey, identity_pkey,
  1512. family_line,
  1513. we_are_hibernating() ? "opt hibernating 1\n" : "",
  1514. options->HidServDirectoryV2 ? "opt hidden-service-dir\n" : "");
  1515. tor_free(family_line);
  1516. tor_free(onion_pkey);
  1517. tor_free(identity_pkey);
  1518. if (result < 0) {
  1519. log_warn(LD_BUG,"descriptor snprintf #1 ran out of room!");
  1520. return -1;
  1521. }
  1522. /* From now on, we use 'written' to remember the current length of 's'. */
  1523. written = result;
  1524. if (options->ContactInfo && strlen(options->ContactInfo)) {
  1525. const char *ci = options->ContactInfo;
  1526. if (strchr(ci, '\n') || strchr(ci, '\r'))
  1527. ci = escaped(ci);
  1528. result = tor_snprintf(s+written,maxlen-written, "contact %s\n", ci);
  1529. if (result<0) {
  1530. log_warn(LD_BUG,"descriptor snprintf #2 ran out of room!");
  1531. return -1;
  1532. }
  1533. written += result;
  1534. }
  1535. /* Write the exit policy to the end of 's'. */
  1536. if (dns_seems_to_be_broken() ||
  1537. !router->exit_policy || !smartlist_len(router->exit_policy)) {
  1538. /* DNS is screwed up; don't claim to be an exit. */
  1539. strlcat(s+written, "reject *:*\n", maxlen-written);
  1540. written += strlen("reject *:*\n");
  1541. tmpe = NULL;
  1542. } else if (router->exit_policy) {
  1543. int i;
  1544. for (i = 0; i < smartlist_len(router->exit_policy); ++i) {
  1545. tmpe = smartlist_get(router->exit_policy, i);
  1546. result = policy_write_item(s+written, maxlen-written, tmpe);
  1547. if (result < 0) {
  1548. log_warn(LD_BUG,"descriptor policy_write_item ran out of room!");
  1549. return -1;
  1550. }
  1551. tor_assert(result == (int)strlen(s+written));
  1552. written += result;
  1553. if (written+2 > maxlen) {
  1554. log_warn(LD_BUG,"descriptor policy_write_item ran out of room (2)!");
  1555. return -1;
  1556. }
  1557. s[written++] = '\n';
  1558. }
  1559. }
  1560. if (written+256 > maxlen) { /* Not enough room for signature. */
  1561. log_warn(LD_BUG,"not enough room left in descriptor for signature!");
  1562. return -1;
  1563. }
  1564. /* Sign the directory */
  1565. strlcpy(s+written, "router-signature\n", maxlen-written);
  1566. written += strlen(s+written);
  1567. s[written] = '\0';
  1568. if (router_get_router_hash(s, digest) < 0) {
  1569. return -1;
  1570. }
  1571. note_crypto_pk_op(SIGN_RTR);
  1572. if (router_append_dirobj_signature(s+written,maxlen-written,
  1573. digest,ident_key)<0) {
  1574. log_warn(LD_BUG, "Couldn't sign router descriptor");
  1575. return -1;
  1576. }
  1577. written += strlen(s+written);
  1578. if (written+2 > maxlen) {
  1579. log_warn(LD_BUG,"Not enough room to finish descriptor.");
  1580. return -1;
  1581. }
  1582. /* include a last '\n' */
  1583. s[written] = '\n';
  1584. s[written+1] = 0;
  1585. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1586. {
  1587. char *s_dup;
  1588. const char *cp;
  1589. routerinfo_t *ri_tmp;
  1590. cp = s_dup = tor_strdup(s);
  1591. ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL);
  1592. if (!ri_tmp) {
  1593. log_err(LD_BUG,
  1594. "We just generated a router descriptor we can't parse.");
  1595. log_err(LD_BUG, "Descriptor was: <<%s>>", s);
  1596. return -1;
  1597. }
  1598. tor_free(s_dup);
  1599. routerinfo_free(ri_tmp);
  1600. }
  1601. #endif
  1602. return (int)written+1;
  1603. }
  1604. /** Write the contents of <b>extrainfo</b> to the <b>maxlen</b>-byte string
  1605. * <b>s</b>, signing them with <b>ident_key</b>. Return 0 on success,
  1606. * negative on failure. */
  1607. int
  1608. extrainfo_dump_to_string(char *s, size_t maxlen, extrainfo_t *extrainfo,
  1609. crypto_pk_env_t *ident_key)
  1610. {
  1611. or_options_t *options = get_options();
  1612. char identity[HEX_DIGEST_LEN+1];
  1613. char published[ISO_TIME_LEN+1];
  1614. char digest[DIGEST_LEN];
  1615. char *bandwidth_usage;
  1616. int result;
  1617. size_t len;
  1618. base16_encode(identity, sizeof(identity),
  1619. extrainfo->cache_info.identity_digest, DIGEST_LEN);
  1620. format_iso_time(published, extrainfo->cache_info.published_on);
  1621. bandwidth_usage = rep_hist_get_bandwidth_lines(1);
  1622. result = tor_snprintf(s, maxlen,
  1623. "extra-info %s %s\n"
  1624. "published %s\n%s",
  1625. extrainfo->nickname, identity,
  1626. published, bandwidth_usage);
  1627. tor_free(bandwidth_usage);
  1628. if (result<0)
  1629. return -1;
  1630. if (options->BridgeRelay && options->BridgeRecordUsageByCountry) {
  1631. char *geoip_summary = geoip_get_client_history(time(NULL));
  1632. if (geoip_summary) {
  1633. char geoip_start[ISO_TIME_LEN+1];
  1634. format_iso_time(geoip_start, geoip_get_history_start());
  1635. result = tor_snprintf(s+strlen(s), maxlen-strlen(s),
  1636. "geoip-start-time %s\n"
  1637. "geoip-client-origins %s\n",
  1638. geoip_start, geoip_summary);
  1639. tor_free(geoip_summary);
  1640. if (result<0)
  1641. return -1;
  1642. }
  1643. }
  1644. len = strlen(s);
  1645. strlcat(s+len, "router-signature\n", maxlen-len);
  1646. len += strlen(s+len);
  1647. if (router_get_extrainfo_hash(s, digest)<0)
  1648. return -1;
  1649. if (router_append_dirobj_signature(s+len, maxlen-len, digest, ident_key)<0)
  1650. return -1;
  1651. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1652. {
  1653. char *cp, *s_dup;
  1654. extrainfo_t *ei_tmp;
  1655. cp = s_dup = tor_strdup(s);
  1656. ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
  1657. if (!ei_tmp) {
  1658. log_err(LD_BUG,
  1659. "We just generated an extrainfo descriptor we can't parse.");
  1660. log_err(LD_BUG, "Descriptor was: <<%s>>", s);
  1661. return -1;
  1662. }
  1663. tor_free(s_dup);
  1664. extrainfo_free(ei_tmp);
  1665. }
  1666. #endif
  1667. return (int)strlen(s)+1;
  1668. }
  1669. /** Return true iff <b>s</b> is a legally valid server nickname. */
  1670. int
  1671. is_legal_nickname(const char *s)
  1672. {
  1673. size_t len;
  1674. tor_assert(s);
  1675. len = strlen(s);
  1676. return len > 0 && len <= MAX_NICKNAME_LEN &&
  1677. strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
  1678. }
  1679. /** Return true iff <b>s</b> is a legally valid server nickname or
  1680. * hex-encoded identity-key digest. */
  1681. int
  1682. is_legal_nickname_or_hexdigest(const char *s)
  1683. {
  1684. if (*s!='$')
  1685. return is_legal_nickname(s);
  1686. else
  1687. return is_legal_hexdigest(s);
  1688. }
  1689. /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
  1690. * digest. */
  1691. int
  1692. is_legal_hexdigest(const char *s)
  1693. {
  1694. size_t len;
  1695. tor_assert(s);
  1696. if (s[0] == '$') s++;
  1697. len = strlen(s);
  1698. if (len > HEX_DIGEST_LEN) {
  1699. if (s[HEX_DIGEST_LEN] == '=' ||
  1700. s[HEX_DIGEST_LEN] == '~') {
  1701. if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
  1702. return 0;
  1703. } else {
  1704. return 0;
  1705. }
  1706. }
  1707. return (len >= HEX_DIGEST_LEN &&
  1708. strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
  1709. }
  1710. /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
  1711. * verbose representation of the identity of <b>router</b>. The format is:
  1712. * A dollar sign.
  1713. * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
  1714. * A "=" if the router is named; a "~" if it is not.
  1715. * The router's nickname.
  1716. **/
  1717. void
  1718. router_get_verbose_nickname(char *buf, routerinfo_t *router)
  1719. {
  1720. buf[0] = '$';
  1721. base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
  1722. DIGEST_LEN);
  1723. buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
  1724. strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
  1725. }
  1726. /** Forget that we have issued any router-related warnings, so that we'll
  1727. * warn again if we see the same errors. */
  1728. void
  1729. router_reset_warnings(void)
  1730. {
  1731. if (warned_nonexistent_family) {
  1732. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  1733. smartlist_clear(warned_nonexistent_family);
  1734. }
  1735. }
  1736. /** Given a router purpose, convert it to a string. Don't call this on
  1737. * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
  1738. * know its string representation. */
  1739. const char *
  1740. router_purpose_to_string(uint8_t p)
  1741. {
  1742. switch (p)
  1743. {
  1744. case ROUTER_PURPOSE_GENERAL: return "general";
  1745. case ROUTER_PURPOSE_BRIDGE: return "bridge";
  1746. case ROUTER_PURPOSE_CONTROLLER: return "controller";
  1747. default:
  1748. tor_assert(0);
  1749. }
  1750. return NULL;
  1751. }
  1752. /** Given a string, convert it to a router purpose. */
  1753. uint8_t
  1754. router_purpose_from_string(const char *s)
  1755. {
  1756. if (!strcmp(s, "general"))
  1757. return ROUTER_PURPOSE_GENERAL;
  1758. else if (!strcmp(s, "bridge"))
  1759. return ROUTER_PURPOSE_BRIDGE;
  1760. else if (!strcmp(s, "controller"))
  1761. return ROUTER_PURPOSE_CONTROLLER;
  1762. else
  1763. return ROUTER_PURPOSE_UNKNOWN;
  1764. }
  1765. /** Release all static resources held in router.c */
  1766. void
  1767. router_free_all(void)
  1768. {
  1769. if (onionkey)
  1770. crypto_free_pk_env(onionkey);
  1771. if (lastonionkey)
  1772. crypto_free_pk_env(lastonionkey);
  1773. if (identitykey)
  1774. crypto_free_pk_env(identitykey);
  1775. if (key_lock)
  1776. tor_mutex_free(key_lock);
  1777. if (desc_routerinfo)
  1778. routerinfo_free(desc_routerinfo);
  1779. if (desc_extrainfo)
  1780. extrainfo_free(desc_extrainfo);
  1781. if (authority_signing_key)
  1782. crypto_free_pk_env(authority_signing_key);
  1783. if (authority_key_certificate)
  1784. authority_cert_free(authority_key_certificate);
  1785. if (warned_nonexistent_family) {
  1786. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  1787. smartlist_free(warned_nonexistent_family);
  1788. }
  1789. }