router.c 60 KB

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