router.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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. /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist,
  112. * create a new RSA key and save it in <b>fname</b>. Return the read/created
  113. * key, or NULL on error.
  114. */
  115. crypto_pk_env_t *init_key_from_file(const char *fname)
  116. {
  117. crypto_pk_env_t *prkey = NULL;
  118. FILE *file = NULL;
  119. if (!(prkey = crypto_new_pk_env())) {
  120. log(LOG_ERR, "Error creating crypto environment.");
  121. goto error;
  122. }
  123. switch(file_status(fname)) {
  124. case FN_DIR:
  125. case FN_ERROR:
  126. log(LOG_ERR, "Can't read key from %s", fname);
  127. goto error;
  128. case FN_NOENT:
  129. log(LOG_INFO, "No key found in %s; generating fresh key.", fname);
  130. if (crypto_pk_generate_key(prkey)) {
  131. log(LOG_ERR, "Error generating onion key");
  132. goto error;
  133. }
  134. if (crypto_pk_check_key(prkey) <= 0) {
  135. log(LOG_ERR, "Generated key seems invalid");
  136. goto error;
  137. }
  138. log(LOG_INFO, "Generated key seems valid");
  139. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  140. log(LOG_ERR, "Couldn't write generated key to %s.", fname);
  141. goto error;
  142. }
  143. return prkey;
  144. case FN_FILE:
  145. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  146. log(LOG_ERR, "Error loading private key.");
  147. goto error;
  148. }
  149. return prkey;
  150. default:
  151. tor_assert(0);
  152. }
  153. error:
  154. if (prkey)
  155. crypto_free_pk_env(prkey);
  156. if (file)
  157. fclose(file);
  158. return NULL;
  159. }
  160. /** Initialize all OR private keys, and the TLS context, as necessary.
  161. * On OPs, this only initializes the tls context.
  162. */
  163. int init_keys(void) {
  164. char keydir[512];
  165. char fingerprint[FINGERPRINT_LEN+MAX_NICKNAME_LEN+3];
  166. char *cp;
  167. const char *tmp, *mydesc, *datadir;
  168. crypto_pk_env_t *prkey;
  169. if (!key_lock)
  170. key_lock = tor_mutex_new();
  171. /* OP's don't need keys. Just initialize the TLS context.*/
  172. if (!options.ORPort) {
  173. tor_assert(!options.DirPort);
  174. if (tor_tls_context_new(NULL, 0, NULL, 0)<0) {
  175. log_fn(LOG_ERR, "Error creating TLS context for OP.");
  176. return -1;
  177. }
  178. return 0;
  179. }
  180. /* Make sure DataDirectory exists, and is private. */
  181. datadir = get_data_directory(&options);
  182. tor_assert(datadir);
  183. if (strlen(datadir) > (512-128)) {
  184. log_fn(LOG_ERR, "DataDirectory is too long.");
  185. return -1;
  186. }
  187. if (check_private_dir(datadir, 1)) {
  188. return -1;
  189. }
  190. /* Check the key directory. */
  191. sprintf(keydir,"%s/keys", datadir);
  192. if (check_private_dir(keydir, 1)) {
  193. return -1;
  194. }
  195. cp = keydir + strlen(keydir); /* End of string. */
  196. /* 1. Read identity key. Make it if none is found. */
  197. strcpy(cp, "/identity.key");
  198. log_fn(LOG_INFO,"Reading/making identity key %s...",keydir);
  199. prkey = init_key_from_file(keydir);
  200. if (!prkey) return -1;
  201. set_identity_key(prkey);
  202. /* 2. Read onion key. Make it if none is found. */
  203. strcpy(cp, "/onion.key");
  204. log_fn(LOG_INFO,"Reading/making onion key %s...",keydir);
  205. prkey = init_key_from_file(keydir);
  206. if (!prkey) return -1;
  207. set_onion_key(prkey);
  208. /* 3. Initialize link key and TLS context. */
  209. if (tor_tls_context_new(get_identity_key(), 1, options.Nickname,
  210. MAX_SSL_KEY_LIFETIME) < 0) {
  211. log_fn(LOG_ERR, "Error initializing TLS context");
  212. return -1;
  213. }
  214. /* 4. Dump router descriptor to 'router.desc' */
  215. /* Must be called after keys are initialized. */
  216. if (!(router_get_my_descriptor())) {
  217. log_fn(LOG_ERR, "Error initializing descriptor.");
  218. return -1;
  219. }
  220. /* We need to add our own fingerprint so it gets recognized. */
  221. if (dirserv_add_own_fingerprint(options.Nickname, get_identity_key())) {
  222. log_fn(LOG_ERR, "Error adding own fingerprint to approved set");
  223. return -1;
  224. }
  225. tmp = mydesc = router_get_my_descriptor();
  226. if (dirserv_add_descriptor(&tmp) != 1) {
  227. log(LOG_ERR, "Unable to add own descriptor to directory.");
  228. return -1;
  229. }
  230. sprintf(keydir,"%s/router.desc", datadir);
  231. log_fn(LOG_INFO,"Dumping descriptor to %s...",keydir);
  232. if (write_str_to_file(keydir, mydesc)) {
  233. return -1;
  234. }
  235. /* 5. Dump fingerprint to 'fingerprint' */
  236. sprintf(keydir,"%s/fingerprint", datadir);
  237. log_fn(LOG_INFO,"Dumping fingerprint to %s...",keydir);
  238. tor_assert(strlen(options.Nickname) <= MAX_NICKNAME_LEN);
  239. strcpy(fingerprint, options.Nickname);
  240. strcat(fingerprint, " ");
  241. if (crypto_pk_get_fingerprint(get_identity_key(),
  242. fingerprint+strlen(fingerprint))<0) {
  243. log_fn(LOG_ERR, "Error computing fingerprint");
  244. return -1;
  245. }
  246. strcat(fingerprint, "\n");
  247. if (write_str_to_file(keydir, fingerprint))
  248. return -1;
  249. if(!options.DirPort)
  250. return 0;
  251. /* 6. [dirserver only] load approved-routers file */
  252. sprintf(keydir,"%s/approved-routers", datadir);
  253. log_fn(LOG_INFO,"Loading approved fingerprints from %s...",keydir);
  254. if(dirserv_parse_fingerprint_file(keydir) < 0) {
  255. log_fn(LOG_ERR, "Error loading fingerprints");
  256. return -1;
  257. }
  258. /* 7. [dirserver only] load old directory, if it's there */
  259. sprintf(keydir,"%s/cached-directory", datadir);
  260. log_fn(LOG_INFO,"Loading cached directory from %s...",keydir);
  261. cp = read_file_to_str(keydir);
  262. if(!cp) {
  263. log_fn(LOG_INFO,"Cached directory %s not present. Ok.",keydir);
  264. } else {
  265. if(options.AuthoritativeDir) {
  266. if(dirserv_load_from_directory_string(cp) < 0){
  267. log_fn(LOG_ERR, "Cached directory %s is corrupt", keydir);
  268. tor_free(cp);
  269. return -1;
  270. }
  271. } else {
  272. /* set time to 1 so it will be replaced on first download. */
  273. dirserv_set_cached_directory(cp, 1);
  274. }
  275. tor_free(cp);
  276. }
  277. /* success */
  278. return 0;
  279. }
  280. /*
  281. * Clique maintenance
  282. */
  283. /** OR only: try to open connections to all of the other ORs we know about.
  284. */
  285. void router_retry_connections(void) {
  286. int i;
  287. routerinfo_t *router;
  288. routerlist_t *rl;
  289. router_get_routerlist(&rl);
  290. for (i=0;i < smartlist_len(rl->routers);i++) {
  291. router = smartlist_get(rl->routers, i);
  292. if(router_is_me(router))
  293. continue;
  294. if(!connection_get_by_identity_digest(router->identity_digest,
  295. CONN_TYPE_OR)) {
  296. /* not in the list */
  297. log_fn(LOG_DEBUG,"connecting to OR %s:%u.",router->address,router->or_port);
  298. connection_or_connect(router->addr, router->or_port, router->identity_digest);
  299. }
  300. }
  301. }
  302. /*
  303. * OR descriptor generation.
  304. */
  305. /** My routerinfo. */
  306. static routerinfo_t *desc_routerinfo = NULL;
  307. /** String representation of my descriptor, signed by me. */
  308. static char descriptor[8192];
  309. /** OR only: try to upload our signed descriptor to all the directory servers
  310. * we know about.
  311. */
  312. void router_upload_dir_desc_to_dirservers(void) {
  313. const char *s;
  314. s = router_get_my_descriptor();
  315. if (!s) {
  316. log_fn(LOG_WARN, "No descriptor; skipping upload");
  317. return;
  318. }
  319. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR, s, strlen(s));
  320. }
  321. #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 *:*"
  322. /** Set the exit policy on <b>router</b> to match the exit policy in the
  323. * current configuration file. If the exit policy doesn't have a catch-all
  324. * rule, then append the default exit policy as well.
  325. */
  326. static void router_add_exit_policy_from_config(routerinfo_t *router) {
  327. struct exit_policy_t *ep;
  328. struct config_line_t default_policy;
  329. config_parse_exit_policy(options.ExitPolicy, &router->exit_policy);
  330. for (ep = router->exit_policy; ep; ep = ep->next) {
  331. if (ep->msk == 0 && ep->prt_min <= 1 && ep->prt_max >= 65535) {
  332. /* if exitpolicy includes a *:* line, then we're done. */
  333. return;
  334. }
  335. }
  336. /* Else, append the default exitpolicy. */
  337. default_policy.key = NULL;
  338. default_policy.value = DEFAULT_EXIT_POLICY;
  339. default_policy.next = NULL;
  340. config_parse_exit_policy(&default_policy, &router->exit_policy);
  341. }
  342. /** OR only: Return false if my exit policy says to allow connection to
  343. * conn. Else return true.
  344. */
  345. int router_compare_to_my_exit_policy(connection_t *conn)
  346. {
  347. tor_assert(desc_routerinfo);
  348. /* make sure it's resolved to something. this way we can't get a
  349. 'maybe' below. */
  350. if (!conn->addr)
  351. return -1;
  352. tor_assert(conn->addr);
  353. return router_compare_addr_to_exit_policy(conn->addr, conn->port,
  354. desc_routerinfo->exit_policy);
  355. }
  356. /** Return true iff <b>router</b> has the same nickname as this OR. (For an
  357. * OP, always returns false.)
  358. */
  359. int router_is_me(routerinfo_t *router)
  360. {
  361. tor_assert(router);
  362. /* XXXX008 should compare identity instead? */
  363. return options.Nickname && !strcasecmp(router->nickname, options.Nickname);
  364. }
  365. /** Return a routerinfo for this OR, rebuilding a fresh one if
  366. * necessary. Return NULL on error, or if called on an OP. */
  367. routerinfo_t *router_get_my_routerinfo(void)
  368. {
  369. if (!options.ORPort)
  370. return NULL;
  371. if (!desc_routerinfo) {
  372. if (router_rebuild_descriptor())
  373. return NULL;
  374. }
  375. return desc_routerinfo;
  376. }
  377. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  378. * one if necessary. Return NULL on error.
  379. */
  380. const char *router_get_my_descriptor(void) {
  381. if (!desc_routerinfo) {
  382. if (router_rebuild_descriptor())
  383. return NULL;
  384. }
  385. log_fn(LOG_DEBUG,"my desc is '%s'",descriptor);
  386. return descriptor;
  387. }
  388. /** Rebuild a fresh routerinfo and signed server descriptor for this
  389. * OR. Return 0 on success, -1 on error.
  390. */
  391. int router_rebuild_descriptor(void) {
  392. routerinfo_t *ri;
  393. struct in_addr addr;
  394. char platform[256];
  395. if (!tor_inet_aton(options.Address, &addr)) {
  396. log_fn(LOG_ERR, "options.Address didn't hold an IP.");
  397. return -1;
  398. }
  399. ri = tor_malloc_zero(sizeof(routerinfo_t));
  400. ri->address = tor_strdup(options.Address);
  401. ri->nickname = tor_strdup(options.Nickname);
  402. ri->addr = (uint32_t) ntohl(addr.s_addr);
  403. ri->or_port = options.ORPort;
  404. ri->socks_port = options.SocksPort;
  405. ri->dir_port = options.DirPort;
  406. ri->published_on = time(NULL);
  407. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from main thread */
  408. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  409. if (crypto_pk_get_digest(ri->identity_pkey, ri->identity_digest)<0) {
  410. routerinfo_free(ri);
  411. return -1;
  412. }
  413. get_platform_str(platform, sizeof(platform));
  414. ri->platform = tor_strdup(platform);
  415. ri->bandwidthrate = options.BandwidthRate;
  416. ri->bandwidthburst = options.BandwidthBurst;
  417. ri->exit_policy = NULL; /* zero it out first */
  418. router_add_exit_policy_from_config(ri);
  419. if (desc_routerinfo)
  420. routerinfo_free(desc_routerinfo);
  421. desc_routerinfo = ri;
  422. if (router_dump_router_to_string(descriptor, 8192, ri, get_identity_key())<0) {
  423. log_fn(LOG_WARN, "Couldn't dump router to string.");
  424. return -1;
  425. }
  426. if (ri->dir_port)
  427. ri->is_trusted_dir = 1;
  428. return 0;
  429. }
  430. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  431. * string describing the version of Tor and the operating system we're
  432. * currently running on.
  433. */
  434. void get_platform_str(char *platform, int len)
  435. {
  436. snprintf(platform, len-1, "Tor %s (up %ld sec) on %s",
  437. VERSION, stats_n_seconds_uptime, get_uname());
  438. platform[len-1] = '\0';
  439. return;
  440. }
  441. /* XXX need to audit this thing and count fenceposts. maybe
  442. * refactor so we don't have to keep asking if we're
  443. * near the end of maxlen?
  444. */
  445. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  446. /** OR only: Given a routerinfo for this router, and an identity key to sign
  447. * with, encode the routerinfo as a signed server descriptor and write the
  448. * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
  449. * failure, and the number of bytes used on success.
  450. */
  451. int router_dump_router_to_string(char *s, int maxlen, routerinfo_t *router,
  452. crypto_pk_env_t *ident_key) {
  453. char *onion_pkey; /* Onion key, PEM-encoded. */
  454. char *identity_pkey; /* Identity key, PEM-encoded. */
  455. char digest[20];
  456. char signature[128];
  457. char published[32];
  458. struct in_addr in;
  459. int onion_pkeylen, identity_pkeylen;
  460. int written;
  461. int result=0;
  462. struct exit_policy_t *tmpe;
  463. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  464. char *s_tmp, *s_dup;
  465. const char *cp;
  466. routerinfo_t *ri_tmp;
  467. #endif
  468. /* Make sure the identity key matches the one in the routerinfo. */
  469. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  470. log_fn(LOG_WARN,"Tried to sign a router with a private key that didn't match router's public key!");
  471. return -1;
  472. }
  473. /* PEM-encode the onion key */
  474. if(crypto_pk_write_public_key_to_string(router->onion_pkey,
  475. &onion_pkey,&onion_pkeylen)<0) {
  476. log_fn(LOG_WARN,"write onion_pkey to string failed!");
  477. return -1;
  478. }
  479. /* PEM-encode the identity key key */
  480. if(crypto_pk_write_public_key_to_string(router->identity_pkey,
  481. &identity_pkey,&identity_pkeylen)<0) {
  482. log_fn(LOG_WARN,"write identity_pkey to string failed!");
  483. tor_free(onion_pkey);
  484. return -1;
  485. }
  486. /* Encode the publication time. */
  487. strftime(published, 32, "%Y-%m-%d %H:%M:%S", gmtime(&router->published_on));
  488. /* Generate the easy portion of the router descriptor. */
  489. result = snprintf(s, maxlen,
  490. "router %s %s %d %d %d\n"
  491. "platform %s\n"
  492. "published %s\n"
  493. "bandwidth %d %d\n"
  494. "onion-key\n%s"
  495. "signing-key\n%s",
  496. router->nickname,
  497. router->address,
  498. router->or_port,
  499. router->socks_port,
  500. /* Due to an 0.0.7 bug, we can't actually say that we have a dirport unles
  501. * we're an authoritative directory.
  502. */
  503. router->is_trusted_dir ? router->dir_port : 0,
  504. router->platform,
  505. published,
  506. (int) router->bandwidthrate,
  507. (int) router->bandwidthburst,
  508. onion_pkey, identity_pkey);
  509. tor_free(onion_pkey);
  510. tor_free(identity_pkey);
  511. if(result < 0 || result >= maxlen) {
  512. /* apparently different glibcs do different things on snprintf error.. so check both */
  513. return -1;
  514. }
  515. /* From now on, we use 'written' to remember the current length of 's'. */
  516. written = result;
  517. if (router->dir_port && !router->is_trusted_dir) {
  518. /* dircacheport wasn't recognized before 0.0.8pre. (When 0.0.7 is gone,
  519. * we can fold this back into dirport anyway.) */
  520. result = snprintf(s+written,maxlen-written, "opt dircacheport %d\n",
  521. router->dir_port);
  522. if (result<0 || result+written > maxlen)
  523. return -1;
  524. written += result;
  525. }
  526. if (options.ContactInfo && strlen(options.ContactInfo)) {
  527. result = snprintf(s+written,maxlen-written, "opt contact %s\n",
  528. options.ContactInfo);
  529. if (result<0 || result+written > maxlen)
  530. return -1;
  531. written += result;
  532. }
  533. /* Write the exit policy to the end of 's'. */
  534. for(tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
  535. in.s_addr = htonl(tmpe->addr);
  536. /* Write: "accept 1.2.3.4" */
  537. result = snprintf(s+written, maxlen-written, "%s %s",
  538. tmpe->policy_type == EXIT_POLICY_ACCEPT ? "accept" : "reject",
  539. tmpe->msk == 0 ? "*" : inet_ntoa(in));
  540. if(result < 0 || result+written > maxlen) {
  541. /* apparently different glibcs do different things on snprintf error.. so check both */
  542. return -1;
  543. }
  544. written += result;
  545. if (tmpe->msk != 0xFFFFFFFFu && tmpe->msk != 0) {
  546. /* Write "/255.255.0.0" */
  547. in.s_addr = htonl(tmpe->msk);
  548. result = snprintf(s+written, maxlen-written, "/%s", inet_ntoa(in));
  549. if (result<0 || result+written > maxlen)
  550. return -1;
  551. written += result;
  552. }
  553. if (tmpe->prt_min == 0 && tmpe->prt_max == 65535) {
  554. /* There is no port set; write ":*" */
  555. if (written > maxlen-4)
  556. return -1;
  557. strcat(s+written, ":*\n");
  558. written += 3;
  559. } else if (tmpe->prt_min == tmpe->prt_max) {
  560. /* There is only one port; write ":80". */
  561. result = snprintf(s+written, maxlen-written, ":%d\n", tmpe->prt_min);
  562. if (result<0 || result+written > maxlen)
  563. return -1;
  564. written += result;
  565. } else {
  566. /* There is a range of ports; write ":79-80". */
  567. result = snprintf(s+written, maxlen-written, ":%d-%d\n", tmpe->prt_min,
  568. tmpe->prt_max);
  569. if (result<0 || result+written > maxlen)
  570. return -1;
  571. written += result;
  572. }
  573. } /* end for */
  574. if (written > maxlen-256) /* Not enough room for signature. */
  575. return -1;
  576. /* Sign the directory */
  577. strcat(s+written, "router-signature\n");
  578. written += strlen(s+written);
  579. s[written] = '\0';
  580. if (router_get_router_hash(s, digest) < 0)
  581. return -1;
  582. if (crypto_pk_private_sign(ident_key, digest, 20, signature) < 0) {
  583. log_fn(LOG_WARN, "Error signing digest");
  584. return -1;
  585. }
  586. strcat(s+written, "-----BEGIN SIGNATURE-----\n");
  587. written += strlen(s+written);
  588. if (base64_encode(s+written, maxlen-written, signature, 128) < 0) {
  589. log_fn(LOG_WARN, "Couldn't base64-encode signature");
  590. return -1;
  591. }
  592. written += strlen(s+written);
  593. strcat(s+written, "-----END SIGNATURE-----\n");
  594. written += strlen(s+written);
  595. if (written > maxlen-2)
  596. return -1;
  597. /* include a last '\n' */
  598. s[written] = '\n';
  599. s[written+1] = 0;
  600. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  601. cp = s_tmp = s_dup = tor_strdup(s);
  602. ri_tmp = router_parse_entry_from_string(cp, NULL);
  603. if (!ri_tmp) {
  604. log_fn(LOG_ERR, "We just generated a router descriptor we can't parse: <<%s>>",
  605. s);
  606. return -1;
  607. }
  608. free(s_dup);
  609. routerinfo_free(ri_tmp);
  610. #endif
  611. return written+1;
  612. }
  613. /*
  614. Local Variables:
  615. mode:c
  616. indent-tabs-mode:nil
  617. c-basic-offset:2
  618. End:
  619. */