router.c 59 KB

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