router.c 51 KB

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