connection_or.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. /**
  5. * \file connection_or.c
  6. * \brief Functions to handle OR connections, TLS handshaking, and
  7. * cells on the network.
  8. **/
  9. #include "or.h"
  10. extern or_options_t options; /**< command-line and config-file options */
  11. static int connection_tls_finish_handshake(connection_t *conn);
  12. static int connection_or_process_cells_from_inbuf(connection_t *conn);
  13. /**************************************************************/
  14. /** Pack the cell_t host-order structure <b>src</b> into network-order
  15. * in the buffer <b>dest</b>. See tor-spec.txt for details about the
  16. * wire format.
  17. */
  18. static void cell_pack(char *dest, const cell_t *src) {
  19. *(uint16_t*)dest = htons(src->circ_id);
  20. *(uint8_t*)(dest+2) = src->command;
  21. memcpy(dest+3, src->payload, CELL_PAYLOAD_SIZE);
  22. }
  23. /** Unpack the network-order buffer <b>src</b> into a host-order
  24. * cell_t structure <b>dest</b>.
  25. */
  26. static void cell_unpack(cell_t *dest, const char *src) {
  27. dest->circ_id = ntohs(*(uint16_t*)(src));
  28. dest->command = *(uint8_t*)(src+2);
  29. memcpy(dest->payload, src+3, CELL_PAYLOAD_SIZE);
  30. }
  31. /** Handle any new bytes that have come in on connection <b>conn</b>.
  32. * If conn is in 'open' state, hand it to
  33. * connection_or_process_cells_from_inbuf()
  34. * (else do nothing).
  35. */
  36. int connection_or_process_inbuf(connection_t *conn) {
  37. tor_assert(conn && conn->type == CONN_TYPE_OR);
  38. if(conn->inbuf_reached_eof) {
  39. log_fn(LOG_INFO,"OR connection reached EOF. Closing.");
  40. connection_mark_for_close(conn);
  41. return 0;
  42. }
  43. if(conn->state != OR_CONN_STATE_OPEN)
  44. return 0; /* don't do anything */
  45. return connection_or_process_cells_from_inbuf(conn);
  46. }
  47. /** Connection <b>conn</b> has finished writing and has no bytes left on
  48. * its outbuf.
  49. *
  50. * Otherwise it's in state "open": stop writing and return.
  51. *
  52. * If <b>conn</b> is broken, mark it for close and return -1, else
  53. * return 0.
  54. */
  55. int connection_or_finished_flushing(connection_t *conn) {
  56. tor_assert(conn && conn->type == CONN_TYPE_OR);
  57. assert_connection_ok(conn,0);
  58. if (conn->state != OR_CONN_STATE_OPEN) {
  59. log_fn(LOG_WARN,"BUG: called in unexpected state %d",conn->state);
  60. return -1;
  61. }
  62. connection_stop_writing(conn);
  63. return 0;
  64. }
  65. /** Connected handler for OR connections: begin the TLS handshake.
  66. */
  67. int connection_or_finished_connecting(connection_t *conn)
  68. {
  69. tor_assert(conn && conn->type == CONN_TYPE_OR);
  70. tor_assert(conn->state == OR_CONN_STATE_CONNECTING);
  71. log_fn(LOG_INFO,"OR connect() to router %s:%u finished.",
  72. conn->address,conn->port);
  73. if(connection_tls_start_handshake(conn, 0) < 0) {
  74. /* TLS handshaking error of some kind. */
  75. connection_mark_for_close(conn);
  76. return -1;
  77. }
  78. return 0;
  79. }
  80. /** Initialize <b>conn</b> to include all the relevant data from <b>router</b>.
  81. * This function is called either from connection_or_connect(), if
  82. * we initiated the connect, or from connection_tls_finish_handshake()
  83. * if the other side initiated it.
  84. */
  85. static void
  86. connection_or_init_conn_from_router(connection_t *conn, routerinfo_t *router) {
  87. conn->addr = router->addr;
  88. conn->port = router->or_port;
  89. conn->receiver_bucket = conn->bandwidth = router->bandwidthburst;
  90. conn->identity_pkey = crypto_pk_dup_key(router->identity_pkey);
  91. crypto_pk_get_digest(conn->identity_pkey, conn->identity_digest);
  92. conn->nickname = tor_strdup(router->nickname);
  93. tor_free(conn->address);
  94. conn->address = tor_strdup(router->address);
  95. }
  96. static void
  97. connection_or_init_conn_from_address(connection_t *conn,
  98. uint32_t addr, uint16_t port,
  99. const char *id_digest)
  100. {
  101. routerinfo_t *r;
  102. struct in_addr in;
  103. r = router_get_by_digest(id_digest);
  104. if (r) {
  105. connection_or_init_conn_from_router(conn,r);
  106. return;
  107. }
  108. conn->addr = addr;
  109. conn->port = port;
  110. /* This next part isn't really right, but it's good enough for now. */
  111. conn->receiver_bucket = conn->bandwidth = options.BandwidthBurst;
  112. memcpy(conn->identity_digest, id_digest, DIGEST_LEN);
  113. conn->nickname = tor_malloc(HEX_DIGEST_LEN+1);
  114. base16_encode(conn->nickname, HEX_DIGEST_LEN+1,
  115. conn->identity_digest, DIGEST_LEN);
  116. tor_free(conn->address);
  117. in.s_addr = htonl(addr);
  118. conn->address = tor_strdup(inet_ntoa(in));
  119. }
  120. /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
  121. * handshake with an OR with identity digest <b>id_digest</b>.
  122. *
  123. * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
  124. * return that connection. If the connect() is in progress, set the
  125. * new conn's state to 'connecting' and return it. If connect() succeeds,
  126. * call * connection_tls_start_handshake() on it.
  127. *
  128. * This function is called from router_retry_connections(), for
  129. * ORs connecting to ORs, and circuit_establish_circuit(), for
  130. * OPs connecting to ORs.
  131. *
  132. * Return the launched conn, or NULL if it failed.
  133. */
  134. connection_t *connection_or_connect(uint32_t addr, uint16_t port,
  135. const char *id_digest) {
  136. connection_t *conn;
  137. routerinfo_t *me;
  138. tor_assert(id_digest);
  139. if(server_mode() && (me=router_get_my_routerinfo()) &&
  140. !memcmp(me->identity_digest, id_digest,DIGEST_LEN)) {
  141. log_fn(LOG_WARN,"Request to connect to myself! Failing.");
  142. return NULL;
  143. }
  144. /* this function should never be called if we're already connected to
  145. * id_digest, but check first to be sure */
  146. /*XXX008 this is getting called, at least by dirservers. */
  147. conn = connection_get_by_identity_digest(id_digest, CONN_TYPE_OR);
  148. if(conn) {
  149. tor_assert(conn->nickname);
  150. log_fn(LOG_WARN,"Asked me to connect to %s, but there's already a connection.", conn->nickname);
  151. return conn;
  152. }
  153. conn = connection_new(CONN_TYPE_OR);
  154. /* set up conn so it's got all the data we need to remember */
  155. connection_or_init_conn_from_address(conn, addr, port, id_digest);
  156. conn->state = OR_CONN_STATE_CONNECTING;
  157. switch(connection_connect(conn, conn->address, addr, port)) {
  158. case -1:
  159. router_mark_as_down(conn->identity_digest);
  160. connection_free(conn);
  161. return NULL;
  162. case 0:
  163. connection_watch_events(conn, POLLIN | POLLOUT | POLLERR);
  164. /* writable indicates finish, readable indicates broken link,
  165. error indicates broken link on windows */
  166. return conn;
  167. /* case 1: fall through */
  168. }
  169. if(connection_tls_start_handshake(conn, 0) >= 0)
  170. return conn;
  171. /* failure */
  172. connection_mark_for_close(conn);
  173. return NULL;
  174. }
  175. /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
  176. * we initiated the connection, else it's 1.
  177. *
  178. * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and pass
  179. * <b>conn</b> to connection_tls_continue_handshake().
  180. *
  181. * Return -1 if <b>conn</b> is broken, else return 0.
  182. */
  183. int connection_tls_start_handshake(connection_t *conn, int receiving) {
  184. int use_no_cert=0;
  185. conn->state = OR_CONN_STATE_HANDSHAKING;
  186. if(receiving) { /* check if he's 0.0.7 and I'm unverified */
  187. routerinfo_t *him, *me;
  188. him = router_get_by_digest(conn->identity_digest);
  189. me = router_get_my_routerinfo();
  190. if(him && !tor_version_as_new_as(him->platform, "0.0.8pre1") &&
  191. (!me || !me->is_verified)) {
  192. log_fn(LOG_INFO,"He's running 0.0.7, and I'm unverified. Acting like OP.");
  193. use_no_cert = 1;
  194. }
  195. }
  196. conn->tls = tor_tls_new(conn->s, receiving, use_no_cert);
  197. if(!conn->tls) {
  198. log_fn(LOG_WARN,"tor_tls_new failed. Closing.");
  199. return -1;
  200. }
  201. connection_start_reading(conn);
  202. log_fn(LOG_DEBUG,"starting the handshake");
  203. if(connection_tls_continue_handshake(conn) < 0) {
  204. return -1;
  205. }
  206. return 0;
  207. }
  208. /** Move forward with the tls handshake. If it finishes, hand
  209. * <b>conn</b> to connection_tls_finish_handshake().
  210. *
  211. * Return -1 if <b>conn</b> is broken, else return 0.
  212. */
  213. int connection_tls_continue_handshake(connection_t *conn) {
  214. switch(tor_tls_handshake(conn->tls)) {
  215. case TOR_TLS_ERROR:
  216. case TOR_TLS_CLOSE:
  217. log_fn(LOG_INFO,"tls error. breaking.");
  218. return -1;
  219. case TOR_TLS_DONE:
  220. return connection_tls_finish_handshake(conn);
  221. case TOR_TLS_WANTWRITE:
  222. connection_start_writing(conn);
  223. log_fn(LOG_DEBUG,"wanted write");
  224. return 0;
  225. case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
  226. log_fn(LOG_DEBUG,"wanted read");
  227. return 0;
  228. }
  229. return 0;
  230. }
  231. static int digest_is_zero(const char *id) {
  232. char ZERO_DIGEST[DIGEST_LEN];
  233. memset(ZERO_DIGEST, 0, DIGEST_LEN);
  234. return !memcmp(ZERO_DIGEST, id, DIGEST_LEN);
  235. }
  236. /** The tls handshake is finished.
  237. *
  238. * Make sure we are happy with the person we just handshaked with:
  239. * If it's an OP (that is, it has no certificate), make sure I'm an OR.
  240. * If it's an OR (it has a certificate), make sure it has a recognized
  241. * nickname, and its cert is signed by the identity key of that nickname.
  242. * If I initiated the connection, make sure it's the right guy; and if
  243. * he initiated the connection, make sure he's not already connected.
  244. *
  245. * If he initiated the conn, also initialize conn from the information
  246. * in router.
  247. *
  248. * If either of us is an OP, set bandwidth to the default OP bandwidth.
  249. *
  250. * If all is successful and he's an OR, then call circuit_n_conn_done()
  251. * to handle events that have been pending on the tls handshake
  252. * completion, and set the directory to be dirty (only matters if I'm
  253. * an authdirserver).
  254. */
  255. static int
  256. connection_tls_finish_handshake(connection_t *conn) {
  257. routerinfo_t *router;
  258. char nickname[MAX_NICKNAME_LEN+1];
  259. connection_t *c;
  260. crypto_pk_env_t *identity_rcvd=NULL;
  261. char digest_rcvd[DIGEST_LEN];
  262. conn->state = OR_CONN_STATE_OPEN;
  263. connection_watch_events(conn, POLLIN);
  264. log_fn(LOG_DEBUG,"tls handshake done. verifying.");
  265. if (! tor_tls_peer_has_cert(conn->tls)) { /* It's an OP. */
  266. if (server_mode()) { /* I'm an OR; good. */
  267. conn->receiver_bucket = conn->bandwidth = DEFAULT_BANDWIDTH_OP;
  268. return 0;
  269. } else { /* Neither side sent a certificate: ouch. */
  270. log_fn(LOG_WARN,"Neither peer sent a cert! Closing.");
  271. return -1;
  272. }
  273. }
  274. /* Okay; the other side is an OR. */
  275. if (tor_tls_get_peer_cert_nickname(conn->tls, nickname, MAX_NICKNAME_LEN)) {
  276. log_fn(LOG_WARN,"Other side (%s:%d) has a cert without a valid nickname. Closing.",
  277. conn->address, conn->port);
  278. return -1;
  279. }
  280. log_fn(LOG_DEBUG, "Other side (%s:%d) claims to be '%s'", conn->address,
  281. conn->port, nickname);
  282. if(tor_tls_verify(conn->tls, &identity_rcvd) < 0) {
  283. log_fn(LOG_WARN,"Other side '%s' (%s:%d) has a cert but it's invalid. Closing.",
  284. nickname, conn->address, conn->port);
  285. return -1;
  286. }
  287. log_fn(LOG_DEBUG,"The router's cert is valid.");
  288. crypto_pk_get_digest(identity_rcvd, digest_rcvd);
  289. crypto_free_pk_env(identity_rcvd);
  290. router = router_get_by_nickname(nickname);
  291. if(router && /* we know this nickname */
  292. router->is_verified && /* make sure it's the right guy */
  293. memcmp(digest_rcvd, router->identity_digest, DIGEST_LEN) != 0) {
  294. log_fn(LOG_WARN, "Identity key not as expected for %s", nickname);
  295. return -1;
  296. }
  297. if (!digest_is_zero(conn->identity_digest)) {
  298. /* I initiated this connection. */
  299. if (strcasecmp(conn->nickname, nickname)) {
  300. log_fn(options.DirPort ? LOG_WARN : LOG_INFO,
  301. "Other side (%s:%d) is '%s', but we tried to connect to '%s'",
  302. conn->address, conn->port, nickname, conn->nickname);
  303. return -1;
  304. }
  305. } else {
  306. if((c=connection_get_by_identity_digest(digest_rcvd, CONN_TYPE_OR))) {
  307. log_fn(LOG_INFO,"Router %s is already connected on fd %d. Dropping fd %d.", nickname, c->s, conn->s);
  308. return -1;
  309. }
  310. connection_or_init_conn_from_address(conn,conn->addr,conn->port,digest_rcvd);
  311. }
  312. if (!server_mode()) { /* If I'm an OP... */
  313. conn->receiver_bucket = conn->bandwidth = DEFAULT_BANDWIDTH_OP;
  314. }
  315. directory_set_dirty();
  316. circuit_n_conn_done(conn, 1); /* send the pending creates, if any. */
  317. /* Note the success */
  318. rep_hist_note_connect_succeeded(conn->identity_digest, time(NULL));
  319. return 0;
  320. }
  321. /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s
  322. * outbuf.
  323. *
  324. * (Commented out) If it's an OR conn, and an entire TLS record is
  325. * ready, then try to flush the record now.
  326. */
  327. void connection_or_write_cell_to_buf(const cell_t *cell, connection_t *conn) {
  328. char networkcell[CELL_NETWORK_SIZE];
  329. char *n = networkcell;
  330. tor_assert(cell && conn);
  331. tor_assert(connection_speaks_cells(conn));
  332. cell_pack(n, cell);
  333. connection_write_to_buf(n, CELL_NETWORK_SIZE, conn);
  334. #if 0 /* commented out -- can we get away with not doing this,
  335. * because we're already round-robining in handle_read?
  336. */
  337. #define MIN_TLS_FLUSHLEN 15872
  338. /* openssl tls record size is 16383, this is close. The goal here is to
  339. * push data out as soon as we know there's enough for a tls record, so
  340. * during periods of high load we won't read the entire megabyte from
  341. * input before pushing any data out. */
  342. if(conn->outbuf_flushlen-CELL_NETWORK_SIZE < MIN_TLS_FLUSHLEN &&
  343. conn->outbuf_flushlen >= MIN_TLS_FLUSHLEN) {
  344. int extra = conn->outbuf_flushlen - MIN_TLS_FLUSHLEN;
  345. conn->outbuf_flushlen = MIN_TLS_FLUSHLEN;
  346. if(connection_handle_write(conn) < 0) {
  347. log_fn(LOG_WARN,"flushing failed.");
  348. return;
  349. }
  350. if(extra) {
  351. conn->outbuf_flushlen += extra;
  352. connection_start_writing(conn);
  353. }
  354. }
  355. #endif
  356. }
  357. /** Process cells from <b>conn</b>'s inbuf.
  358. *
  359. * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
  360. * and hand it to command_process_cell().
  361. *
  362. * Always return 0.
  363. */
  364. static int connection_or_process_cells_from_inbuf(connection_t *conn) {
  365. char buf[CELL_NETWORK_SIZE];
  366. cell_t cell;
  367. loop:
  368. log_fn(LOG_DEBUG,"%d: starting, inbuf_datalen %d (%d pending in tls object).",
  369. conn->s,(int)buf_datalen(conn->inbuf),tor_tls_get_pending_bytes(conn->tls));
  370. if(buf_datalen(conn->inbuf) < CELL_NETWORK_SIZE) /* entire response available? */
  371. return 0; /* not yet */
  372. connection_fetch_from_buf(buf, CELL_NETWORK_SIZE, conn);
  373. /* retrieve cell info from buf (create the host-order struct from the
  374. * network-order string) */
  375. cell_unpack(&cell, buf);
  376. command_process_cell(&cell, conn);
  377. goto loop; /* process the remainder of the buffer */
  378. }
  379. /*
  380. Local Variables:
  381. mode:c
  382. indent-tabs-mode:nil
  383. c-basic-offset:2
  384. End:
  385. */