router.c 43 KB

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