router.c 58 KB

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