router.c 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char router_c_id[] = "$Id$";
  7. #include "or.h"
  8. /**
  9. * \file router.c
  10. * \brief OR functionality, including key maintenance, generating
  11. * and uploading server descriptors, retrying OR connections.
  12. **/
  13. extern long stats_n_seconds_working;
  14. /* Exposed for test.c. */ void get_platform_str(char *platform, size_t len);
  15. /************************************************************/
  16. /*****
  17. * Key management: ORs only.
  18. *****/
  19. /** Private keys for this OR. There is also an SSL key managed by tortls.c.
  20. */
  21. static tor_mutex_t *key_lock=NULL;
  22. static time_t onionkey_set_at=0; /* When was onionkey last changed? */
  23. static crypto_pk_env_t *onionkey=NULL;
  24. static crypto_pk_env_t *lastonionkey=NULL;
  25. static crypto_pk_env_t *identitykey=NULL;
  26. /** Replace the current onion key with <b>k</b>. Does not affect lastonionkey;
  27. * to update onionkey correctly, call rotate_onion_key().
  28. */
  29. void
  30. set_onion_key(crypto_pk_env_t *k)
  31. {
  32. tor_mutex_acquire(key_lock);
  33. onionkey = k;
  34. onionkey_set_at = time(NULL);
  35. tor_mutex_release(key_lock);
  36. mark_my_descriptor_dirty();
  37. }
  38. /** Return the current onion key. Requires that the onion key has been
  39. * loaded or generated. */
  40. crypto_pk_env_t *
  41. get_onion_key(void)
  42. {
  43. tor_assert(onionkey);
  44. return onionkey;
  45. }
  46. /** Return the onion key that was current before the most recent onion
  47. * key rotation. If no rotation has been performed since this process
  48. * started, return NULL.
  49. */
  50. crypto_pk_env_t *
  51. get_previous_onion_key(void)
  52. {
  53. return lastonionkey;
  54. }
  55. /** Store a copy of the current onion key into *<b>key</b>, and a copy
  56. * of the most recent onion key into *<b>last</b>.
  57. */
  58. void
  59. dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
  60. {
  61. tor_assert(key);
  62. tor_assert(last);
  63. tor_mutex_acquire(key_lock);
  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. }
  89. /** Returns the current identity key; requires that the identity key has been
  90. * set.
  91. */
  92. crypto_pk_env_t *
  93. get_identity_key(void)
  94. {
  95. tor_assert(identitykey);
  96. return identitykey;
  97. }
  98. /** Return true iff the identity key has been set. */
  99. int
  100. identity_key_is_set(void)
  101. {
  102. return identitykey != NULL;
  103. }
  104. /** Replace the previous onion key with the current onion key, and generate
  105. * a new previous onion key. Immediately after calling this function,
  106. * the OR should:
  107. * - schedule all previous cpuworkers to shut down _after_ processing
  108. * pending work. (This will cause fresh cpuworkers to be generated.)
  109. * - generate and upload a fresh routerinfo.
  110. */
  111. void
  112. rotate_onion_key(void)
  113. {
  114. char fname[512];
  115. char fname_prev[512];
  116. crypto_pk_env_t *prkey;
  117. tor_snprintf(fname,sizeof(fname),
  118. "%s/keys/secret_onion_key",get_options()->DataDirectory);
  119. tor_snprintf(fname_prev,sizeof(fname_prev),
  120. "%s/keys/secret_onion_key.old",get_options()->DataDirectory);
  121. if (!(prkey = crypto_new_pk_env())) {
  122. err(LD_GENERAL,"Error creating crypto environment.");
  123. goto error;
  124. }
  125. if (crypto_pk_generate_key(prkey)) {
  126. err(LD_BUG,"Error generating onion key");
  127. goto error;
  128. }
  129. if (file_status(fname) == FN_FILE) {
  130. if (replace_file(fname, fname_prev))
  131. goto error;
  132. }
  133. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  134. err(LD_FS,"Couldn't write generated key to \"%s\".", fname);
  135. goto error;
  136. }
  137. info(LD_GENERAL, "Rotating onion key");
  138. tor_mutex_acquire(key_lock);
  139. if (lastonionkey)
  140. crypto_free_pk_env(lastonionkey);
  141. lastonionkey = onionkey;
  142. onionkey = prkey;
  143. onionkey_set_at = time(NULL);
  144. tor_mutex_release(key_lock);
  145. mark_my_descriptor_dirty();
  146. return;
  147. error:
  148. warn(LD_GENERAL, "Couldn't rotate onion key.");
  149. }
  150. /* Read an RSA secret key key from a file that was once named fname_old,
  151. * but is now named fname_new. Rename the file from old to new as needed.
  152. */
  153. static crypto_pk_env_t *
  154. init_key_from_file_name_changed(const char *fname_old,
  155. const char *fname_new)
  156. {
  157. if (file_status(fname_new) == FN_FILE || file_status(fname_old) != FN_FILE)
  158. /* The new filename is there, or both are, or neither is. */
  159. return init_key_from_file(fname_new);
  160. /* The old filename exists, and the new one doesn't. Rename and load. */
  161. if (rename(fname_old, fname_new) < 0) {
  162. log_fn(LOG_ERR, LD_FS, "Couldn't rename \"%s\" to \"%s\": %s",
  163. fname_old, fname_new, strerror(errno));
  164. return NULL;
  165. }
  166. return init_key_from_file(fname_new);
  167. }
  168. /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist,
  169. * create a new RSA key and save it in <b>fname</b>. Return the read/created
  170. * key, or NULL on error.
  171. */
  172. crypto_pk_env_t *
  173. init_key_from_file(const char *fname)
  174. {
  175. crypto_pk_env_t *prkey = NULL;
  176. FILE *file = NULL;
  177. if (!(prkey = crypto_new_pk_env())) {
  178. err(LD_GENERAL,"Error creating crypto environment.");
  179. goto error;
  180. }
  181. switch (file_status(fname)) {
  182. case FN_DIR:
  183. case FN_ERROR:
  184. err(LD_FS,"Can't read key from \"%s\"", fname);
  185. goto error;
  186. case FN_NOENT:
  187. info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.", fname);
  188. if (crypto_pk_generate_key(prkey)) {
  189. err(LD_GENERAL,"Error generating onion key");
  190. goto error;
  191. }
  192. if (crypto_pk_check_key(prkey) <= 0) {
  193. err(LD_GENERAL,"Generated key seems invalid");
  194. goto error;
  195. }
  196. info(LD_GENERAL, "Generated key seems valid");
  197. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  198. err(LD_FS,"Couldn't write generated key to \"%s\".", fname);
  199. goto error;
  200. }
  201. return prkey;
  202. case FN_FILE:
  203. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  204. err(LD_GENERAL,"Error loading private key.");
  205. goto error;
  206. }
  207. return prkey;
  208. default:
  209. tor_assert(0);
  210. }
  211. error:
  212. if (prkey)
  213. crypto_free_pk_env(prkey);
  214. if (file)
  215. fclose(file);
  216. return NULL;
  217. }
  218. /** Initialize all OR private keys, and the TLS context, as necessary.
  219. * On OPs, this only initializes the tls context.
  220. */
  221. int
  222. init_keys(void)
  223. {
  224. /* XXX009 Two problems with how this is called:
  225. * 1. It should be idempotent for servers, so we can call init_keys
  226. * as much as we need to.
  227. */
  228. char keydir[512];
  229. char keydir2[512];
  230. char fingerprint[FINGERPRINT_LEN+1];
  231. char fingerprint_line[FINGERPRINT_LEN+MAX_NICKNAME_LEN+3];/*nickname fp\n\0 */
  232. char *cp;
  233. const char *mydesc, *datadir;
  234. crypto_pk_env_t *prkey;
  235. char digest[20];
  236. or_options_t *options = get_options();
  237. if (!key_lock)
  238. key_lock = tor_mutex_new();
  239. /* OP's don't need persistent keys; just make up an identity and
  240. * initialize the TLS context. */
  241. if (!server_mode(options)) {
  242. if (!(prkey = crypto_new_pk_env()))
  243. return -1;
  244. if (crypto_pk_generate_key(prkey))
  245. return -1;
  246. set_identity_key(prkey);
  247. /* Create a TLS context; default the client nickname to "client". */
  248. if (tor_tls_context_new(get_identity_key(), 1,
  249. options->Nickname ? options->Nickname : "client",
  250. MAX_SSL_KEY_LIFETIME) < 0) {
  251. err(LD_GENERAL,"Error creating TLS context for OP.");
  252. return -1;
  253. }
  254. return 0;
  255. }
  256. /* Make sure DataDirectory exists, and is private. */
  257. datadir = options->DataDirectory;
  258. if (check_private_dir(datadir, CPD_CREATE)) {
  259. return -1;
  260. }
  261. /* Check the key directory. */
  262. tor_snprintf(keydir,sizeof(keydir),"%s/keys", datadir);
  263. if (check_private_dir(keydir, CPD_CREATE)) {
  264. return -1;
  265. }
  266. cp = keydir + strlen(keydir); /* End of string. */
  267. /* 1. Read identity key. Make it if none is found. */
  268. tor_snprintf(keydir,sizeof(keydir),"%s/keys/identity.key",datadir);
  269. tor_snprintf(keydir2,sizeof(keydir2),"%s/keys/secret_id_key",datadir);
  270. info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir2);
  271. prkey = init_key_from_file_name_changed(keydir,keydir2);
  272. if (!prkey) return -1;
  273. set_identity_key(prkey);
  274. /* 2. Read onion key. Make it if none is found. */
  275. tor_snprintf(keydir,sizeof(keydir),"%s/keys/onion.key",datadir);
  276. tor_snprintf(keydir2,sizeof(keydir2),"%s/keys/secret_onion_key",datadir);
  277. info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir2);
  278. prkey = init_key_from_file_name_changed(keydir,keydir2);
  279. if (!prkey) return -1;
  280. set_onion_key(prkey);
  281. tor_snprintf(keydir,sizeof(keydir),"%s/keys/secret_onion_key.old",datadir);
  282. if (file_status(keydir) == FN_FILE) {
  283. prkey = init_key_from_file(keydir);
  284. if (prkey)
  285. lastonionkey = prkey;
  286. }
  287. /* 3. Initialize link key and TLS context. */
  288. if (tor_tls_context_new(get_identity_key(), 1, options->Nickname,
  289. MAX_SSL_KEY_LIFETIME) < 0) {
  290. err(LD_GENERAL,"Error initializing TLS context");
  291. return -1;
  292. }
  293. /* 4. Dump router descriptor to 'router.desc' */
  294. /* Must be called after keys are initialized. */
  295. mydesc = router_get_my_descriptor();
  296. if (!mydesc) {
  297. err(LD_GENERAL,"Error initializing descriptor.");
  298. return -1;
  299. }
  300. if (authdir_mode(options)) {
  301. const char *m;
  302. /* We need to add our own fingerprint so it gets recognized. */
  303. if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
  304. err(LD_GENERAL,"Error adding own fingerprint to approved set");
  305. return -1;
  306. }
  307. if (dirserv_add_descriptor(mydesc, &m) < 0) {
  308. err(LD_GENERAL,"Unable to add own descriptor to directory: %s",
  309. m?m:"<unknown error>");
  310. return -1;
  311. }
  312. }
  313. tor_snprintf(keydir,sizeof(keydir),"%s/router.desc", datadir);
  314. info(LD_GENERAL,"Dumping descriptor to \"%s\"...",keydir);
  315. if (write_str_to_file(keydir, mydesc,0)) {
  316. return -1;
  317. }
  318. /* 5. Dump fingerprint to 'fingerprint' */
  319. tor_snprintf(keydir,sizeof(keydir),"%s/fingerprint", datadir);
  320. info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
  321. if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 1)<0) {
  322. err(LD_GENERAL,"Error computing fingerprint");
  323. return -1;
  324. }
  325. tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
  326. if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
  327. "%s %s\n",options->Nickname, fingerprint) < 0) {
  328. err(LD_GENERAL,"Error writing fingerprint line");
  329. return -1;
  330. }
  331. if (write_str_to_file(keydir, fingerprint_line, 0)) {
  332. err(LD_FS, "Error writing fingerprint line to file");
  333. return -1;
  334. }
  335. if (!authdir_mode(options))
  336. return 0;
  337. /* 6. [authdirserver only] load approved-routers file */
  338. tor_snprintf(keydir,sizeof(keydir),"%s/approved-routers", datadir);
  339. info(LD_DIRSERV,"Loading approved fingerprints from \"%s\"...",keydir);
  340. if (dirserv_parse_fingerprint_file(keydir) < 0) {
  341. err(LD_GENERAL,"Error loading fingerprints");
  342. return -1;
  343. }
  344. /* 6b. [authdirserver only] add own key to approved directories. */
  345. crypto_pk_get_digest(get_identity_key(), digest);
  346. if (!router_digest_is_trusted_dir(digest)) {
  347. add_trusted_dir_server(options->Nickname, NULL,
  348. (uint16_t)options->DirPort, digest,
  349. options->V1AuthoritativeDir);
  350. }
  351. /* success */
  352. return 0;
  353. }
  354. /* Keep track of whether we should upload our server descriptor,
  355. * and what type of server we are.
  356. */
  357. /** Whether we can reach our ORPort from the outside. */
  358. static int can_reach_or_port = 0;
  359. /** Whether we can reach our DirPort from the outside. */
  360. static int can_reach_dir_port = 0;
  361. /** Return 1 if or port is known reachable; else return 0. */
  362. int
  363. check_whether_orport_reachable(void)
  364. {
  365. or_options_t *options = get_options();
  366. return clique_mode(options) ||
  367. options->AssumeReachable ||
  368. can_reach_or_port;
  369. }
  370. /** Return 1 if we don't have a dirport configured, or if it's reachable. */
  371. int
  372. check_whether_dirport_reachable(void)
  373. {
  374. or_options_t *options = get_options();
  375. return !options->DirPort ||
  376. options->AssumeReachable ||
  377. we_are_hibernating() ||
  378. can_reach_dir_port;
  379. }
  380. /** Look at a variety of factors, and return 0 if we don't want to
  381. * advertise the fact that we have a DirPort open. Else return the
  382. * DirPort we want to advertise. */
  383. static int
  384. decide_to_advertise_dirport(or_options_t *options, routerinfo_t *router)
  385. {
  386. if (!router->dir_port) /* short circuit the rest of the function */
  387. return 0;
  388. if (authdir_mode(options)) /* always publish */
  389. return router->dir_port;
  390. if (we_are_hibernating())
  391. return 0;
  392. if (!check_whether_dirport_reachable())
  393. return 0;
  394. if (router->bandwidthcapacity >= router->bandwidthrate) {
  395. /* check if we might potentially hibernate. */
  396. if (options->AccountingMax != 0)
  397. return 0;
  398. /* also check if we're advertising a small amount, and have
  399. a "boring" DirPort. */
  400. if (router->bandwidthrate < 50000 && router->dir_port > 1024)
  401. return 0;
  402. }
  403. /* Sounds like a great idea. Let's publish it. */
  404. return router->dir_port;
  405. }
  406. /** Some time has passed, or we just got new directory information.
  407. * See if we currently believe our ORPort or DirPort to be
  408. * unreachable. If so, launch a new test for it.
  409. *
  410. * For ORPort, we simply try making a circuit that ends at ourselves.
  411. * Success is noticed in onionskin_answer().
  412. *
  413. * For DirPort, we make a connection via Tor to our DirPort and ask
  414. * for our own server descriptor.
  415. * Success is noticed in connection_dir_client_reached_eof().
  416. */
  417. void
  418. consider_testing_reachability(void)
  419. {
  420. routerinfo_t *me = router_get_my_routerinfo();
  421. if (!me) {
  422. warn(LD_BUG,"Bug: router_get_my_routerinfo() did not find my routerinfo?");
  423. return;
  424. }
  425. if (!check_whether_orport_reachable()) {
  426. circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me, 0, 1, 1);
  427. }
  428. if (!check_whether_dirport_reachable()) {
  429. /* ask myself, via tor, for my server descriptor. */
  430. directory_initiate_command_router(me, DIR_PURPOSE_FETCH_SERVERDESC,
  431. 1, "authority", NULL, 0);
  432. }
  433. }
  434. /** Annotate that we found our ORPort reachable. */
  435. void
  436. router_orport_found_reachable(void)
  437. {
  438. if (!can_reach_or_port) {
  439. if (!clique_mode(get_options()))
  440. notice(LD_OR,"Self-testing indicates your ORPort is reachable from the outside. Excellent.%s",
  441. get_options()->NoPublish ? "" : " Publishing server descriptor.");
  442. can_reach_or_port = 1;
  443. mark_my_descriptor_dirty();
  444. consider_publishable_server(time(NULL), 1);
  445. }
  446. }
  447. /** Annotate that we found our DirPort reachable. */
  448. void
  449. router_dirport_found_reachable(void)
  450. {
  451. if (!can_reach_dir_port) {
  452. notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable from the outside. Excellent.");
  453. can_reach_dir_port = 1;
  454. }
  455. }
  456. /** Our router has just moved to a new IP. Reset stats. */
  457. void
  458. server_has_changed_ip(void)
  459. {
  460. stats_n_seconds_working = 0;
  461. can_reach_or_port = 0;
  462. can_reach_dir_port = 0;
  463. mark_my_descriptor_dirty();
  464. }
  465. /** Return true iff we believe ourselves to be an authoritative
  466. * directory server.
  467. */
  468. int
  469. authdir_mode(or_options_t *options)
  470. {
  471. return options->AuthoritativeDir != 0;
  472. }
  473. /** Return true iff we try to stay connected to all ORs at once.
  474. */
  475. int
  476. clique_mode(or_options_t *options)
  477. {
  478. return authdir_mode(options);
  479. }
  480. /** Return true iff we are trying to be a server.
  481. */
  482. int
  483. server_mode(or_options_t *options)
  484. {
  485. if (options->ClientOnly) return 0;
  486. return (options->ORPort != 0 || options->ORListenAddress);
  487. }
  488. /** Remember if we've advertised ourselves to the dirservers. */
  489. static int server_is_advertised=0;
  490. /** Return true iff we have published our descriptor lately.
  491. */
  492. int
  493. advertised_server_mode(void)
  494. {
  495. return server_is_advertised;
  496. }
  497. /**
  498. * Called with a boolean: set whether we have recently published our descriptor.
  499. */
  500. static void
  501. set_server_advertised(int s)
  502. {
  503. server_is_advertised = s;
  504. }
  505. /** Return true iff we are trying to be a socks proxy. */
  506. int
  507. proxy_mode(or_options_t *options)
  508. {
  509. return (options->SocksPort != 0 || options->SocksListenAddress);
  510. }
  511. /** Decide if we're a publishable server. We are a publishable server if:
  512. * - We don't have the ClientOnly option set
  513. * and
  514. * - We don't have the NoPublish option set
  515. * and
  516. * - We have ORPort set
  517. * and
  518. * - We believe we are reachable from the outside; or
  519. * - We have the AuthoritativeDirectory option set.
  520. */
  521. static int
  522. decide_if_publishable_server(time_t now)
  523. {
  524. or_options_t *options = get_options();
  525. if (options->ClientOnly)
  526. return 0;
  527. if (options->NoPublish)
  528. return 0;
  529. if (!server_mode(options))
  530. return 0;
  531. if (options->AuthoritativeDir)
  532. return 1;
  533. return check_whether_orport_reachable();
  534. }
  535. /** Initiate server descriptor upload as reasonable (if server is publishable,
  536. * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
  537. */
  538. void
  539. consider_publishable_server(time_t now, int force)
  540. {
  541. if (decide_if_publishable_server(now)) {
  542. set_server_advertised(1);
  543. if (router_rebuild_descriptor(0) == 0)
  544. router_upload_dir_desc_to_dirservers(force);
  545. } else {
  546. set_server_advertised(0);
  547. }
  548. }
  549. /*
  550. * Clique maintenance
  551. */
  552. /** OR only: if in clique mode, try to open connections to all of the
  553. * other ORs we know about. Otherwise, open connections to those we
  554. * think are in clique mode.o
  555. *
  556. * If <b>force</b> is zero, only open the connection if we don't already
  557. * have one.
  558. */
  559. void
  560. router_retry_connections(int force)
  561. {
  562. time_t now = time(NULL);
  563. routerlist_t *rl = router_get_routerlist();
  564. or_options_t *options = get_options();
  565. tor_assert(server_mode(options));
  566. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, router, {
  567. if (router_is_me(router))
  568. continue;
  569. if (!clique_mode(options) && !router_is_clique_mode(router))
  570. continue;
  571. if (force ||
  572. !connection_get_by_identity_digest(router->cache_info.identity_digest,
  573. CONN_TYPE_OR)) {
  574. debug(LD_OR,"%sconnecting to %s at %s:%u.",
  575. clique_mode(options) ? "(forced) " : "",
  576. router->nickname, router->address, router->or_port);
  577. /* Remember when we started trying to determine reachability */
  578. if (!router->testing_since)
  579. router->testing_since = now;
  580. connection_or_connect(router->addr, router->or_port,
  581. router->cache_info.identity_digest);
  582. }
  583. });
  584. }
  585. /** Return true iff this OR should try to keep connections open to all
  586. * other ORs. */
  587. int
  588. router_is_clique_mode(routerinfo_t *router)
  589. {
  590. if (router_digest_is_trusted_dir(router->cache_info.identity_digest))
  591. return 1;
  592. return 0;
  593. }
  594. /*
  595. * OR descriptor generation.
  596. */
  597. /** My routerinfo. */
  598. static routerinfo_t *desc_routerinfo = NULL;
  599. /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
  600. * now. */
  601. static time_t desc_clean_since = 0;
  602. /** Boolean: do we need to regenerate the above? */
  603. static int desc_needs_upload = 0;
  604. /** OR only: If <b>force</b> is true, or we haven't uploaded this
  605. * descriptor successfully yet, try to upload our signed descriptor to
  606. * all the directory servers we know about.
  607. */
  608. void
  609. router_upload_dir_desc_to_dirservers(int force)
  610. {
  611. const char *s;
  612. s = router_get_my_descriptor();
  613. if (!s) {
  614. warn(LD_GENERAL, "No descriptor; skipping upload");
  615. return;
  616. }
  617. if (!force && !desc_needs_upload)
  618. return;
  619. desc_needs_upload = 0;
  620. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR, s, strlen(s));
  621. }
  622. /** OR only: Check whether my exit policy says to allow connection to
  623. * conn. Return 0 if we accept; non-0 if we reject.
  624. */
  625. int
  626. router_compare_to_my_exit_policy(connection_t *conn)
  627. {
  628. tor_assert(desc_routerinfo);
  629. /* make sure it's resolved to something. this way we can't get a
  630. 'maybe' below. */
  631. if (!conn->addr)
  632. return -1;
  633. return router_compare_addr_to_addr_policy(conn->addr, conn->port,
  634. desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
  635. }
  636. /** Return true iff I'm a server and <b>digest</b> is equal to
  637. * my identity digest. */
  638. int
  639. router_digest_is_me(const char *digest)
  640. {
  641. routerinfo_t *me = router_get_my_routerinfo();
  642. if (!me || memcmp(me->cache_info.identity_digest, digest, DIGEST_LEN))
  643. return 0;
  644. return 1;
  645. }
  646. /** A wrapper around router_digest_is_me(). */
  647. int
  648. router_is_me(routerinfo_t *router)
  649. {
  650. return router_digest_is_me(router->cache_info.identity_digest);
  651. }
  652. /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
  653. int
  654. router_fingerprint_is_me(const char *fp)
  655. {
  656. char digest[DIGEST_LEN];
  657. if (strlen(fp) == HEX_DIGEST_LEN &&
  658. base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
  659. return router_digest_is_me(digest);
  660. return 0;
  661. }
  662. /** Return a routerinfo for this OR, rebuilding a fresh one if
  663. * necessary. Return NULL on error, or if called on an OP. */
  664. routerinfo_t *
  665. router_get_my_routerinfo(void)
  666. {
  667. if (!server_mode(get_options()))
  668. return NULL;
  669. if (!desc_routerinfo) {
  670. if (router_rebuild_descriptor(1))
  671. return NULL;
  672. }
  673. return desc_routerinfo;
  674. }
  675. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  676. * one if necessary. Return NULL on error.
  677. */
  678. const char *
  679. router_get_my_descriptor(void)
  680. {
  681. if (!desc_routerinfo) {
  682. if (router_rebuild_descriptor(1))
  683. return NULL;
  684. }
  685. debug(LD_GENERAL,"my desc is '%s'",
  686. desc_routerinfo->cache_info.signed_descriptor);
  687. return desc_routerinfo->cache_info.signed_descriptor;
  688. }
  689. /*DOCDOC*/
  690. static smartlist_t *warned_nonexistent_family = NULL;
  691. /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild
  692. * a fresh routerinfo and signed server descriptor for this OR.
  693. * Return 0 on success, -1 on error.
  694. */
  695. int
  696. router_rebuild_descriptor(int force)
  697. {
  698. routerinfo_t *ri;
  699. uint32_t addr;
  700. char platform[256];
  701. int hibernating = we_are_hibernating();
  702. or_options_t *options = get_options();
  703. if (desc_clean_since && !force)
  704. return 0;
  705. if (resolve_my_address(options, &addr, NULL) < 0) {
  706. warn(LD_CONFIG,"options->Address didn't resolve into an IP.");
  707. return -1;
  708. }
  709. ri = tor_malloc_zero(sizeof(routerinfo_t));
  710. ri->address = tor_dup_addr(addr);
  711. ri->nickname = tor_strdup(options->Nickname);
  712. ri->addr = addr;
  713. ri->or_port = options->ORPort;
  714. ri->dir_port = options->DirPort;
  715. ri->cache_info.published_on = time(NULL);
  716. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from main thread */
  717. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  718. if (crypto_pk_get_digest(ri->identity_pkey,
  719. ri->cache_info.identity_digest)<0) {
  720. routerinfo_free(ri);
  721. return -1;
  722. }
  723. get_platform_str(platform, sizeof(platform));
  724. ri->platform = tor_strdup(platform);
  725. ri->bandwidthrate = (int)options->BandwidthRate;
  726. ri->bandwidthburst = (int)options->BandwidthBurst;
  727. ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
  728. if (options->BandwidthRate > options->MaxAdvertisedBandwidth)
  729. ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
  730. config_parse_addr_policy(get_options()->ExitPolicy, &ri->exit_policy, -1);
  731. options_append_default_exit_policy(&ri->exit_policy);
  732. if (desc_routerinfo) { /* inherit values */
  733. ri->is_verified = desc_routerinfo->is_verified;
  734. ri->is_running = desc_routerinfo->is_running;
  735. ri->is_named = desc_routerinfo->is_named;
  736. }
  737. if (authdir_mode(options))
  738. ri->is_verified = ri->is_named = 1; /* believe in yourself */
  739. if (options->MyFamily) {
  740. smartlist_t *family;
  741. if (!warned_nonexistent_family)
  742. warned_nonexistent_family = smartlist_create();
  743. family = smartlist_create();
  744. ri->declared_family = smartlist_create();
  745. smartlist_split_string(family, options->MyFamily, ",",
  746. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  747. SMARTLIST_FOREACH(family, char *, name,
  748. {
  749. routerinfo_t *member;
  750. if (!strcasecmp(name, options->Nickname))
  751. member = ri;
  752. else
  753. member = router_get_by_nickname(name, 1);
  754. if (!member) {
  755. if (!smartlist_string_isin(warned_nonexistent_family, name)) {
  756. warn(LD_CONFIG, "I have no descriptor for the router named \"%s\" "
  757. "in my declared family; I'll use the nickname as is, but "
  758. "this may confuse clients.", name);
  759. smartlist_add(warned_nonexistent_family, tor_strdup(name));
  760. }
  761. smartlist_add(ri->declared_family, name);
  762. name = NULL;
  763. } else {
  764. char *fp = tor_malloc(HEX_DIGEST_LEN+2);
  765. fp[0] = '$';
  766. base16_encode(fp+1,HEX_DIGEST_LEN+1,
  767. member->cache_info.identity_digest, DIGEST_LEN);
  768. smartlist_add(ri->declared_family, fp);
  769. if (smartlist_string_isin(warned_nonexistent_family, name))
  770. smartlist_string_remove(warned_nonexistent_family, name);
  771. }
  772. tor_free(name);
  773. });
  774. smartlist_free(family);
  775. }
  776. ri->cache_info.signed_descriptor = tor_malloc(8192);
  777. if (router_dump_router_to_string(ri->cache_info.signed_descriptor, 8192,
  778. ri, get_identity_key())<0) {
  779. warn(LD_BUG, "Couldn't allocate string for descriptor.");
  780. return -1;
  781. }
  782. ri->cache_info.signed_descriptor_len =
  783. strlen(ri->cache_info.signed_descriptor);
  784. crypto_digest(ri->cache_info.signed_descriptor_digest,
  785. ri->cache_info.signed_descriptor,
  786. ri->cache_info.signed_descriptor_len);
  787. if (desc_routerinfo)
  788. routerinfo_free(desc_routerinfo);
  789. desc_routerinfo = ri;
  790. desc_clean_since = time(NULL);
  791. desc_needs_upload = 1;
  792. return 0;
  793. }
  794. /** Mark descriptor out of date if it's older than <b>when</b> */
  795. void
  796. mark_my_descriptor_dirty_if_older_than(time_t when)
  797. {
  798. if (desc_clean_since < when)
  799. mark_my_descriptor_dirty();
  800. }
  801. /** Call when the current descriptor is out of date. */
  802. void
  803. mark_my_descriptor_dirty(void)
  804. {
  805. desc_clean_since = 0;
  806. }
  807. #define MAX_BANDWIDTH_CHANGE_FREQ 20*60
  808. /** Check whether bandwidth has changed a lot since the last time we announced
  809. * bandwidth. If so, mark our descriptor dirty. */
  810. void
  811. check_descriptor_bandwidth_changed(time_t now)
  812. {
  813. static time_t last_changed = 0;
  814. uint64_t prev, cur;
  815. if (!desc_routerinfo)
  816. return;
  817. prev = desc_routerinfo->bandwidthcapacity;
  818. cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
  819. if ((prev != cur && (!prev || !cur)) ||
  820. cur > prev*2 ||
  821. cur < prev/2) {
  822. if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
  823. info(LD_GENERAL,"Measured bandwidth has changed; rebuilding descriptor.");
  824. mark_my_descriptor_dirty();
  825. last_changed = now;
  826. }
  827. }
  828. }
  829. /** Check whether our own address as defined by the Address configuration
  830. * has changed. This is for routers that get their address from a service
  831. * like dyndns. If our address has changed, mark our descriptor dirty. */
  832. void
  833. check_descriptor_ipaddress_changed(time_t now)
  834. {
  835. uint32_t prev, cur;
  836. or_options_t *options = get_options();
  837. if (!desc_routerinfo)
  838. return;
  839. prev = desc_routerinfo->addr;
  840. if (resolve_my_address(options, &cur, NULL) < 0) {
  841. warn(LD_CONFIG,"options->Address didn't resolve into an IP.");
  842. return;
  843. }
  844. if (prev != cur) {
  845. char addrbuf_prev[INET_NTOA_BUF_LEN];
  846. char addrbuf_cur[INET_NTOA_BUF_LEN];
  847. struct in_addr in_prev;
  848. struct in_addr in_cur;
  849. in_prev.s_addr = htonl(prev);
  850. tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
  851. in_cur.s_addr = htonl(cur);
  852. tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
  853. info(LD_GENERAL,"Our IP Address has changed from %s to %s; rebuilding descriptor.", addrbuf_prev, addrbuf_cur);
  854. mark_my_descriptor_dirty();
  855. }
  856. }
  857. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  858. * string describing the version of Tor and the operating system we're
  859. * currently running on.
  860. */
  861. void
  862. get_platform_str(char *platform, size_t len)
  863. {
  864. tor_snprintf(platform, len, "Tor %s on %s",
  865. VERSION, get_uname());
  866. return;
  867. }
  868. /* XXX need to audit this thing and count fenceposts. maybe
  869. * refactor so we don't have to keep asking if we're
  870. * near the end of maxlen?
  871. */
  872. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  873. /** OR only: Given a routerinfo for this router, and an identity key to sign
  874. * with, encode the routerinfo as a signed server descriptor and write the
  875. * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
  876. * failure, and the number of bytes used on success.
  877. */
  878. int
  879. router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
  880. crypto_pk_env_t *ident_key)
  881. {
  882. char *onion_pkey; /* Onion key, PEM-encoded. */
  883. char *identity_pkey; /* Identity key, PEM-encoded. */
  884. char digest[DIGEST_LEN];
  885. char published[ISO_TIME_LEN+1];
  886. char fingerprint[FINGERPRINT_LEN+1];
  887. struct in_addr in;
  888. char addrbuf[INET_NTOA_BUF_LEN];
  889. size_t onion_pkeylen, identity_pkeylen;
  890. size_t written;
  891. int result=0;
  892. addr_policy_t *tmpe;
  893. char *bandwidth_usage;
  894. char *family_line;
  895. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  896. char *s_tmp, *s_dup;
  897. const char *cp;
  898. routerinfo_t *ri_tmp;
  899. #endif
  900. or_options_t *options = get_options();
  901. /* Make sure the identity key matches the one in the routerinfo. */
  902. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  903. warn(LD_BUG,"Tried to sign a router with a private key that didn't match router's public key!");
  904. return -1;
  905. }
  906. /* record our fingerprint, so we can include it in the descriptor */
  907. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
  908. err(LD_BUG,"Error computing fingerprint");
  909. return -1;
  910. }
  911. /* PEM-encode the onion key */
  912. if (crypto_pk_write_public_key_to_string(router->onion_pkey,
  913. &onion_pkey,&onion_pkeylen)<0) {
  914. warn(LD_BUG,"write onion_pkey to string failed!");
  915. return -1;
  916. }
  917. /* PEM-encode the identity key key */
  918. if (crypto_pk_write_public_key_to_string(router->identity_pkey,
  919. &identity_pkey,&identity_pkeylen)<0) {
  920. warn(LD_BUG,"write identity_pkey to string failed!");
  921. tor_free(onion_pkey);
  922. return -1;
  923. }
  924. /* Encode the publication time. */
  925. format_iso_time(published, router->cache_info.published_on);
  926. /* How busy have we been? */
  927. bandwidth_usage = rep_hist_get_bandwidth_lines();
  928. if (router->declared_family && smartlist_len(router->declared_family)) {
  929. size_t n;
  930. char *s = smartlist_join_strings(router->declared_family, " ", 0, &n);
  931. n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
  932. family_line = tor_malloc(n);
  933. tor_snprintf(family_line, n, "family %s\n", s);
  934. tor_free(s);
  935. } else {
  936. family_line = tor_strdup("");
  937. }
  938. /* Generate the easy portion of the router descriptor. */
  939. result = tor_snprintf(s, maxlen,
  940. "router %s %s %d 0 %d\n"
  941. "platform %s\n"
  942. "published %s\n"
  943. "opt fingerprint %s\n"
  944. "uptime %ld\n"
  945. "bandwidth %d %d %d\n"
  946. "onion-key\n%s"
  947. "signing-key\n%s%s%s%s",
  948. router->nickname,
  949. router->address,
  950. router->or_port,
  951. decide_to_advertise_dirport(options, router),
  952. router->platform,
  953. published,
  954. fingerprint,
  955. stats_n_seconds_working,
  956. (int) router->bandwidthrate,
  957. (int) router->bandwidthburst,
  958. (int) router->bandwidthcapacity,
  959. onion_pkey, identity_pkey,
  960. family_line, bandwidth_usage,
  961. we_are_hibernating() ? "opt hibernating 1\n" : "");
  962. tor_free(family_line);
  963. tor_free(onion_pkey);
  964. tor_free(identity_pkey);
  965. tor_free(bandwidth_usage);
  966. if (result < 0)
  967. return -1;
  968. /* From now on, we use 'written' to remember the current length of 's'. */
  969. written = result;
  970. if (options->ContactInfo && strlen(options->ContactInfo)) {
  971. result = tor_snprintf(s+written,maxlen-written, "contact %s\n",
  972. options->ContactInfo);
  973. if (result<0)
  974. return -1;
  975. written += result;
  976. }
  977. /* Write the exit policy to the end of 's'. */
  978. for (tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
  979. /* Write: "accept 1.2.3.4" */
  980. in.s_addr = htonl(tmpe->addr);
  981. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  982. result = tor_snprintf(s+written, maxlen-written, "%s %s",
  983. tmpe->policy_type == ADDR_POLICY_ACCEPT ? "accept" : "reject",
  984. tmpe->msk == 0 ? "*" : addrbuf);
  985. if (result < 0)
  986. return -1;
  987. written += result;
  988. if (tmpe->msk != 0xFFFFFFFFu && tmpe->msk != 0) {
  989. /* Write "/255.255.0.0" */
  990. in.s_addr = htonl(tmpe->msk);
  991. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  992. result = tor_snprintf(s+written, maxlen-written, "/%s", addrbuf);
  993. if (result<0)
  994. return -1;
  995. written += result;
  996. }
  997. if (tmpe->prt_min <= 1 && tmpe->prt_max == 65535) {
  998. /* There is no port set; write ":*" */
  999. if (written+4 > maxlen)
  1000. return -1;
  1001. strlcat(s+written, ":*\n", maxlen-written);
  1002. written += 3;
  1003. } else if (tmpe->prt_min == tmpe->prt_max) {
  1004. /* There is only one port; write ":80". */
  1005. result = tor_snprintf(s+written, maxlen-written, ":%d\n", tmpe->prt_min);
  1006. if (result<0)
  1007. return -1;
  1008. written += result;
  1009. } else {
  1010. /* There is a range of ports; write ":79-80". */
  1011. result = tor_snprintf(s+written, maxlen-written, ":%d-%d\n", tmpe->prt_min,
  1012. tmpe->prt_max);
  1013. if (result<0)
  1014. return -1;
  1015. written += result;
  1016. }
  1017. if (tmpe->msk == 0 && tmpe->prt_min <= 1 && tmpe->prt_max == 65535)
  1018. /* This was a catch-all rule, so future rules are irrelevant. */
  1019. break;
  1020. } /* end for */
  1021. if (written+256 > maxlen) /* Not enough room for signature. */
  1022. return -1;
  1023. /* Sign the directory */
  1024. strlcat(s+written, "router-signature\n", maxlen-written);
  1025. written += strlen(s+written);
  1026. s[written] = '\0';
  1027. if (router_get_router_hash(s, digest) < 0)
  1028. return -1;
  1029. if (router_append_dirobj_signature(s+written,maxlen-written,
  1030. digest,ident_key)<0) {
  1031. warn(LD_BUG, "Couldn't sign router descriptor");
  1032. return -1;
  1033. }
  1034. written += strlen(s+written);
  1035. if (written+2 > maxlen)
  1036. return -1;
  1037. /* include a last '\n' */
  1038. s[written] = '\n';
  1039. s[written+1] = 0;
  1040. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1041. cp = s_tmp = s_dup = tor_strdup(s);
  1042. ri_tmp = router_parse_entry_from_string(cp, NULL);
  1043. if (!ri_tmp) {
  1044. err(LD_BUG,"We just generated a router descriptor we can't parse: <<%s>>", s);
  1045. return -1;
  1046. }
  1047. tor_free(s_dup);
  1048. routerinfo_free(ri_tmp);
  1049. #endif
  1050. return written+1;
  1051. }
  1052. /** Return true iff <b>s</b> is a legally valid server nickname. */
  1053. int
  1054. is_legal_nickname(const char *s)
  1055. {
  1056. size_t len;
  1057. tor_assert(s);
  1058. len = strlen(s);
  1059. return len > 0 && len <= MAX_NICKNAME_LEN &&
  1060. strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
  1061. }
  1062. /** Return true iff <b>s</b> is a legally valid server nickname or
  1063. * hex-encoded identity-key digest. */
  1064. int
  1065. is_legal_nickname_or_hexdigest(const char *s)
  1066. {
  1067. size_t len;
  1068. tor_assert(s);
  1069. if (*s!='$')
  1070. return is_legal_nickname(s);
  1071. len = strlen(s);
  1072. return len == HEX_DIGEST_LEN+1 && strspn(s+1,HEX_CHARACTERS)==len-1;
  1073. }
  1074. /** Forget that we have issued any router-related warnings, so that we'll
  1075. * warn again if we see the same errors. */
  1076. void
  1077. router_reset_warnings(void)
  1078. {
  1079. if (warned_nonexistent_family) {
  1080. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  1081. smartlist_clear(warned_nonexistent_family);
  1082. }
  1083. }
  1084. /** Release all static resources held in router.c */
  1085. void
  1086. router_free_all(void)
  1087. {
  1088. if (onionkey)
  1089. crypto_free_pk_env(onionkey);
  1090. if (lastonionkey)
  1091. crypto_free_pk_env(lastonionkey);
  1092. if (identitykey)
  1093. crypto_free_pk_env(identitykey);
  1094. if (key_lock)
  1095. tor_mutex_free(key_lock);
  1096. if (desc_routerinfo)
  1097. routerinfo_free(desc_routerinfo);
  1098. if (warned_nonexistent_family) {
  1099. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  1100. smartlist_free(warned_nonexistent_family);
  1101. }
  1102. }