router.c 60 KB

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