router.c 39 KB

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