router.c 61 KB

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