router.c 41 KB

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