router.c 49 KB

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