router.c 42 KB

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