Fix more leaks in unit tests.
[tor/rransom.git] / src / or / connection_or.c
blob2cd96688f23917bf84783b300c63d29fc539ca68
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2008, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 /* $Id$ */
7 const char connection_or_c_id[] =
8 "$Id$";
10 /**
11 * \file connection_or.c
12 * \brief Functions to handle OR connections, TLS handshaking, and
13 * cells on the network.
14 **/
16 #include "or.h"
18 static int connection_tls_finish_handshake(or_connection_t *conn);
19 static int connection_or_process_cells_from_inbuf(or_connection_t *conn);
20 static int connection_or_send_versions(or_connection_t *conn);
21 static int connection_init_or_handshake_state(or_connection_t *conn,
22 int started_here);
23 static int connection_or_check_valid_tls_handshake(or_connection_t *conn,
24 int started_here,
25 char *digest_rcvd_out);
27 /**************************************************************/
29 /** Map from identity digest of connected OR or desired OR to a connection_t
30 * with that identity digest. If there is more than one such connection_t,
31 * they form a linked list, with next_with_same_id as the next pointer. */
32 static digestmap_t *orconn_identity_map = NULL;
34 /** If conn is listed in orconn_identity_map, remove it, and clear
35 * conn->identity_digest. Otherwise do nothing. */
36 void
37 connection_or_remove_from_identity_map(or_connection_t *conn)
39 or_connection_t *tmp;
40 tor_assert(conn);
41 if (!orconn_identity_map)
42 return;
43 tmp = digestmap_get(orconn_identity_map, conn->identity_digest);
44 if (!tmp) {
45 if (!tor_digest_is_zero(conn->identity_digest)) {
46 log_warn(LD_BUG, "Didn't find connection '%s' on identity map when "
47 "trying to remove it.",
48 conn->nickname ? conn->nickname : "NULL");
50 return;
52 if (conn == tmp) {
53 if (conn->next_with_same_id)
54 digestmap_set(orconn_identity_map, conn->identity_digest,
55 conn->next_with_same_id);
56 else
57 digestmap_remove(orconn_identity_map, conn->identity_digest);
58 } else {
59 while (tmp->next_with_same_id) {
60 if (tmp->next_with_same_id == conn) {
61 tmp->next_with_same_id = conn->next_with_same_id;
62 break;
64 tmp = tmp->next_with_same_id;
67 memset(conn->identity_digest, 0, DIGEST_LEN);
68 conn->next_with_same_id = NULL;
71 /** Remove all entries from the identity-to-orconn map, and clear
72 * all identities in OR conns.*/
73 void
74 connection_or_clear_identity_map(void)
76 smartlist_t *conns = get_connection_array();
77 SMARTLIST_FOREACH(conns, connection_t *, conn,
79 if (conn->type == CONN_TYPE_OR) {
80 or_connection_t *or_conn = TO_OR_CONN(conn);
81 memset(or_conn->identity_digest, 0, DIGEST_LEN);
82 or_conn->next_with_same_id = NULL;
84 });
86 if (orconn_identity_map) {
87 digestmap_free(orconn_identity_map, NULL);
88 orconn_identity_map = NULL;
92 /** Change conn->identity_digest to digest, and add conn into
93 * orconn_digest_map. */
94 static void
95 connection_or_set_identity_digest(or_connection_t *conn, const char *digest)
97 or_connection_t *tmp;
98 tor_assert(conn);
99 tor_assert(digest);
101 if (!orconn_identity_map)
102 orconn_identity_map = digestmap_new();
103 if (!memcmp(conn->identity_digest, digest, DIGEST_LEN))
104 return;
106 /* If the identity was set previously, remove the old mapping. */
107 if (! tor_digest_is_zero(conn->identity_digest))
108 connection_or_remove_from_identity_map(conn);
110 memcpy(conn->identity_digest, digest, DIGEST_LEN);
112 /* If we're setting the ID to zero, don't add a mapping. */
113 if (tor_digest_is_zero(digest))
114 return;
116 tmp = digestmap_set(orconn_identity_map, digest, conn);
117 conn->next_with_same_id = tmp;
119 #if 1
120 /* Testing code to check for bugs in representation. */
121 for (; tmp; tmp = tmp->next_with_same_id) {
122 tor_assert(!memcmp(tmp->identity_digest, digest, DIGEST_LEN));
123 tor_assert(tmp != conn);
125 #endif
128 /** Pack the cell_t host-order structure <b>src</b> into network-order
129 * in the buffer <b>dest</b>. See tor-spec.txt for details about the
130 * wire format.
132 * Note that this function doesn't touch <b>dst</b>-\>next: the caller
133 * should set it or clear it as appropriate.
135 void
136 cell_pack(packed_cell_t *dst, const cell_t *src)
138 char *dest = dst->body;
139 *(uint16_t*)dest = htons(src->circ_id);
140 *(uint8_t*)(dest+2) = src->command;
141 memcpy(dest+3, src->payload, CELL_PAYLOAD_SIZE);
144 /** Unpack the network-order buffer <b>src</b> into a host-order
145 * cell_t structure <b>dest</b>.
147 static void
148 cell_unpack(cell_t *dest, const char *src)
150 dest->circ_id = ntohs(*(uint16_t*)(src));
151 dest->command = *(uint8_t*)(src+2);
152 memcpy(dest->payload, src+3, CELL_PAYLOAD_SIZE);
155 /** Write the header of <b>cell</b> into the first VAR_CELL_HEADER_SIZE
156 * bytes of <b>hdr_out</b>. */
157 void
158 var_cell_pack_header(const var_cell_t *cell, char *hdr_out)
160 set_uint16(hdr_out, htons(cell->circ_id));
161 set_uint8(hdr_out+2, cell->command);
162 set_uint16(hdr_out+3, htons(cell->payload_len));
165 /** Allocate and return a new var_cell_t with <b>payload_len</b> bytes of
166 * payload space. */
167 var_cell_t *
168 var_cell_new(uint16_t payload_len)
170 var_cell_t *cell = tor_malloc(sizeof(var_cell_t)+payload_len-1);
171 cell->payload_len = payload_len;
172 cell->command = 0;
173 cell->circ_id = 0;
174 return cell;
177 /** Release all space held by <b>cell</b>. */
178 void
179 var_cell_free(var_cell_t *cell)
181 tor_free(cell);
184 /** We've received an EOF from <b>conn</b>. Mark it for close and return. */
186 connection_or_reached_eof(or_connection_t *conn)
188 log_info(LD_OR,"OR connection reached EOF. Closing.");
189 connection_mark_for_close(TO_CONN(conn));
190 return 0;
193 /** Read conn's inbuf. If the http response from the proxy is all
194 * here, make sure it's good news, and begin the tls handshake. If
195 * it's bad news, close the connection and return -1. Else return 0
196 * and hope for better luck next time.
198 static int
199 connection_or_read_proxy_response(or_connection_t *or_conn)
201 char *headers;
202 char *reason=NULL;
203 int status_code;
204 time_t date_header;
205 connection_t *conn = TO_CONN(or_conn);
207 switch (fetch_from_buf_http(conn->inbuf,
208 &headers, MAX_HEADERS_SIZE,
209 NULL, NULL, 10000, 0)) {
210 case -1: /* overflow */
211 log_warn(LD_PROTOCOL,
212 "Your https proxy sent back an oversized response. Closing.");
213 return -1;
214 case 0:
215 log_info(LD_OR,"https proxy response not all here yet. Waiting.");
216 return 0;
217 /* case 1, fall through */
220 if (parse_http_response(headers, &status_code, &date_header,
221 NULL, &reason) < 0) {
222 log_warn(LD_OR,
223 "Unparseable headers from proxy (connecting to '%s'). Closing.",
224 conn->address);
225 tor_free(headers);
226 return -1;
228 if (!reason) reason = tor_strdup("[no reason given]");
230 if (status_code == 200) {
231 log_info(LD_OR,
232 "HTTPS connect to '%s' successful! (200 %s) Starting TLS.",
233 conn->address, escaped(reason));
234 tor_free(reason);
235 if (connection_tls_start_handshake(or_conn, 0) < 0) {
236 /* TLS handshaking error of some kind. */
237 connection_mark_for_close(conn);
239 return -1;
241 return 0;
243 /* else, bad news on the status code */
244 log_warn(LD_OR,
245 "The https proxy sent back an unexpected status code %d (%s). "
246 "Closing.",
247 status_code, escaped(reason));
248 tor_free(reason);
249 connection_mark_for_close(conn);
250 return -1;
253 /** Handle any new bytes that have come in on connection <b>conn</b>.
254 * If conn is in 'open' state, hand it to
255 * connection_or_process_cells_from_inbuf()
256 * (else do nothing).
259 connection_or_process_inbuf(or_connection_t *conn)
261 tor_assert(conn);
263 switch (conn->_base.state) {
264 case OR_CONN_STATE_PROXY_READING:
265 return connection_or_read_proxy_response(conn);
266 case OR_CONN_STATE_OPEN:
267 case OR_CONN_STATE_OR_HANDSHAKING:
268 return connection_or_process_cells_from_inbuf(conn);
269 default:
270 return 0; /* don't do anything */
274 /** When adding cells to an OR connection's outbuf, keep adding until the
275 * outbuf is at least this long, or we run out of cells. */
276 #define OR_CONN_HIGHWATER (32*1024)
278 /** Add cells to an OR connection's outbuf whenever the outbuf's data length
279 * drops below this size. */
280 #define OR_CONN_LOWWATER (16*1024)
282 /** Called whenever we have flushed some data on an or_conn: add more data
283 * from active circuits. */
285 connection_or_flushed_some(or_connection_t *conn)
287 size_t datalen = buf_datalen(conn->_base.outbuf);
288 time_t now = time(NULL);
289 /* If we're under the low water mark, add cells until we're just over the
290 * high water mark. */
291 if (datalen < OR_CONN_LOWWATER) {
292 ssize_t n = (OR_CONN_HIGHWATER - datalen + CELL_NETWORK_SIZE-1)
293 / CELL_NETWORK_SIZE;
294 while (conn->active_circuits && n > 0) {
295 int flushed;
296 flushed = connection_or_flush_from_first_active_circuit(conn, 1, now);
297 n -= flushed;
300 return 0;
303 /** Connection <b>conn</b> has finished writing and has no bytes left on
304 * its outbuf.
306 * Otherwise it's in state "open": stop writing and return.
308 * If <b>conn</b> is broken, mark it for close and return -1, else
309 * return 0.
312 connection_or_finished_flushing(or_connection_t *conn)
314 tor_assert(conn);
315 assert_connection_ok(TO_CONN(conn),0);
317 switch (conn->_base.state) {
318 case OR_CONN_STATE_PROXY_FLUSHING:
319 log_debug(LD_OR,"finished sending CONNECT to proxy.");
320 conn->_base.state = OR_CONN_STATE_PROXY_READING;
321 connection_stop_writing(TO_CONN(conn));
322 break;
323 case OR_CONN_STATE_OPEN:
324 case OR_CONN_STATE_OR_HANDSHAKING:
325 connection_stop_writing(TO_CONN(conn));
326 break;
327 default:
328 log_err(LD_BUG,"Called in unexpected state %d.", conn->_base.state);
329 tor_fragile_assert();
330 return -1;
332 return 0;
335 /** Connected handler for OR connections: begin the TLS handshake.
338 connection_or_finished_connecting(or_connection_t *or_conn)
340 connection_t *conn;
341 tor_assert(or_conn);
342 conn = TO_CONN(or_conn);
343 tor_assert(conn->state == OR_CONN_STATE_CONNECTING);
345 log_debug(LD_OR,"OR connect() to router at %s:%u finished.",
346 conn->address,conn->port);
347 control_event_bootstrap(BOOTSTRAP_STATUS_HANDSHAKE, 0);
349 if (get_options()->HttpsProxy) {
350 char buf[1024];
351 char *base64_authenticator=NULL;
352 const char *authenticator = get_options()->HttpsProxyAuthenticator;
354 if (authenticator) {
355 base64_authenticator = alloc_http_authenticator(authenticator);
356 if (!base64_authenticator)
357 log_warn(LD_OR, "Encoding https authenticator failed");
359 if (base64_authenticator) {
360 tor_snprintf(buf, sizeof(buf), "CONNECT %s:%d HTTP/1.1\r\n"
361 "Proxy-Authorization: Basic %s\r\n\r\n",
362 fmt_addr(&conn->addr),
363 conn->port, base64_authenticator);
364 tor_free(base64_authenticator);
365 } else {
366 tor_snprintf(buf, sizeof(buf), "CONNECT %s:%d HTTP/1.0\r\n\r\n",
367 fmt_addr(&conn->addr), conn->port);
369 connection_write_to_buf(buf, strlen(buf), conn);
370 conn->state = OR_CONN_STATE_PROXY_FLUSHING;
371 return 0;
374 if (connection_tls_start_handshake(or_conn, 0) < 0) {
375 /* TLS handshaking error of some kind. */
376 connection_mark_for_close(conn);
377 return -1;
379 return 0;
382 /** If we don't necessarily know the router we're connecting to, but we
383 * have an addr/port/id_digest, then fill in as much as we can. Start
384 * by checking to see if this describes a router we know. */
385 static void
386 connection_or_init_conn_from_address(or_connection_t *conn,
387 const tor_addr_t *addr, uint16_t port,
388 const char *id_digest,
389 int started_here)
391 or_options_t *options = get_options();
392 routerinfo_t *r = router_get_by_digest(id_digest);
393 conn->bandwidthrate = (int)options->BandwidthRate;
394 conn->read_bucket = conn->bandwidthburst = (int)options->BandwidthBurst;
395 connection_or_set_identity_digest(conn, id_digest);
397 conn->_base.port = port;
398 tor_addr_copy(&conn->_base.addr, addr);
399 tor_addr_copy(&conn->real_addr, addr);
400 if (r) {
401 /* XXXX021 proposal 118 will make this more complex. */
402 if (tor_addr_eq_ipv4h(&conn->_base.addr, r->addr))
403 conn->is_canonical = 1;
404 if (!started_here) {
405 /* Override the addr/port, so our log messages will make sense.
406 * This is dangerous, since if we ever try looking up a conn by
407 * its actual addr/port, we won't remember. Careful! */
408 /* XXXX021 arma: this is stupid, and it's the reason we need real_addr
409 * to track is_canonical properly. What requires it? */
410 /* XXXX <arma> i believe the reason we did this, originally, is because
411 * we wanted to log what OR a connection was to, and if we logged the
412 * right IP address and port 56244, that wouldn't be as helpful. now we
413 * log the "right" port too, so we know if it's moria1 or moria2.
415 tor_addr_from_ipv4h(&conn->_base.addr, r->addr);
416 conn->_base.port = r->or_port;
418 conn->nickname = tor_strdup(r->nickname);
419 tor_free(conn->_base.address);
420 conn->_base.address = tor_strdup(r->address);
421 } else {
422 const char *n;
423 /* If we're an authoritative directory server, we may know a
424 * nickname for this router. */
425 n = dirserv_get_nickname_by_digest(id_digest);
426 if (n) {
427 conn->nickname = tor_strdup(n);
428 } else {
429 conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
430 conn->nickname[0] = '$';
431 base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
432 conn->identity_digest, DIGEST_LEN);
434 tor_free(conn->_base.address);
435 conn->_base.address = tor_dup_addr(addr);
439 /** Return the best connection of type OR with the
440 * digest <b>digest</b> that we have, or NULL if we have none.
442 * 1) Don't return it if it's marked for close.
443 * 2) If there are any open conns, ignore non-open conns.
444 * 3) If there are any non-obsolete conns, ignore obsolete conns.
445 * 4) Then if there are any non-empty conns, ignore empty conns.
446 * 5) Of the remaining conns, prefer newer conns.
448 or_connection_t *
449 connection_or_get_by_identity_digest(const char *digest)
451 int newer;
452 or_connection_t *conn, *best=NULL;
454 if (!orconn_identity_map)
455 return NULL;
457 conn = digestmap_get(orconn_identity_map, digest);
459 for (; conn; conn = conn->next_with_same_id) {
460 tor_assert(conn->_base.magic == OR_CONNECTION_MAGIC);
461 tor_assert(conn->_base.type == CONN_TYPE_OR);
462 tor_assert(!memcmp(conn->identity_digest, digest, DIGEST_LEN));
463 if (conn->_base.marked_for_close)
464 continue;
465 if (!best) {
466 best = conn; /* whatever it is, it's better than nothing. */
467 continue;
469 if (best->_base.state == OR_CONN_STATE_OPEN &&
470 conn->_base.state != OR_CONN_STATE_OPEN)
471 continue; /* avoid non-open conns if we can */
472 newer = best->_base.timestamp_created < conn->_base.timestamp_created;
474 if (best->is_canonical && !conn->is_canonical)
475 continue; /* A canonical connection is best. */
477 if (!best->is_bad_for_new_circs && conn->is_bad_for_new_circs)
478 continue; /* We never prefer obsolete over non-obsolete connections. */
480 if (
481 /* We prefer canonical connections: */
482 (!best->is_canonical && conn->is_canonical) ||
483 /* We prefer non-obsolete connections: */
484 (best->is_bad_for_new_circs && !conn->is_bad_for_new_circs) ||
485 /* If both have circuits we prefer the newer: */
486 (best->n_circuits && conn->n_circuits && newer) ||
487 /* If neither has circuits we prefer the newer: */
488 (!best->n_circuits && !conn->n_circuits && newer) ||
489 /* We prefer connections with circuits: */
490 (!best->n_circuits && conn->n_circuits)) {
491 best = conn;
494 return best;
497 /** <b>conn</b> is in the 'connecting' state, and it failed to complete
498 * a TCP connection. Send notifications appropriately.
500 * <b>reason</b> specifies the or_conn_end_reason for the failure;
501 * <b>msg</b> specifies the strerror-style error message.
503 void
504 connection_or_connect_failed(or_connection_t *conn,
505 int reason, const char *msg)
507 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED, reason);
508 if (!authdir_mode_tests_reachability(get_options()))
509 control_event_bootstrap_problem(msg, reason);
512 /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
513 * handshake with an OR with identity digest <b>id_digest</b>.
515 * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
516 * return that connection. If the connect() is in progress, set the
517 * new conn's state to 'connecting' and return it. If connect() succeeds,
518 * call connection_tls_start_handshake() on it.
520 * This function is called from router_retry_connections(), for
521 * ORs connecting to ORs, and circuit_establish_circuit(), for
522 * OPs connecting to ORs.
524 * Return the launched conn, or NULL if it failed.
526 or_connection_t *
527 connection_or_connect(const tor_addr_t *_addr, uint16_t port,
528 const char *id_digest)
530 or_connection_t *conn;
531 or_options_t *options = get_options();
532 int socket_error = 0;
533 tor_addr_t addr;
535 tor_assert(_addr);
536 tor_assert(id_digest);
537 tor_addr_copy(&addr, _addr);
539 if (server_mode(options) && router_digest_is_me(id_digest)) {
540 log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
541 return NULL;
544 conn = or_connection_new(AF_INET);
546 /* set up conn so it's got all the data we need to remember */
547 connection_or_init_conn_from_address(conn, &addr, port, id_digest, 1);
548 conn->_base.state = OR_CONN_STATE_CONNECTING;
549 control_event_or_conn_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
551 if (options->HttpsProxy) {
552 /* we shouldn't connect directly. use the https proxy instead. */
553 tor_addr_from_ipv4h(&addr, options->HttpsProxyAddr);
554 port = options->HttpsProxyPort;
557 switch (connection_connect(TO_CONN(conn), conn->_base.address,
558 &addr, port, &socket_error)) {
559 case -1:
560 /* If the connection failed immediately, and we're using
561 * an https proxy, our https proxy is down. Don't blame the
562 * Tor server. */
563 if (!options->HttpsProxy) {
564 entry_guard_register_connect_status(conn->identity_digest, 0,
565 time(NULL));
566 router_set_status(conn->identity_digest, 0);
568 connection_or_connect_failed(conn,
569 errno_to_orconn_end_reason(socket_error),
570 tor_socket_strerror(socket_error));
571 connection_free(TO_CONN(conn));
572 return NULL;
573 case 0:
574 connection_watch_events(TO_CONN(conn), EV_READ | EV_WRITE);
575 /* writable indicates finish, readable indicates broken link,
576 error indicates broken link on windows */
577 return conn;
578 /* case 1: fall through */
581 if (connection_or_finished_connecting(conn) < 0) {
582 /* already marked for close */
583 return NULL;
585 return conn;
588 /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
589 * we initiated the connection, else it's 1.
591 * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
592 * pass <b>conn</b> to connection_tls_continue_handshake().
594 * Return -1 if <b>conn</b> is broken, else return 0.
597 connection_tls_start_handshake(or_connection_t *conn, int receiving)
599 conn->_base.state = OR_CONN_STATE_TLS_HANDSHAKING;
600 conn->tls = tor_tls_new(conn->_base.s, receiving);
601 tor_tls_set_logged_address(conn->tls, escaped_safe_str(conn->_base.address));
602 if (!conn->tls) {
603 log_warn(LD_BUG,"tor_tls_new failed. Closing.");
604 return -1;
606 connection_start_reading(TO_CONN(conn));
607 log_debug(LD_OR,"starting TLS handshake on fd %d", conn->_base.s);
608 note_crypto_pk_op(receiving ? TLS_HANDSHAKE_S : TLS_HANDSHAKE_C);
610 if (connection_tls_continue_handshake(conn) < 0) {
611 return -1;
613 return 0;
616 /** Invoked on the server side from inside tor_tls_read() when the server
617 * gets a successful TLS renegotiation from the client. */
618 static void
619 connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn)
621 or_connection_t *conn = _conn;
622 (void)tls;
624 /* Don't invoke this again. */
625 tor_tls_set_renegotiate_callback(tls, NULL, NULL);
627 if (connection_tls_finish_handshake(conn) < 0) {
628 /* XXXX_TLS double-check that it's ok to do this from inside read. */
629 /* XXXX_TLS double-check that this verifies certificates. */
630 connection_mark_for_close(TO_CONN(conn));
634 /** Move forward with the tls handshake. If it finishes, hand
635 * <b>conn</b> to connection_tls_finish_handshake().
637 * Return -1 if <b>conn</b> is broken, else return 0.
640 connection_tls_continue_handshake(or_connection_t *conn)
642 int result;
643 check_no_tls_errors();
644 again:
645 if (conn->_base.state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
646 // log_notice(LD_OR, "Renegotiate with %p", conn->tls);
647 result = tor_tls_renegotiate(conn->tls);
648 // log_notice(LD_OR, "Result: %d", result);
649 } else {
650 tor_assert(conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING);
651 // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
652 result = tor_tls_handshake(conn->tls);
653 // log_notice(LD_OR, "Result: %d", result);
655 switch (result) {
656 CASE_TOR_TLS_ERROR_ANY:
657 log_info(LD_OR,"tls error [%s]. breaking connection.",
658 tor_tls_err_to_string(result));
659 return -1;
660 case TOR_TLS_DONE:
661 if (! tor_tls_used_v1_handshake(conn->tls)) {
662 if (!tor_tls_is_server(conn->tls)) {
663 if (conn->_base.state == OR_CONN_STATE_TLS_HANDSHAKING) {
664 // log_notice(LD_OR,"Done. state was TLS_HANDSHAKING.");
665 conn->_base.state = OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING;
666 goto again;
668 // log_notice(LD_OR,"Done. state was %d.", conn->_base.state);
669 } else {
670 /* improved handshake, but not a client. */
671 tor_tls_set_renegotiate_callback(conn->tls,
672 connection_or_tls_renegotiated_cb,
673 conn);
674 conn->_base.state = OR_CONN_STATE_TLS_SERVER_RENEGOTIATING;
675 connection_stop_writing(TO_CONN(conn));
676 connection_start_reading(TO_CONN(conn));
677 return 0;
680 return connection_tls_finish_handshake(conn);
681 case TOR_TLS_WANTWRITE:
682 connection_start_writing(TO_CONN(conn));
683 log_debug(LD_OR,"wanted write");
684 return 0;
685 case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
686 log_debug(LD_OR,"wanted read");
687 return 0;
688 case TOR_TLS_CLOSE:
689 log_info(LD_OR,"tls closed. breaking connection.");
690 return -1;
692 return 0;
695 /** Return 1 if we initiated this connection, or 0 if it started
696 * out as an incoming connection.
699 connection_or_nonopen_was_started_here(or_connection_t *conn)
701 tor_assert(conn->_base.type == CONN_TYPE_OR);
702 if (!conn->tls)
703 return 1; /* it's still in proxy states or something */
704 if (conn->handshake_state)
705 return conn->handshake_state->started_here;
706 return !tor_tls_is_server(conn->tls);
709 /** <b>Conn</b> just completed its handshake. Return 0 if all is well, and
710 * return -1 if he is lying, broken, or otherwise something is wrong.
712 * If we initiated this connection (<b>started_here</b> is true), make sure
713 * the other side sent sent a correctly formed certificate. If I initiated the
714 * connection, make sure it's the right guy.
716 * Otherwise (if we _didn't_ initiate this connection), it's okay for
717 * the certificate to be weird or absent.
719 * If we return 0, and the certificate is as expected, write a hash of the
720 * identity key into digest_rcvd, which must have DIGEST_LEN space in it. (If
721 * we return -1 this buffer is undefined.) If the certificate is invalid
722 * or missing on an incoming connection, we return 0 and set digest_rcvd to
723 * DIGEST_LEN 0 bytes.
725 * As side effects,
726 * 1) Set conn->circ_id_type according to tor-spec.txt.
727 * 2) If we're an authdirserver and we initiated the connection: drop all
728 * descriptors that claim to be on that IP/port but that aren't
729 * this guy; and note that this guy is reachable.
731 static int
732 connection_or_check_valid_tls_handshake(or_connection_t *conn,
733 int started_here,
734 char *digest_rcvd_out)
736 crypto_pk_env_t *identity_rcvd=NULL;
737 or_options_t *options = get_options();
738 int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
739 const char *safe_address =
740 started_here ? conn->_base.address : safe_str(conn->_base.address);
741 const char *conn_type = started_here ? "outgoing" : "incoming";
742 int has_cert = 0, has_identity=0;
744 check_no_tls_errors();
745 has_cert = tor_tls_peer_has_cert(conn->tls);
746 if (started_here && !has_cert) {
747 log_info(LD_PROTOCOL,"Tried connecting to router at %s:%d, but it didn't "
748 "send a cert! Closing.",
749 safe_address, conn->_base.port);
750 return -1;
751 } else if (!has_cert) {
752 log_debug(LD_PROTOCOL,"Got incoming connection with no certificate. "
753 "That's ok.");
755 check_no_tls_errors();
757 if (has_cert) {
758 int v = tor_tls_verify(started_here?severity:LOG_INFO,
759 conn->tls, &identity_rcvd);
760 if (started_here && v<0) {
761 log_fn(severity,LD_OR,"Tried connecting to router at %s:%d: It"
762 " has a cert but it's invalid. Closing.",
763 safe_address, conn->_base.port);
764 return -1;
765 } else if (v<0) {
766 log_info(LD_PROTOCOL,"Incoming connection gave us an invalid cert "
767 "chain; ignoring.");
768 } else {
769 log_debug(LD_OR,"The certificate seems to be valid on %s connection "
770 "with %s:%d", conn_type, safe_address, conn->_base.port);
772 check_no_tls_errors();
775 if (identity_rcvd) {
776 has_identity = 1;
777 crypto_pk_get_digest(identity_rcvd, digest_rcvd_out);
778 if (crypto_pk_cmp_keys(get_identity_key(), identity_rcvd)<0) {
779 conn->circ_id_type = CIRC_ID_TYPE_LOWER;
780 } else {
781 conn->circ_id_type = CIRC_ID_TYPE_HIGHER;
783 crypto_free_pk_env(identity_rcvd);
784 } else {
785 memset(digest_rcvd_out, 0, DIGEST_LEN);
786 conn->circ_id_type = CIRC_ID_TYPE_NEITHER;
789 if (started_here && tor_digest_is_zero(conn->identity_digest)) {
790 connection_or_set_identity_digest(conn, digest_rcvd_out);
791 tor_free(conn->nickname);
792 conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
793 conn->nickname[0] = '$';
794 base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
795 conn->identity_digest, DIGEST_LEN);
796 log_info(LD_OR, "Connected to router %s at %s:%d without knowing "
797 "its key. Hoping for the best.",
798 conn->nickname, conn->_base.address, conn->_base.port);
801 if (started_here) {
802 int as_advertised = 1;
803 tor_assert(has_cert);
804 tor_assert(has_identity);
805 if (memcmp(digest_rcvd_out, conn->identity_digest, DIGEST_LEN)) {
806 /* I was aiming for a particular digest. I didn't get it! */
807 char seen[HEX_DIGEST_LEN+1];
808 char expected[HEX_DIGEST_LEN+1];
809 base16_encode(seen, sizeof(seen), digest_rcvd_out, DIGEST_LEN);
810 base16_encode(expected, sizeof(expected), conn->identity_digest,
811 DIGEST_LEN);
812 log_fn(severity, LD_OR,
813 "Tried connecting to router at %s:%d, but identity key was not "
814 "as expected: wanted %s but got %s.",
815 conn->_base.address, conn->_base.port, expected, seen);
816 entry_guard_register_connect_status(conn->identity_digest,0,time(NULL));
817 router_set_status(conn->identity_digest, 0);
818 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED,
819 END_OR_CONN_REASON_OR_IDENTITY);
820 if (!authdir_mode_tests_reachability(options))
821 control_event_bootstrap_problem("foo", END_OR_CONN_REASON_OR_IDENTITY);
822 as_advertised = 0;
824 if (authdir_mode_tests_reachability(options)) {
825 /* We initiated this connection to address:port. Drop all routers
826 * with the same address:port and a different key.
828 dirserv_orconn_tls_done(conn->_base.address, conn->_base.port,
829 digest_rcvd_out, as_advertised);
831 if (!as_advertised)
832 return -1;
834 return 0;
837 /** The tls handshake is finished.
839 * Make sure we are happy with the person we just handshaked with.
841 * If he initiated the connection, make sure he's not already connected,
842 * then initialize conn from the information in router.
844 * If all is successful, call circuit_n_conn_done() to handle events
845 * that have been pending on the <tls handshake completion. Also set the
846 * directory to be dirty (only matters if I'm an authdirserver).
848 static int
849 connection_tls_finish_handshake(or_connection_t *conn)
851 char digest_rcvd[DIGEST_LEN];
852 int started_here = connection_or_nonopen_was_started_here(conn);
854 log_debug(LD_OR,"tls handshake with %s done. verifying.",
855 safe_str(conn->_base.address));
857 directory_set_dirty();
859 if (connection_or_check_valid_tls_handshake(conn, started_here,
860 digest_rcvd) < 0)
861 return -1;
863 if (tor_tls_used_v1_handshake(conn->tls)) {
864 conn->link_proto = 1;
865 if (!started_here) {
866 connection_or_init_conn_from_address(conn, &conn->_base.addr,
867 conn->_base.port, digest_rcvd, 0);
869 return connection_or_set_state_open(conn);
870 } else {
871 conn->_base.state = OR_CONN_STATE_OR_HANDSHAKING;
872 if (connection_init_or_handshake_state(conn, started_here) < 0)
873 return -1;
874 if (!started_here) {
875 connection_or_init_conn_from_address(conn, &conn->_base.addr,
876 conn->_base.port, digest_rcvd, 0);
878 return connection_or_send_versions(conn);
882 /** Allocate a new connection handshake state for the connection
883 * <b>conn</b>. Return 0 on success, -1 on failure. */
884 static int
885 connection_init_or_handshake_state(or_connection_t *conn, int started_here)
887 or_handshake_state_t *s;
888 s = conn->handshake_state = tor_malloc_zero(sizeof(or_handshake_state_t));
889 s->started_here = started_here ? 1 : 0;
890 return 0;
893 /** Free all storage held by <b>state</b>. */
894 void
895 or_handshake_state_free(or_handshake_state_t *state)
897 tor_assert(state);
898 memset(state, 0xBE, sizeof(or_handshake_state_t));
899 tor_free(state);
902 /** Set <b>conn</b>'s state to OR_CONN_STATE_OPEN, and tell other subsystems
903 * as appropriate. Called when we are done with all TLS and OR handshaking.
906 connection_or_set_state_open(or_connection_t *conn)
908 int started_here = connection_or_nonopen_was_started_here(conn);
909 time_t now = time(NULL);
910 conn->_base.state = OR_CONN_STATE_OPEN;
911 control_event_or_conn_status(conn, OR_CONN_EVENT_CONNECTED, 0);
913 if (started_here) {
914 rep_hist_note_connect_succeeded(conn->identity_digest, now);
915 if (entry_guard_register_connect_status(conn->identity_digest,
916 1, now) < 0) {
917 /* Close any circuits pending on this conn. We leave it in state
918 * 'open' though, because it didn't actually *fail* -- we just
919 * chose not to use it. (Otherwise
920 * connection_about_to_close_connection() will call a big pile of
921 * functions to indicate we shouldn't try it again.) */
922 log_debug(LD_OR, "New entry guard was reachable, but closing this "
923 "connection so we can retry the earlier entry guards.");
924 circuit_n_conn_done(conn, 0);
925 return -1;
927 router_set_status(conn->identity_digest, 1);
928 } else {
929 /* only report it to the geoip module if it's not a known router */
930 if (!router_get_by_digest(conn->identity_digest)) {
931 if (tor_addr_family(&TO_CONN(conn)->addr) == AF_INET) {
932 /*XXXX021 IP6 support ipv6 geoip.*/
933 uint32_t a = tor_addr_to_ipv4h(&TO_CONN(conn)->addr);
934 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, a, now);
938 if (conn->handshake_state) {
939 or_handshake_state_free(conn->handshake_state);
940 conn->handshake_state = NULL;
942 connection_start_reading(TO_CONN(conn));
943 circuit_n_conn_done(conn, 1); /* send the pending creates, if any. */
945 return 0;
948 /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
949 * For cells that use or affect a circuit, this should only be called by
950 * connection_or_flush_from_first_active_circuit().
952 void
953 connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
955 packed_cell_t networkcell;
957 tor_assert(cell);
958 tor_assert(conn);
960 cell_pack(&networkcell, cell);
962 connection_write_to_buf(networkcell.body, CELL_NETWORK_SIZE, TO_CONN(conn));
964 if (cell->command != CELL_PADDING)
965 conn->timestamp_last_added_nonpadding = time(NULL);
968 /** Pack a variable-length <b>cell</b> into wire-format, and write it onto
969 * <b>conn</b>'s outbuf. Right now, this <em>DOES NOT</em> support cells that
970 * affect a circuit.
972 void
973 connection_or_write_var_cell_to_buf(const var_cell_t *cell,
974 or_connection_t *conn)
976 char hdr[VAR_CELL_HEADER_SIZE];
977 tor_assert(cell);
978 tor_assert(conn);
979 var_cell_pack_header(cell, hdr);
980 connection_write_to_buf(hdr, sizeof(hdr), TO_CONN(conn));
981 connection_write_to_buf(cell->payload, cell->payload_len, TO_CONN(conn));
982 if (cell->command != CELL_PADDING)
983 conn->timestamp_last_added_nonpadding = time(NULL);
986 /** See whether there's a variable-length cell waiting on <b>conn</b>'s
987 * inbuf. Return values as for fetch_var_cell_from_buf(). */
988 static int
989 connection_fetch_var_cell_from_buf(or_connection_t *conn, var_cell_t **out)
991 return fetch_var_cell_from_buf(conn->_base.inbuf, out, conn->link_proto);
994 /** Process cells from <b>conn</b>'s inbuf.
996 * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
997 * and hand it to command_process_cell().
999 * Always return 0.
1001 static int
1002 connection_or_process_cells_from_inbuf(or_connection_t *conn)
1004 var_cell_t *var_cell;
1006 while (1) {
1007 log_debug(LD_OR,
1008 "%d: starting, inbuf_datalen %d (%d pending in tls object).",
1009 conn->_base.s,(int)buf_datalen(conn->_base.inbuf),
1010 tor_tls_get_pending_bytes(conn->tls));
1011 if (connection_fetch_var_cell_from_buf(conn, &var_cell)) {
1012 if (!var_cell)
1013 return 0; /* not yet. */
1014 command_process_var_cell(var_cell, conn);
1015 var_cell_free(var_cell);
1016 } else {
1017 char buf[CELL_NETWORK_SIZE];
1018 cell_t cell;
1019 if (buf_datalen(conn->_base.inbuf) < CELL_NETWORK_SIZE) /* whole response
1020 available? */
1021 return 0; /* not yet */
1023 connection_fetch_from_buf(buf, CELL_NETWORK_SIZE, TO_CONN(conn));
1025 /* retrieve cell info from buf (create the host-order struct from the
1026 * network-order string) */
1027 cell_unpack(&cell, buf);
1029 command_process_cell(&cell, conn);
1034 /** Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
1035 * onto OR connection <b>conn</b>. Don't perform range-checking on reason:
1036 * we may want to propagate reasons from other cells.
1038 * Return 0.
1041 connection_or_send_destroy(circid_t circ_id, or_connection_t *conn, int reason)
1043 cell_t cell;
1045 tor_assert(conn);
1047 memset(&cell, 0, sizeof(cell_t));
1048 cell.circ_id = circ_id;
1049 cell.command = CELL_DESTROY;
1050 cell.payload[0] = (uint8_t) reason;
1051 log_debug(LD_OR,"Sending destroy (circID %d).", circ_id);
1053 /* XXXX It's possible that under some circumstances, we want the destroy
1054 * to take precedence over other data waiting on the circuit's cell queue.
1057 connection_or_write_cell_to_buf(&cell, conn);
1058 return 0;
1061 /** Array of recognized link protocol versions. */
1062 static const uint16_t or_protocol_versions[] = { 1, 2 };
1063 /** Number of versions in <b>or_protocol_versions</b>. */
1064 static const int n_or_protocol_versions =
1065 (int)( sizeof(or_protocol_versions)/sizeof(uint16_t) );
1067 /** Return true iff <b>v</b> is a link protocol version that this Tor
1068 * implementation believes it can support. */
1070 is_or_protocol_version_known(uint16_t v)
1072 int i;
1073 for (i = 0; i < n_or_protocol_versions; ++i) {
1074 if (or_protocol_versions[i] == v)
1075 return 1;
1077 return 0;
1080 /** Send a VERSIONS cell on <b>conn</b>, telling the other host about the
1081 * link protocol versions that this Tor can support. */
1082 static int
1083 connection_or_send_versions(or_connection_t *conn)
1085 var_cell_t *cell;
1086 int i;
1087 tor_assert(conn->handshake_state &&
1088 !conn->handshake_state->sent_versions_at);
1089 cell = var_cell_new(n_or_protocol_versions * 2);
1090 cell->command = CELL_VERSIONS;
1091 for (i = 0; i < n_or_protocol_versions; ++i) {
1092 uint16_t v = or_protocol_versions[i];
1093 set_uint16(cell->payload+(2*i), htons(v));
1096 connection_or_write_var_cell_to_buf(cell, conn);
1097 conn->handshake_state->sent_versions_at = time(NULL);
1099 var_cell_free(cell);
1100 return 0;
1103 /** Send a NETINFO cell on <b>conn</b>, telling the other server what we know
1104 * about their address, our address, and the current time. */
1106 connection_or_send_netinfo(or_connection_t *conn)
1108 cell_t cell;
1109 time_t now = time(NULL);
1110 routerinfo_t *me;
1111 int len;
1112 char *out;
1114 memset(&cell, 0, sizeof(cell_t));
1115 cell.command = CELL_NETINFO;
1117 /* Timestamp. */
1118 set_uint32(cell.payload, htonl((uint32_t)now));
1120 /* Their address. */
1121 out = cell.payload + 4;
1122 len = append_address_to_payload(out, &conn->_base.addr);
1123 if (len<0)
1124 return -1;
1125 out += len;
1127 /* My address. */
1128 if ((me = router_get_my_routerinfo())) {
1129 tor_addr_t my_addr;
1130 *out++ = 1; /* only one address is supported. */
1132 tor_addr_from_ipv4h(&my_addr, me->addr);
1133 len = append_address_to_payload(out, &my_addr);
1134 if (len < 0)
1135 return -1;
1136 out += len;
1137 } else {
1138 *out++ = 0;
1141 connection_or_write_cell_to_buf(&cell, conn);
1143 return 0;