connection_or.c 15 KB

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