router.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266
  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.
  214. */
  215. int
  216. init_keys(void)
  217. {
  218. char keydir[512];
  219. char keydir2[512];
  220. char fingerprint[FINGERPRINT_LEN+1];
  221. /*nickname<space>fp\n\0 */
  222. char fingerprint_line[MAX_NICKNAME_LEN+FINGERPRINT_LEN+3];
  223. char *cp;
  224. const char *mydesc, *datadir;
  225. crypto_pk_env_t *prkey;
  226. char digest[20];
  227. or_options_t *options = get_options();
  228. if (!key_lock)
  229. key_lock = tor_mutex_new();
  230. /* OP's don't need persistent keys; just make up an identity and
  231. * initialize the TLS context. */
  232. if (!server_mode(options)) {
  233. if (!(prkey = crypto_new_pk_env()))
  234. return -1;
  235. if (crypto_pk_generate_key(prkey))
  236. return -1;
  237. set_identity_key(prkey);
  238. /* Create a TLS context; default the client nickname to "client". */
  239. if (tor_tls_context_new(get_identity_key(), 1,
  240. options->Nickname ? options->Nickname : "client",
  241. MAX_SSL_KEY_LIFETIME) < 0) {
  242. log_err(LD_GENERAL,"Error creating TLS context for OP.");
  243. return -1;
  244. }
  245. return 0;
  246. }
  247. /* Make sure DataDirectory exists, and is private. */
  248. datadir = options->DataDirectory;
  249. if (check_private_dir(datadir, CPD_CREATE)) {
  250. return -1;
  251. }
  252. /* Check the key directory. */
  253. tor_snprintf(keydir,sizeof(keydir),"%s/keys", datadir);
  254. if (check_private_dir(keydir, CPD_CREATE)) {
  255. return -1;
  256. }
  257. cp = keydir + strlen(keydir); /* End of string. */
  258. /* 1. Read identity key. Make it if none is found. */
  259. tor_snprintf(keydir,sizeof(keydir),"%s/keys/identity.key",datadir);
  260. tor_snprintf(keydir2,sizeof(keydir2),"%s/keys/secret_id_key",datadir);
  261. log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir2);
  262. prkey = init_key_from_file_name_changed(keydir,keydir2);
  263. if (!prkey) return -1;
  264. set_identity_key(prkey);
  265. /* 2. Read onion key. Make it if none is found. */
  266. tor_snprintf(keydir,sizeof(keydir),"%s/keys/onion.key",datadir);
  267. tor_snprintf(keydir2,sizeof(keydir2),"%s/keys/secret_onion_key",datadir);
  268. log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir2);
  269. prkey = init_key_from_file_name_changed(keydir,keydir2);
  270. if (!prkey) return -1;
  271. set_onion_key(prkey);
  272. tor_snprintf(keydir,sizeof(keydir),"%s/keys/secret_onion_key.old",datadir);
  273. if (file_status(keydir) == FN_FILE) {
  274. prkey = init_key_from_file(keydir);
  275. if (prkey)
  276. lastonionkey = prkey;
  277. }
  278. /* 3. Initialize link key and TLS context. */
  279. if (tor_tls_context_new(get_identity_key(), 1, options->Nickname,
  280. MAX_SSL_KEY_LIFETIME) < 0) {
  281. log_err(LD_GENERAL,"Error initializing TLS context");
  282. return -1;
  283. }
  284. /* 4. Build our router descriptor. */
  285. /* Must be called after keys are initialized. */
  286. mydesc = router_get_my_descriptor();
  287. if (!mydesc) {
  288. log_err(LD_GENERAL,"Error initializing descriptor.");
  289. return -1;
  290. }
  291. if (authdir_mode(options)) {
  292. const char *m;
  293. /* We need to add our own fingerprint so it gets recognized. */
  294. if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
  295. log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
  296. return -1;
  297. }
  298. if (dirserv_add_descriptor(mydesc, &m) < 0) {
  299. log_err(LD_GENERAL,"Unable to add own descriptor to directory: %s",
  300. m?m:"<unknown error>");
  301. return -1;
  302. }
  303. }
  304. #if 0
  305. tor_snprintf(keydir,sizeof(keydir),"%s/router.desc", datadir);
  306. log_info(LD_GENERAL,"Dumping descriptor to \"%s\"...",keydir);
  307. if (write_str_to_file(keydir, mydesc,0)) {
  308. return -1;
  309. }
  310. #endif
  311. /* 5. Dump fingerprint to 'fingerprint' */
  312. tor_snprintf(keydir,sizeof(keydir),"%s/fingerprint", datadir);
  313. log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
  314. if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 1)<0) {
  315. log_err(LD_GENERAL,"Error computing fingerprint");
  316. return -1;
  317. }
  318. tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
  319. if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
  320. "%s %s\n",options->Nickname, fingerprint) < 0) {
  321. log_err(LD_GENERAL,"Error writing fingerprint line");
  322. return -1;
  323. }
  324. if (write_str_to_file(keydir, fingerprint_line, 0)) {
  325. log_err(LD_FS, "Error writing fingerprint line to file");
  326. return -1;
  327. }
  328. log(LOG_NOTICE, LD_GENERAL,
  329. "Your Tor server's identity key fingerprint is '%s %s'",
  330. options->Nickname, fingerprint);
  331. if (!authdir_mode(options))
  332. return 0;
  333. /* 6. [authdirserver only] load approved-routers file */
  334. tor_snprintf(keydir,sizeof(keydir),"%s/approved-routers", datadir);
  335. log_info(LD_DIRSERV,"Loading approved fingerprints from \"%s\"...",keydir);
  336. if (dirserv_parse_fingerprint_file(keydir) < 0) {
  337. log_err(LD_GENERAL,"Error loading fingerprints");
  338. return -1;
  339. }
  340. /* 6b. [authdirserver only] add own key to approved directories. */
  341. crypto_pk_get_digest(get_identity_key(), digest);
  342. if (!router_digest_is_trusted_dir(digest)) {
  343. add_trusted_dir_server(options->Nickname, NULL,
  344. (uint16_t)options->DirPort, digest,
  345. options->V1AuthoritativeDir);
  346. }
  347. /* success */
  348. return 0;
  349. }
  350. /* Keep track of whether we should upload our server descriptor,
  351. * and what type of server we are.
  352. */
  353. /** Whether we can reach our ORPort from the outside. */
  354. static int can_reach_or_port = 0;
  355. /** Whether we can reach our DirPort from the outside. */
  356. static int can_reach_dir_port = 0;
  357. /** Return 1 if or port is known reachable; else return 0. */
  358. int
  359. check_whether_orport_reachable(void)
  360. {
  361. or_options_t *options = get_options();
  362. return clique_mode(options) ||
  363. options->AssumeReachable ||
  364. can_reach_or_port;
  365. }
  366. /** Return 1 if we don't have a dirport configured, or if it's reachable. */
  367. int
  368. check_whether_dirport_reachable(void)
  369. {
  370. or_options_t *options = get_options();
  371. return !options->DirPort ||
  372. options->AssumeReachable ||
  373. we_are_hibernating() ||
  374. can_reach_dir_port;
  375. }
  376. /** Look at a variety of factors, and return 0 if we don't want to
  377. * advertise the fact that we have a DirPort open. Else return the
  378. * DirPort we want to advertise. */
  379. static int
  380. decide_to_advertise_dirport(or_options_t *options, routerinfo_t *router)
  381. {
  382. if (!router->dir_port) /* short circuit the rest of the function */
  383. return 0;
  384. if (authdir_mode(options)) /* always publish */
  385. return router->dir_port;
  386. if (we_are_hibernating())
  387. return 0;
  388. if (!check_whether_dirport_reachable())
  389. return 0;
  390. if (router->bandwidthcapacity >= router->bandwidthrate) {
  391. /* check if we might potentially hibernate. */
  392. if (options->AccountingMax != 0)
  393. return 0;
  394. /* also check if we're advertising a small amount, and have
  395. a "boring" DirPort. */
  396. if (router->bandwidthrate < 50000 && router->dir_port > 1024)
  397. return 0;
  398. }
  399. /* Sounds like a great idea. Let's publish it. */
  400. return router->dir_port;
  401. }
  402. /** Some time has passed, or we just got new directory information.
  403. * See if we currently believe our ORPort or DirPort to be
  404. * unreachable. If so, launch a new test for it.
  405. *
  406. * For ORPort, we simply try making a circuit that ends at ourselves.
  407. * Success is noticed in onionskin_answer().
  408. *
  409. * For DirPort, we make a connection via Tor to our DirPort and ask
  410. * for our own server descriptor.
  411. * Success is noticed in connection_dir_client_reached_eof().
  412. */
  413. void
  414. consider_testing_reachability(void)
  415. {
  416. routerinfo_t *me = router_get_my_routerinfo();
  417. if (!me) {
  418. log_warn(LD_BUG,
  419. "Bug: router_get_my_routerinfo() did not find my routerinfo?");
  420. return;
  421. }
  422. if (!check_whether_orport_reachable()) {
  423. circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me, 0, 1, 1);
  424. }
  425. if (!check_whether_dirport_reachable()) {
  426. /* ask myself, via tor, for my server descriptor. */
  427. directory_initiate_command_router(me, DIR_PURPOSE_FETCH_SERVERDESC,
  428. 1, "authority", NULL, 0);
  429. }
  430. }
  431. /** Annotate that we found our ORPort reachable. */
  432. void
  433. router_orport_found_reachable(void)
  434. {
  435. if (!can_reach_or_port) {
  436. if (!clique_mode(get_options()))
  437. log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
  438. "the outside. Excellent.%s",
  439. get_options()->PublishServerDescriptor ?
  440. " Publishing server descriptor." : "");
  441. can_reach_or_port = 1;
  442. mark_my_descriptor_dirty();
  443. consider_publishable_server(time(NULL), 1);
  444. }
  445. }
  446. /** Annotate that we found our DirPort reachable. */
  447. void
  448. router_dirport_found_reachable(void)
  449. {
  450. if (!can_reach_dir_port) {
  451. log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
  452. "from the outside. Excellent.");
  453. can_reach_dir_port = 1;
  454. }
  455. }
  456. /** Our router has just moved to a new IP. Reset stats. */
  457. void
  458. server_has_changed_ip(void)
  459. {
  460. stats_n_seconds_working = 0;
  461. can_reach_or_port = 0;
  462. can_reach_dir_port = 0;
  463. mark_my_descriptor_dirty();
  464. }
  465. /** Return true iff we believe ourselves to be an authoritative
  466. * directory server.
  467. */
  468. int
  469. authdir_mode(or_options_t *options)
  470. {
  471. return options->AuthoritativeDir != 0;
  472. }
  473. /** Return true iff we try to stay connected to all ORs at once.
  474. */
  475. int
  476. clique_mode(or_options_t *options)
  477. {
  478. return authdir_mode(options);
  479. }
  480. /** Return true iff we are trying to be a server.
  481. */
  482. int
  483. server_mode(or_options_t *options)
  484. {
  485. if (options->ClientOnly) return 0;
  486. return (options->ORPort != 0 || options->ORListenAddress);
  487. }
  488. /** Remember if we've advertised ourselves to the dirservers. */
  489. static int server_is_advertised=0;
  490. /** Return true iff we have published our descriptor lately.
  491. */
  492. int
  493. advertised_server_mode(void)
  494. {
  495. return server_is_advertised;
  496. }
  497. /**
  498. * Called with a boolean: set whether we have recently published our
  499. * descriptor.
  500. */
  501. static void
  502. set_server_advertised(int s)
  503. {
  504. server_is_advertised = s;
  505. }
  506. /** Return true iff we are trying to be a socks proxy. */
  507. int
  508. proxy_mode(or_options_t *options)
  509. {
  510. return (options->SocksPort != 0 || options->SocksListenAddress);
  511. }
  512. /** Decide if we're a publishable server. We are a publishable server if:
  513. * - We don't have the ClientOnly option set
  514. * and
  515. * - We have the PublishServerDescriptor option set
  516. * and
  517. * - We have ORPort set
  518. * and
  519. * - We believe we are reachable from the outside; or
  520. * - We have the AuthoritativeDirectory option set.
  521. */
  522. static int
  523. decide_if_publishable_server(time_t now)
  524. {
  525. or_options_t *options = get_options();
  526. if (options->ClientOnly)
  527. return 0;
  528. if (!options->PublishServerDescriptor)
  529. return 0;
  530. if (!server_mode(options))
  531. return 0;
  532. if (options->AuthoritativeDir)
  533. return 1;
  534. return check_whether_orport_reachable();
  535. }
  536. /** Initiate server descriptor upload as reasonable (if server is publishable,
  537. * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
  538. *
  539. * We need to rebuild the descriptor if it's dirty even if we're not
  540. * uploading, because our reachability testing *uses* our descriptor to
  541. * determine what IP address and ports to test.
  542. */
  543. void
  544. consider_publishable_server(time_t now, int force)
  545. {
  546. int rebuilt;
  547. if (!server_mode(get_options()))
  548. return;
  549. rebuilt = router_rebuild_descriptor(0);
  550. if (decide_if_publishable_server(now)) {
  551. set_server_advertised(1);
  552. if (rebuilt == 0)
  553. router_upload_dir_desc_to_dirservers(force);
  554. } else {
  555. set_server_advertised(0);
  556. }
  557. }
  558. /*
  559. * Clique maintenance
  560. */
  561. /** OR only: if in clique mode, try to open connections to all of the
  562. * other ORs we know about. Otherwise, open connections to those we
  563. * think are in clique mode.
  564. *
  565. * If <b>testing_reachability</b> is 0, try to open the connections
  566. * but only if we don't already have one. If it's 1, then we're an
  567. * auth dir server, and we should try to connect regardless of
  568. * whether we already have a connection open -- but if <b>try_all</b>
  569. * is 0, we want to load balance such that we only try a few connections
  570. * per call.
  571. *
  572. * The load balancing is such that if we get called once every ten
  573. * seconds, we will cycle through all the tests in 1280 seconds (a
  574. * bit over 20 minutes).
  575. */
  576. void
  577. router_retry_connections(int testing_reachability, int try_all)
  578. {
  579. time_t now = time(NULL);
  580. routerlist_t *rl = router_get_routerlist();
  581. or_options_t *options = get_options();
  582. static char ctr = 0;
  583. tor_assert(server_mode(options));
  584. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, router, {
  585. const char *id_digest = router->cache_info.identity_digest;
  586. if (router_is_me(router))
  587. continue;
  588. if (!clique_mode(options) && !router_is_clique_mode(router))
  589. continue;
  590. if ((testing_reachability &&
  591. (try_all || (((uint8_t)id_digest[0]) % 128) == ctr)) ||
  592. (!testing_reachability &&
  593. !connection_or_get_by_identity_digest(id_digest))) {
  594. log_debug(LD_OR,"%sconnecting to %s at %s:%u.",
  595. clique_mode(options) ? "(forced) " : "",
  596. router->nickname, router->address, router->or_port);
  597. /* Remember when we started trying to determine reachability */
  598. if (!router->testing_since)
  599. router->testing_since = now;
  600. connection_or_connect(router->addr, router->or_port,
  601. id_digest);
  602. }
  603. });
  604. if (testing_reachability && !try_all) /* increment ctr */
  605. ctr = (ctr + 1) % 128;
  606. }
  607. /** Return true iff this OR should try to keep connections open to all
  608. * other ORs. */
  609. int
  610. router_is_clique_mode(routerinfo_t *router)
  611. {
  612. if (router_digest_is_trusted_dir(router->cache_info.identity_digest))
  613. return 1;
  614. return 0;
  615. }
  616. /*
  617. * OR descriptor generation.
  618. */
  619. /** My routerinfo. */
  620. static routerinfo_t *desc_routerinfo = NULL;
  621. /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
  622. * now. */
  623. static time_t desc_clean_since = 0;
  624. /** Boolean: do we need to regenerate the above? */
  625. static int desc_needs_upload = 0;
  626. /** OR only: If <b>force</b> is true, or we haven't uploaded this
  627. * descriptor successfully yet, try to upload our signed descriptor to
  628. * all the directory servers we know about.
  629. */
  630. void
  631. router_upload_dir_desc_to_dirservers(int force)
  632. {
  633. const char *s;
  634. s = router_get_my_descriptor();
  635. if (!s) {
  636. log_warn(LD_GENERAL, "No descriptor; skipping upload");
  637. return;
  638. }
  639. if (!get_options()->PublishServerDescriptor)
  640. return;
  641. if (!force && !desc_needs_upload)
  642. return;
  643. desc_needs_upload = 0;
  644. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR, s, strlen(s));
  645. }
  646. /** OR only: Check whether my exit policy says to allow connection to
  647. * conn. Return 0 if we accept; non-0 if we reject.
  648. */
  649. int
  650. router_compare_to_my_exit_policy(connection_t *conn)
  651. {
  652. tor_assert(desc_routerinfo);
  653. /* make sure it's resolved to something. this way we can't get a
  654. 'maybe' below. */
  655. if (!conn->addr)
  656. return -1;
  657. return compare_addr_to_addr_policy(conn->addr, conn->port,
  658. desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
  659. }
  660. /** Return true iff I'm a server and <b>digest</b> is equal to
  661. * my identity digest. */
  662. int
  663. router_digest_is_me(const char *digest)
  664. {
  665. routerinfo_t *me = router_get_my_routerinfo();
  666. if (!me || memcmp(me->cache_info.identity_digest, digest, DIGEST_LEN))
  667. return 0;
  668. return 1;
  669. }
  670. /** A wrapper around router_digest_is_me(). */
  671. int
  672. router_is_me(routerinfo_t *router)
  673. {
  674. return router_digest_is_me(router->cache_info.identity_digest);
  675. }
  676. /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
  677. int
  678. router_fingerprint_is_me(const char *fp)
  679. {
  680. char digest[DIGEST_LEN];
  681. if (strlen(fp) == HEX_DIGEST_LEN &&
  682. base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
  683. return router_digest_is_me(digest);
  684. return 0;
  685. }
  686. /** Return a routerinfo for this OR, rebuilding a fresh one if
  687. * necessary. Return NULL on error, or if called on an OP. */
  688. routerinfo_t *
  689. router_get_my_routerinfo(void)
  690. {
  691. if (!server_mode(get_options()))
  692. return NULL;
  693. if (!desc_routerinfo || !desc_clean_since)
  694. if (router_rebuild_descriptor(!desc_routerinfo))
  695. return NULL;
  696. return desc_routerinfo;
  697. }
  698. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  699. * one if necessary. Return NULL on error.
  700. */
  701. const char *
  702. router_get_my_descriptor(void)
  703. {
  704. const char *body;
  705. if (!router_get_my_routerinfo())
  706. return NULL;
  707. body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
  708. log_debug(LD_GENERAL,"my desc is '%s'", body);
  709. return body;
  710. }
  711. /*DOCDOC*/
  712. static smartlist_t *warned_nonexistent_family = NULL;
  713. /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild
  714. * a fresh routerinfo and signed server descriptor for this OR.
  715. * Return 0 on success, -1 on error.
  716. */
  717. int
  718. router_rebuild_descriptor(int force)
  719. {
  720. routerinfo_t *ri;
  721. uint32_t addr;
  722. char platform[256];
  723. int hibernating = we_are_hibernating();
  724. or_options_t *options = get_options();
  725. if (desc_clean_since && !force)
  726. return 0;
  727. if (resolve_my_address(options, &addr, NULL) < 0) {
  728. log_warn(LD_CONFIG,"options->Address didn't resolve into an IP.");
  729. return -1;
  730. }
  731. ri = tor_malloc_zero(sizeof(routerinfo_t));
  732. ri->address = tor_dup_addr(addr);
  733. ri->nickname = tor_strdup(options->Nickname);
  734. ri->addr = addr;
  735. ri->or_port = options->ORPort;
  736. ri->dir_port = options->DirPort;
  737. ri->cache_info.published_on = time(NULL);
  738. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
  739. * main thread */
  740. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  741. if (crypto_pk_get_digest(ri->identity_pkey,
  742. ri->cache_info.identity_digest)<0) {
  743. routerinfo_free(ri);
  744. return -1;
  745. }
  746. get_platform_str(platform, sizeof(platform));
  747. ri->platform = tor_strdup(platform);
  748. ri->bandwidthrate = (int)options->BandwidthRate;
  749. ri->bandwidthburst = (int)options->BandwidthBurst;
  750. ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
  751. if (options->BandwidthRate > options->MaxAdvertisedBandwidth)
  752. ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
  753. policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
  754. options->ExitPolicyRejectPrivate);
  755. if (desc_routerinfo) { /* inherit values */
  756. ri->is_valid = desc_routerinfo->is_valid;
  757. ri->is_running = desc_routerinfo->is_running;
  758. ri->is_named = desc_routerinfo->is_named;
  759. }
  760. if (authdir_mode(options))
  761. ri->is_valid = ri->is_named = 1; /* believe in yourself */
  762. if (options->MyFamily) {
  763. smartlist_t *family;
  764. if (!warned_nonexistent_family)
  765. warned_nonexistent_family = smartlist_create();
  766. family = smartlist_create();
  767. ri->declared_family = smartlist_create();
  768. smartlist_split_string(family, options->MyFamily, ",",
  769. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  770. SMARTLIST_FOREACH(family, char *, name,
  771. {
  772. routerinfo_t *member;
  773. if (!strcasecmp(name, options->Nickname))
  774. member = ri;
  775. else
  776. member = router_get_by_nickname(name, 1);
  777. if (!member) {
  778. if (!smartlist_string_isin(warned_nonexistent_family, name) &&
  779. !is_legal_hexdigest(name)) {
  780. log_warn(LD_CONFIG,
  781. "I have no descriptor for the router named \"%s\" "
  782. "in my declared family; I'll use the nickname as is, but "
  783. "this may confuse clients.", name);
  784. smartlist_add(warned_nonexistent_family, tor_strdup(name));
  785. }
  786. smartlist_add(ri->declared_family, name);
  787. name = NULL;
  788. } else {
  789. char *fp = tor_malloc(HEX_DIGEST_LEN+2);
  790. fp[0] = '$';
  791. base16_encode(fp+1,HEX_DIGEST_LEN+1,
  792. member->cache_info.identity_digest, DIGEST_LEN);
  793. smartlist_add(ri->declared_family, fp);
  794. if (smartlist_string_isin(warned_nonexistent_family, name))
  795. smartlist_string_remove(warned_nonexistent_family, name);
  796. }
  797. tor_free(name);
  798. });
  799. smartlist_free(family);
  800. }
  801. ri->cache_info.signed_descriptor_body = tor_malloc(8192);
  802. if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
  803. ri, get_identity_key())<0) {
  804. log_warn(LD_BUG, "Couldn't allocate string for descriptor.");
  805. return -1;
  806. }
  807. ri->cache_info.signed_descriptor_len =
  808. strlen(ri->cache_info.signed_descriptor_body);
  809. crypto_digest(ri->cache_info.signed_descriptor_digest,
  810. ri->cache_info.signed_descriptor_body,
  811. ri->cache_info.signed_descriptor_len);
  812. if (desc_routerinfo)
  813. routerinfo_free(desc_routerinfo);
  814. desc_routerinfo = ri;
  815. desc_clean_since = time(NULL);
  816. desc_needs_upload = 1;
  817. return 0;
  818. }
  819. /** Mark descriptor out of date if it's older than <b>when</b> */
  820. void
  821. mark_my_descriptor_dirty_if_older_than(time_t when)
  822. {
  823. if (desc_clean_since < when)
  824. mark_my_descriptor_dirty();
  825. }
  826. /** Call when the current descriptor is out of date. */
  827. void
  828. mark_my_descriptor_dirty(void)
  829. {
  830. desc_clean_since = 0;
  831. }
  832. /** How frequently will we republish our descriptor because of large (factor
  833. * of 2) shifts in estimated bandwidth? */
  834. #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
  835. /** Check whether bandwidth has changed a lot since the last time we announced
  836. * bandwidth. If so, mark our descriptor dirty. */
  837. void
  838. check_descriptor_bandwidth_changed(time_t now)
  839. {
  840. static time_t last_changed = 0;
  841. uint64_t prev, cur;
  842. if (!desc_routerinfo)
  843. return;
  844. prev = desc_routerinfo->bandwidthcapacity;
  845. cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
  846. if ((prev != cur && (!prev || !cur)) ||
  847. cur > prev*2 ||
  848. cur < prev/2) {
  849. if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
  850. log_info(LD_GENERAL,
  851. "Measured bandwidth has changed; rebuilding descriptor.");
  852. mark_my_descriptor_dirty();
  853. last_changed = now;
  854. }
  855. }
  856. }
  857. /** Check whether our own address as defined by the Address configuration
  858. * has changed. This is for routers that get their address from a service
  859. * like dyndns. If our address has changed, mark our descriptor dirty. */
  860. void
  861. check_descriptor_ipaddress_changed(time_t now)
  862. {
  863. uint32_t prev, cur;
  864. or_options_t *options = get_options();
  865. if (!desc_routerinfo)
  866. return;
  867. prev = desc_routerinfo->addr;
  868. if (resolve_my_address(options, &cur, NULL) < 0) {
  869. log_warn(LD_CONFIG,"options->Address didn't resolve into an IP.");
  870. return;
  871. }
  872. if (prev != cur) {
  873. char addrbuf_prev[INET_NTOA_BUF_LEN];
  874. char addrbuf_cur[INET_NTOA_BUF_LEN];
  875. struct in_addr in_prev;
  876. struct in_addr in_cur;
  877. in_prev.s_addr = htonl(prev);
  878. tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
  879. in_cur.s_addr = htonl(cur);
  880. tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
  881. log_info(LD_GENERAL,
  882. "Our IP Address has changed from %s to %s; "
  883. "rebuilding descriptor.",
  884. addrbuf_prev, addrbuf_cur);
  885. mark_my_descriptor_dirty();
  886. }
  887. }
  888. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  889. * string describing the version of Tor and the operating system we're
  890. * currently running on.
  891. */
  892. void
  893. get_platform_str(char *platform, size_t len)
  894. {
  895. tor_snprintf(platform, len, "Tor %s on %s",
  896. VERSION, get_uname());
  897. return;
  898. }
  899. /* XXX need to audit this thing and count fenceposts. maybe
  900. * refactor so we don't have to keep asking if we're
  901. * near the end of maxlen?
  902. */
  903. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  904. /** OR only: Given a routerinfo for this router, and an identity key to sign
  905. * with, encode the routerinfo as a signed server descriptor and write the
  906. * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
  907. * failure, and the number of bytes used on success.
  908. */
  909. int
  910. router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
  911. crypto_pk_env_t *ident_key)
  912. {
  913. char *onion_pkey; /* Onion key, PEM-encoded. */
  914. char *identity_pkey; /* Identity key, PEM-encoded. */
  915. char digest[DIGEST_LEN];
  916. char published[ISO_TIME_LEN+1];
  917. char fingerprint[FINGERPRINT_LEN+1];
  918. struct in_addr in;
  919. char addrbuf[INET_NTOA_BUF_LEN];
  920. size_t onion_pkeylen, identity_pkeylen;
  921. size_t written;
  922. int result=0;
  923. addr_policy_t *tmpe;
  924. char *bandwidth_usage;
  925. char *family_line;
  926. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  927. char *s_tmp, *s_dup;
  928. const char *cp;
  929. routerinfo_t *ri_tmp;
  930. #endif
  931. or_options_t *options = get_options();
  932. /* Make sure the identity key matches the one in the routerinfo. */
  933. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  934. log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
  935. "match router's public key!");
  936. return -1;
  937. }
  938. /* record our fingerprint, so we can include it in the descriptor */
  939. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
  940. log_err(LD_BUG,"Error computing fingerprint");
  941. return -1;
  942. }
  943. /* PEM-encode the onion key */
  944. if (crypto_pk_write_public_key_to_string(router->onion_pkey,
  945. &onion_pkey,&onion_pkeylen)<0) {
  946. log_warn(LD_BUG,"write onion_pkey to string failed!");
  947. return -1;
  948. }
  949. /* PEM-encode the identity key key */
  950. if (crypto_pk_write_public_key_to_string(router->identity_pkey,
  951. &identity_pkey,&identity_pkeylen)<0) {
  952. log_warn(LD_BUG,"write identity_pkey to string failed!");
  953. tor_free(onion_pkey);
  954. return -1;
  955. }
  956. /* Encode the publication time. */
  957. format_iso_time(published, router->cache_info.published_on);
  958. /* How busy have we been? */
  959. bandwidth_usage = rep_hist_get_bandwidth_lines();
  960. if (router->declared_family && smartlist_len(router->declared_family)) {
  961. size_t n;
  962. char *s = smartlist_join_strings(router->declared_family, " ", 0, &n);
  963. n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
  964. family_line = tor_malloc(n);
  965. tor_snprintf(family_line, n, "family %s\n", s);
  966. tor_free(s);
  967. } else {
  968. family_line = tor_strdup("");
  969. }
  970. /* Generate the easy portion of the router descriptor. */
  971. result = tor_snprintf(s, maxlen,
  972. "router %s %s %d 0 %d\n"
  973. "platform %s\n"
  974. "published %s\n"
  975. "opt fingerprint %s\n"
  976. "uptime %ld\n"
  977. "bandwidth %d %d %d\n"
  978. "onion-key\n%s"
  979. "signing-key\n%s%s%s%s",
  980. router->nickname,
  981. router->address,
  982. router->or_port,
  983. decide_to_advertise_dirport(options, router),
  984. router->platform,
  985. published,
  986. fingerprint,
  987. stats_n_seconds_working,
  988. (int) router->bandwidthrate,
  989. (int) router->bandwidthburst,
  990. (int) router->bandwidthcapacity,
  991. onion_pkey, identity_pkey,
  992. family_line, bandwidth_usage,
  993. we_are_hibernating() ? "opt hibernating 1\n" : "");
  994. tor_free(family_line);
  995. tor_free(onion_pkey);
  996. tor_free(identity_pkey);
  997. tor_free(bandwidth_usage);
  998. if (result < 0)
  999. return -1;
  1000. /* From now on, we use 'written' to remember the current length of 's'. */
  1001. written = result;
  1002. if (options->ContactInfo && strlen(options->ContactInfo)) {
  1003. result = tor_snprintf(s+written,maxlen-written, "contact %s\n",
  1004. options->ContactInfo);
  1005. if (result<0)
  1006. return -1;
  1007. written += result;
  1008. }
  1009. /* Write the exit policy to the end of 's'. */
  1010. for (tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
  1011. /* Write: "accept 1.2.3.4" */
  1012. in.s_addr = htonl(tmpe->addr);
  1013. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  1014. result = tor_snprintf(s+written, maxlen-written, "%s %s",
  1015. tmpe->policy_type == ADDR_POLICY_ACCEPT ? "accept" : "reject",
  1016. tmpe->msk == 0 ? "*" : addrbuf);
  1017. if (result < 0)
  1018. return -1;
  1019. written += result;
  1020. if (tmpe->msk != 0xFFFFFFFFu && tmpe->msk != 0) {
  1021. int n_bits = addr_mask_get_bits(tmpe->msk);
  1022. if (n_bits >= 0) {
  1023. if (tor_snprintf(s+written, maxlen-written, "/%d", n_bits)<0)
  1024. return -1;
  1025. } else {
  1026. /* Write "/255.255.0.0" */
  1027. in.s_addr = htonl(tmpe->msk);
  1028. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  1029. if (tor_snprintf(s+written, maxlen-written, "/%s", addrbuf)<0)
  1030. return -1;
  1031. }
  1032. written += strlen(s+written);
  1033. }
  1034. if (tmpe->prt_min <= 1 && tmpe->prt_max == 65535) {
  1035. /* There is no port set; write ":*" */
  1036. if (written+4 > maxlen)
  1037. return -1;
  1038. strlcat(s+written, ":*\n", maxlen-written);
  1039. written += 3;
  1040. } else if (tmpe->prt_min == tmpe->prt_max) {
  1041. /* There is only one port; write ":80". */
  1042. result = tor_snprintf(s+written, maxlen-written, ":%d\n", tmpe->prt_min);
  1043. if (result<0)
  1044. return -1;
  1045. written += result;
  1046. } else {
  1047. /* There is a range of ports; write ":79-80". */
  1048. result = tor_snprintf(s+written, maxlen-written, ":%d-%d\n",
  1049. tmpe->prt_min, tmpe->prt_max);
  1050. if (result<0)
  1051. return -1;
  1052. written += result;
  1053. }
  1054. } /* end for */
  1055. if (written+256 > maxlen) /* Not enough room for signature. */
  1056. return -1;
  1057. /* Sign the directory */
  1058. strlcat(s+written, "router-signature\n", maxlen-written);
  1059. written += strlen(s+written);
  1060. s[written] = '\0';
  1061. if (router_get_router_hash(s, digest) < 0)
  1062. return -1;
  1063. if (router_append_dirobj_signature(s+written,maxlen-written,
  1064. digest,ident_key)<0) {
  1065. log_warn(LD_BUG, "Couldn't sign router descriptor");
  1066. return -1;
  1067. }
  1068. written += strlen(s+written);
  1069. if (written+2 > maxlen)
  1070. return -1;
  1071. /* include a last '\n' */
  1072. s[written] = '\n';
  1073. s[written+1] = 0;
  1074. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1075. cp = s_tmp = s_dup = tor_strdup(s);
  1076. ri_tmp = router_parse_entry_from_string(cp, NULL);
  1077. if (!ri_tmp) {
  1078. log_err(LD_BUG,
  1079. "We just generated a router descriptor we can't parse: <<%s>>",
  1080. s);
  1081. return -1;
  1082. }
  1083. tor_free(s_dup);
  1084. routerinfo_free(ri_tmp);
  1085. #endif
  1086. return written+1;
  1087. }
  1088. /** Return true iff <b>s</b> is a legally valid server nickname. */
  1089. int
  1090. is_legal_nickname(const char *s)
  1091. {
  1092. size_t len;
  1093. tor_assert(s);
  1094. len = strlen(s);
  1095. return len > 0 && len <= MAX_NICKNAME_LEN &&
  1096. strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
  1097. }
  1098. /** Return true iff <b>s</b> is a legally valid server nickname or
  1099. * hex-encoded identity-key digest. */
  1100. int
  1101. is_legal_nickname_or_hexdigest(const char *s)
  1102. {
  1103. if (*s!='$')
  1104. return is_legal_nickname(s);
  1105. else
  1106. return is_legal_hexdigest(s);
  1107. }
  1108. /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
  1109. * digest. */
  1110. int
  1111. is_legal_hexdigest(const char *s)
  1112. {
  1113. size_t len;
  1114. tor_assert(s);
  1115. len = strlen(s);
  1116. return (len == HEX_DIGEST_LEN+1 &&
  1117. s[0] == '$' &&
  1118. strspn(s+1,HEX_CHARACTERS)==len-1);
  1119. }
  1120. /** Forget that we have issued any router-related warnings, so that we'll
  1121. * warn again if we see the same errors. */
  1122. void
  1123. router_reset_warnings(void)
  1124. {
  1125. if (warned_nonexistent_family) {
  1126. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  1127. smartlist_clear(warned_nonexistent_family);
  1128. }
  1129. }
  1130. /** Release all static resources held in router.c */
  1131. void
  1132. router_free_all(void)
  1133. {
  1134. if (onionkey)
  1135. crypto_free_pk_env(onionkey);
  1136. if (lastonionkey)
  1137. crypto_free_pk_env(lastonionkey);
  1138. if (identitykey)
  1139. crypto_free_pk_env(identitykey);
  1140. if (key_lock)
  1141. tor_mutex_free(key_lock);
  1142. if (desc_routerinfo)
  1143. routerinfo_free(desc_routerinfo);
  1144. if (warned_nonexistent_family) {
  1145. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  1146. smartlist_free(warned_nonexistent_family);
  1147. }
  1148. }