router.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. #include "or.h"
  5. /**
  6. * \file router.c
  7. * \brief OR functionality, including key maintenance, generating
  8. * and uploading server descriptors, retrying OR connections.
  9. **/
  10. extern or_options_t options; /* command-line and config-file options */
  11. extern long stats_n_seconds_uptime;
  12. /** Exposed for test.c. */ void get_platform_str(char *platform, int len);
  13. /************************************************************/
  14. /*****
  15. * Key management: ORs only.
  16. *****/
  17. /** Private keys for this OR. There is also an SSL key managed by tortls.c.
  18. */
  19. static tor_mutex_t *key_lock=NULL;
  20. static time_t onionkey_set_at=0; /* When was onionkey last changed? */
  21. static crypto_pk_env_t *onionkey=NULL;
  22. static crypto_pk_env_t *lastonionkey=NULL;
  23. static crypto_pk_env_t *identitykey=NULL;
  24. /** Replace the current onion key with <b>k</b>. Does not affect lastonionkey;
  25. * to update onionkey correctly, call rotate_onion_key().
  26. */
  27. void set_onion_key(crypto_pk_env_t *k) {
  28. tor_mutex_acquire(key_lock);
  29. onionkey = k;
  30. onionkey_set_at = time(NULL);
  31. tor_mutex_release(key_lock);
  32. }
  33. /** Return the current onion key. Requires that the onion key has been
  34. * loaded or generated. */
  35. crypto_pk_env_t *get_onion_key(void) {
  36. tor_assert(onionkey);
  37. return onionkey;
  38. }
  39. /** Return the onion key that was current before the most recent onion
  40. * key rotation. If no rotation has been performed since this process
  41. * started, return NULL.
  42. */
  43. crypto_pk_env_t *get_previous_onion_key(void) {
  44. return lastonionkey;
  45. }
  46. void dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
  47. {
  48. tor_assert(key && last);
  49. tor_mutex_acquire(key_lock);
  50. *key = crypto_pk_dup_key(onionkey);
  51. if (lastonionkey)
  52. *last = crypto_pk_dup_key(lastonionkey);
  53. else
  54. *last = NULL;
  55. tor_mutex_release(key_lock);
  56. }
  57. /** Return the time when the onion key was last set. This is either the time
  58. * when the process launched, or the time of the most recent key rotation since
  59. * the process launched.
  60. */
  61. time_t get_onion_key_set_at(void) {
  62. return onionkey_set_at;
  63. }
  64. /** Set the current identity key to k.
  65. */
  66. void set_identity_key(crypto_pk_env_t *k) {
  67. identitykey = k;
  68. }
  69. /** Returns the current identity key; requires that the identity key has been
  70. * set.
  71. */
  72. crypto_pk_env_t *get_identity_key(void) {
  73. tor_assert(identitykey);
  74. return identitykey;
  75. }
  76. /** Replace the previous onion key with the current onion key, and generate
  77. * a new previous onion key. Immediately after calling this function,
  78. * the OR should:
  79. * - schedule all previous cpuworkers to shut down _after_ processing
  80. * pending work. (This will cause fresh cpuworkers to be generated.)
  81. * - generate and upload a fresh routerinfo.
  82. */
  83. void rotate_onion_key(void)
  84. {
  85. char fname[512];
  86. crypto_pk_env_t *prkey;
  87. sprintf(fname,"%s/keys/onion.key",get_data_directory(&options));
  88. if (!(prkey = crypto_new_pk_env())) {
  89. log(LOG_ERR, "Error creating crypto environment.");
  90. goto error;
  91. }
  92. if (crypto_pk_generate_key(prkey)) {
  93. log(LOG_ERR, "Error generating onion key");
  94. goto error;
  95. }
  96. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  97. log(LOG_ERR, "Couldn't write generated key to %s.", fname);
  98. goto error;
  99. }
  100. tor_mutex_acquire(key_lock);
  101. if (lastonionkey)
  102. crypto_free_pk_env(lastonionkey);
  103. log_fn(LOG_INFO, "Rotating onion key");
  104. lastonionkey = onionkey;
  105. set_onion_key(prkey);
  106. tor_mutex_release(key_lock);
  107. return;
  108. error:
  109. log_fn(LOG_WARN, "Couldn't rotate onion key.");
  110. }
  111. /* Read an RSA secret key key from a file that was once named fname_old,
  112. * but is now named fname_new. Rename the file from old to new as needed.
  113. */
  114. crypto_pk_env_t *init_key_from_file_name_changed(const char *fname_old,
  115. const char *fname_new)
  116. {
  117. int fs;
  118. fs = file_status(fname_new);
  119. if (fs == FN_FILE)
  120. /* The new filename is there. */
  121. return init_key_from_file(fname_new);
  122. fs = file_status(fname_old);
  123. if (fs != FN_FILE)
  124. /* There is no key under either name. */
  125. return init_key_from_file(fname_new);
  126. /* The old filename exists, and the new one doesn't. Rename and load. */
  127. if (rename(fname_old, fname_new) < 0) {
  128. log_fn(LOG_ERR, "Couldn't rename %s to %s: %s", fname_old, fname_new,
  129. strerror(errno));
  130. return NULL;
  131. }
  132. return init_key_from_file(fname_new);
  133. }
  134. /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist,
  135. * create a new RSA key and save it in <b>fname</b>. Return the read/created
  136. * key, or NULL on error.
  137. */
  138. crypto_pk_env_t *init_key_from_file(const char *fname)
  139. {
  140. crypto_pk_env_t *prkey = NULL;
  141. FILE *file = NULL;
  142. if (!(prkey = crypto_new_pk_env())) {
  143. log(LOG_ERR, "Error creating crypto environment.");
  144. goto error;
  145. }
  146. switch(file_status(fname)) {
  147. case FN_DIR:
  148. case FN_ERROR:
  149. log(LOG_ERR, "Can't read key from %s", fname);
  150. goto error;
  151. case FN_NOENT:
  152. log(LOG_INFO, "No key found in %s; generating fresh key.", fname);
  153. if (crypto_pk_generate_key(prkey)) {
  154. log(LOG_ERR, "Error generating onion key");
  155. goto error;
  156. }
  157. if (crypto_pk_check_key(prkey) <= 0) {
  158. log(LOG_ERR, "Generated key seems invalid");
  159. goto error;
  160. }
  161. log(LOG_INFO, "Generated key seems valid");
  162. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  163. log(LOG_ERR, "Couldn't write generated key to %s.", fname);
  164. goto error;
  165. }
  166. return prkey;
  167. case FN_FILE:
  168. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  169. log(LOG_ERR, "Error loading private key.");
  170. goto error;
  171. }
  172. return prkey;
  173. default:
  174. tor_assert(0);
  175. }
  176. error:
  177. if (prkey)
  178. crypto_free_pk_env(prkey);
  179. if (file)
  180. fclose(file);
  181. return NULL;
  182. }
  183. /** Initialize all OR private keys, and the TLS context, as necessary.
  184. * On OPs, this only initializes the tls context.
  185. */
  186. int init_keys(void) {
  187. char keydir[512];
  188. char keydir2[512];
  189. char fingerprint[FINGERPRINT_LEN+MAX_NICKNAME_LEN+3];
  190. char *cp;
  191. const char *tmp, *mydesc, *datadir;
  192. crypto_pk_env_t *prkey;
  193. if (!key_lock)
  194. key_lock = tor_mutex_new();
  195. /* OP's don't need persistant keys; just make up an identity and
  196. * initialize the TLS context. */
  197. if (!server_mode()) {
  198. tor_assert(!options.DirPort);
  199. #if 0
  200. /* XXXX008 enable this once we make ORs tolerate unknown routers. */
  201. if (!(prkey = crypto_new_pk_env()))
  202. return -1;
  203. if (crypto_pk_generate_key(prkey))
  204. return -1;
  205. set_identity_key(prkey);
  206. if (tor_tls_context_new(get_identity_key(), 1, options.Nickname,
  207. MAX_SSL_KEY_LIFETIME) < 0) {
  208. log_fn(LOG_ERR, "Error creating TLS context for OP.");
  209. return -1;
  210. }
  211. #endif
  212. if (tor_tls_context_new(NULL, 0, NULL, MAX_SSL_KEY_LIFETIME)<0) {
  213. log_fn(LOG_ERR, "Error creating TLS context for OP.");
  214. return -1;
  215. }
  216. return 0;
  217. }
  218. /* Make sure DataDirectory exists, and is private. */
  219. datadir = get_data_directory(&options);
  220. tor_assert(datadir);
  221. if (strlen(datadir) > (512-128)) {
  222. log_fn(LOG_ERR, "DataDirectory is too long.");
  223. return -1;
  224. }
  225. if (check_private_dir(datadir, 1)) {
  226. return -1;
  227. }
  228. /* Check the key directory. */
  229. sprintf(keydir,"%s/keys", datadir);
  230. if (check_private_dir(keydir, 1)) {
  231. return -1;
  232. }
  233. cp = keydir + strlen(keydir); /* End of string. */
  234. /* 1. Read identity key. Make it if none is found. */
  235. sprintf(keydir,"%s/keys/identity.key",datadir);
  236. sprintf(keydir2,"%s/keys/secret_id_key",datadir);
  237. log_fn(LOG_INFO,"Reading/making identity key %s...",keydir2);
  238. prkey = init_key_from_file_name_changed(keydir,keydir2);
  239. if (!prkey) return -1;
  240. set_identity_key(prkey);
  241. /* 2. Read onion key. Make it if none is found. */
  242. sprintf(keydir,"%s/keys/onion.key",datadir);
  243. sprintf(keydir2,"%s/keys/secret_onion_key",datadir);
  244. log_fn(LOG_INFO,"Reading/making onion key %s...",keydir2);
  245. prkey = init_key_from_file_name_changed(keydir,keydir2);
  246. if (!prkey) return -1;
  247. set_onion_key(prkey);
  248. /* 3. Initialize link key and TLS context. */
  249. if (tor_tls_context_new(get_identity_key(), 1, options.Nickname,
  250. MAX_SSL_KEY_LIFETIME) < 0) {
  251. log_fn(LOG_ERR, "Error initializing TLS context");
  252. return -1;
  253. }
  254. /* 4. Dump router descriptor to 'router.desc' */
  255. /* Must be called after keys are initialized. */
  256. tmp = mydesc = router_get_my_descriptor();
  257. if (!mydesc) {
  258. log_fn(LOG_ERR, "Error initializing descriptor.");
  259. return -1;
  260. }
  261. if(authdir_mode()) {
  262. /* We need to add our own fingerprint so it gets recognized. */
  263. if (dirserv_add_own_fingerprint(options.Nickname, get_identity_key())) {
  264. log_fn(LOG_ERR, "Error adding own fingerprint to approved set");
  265. return -1;
  266. }
  267. if (dirserv_add_descriptor(&tmp) != 1) {
  268. log(LOG_ERR, "Unable to add own descriptor to directory.");
  269. return -1;
  270. }
  271. }
  272. sprintf(keydir,"%s/router.desc", datadir);
  273. log_fn(LOG_INFO,"Dumping descriptor to %s...",keydir);
  274. if (write_str_to_file(keydir, mydesc)) {
  275. return -1;
  276. }
  277. /* 5. Dump fingerprint to 'fingerprint' */
  278. sprintf(keydir,"%s/fingerprint", datadir);
  279. log_fn(LOG_INFO,"Dumping fingerprint to %s...",keydir);
  280. tor_assert(strlen(options.Nickname) <= MAX_NICKNAME_LEN);
  281. strcpy(fingerprint, options.Nickname);
  282. strcat(fingerprint, " ");
  283. if (crypto_pk_get_fingerprint(get_identity_key(),
  284. fingerprint+strlen(fingerprint))<0) {
  285. log_fn(LOG_ERR, "Error computing fingerprint");
  286. return -1;
  287. }
  288. strcat(fingerprint, "\n");
  289. if (write_str_to_file(keydir, fingerprint))
  290. return -1;
  291. if(!authdir_mode())
  292. return 0;
  293. /* 6. [authdirserver only] load approved-routers file */
  294. sprintf(keydir,"%s/approved-routers", datadir);
  295. log_fn(LOG_INFO,"Loading approved fingerprints from %s...",keydir);
  296. if(dirserv_parse_fingerprint_file(keydir) < 0) {
  297. log_fn(LOG_ERR, "Error loading fingerprints");
  298. return -1;
  299. }
  300. /* 7. [authdirserver only] load old directory, if it's there */
  301. sprintf(keydir,"%s/cached-directory", datadir);
  302. log_fn(LOG_INFO,"Loading cached directory from %s...",keydir);
  303. cp = read_file_to_str(keydir);
  304. if(!cp) {
  305. log_fn(LOG_INFO,"Cached directory %s not present. Ok.",keydir);
  306. } else {
  307. if(dirserv_load_from_directory_string(cp) < 0){
  308. log_fn(LOG_ERR, "Cached directory %s is corrupt", keydir);
  309. tor_free(cp);
  310. return -1;
  311. }
  312. tor_free(cp);
  313. }
  314. /* success */
  315. return 0;
  316. }
  317. /*
  318. * Clique maintenance
  319. */
  320. /** OR only: try to open connections to all of the other ORs we know about.
  321. */
  322. void router_retry_connections(void) {
  323. int i;
  324. routerinfo_t *router;
  325. routerlist_t *rl;
  326. router_get_routerlist(&rl);
  327. for (i=0;i < smartlist_len(rl->routers);i++) {
  328. router = smartlist_get(rl->routers, i);
  329. if(router_is_me(router))
  330. continue;
  331. if(!connection_get_by_identity_digest(router->identity_digest,
  332. CONN_TYPE_OR)) {
  333. /* not in the list */
  334. log_fn(LOG_DEBUG,"connecting to OR %s:%u.",router->address,router->or_port);
  335. connection_or_connect(router->addr, router->or_port, router->identity_digest);
  336. }
  337. }
  338. }
  339. int router_is_clique_mode(routerinfo_t *router) {
  340. if(router->is_trusted_dir)
  341. return 1;
  342. if(!strncmp(router->platform, "Tor 0.0.7", 9))
  343. return 1;
  344. return 0;
  345. }
  346. /*
  347. * OR descriptor generation.
  348. */
  349. /** My routerinfo. */
  350. static routerinfo_t *desc_routerinfo = NULL;
  351. /** String representation of my descriptor, signed by me. */
  352. static char descriptor[8192];
  353. /** OR only: try to upload our signed descriptor to all the directory servers
  354. * we know about.
  355. */
  356. void router_upload_dir_desc_to_dirservers(void) {
  357. const char *s;
  358. s = router_get_my_descriptor();
  359. if (!s) {
  360. log_fn(LOG_WARN, "No descriptor; skipping upload");
  361. return;
  362. }
  363. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR, s, strlen(s));
  364. }
  365. #define DEFAULT_EXIT_POLICY "reject 0.0.0.0/8,reject 169.254.0.0/16,reject 127.0.0.0/8,reject 192.168.0.0/16,reject 10.0.0.0/8,reject 172.16.0.0/12,accept *:20-22,accept *:53,accept *:79-81,accept *:110,accept *:143,accept *:443,accept *:873,accept *:993,accept *:995,accept *:1024-65535,reject *:*"
  366. /** Set the exit policy on <b>router</b> to match the exit policy in the
  367. * current configuration file. If the exit policy doesn't have a catch-all
  368. * rule, then append the default exit policy as well.
  369. */
  370. static void router_add_exit_policy_from_config(routerinfo_t *router) {
  371. struct exit_policy_t *ep;
  372. struct config_line_t default_policy;
  373. config_parse_exit_policy(options.ExitPolicy, &router->exit_policy);
  374. for (ep = router->exit_policy; ep; ep = ep->next) {
  375. if (ep->msk == 0 && ep->prt_min <= 1 && ep->prt_max >= 65535) {
  376. /* if exitpolicy includes a *:* line, then we're done. */
  377. return;
  378. }
  379. }
  380. /* Else, append the default exitpolicy. */
  381. default_policy.key = NULL;
  382. default_policy.value = DEFAULT_EXIT_POLICY;
  383. default_policy.next = NULL;
  384. config_parse_exit_policy(&default_policy, &router->exit_policy);
  385. }
  386. /** OR only: Return false if my exit policy says to allow connection to
  387. * conn. Else return true.
  388. */
  389. int router_compare_to_my_exit_policy(connection_t *conn)
  390. {
  391. tor_assert(desc_routerinfo);
  392. /* make sure it's resolved to something. this way we can't get a
  393. 'maybe' below. */
  394. if (!conn->addr)
  395. return -1;
  396. return router_compare_addr_to_exit_policy(conn->addr, conn->port,
  397. desc_routerinfo->exit_policy);
  398. }
  399. /** Return true iff <b>router</b> has the same nickname as this OR. (For an
  400. * OP, always returns false.)
  401. */
  402. int router_is_me(routerinfo_t *router)
  403. {
  404. tor_assert(router);
  405. /* XXXX008 should compare identity instead? */
  406. return options.Nickname && !strcasecmp(router->nickname, options.Nickname);
  407. }
  408. /** Return a routerinfo for this OR, rebuilding a fresh one if
  409. * necessary. Return NULL on error, or if called on an OP. */
  410. routerinfo_t *router_get_my_routerinfo(void)
  411. {
  412. if (!server_mode())
  413. return NULL;
  414. if (!desc_routerinfo) {
  415. if (router_rebuild_descriptor())
  416. return NULL;
  417. }
  418. return desc_routerinfo;
  419. }
  420. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  421. * one if necessary. Return NULL on error.
  422. */
  423. const char *router_get_my_descriptor(void) {
  424. if (!desc_routerinfo) {
  425. if (router_rebuild_descriptor())
  426. return NULL;
  427. }
  428. log_fn(LOG_DEBUG,"my desc is '%s'",descriptor);
  429. return descriptor;
  430. }
  431. /** Rebuild a fresh routerinfo and signed server descriptor for this
  432. * OR. Return 0 on success, -1 on error.
  433. */
  434. int router_rebuild_descriptor(void) {
  435. routerinfo_t *ri;
  436. struct in_addr addr;
  437. char platform[256];
  438. if (!tor_inet_aton(options.Address, &addr)) {
  439. log_fn(LOG_ERR, "options.Address didn't hold an IP.");
  440. return -1;
  441. }
  442. ri = tor_malloc_zero(sizeof(routerinfo_t));
  443. ri->address = tor_strdup(options.Address);
  444. ri->nickname = tor_strdup(options.Nickname);
  445. ri->addr = (uint32_t) ntohl(addr.s_addr);
  446. ri->or_port = options.ORPort;
  447. ri->socks_port = options.SocksPort;
  448. ri->dir_port = options.DirPort;
  449. ri->published_on = time(NULL);
  450. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from main thread */
  451. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  452. if (crypto_pk_get_digest(ri->identity_pkey, ri->identity_digest)<0) {
  453. routerinfo_free(ri);
  454. return -1;
  455. }
  456. get_platform_str(platform, sizeof(platform));
  457. ri->platform = tor_strdup(platform);
  458. ri->bandwidthrate = options.BandwidthRate;
  459. ri->bandwidthburst = options.BandwidthBurst;
  460. ri->exit_policy = NULL; /* zero it out first */
  461. router_add_exit_policy_from_config(ri);
  462. if (desc_routerinfo)
  463. routerinfo_free(desc_routerinfo);
  464. desc_routerinfo = ri;
  465. if (router_dump_router_to_string(descriptor, 8192, ri, get_identity_key())<0) {
  466. log_fn(LOG_WARN, "Couldn't dump router to string.");
  467. return -1;
  468. }
  469. ri->is_trusted_dir = ri->dir_port &&
  470. router_digest_is_trusted_dir(ri->identity_digest);
  471. return 0;
  472. }
  473. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  474. * string describing the version of Tor and the operating system we're
  475. * currently running on.
  476. */
  477. void get_platform_str(char *platform, int len)
  478. {
  479. snprintf(platform, len-1, "Tor %s on %s",
  480. VERSION, get_uname());
  481. platform[len-1] = '\0';
  482. return;
  483. }
  484. /* XXX need to audit this thing and count fenceposts. maybe
  485. * refactor so we don't have to keep asking if we're
  486. * near the end of maxlen?
  487. */
  488. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  489. /** OR only: Given a routerinfo for this router, and an identity key to sign
  490. * with, encode the routerinfo as a signed server descriptor and write the
  491. * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
  492. * failure, and the number of bytes used on success.
  493. */
  494. int router_dump_router_to_string(char *s, int maxlen, routerinfo_t *router,
  495. crypto_pk_env_t *ident_key) {
  496. char *onion_pkey; /* Onion key, PEM-encoded. */
  497. char *identity_pkey; /* Identity key, PEM-encoded. */
  498. char digest[20];
  499. char signature[128];
  500. char published[32];
  501. struct in_addr in;
  502. int onion_pkeylen, identity_pkeylen;
  503. int written;
  504. int result=0;
  505. struct exit_policy_t *tmpe;
  506. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  507. char *s_tmp, *s_dup;
  508. const char *cp;
  509. routerinfo_t *ri_tmp;
  510. #endif
  511. /* Make sure the identity key matches the one in the routerinfo. */
  512. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  513. log_fn(LOG_WARN,"Tried to sign a router with a private key that didn't match router's public key!");
  514. return -1;
  515. }
  516. /* PEM-encode the onion key */
  517. if(crypto_pk_write_public_key_to_string(router->onion_pkey,
  518. &onion_pkey,&onion_pkeylen)<0) {
  519. log_fn(LOG_WARN,"write onion_pkey to string failed!");
  520. return -1;
  521. }
  522. /* PEM-encode the identity key key */
  523. if(crypto_pk_write_public_key_to_string(router->identity_pkey,
  524. &identity_pkey,&identity_pkeylen)<0) {
  525. log_fn(LOG_WARN,"write identity_pkey to string failed!");
  526. tor_free(onion_pkey);
  527. return -1;
  528. }
  529. /* Encode the publication time. */
  530. strftime(published, 32, "%Y-%m-%d %H:%M:%S", gmtime(&router->published_on));
  531. /* Generate the easy portion of the router descriptor. */
  532. result = snprintf(s, maxlen,
  533. "router %s %s %d %d %d\n"
  534. "platform %s\n"
  535. "published %s\n"
  536. "opt uptime %ld\n"
  537. "bandwidth %d %d %d\n"
  538. "onion-key\n%s"
  539. "signing-key\n%s",
  540. router->nickname,
  541. router->address,
  542. router->or_port,
  543. router->socks_port,
  544. /* Due to an 0.0.7 bug, we can't actually say that we have a dirport unles
  545. * we're an authoritative directory.
  546. */
  547. router->is_trusted_dir ? router->dir_port : 0,
  548. router->platform,
  549. published,
  550. stats_n_seconds_uptime,
  551. (int) router->bandwidthrate,
  552. (int) router->bandwidthburst,
  553. (int) router->advertisedbandwidth,
  554. onion_pkey, identity_pkey);
  555. tor_free(onion_pkey);
  556. tor_free(identity_pkey);
  557. if(result < 0 || result >= maxlen) {
  558. /* apparently different glibcs do different things on snprintf error.. so check both */
  559. return -1;
  560. }
  561. /* From now on, we use 'written' to remember the current length of 's'. */
  562. written = result;
  563. if (router->dir_port && !router->is_trusted_dir) {
  564. /* dircacheport wasn't recognized before 0.0.8pre. (When 0.0.7 is gone,
  565. * we can fold this back into dirport anyway.) */
  566. result = snprintf(s+written,maxlen-written, "opt dircacheport %d\n",
  567. router->dir_port);
  568. if (result<0 || result+written > maxlen)
  569. return -1;
  570. written += result;
  571. }
  572. if (options.ContactInfo && strlen(options.ContactInfo)) {
  573. result = snprintf(s+written,maxlen-written, "opt contact %s\n",
  574. options.ContactInfo);
  575. if (result<0 || result+written > maxlen)
  576. return -1;
  577. written += result;
  578. }
  579. /* Write the exit policy to the end of 's'. */
  580. for(tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
  581. in.s_addr = htonl(tmpe->addr);
  582. /* Write: "accept 1.2.3.4" */
  583. result = snprintf(s+written, maxlen-written, "%s %s",
  584. tmpe->policy_type == EXIT_POLICY_ACCEPT ? "accept" : "reject",
  585. tmpe->msk == 0 ? "*" : inet_ntoa(in));
  586. if(result < 0 || result+written > maxlen) {
  587. /* apparently different glibcs do different things on snprintf error.. so check both */
  588. return -1;
  589. }
  590. written += result;
  591. if (tmpe->msk != 0xFFFFFFFFu && tmpe->msk != 0) {
  592. /* Write "/255.255.0.0" */
  593. in.s_addr = htonl(tmpe->msk);
  594. result = snprintf(s+written, maxlen-written, "/%s", inet_ntoa(in));
  595. if (result<0 || result+written > maxlen)
  596. return -1;
  597. written += result;
  598. }
  599. if (tmpe->prt_min == 0 && tmpe->prt_max == 65535) {
  600. /* There is no port set; write ":*" */
  601. if (written > maxlen-4)
  602. return -1;
  603. strcat(s+written, ":*\n");
  604. written += 3;
  605. } else if (tmpe->prt_min == tmpe->prt_max) {
  606. /* There is only one port; write ":80". */
  607. result = snprintf(s+written, maxlen-written, ":%d\n", tmpe->prt_min);
  608. if (result<0 || result+written > maxlen)
  609. return -1;
  610. written += result;
  611. } else {
  612. /* There is a range of ports; write ":79-80". */
  613. result = snprintf(s+written, maxlen-written, ":%d-%d\n", tmpe->prt_min,
  614. tmpe->prt_max);
  615. if (result<0 || result+written > maxlen)
  616. return -1;
  617. written += result;
  618. }
  619. } /* end for */
  620. if (written > maxlen-256) /* Not enough room for signature. */
  621. return -1;
  622. /* Sign the directory */
  623. strcat(s+written, "router-signature\n");
  624. written += strlen(s+written);
  625. s[written] = '\0';
  626. if (router_get_router_hash(s, digest) < 0)
  627. return -1;
  628. if (crypto_pk_private_sign(ident_key, digest, 20, signature) < 0) {
  629. log_fn(LOG_WARN, "Error signing digest");
  630. return -1;
  631. }
  632. strcat(s+written, "-----BEGIN SIGNATURE-----\n");
  633. written += strlen(s+written);
  634. if (base64_encode(s+written, maxlen-written, signature, 128) < 0) {
  635. log_fn(LOG_WARN, "Couldn't base64-encode signature");
  636. return -1;
  637. }
  638. written += strlen(s+written);
  639. strcat(s+written, "-----END SIGNATURE-----\n");
  640. written += strlen(s+written);
  641. if (written > maxlen-2)
  642. return -1;
  643. /* include a last '\n' */
  644. s[written] = '\n';
  645. s[written+1] = 0;
  646. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  647. cp = s_tmp = s_dup = tor_strdup(s);
  648. ri_tmp = router_parse_entry_from_string(cp, NULL);
  649. if (!ri_tmp) {
  650. log_fn(LOG_ERR, "We just generated a router descriptor we can't parse: <<%s>>",
  651. s);
  652. return -1;
  653. }
  654. free(s_dup);
  655. routerinfo_free(ri_tmp);
  656. #endif
  657. return written+1;
  658. }
  659. /*
  660. Local Variables:
  661. mode:c
  662. indent-tabs-mode:nil
  663. c-basic-offset:2
  664. End:
  665. */