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-2010, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
8 * \file connection_or.c
9 * \brief Functions to handle OR connections, TLS handshaking, and
10 * cells on the network.
15 static int connection_tls_finish_handshake(or_connection_t
*conn
);
16 static int connection_or_process_cells_from_inbuf(or_connection_t
*conn
);
17 static int connection_or_send_versions(or_connection_t
*conn
);
18 static int connection_init_or_handshake_state(or_connection_t
*conn
,
20 static int connection_or_check_valid_tls_handshake(or_connection_t
*conn
,
22 char *digest_rcvd_out
);
24 /**************************************************************/
26 /** Map from identity digest of connected OR or desired OR to a connection_t
27 * with that identity digest. If there is more than one such connection_t,
28 * they form a linked list, with next_with_same_id as the next pointer. */
29 static digestmap_t
*orconn_identity_map
= NULL
;
31 /** If conn is listed in orconn_identity_map, remove it, and clear
32 * conn->identity_digest. Otherwise do nothing. */
34 connection_or_remove_from_identity_map(or_connection_t
*conn
)
38 if (!orconn_identity_map
)
40 tmp
= digestmap_get(orconn_identity_map
, conn
->identity_digest
);
42 if (!tor_digest_is_zero(conn
->identity_digest
)) {
43 log_warn(LD_BUG
, "Didn't find connection '%s' on identity map when "
44 "trying to remove it.",
45 conn
->nickname
? conn
->nickname
: "NULL");
50 if (conn
->next_with_same_id
)
51 digestmap_set(orconn_identity_map
, conn
->identity_digest
,
52 conn
->next_with_same_id
);
54 digestmap_remove(orconn_identity_map
, conn
->identity_digest
);
56 while (tmp
->next_with_same_id
) {
57 if (tmp
->next_with_same_id
== conn
) {
58 tmp
->next_with_same_id
= conn
->next_with_same_id
;
61 tmp
= tmp
->next_with_same_id
;
64 memset(conn
->identity_digest
, 0, DIGEST_LEN
);
65 conn
->next_with_same_id
= NULL
;
68 /** Remove all entries from the identity-to-orconn map, and clear
69 * all identities in OR conns.*/
71 connection_or_clear_identity_map(void)
73 smartlist_t
*conns
= get_connection_array();
74 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
76 if (conn
->type
== CONN_TYPE_OR
) {
77 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
78 memset(or_conn
->identity_digest
, 0, DIGEST_LEN
);
79 or_conn
->next_with_same_id
= NULL
;
83 if (orconn_identity_map
) {
84 digestmap_free(orconn_identity_map
, NULL
);
85 orconn_identity_map
= NULL
;
89 /** Change conn->identity_digest to digest, and add conn into
90 * orconn_digest_map. */
92 connection_or_set_identity_digest(or_connection_t
*conn
, const char *digest
)
98 if (!orconn_identity_map
)
99 orconn_identity_map
= digestmap_new();
100 if (!memcmp(conn
->identity_digest
, digest
, DIGEST_LEN
))
103 /* If the identity was set previously, remove the old mapping. */
104 if (! tor_digest_is_zero(conn
->identity_digest
))
105 connection_or_remove_from_identity_map(conn
);
107 memcpy(conn
->identity_digest
, digest
, DIGEST_LEN
);
109 /* If we're setting the ID to zero, don't add a mapping. */
110 if (tor_digest_is_zero(digest
))
113 tmp
= digestmap_set(orconn_identity_map
, digest
, conn
);
114 conn
->next_with_same_id
= tmp
;
117 /* Testing code to check for bugs in representation. */
118 for (; tmp
; tmp
= tmp
->next_with_same_id
) {
119 tor_assert(!memcmp(tmp
->identity_digest
, digest
, DIGEST_LEN
));
120 tor_assert(tmp
!= conn
);
125 /** Pack the cell_t host-order structure <b>src</b> into network-order
126 * in the buffer <b>dest</b>. See tor-spec.txt for details about the
129 * Note that this function doesn't touch <b>dst</b>-\>next: the caller
130 * should set it or clear it as appropriate.
133 cell_pack(packed_cell_t
*dst
, const cell_t
*src
)
135 char *dest
= dst
->body
;
136 *(uint16_t*)dest
= htons(src
->circ_id
);
137 *(uint8_t*)(dest
+2) = src
->command
;
138 memcpy(dest
+3, src
->payload
, CELL_PAYLOAD_SIZE
);
141 /** Unpack the network-order buffer <b>src</b> into a host-order
142 * cell_t structure <b>dest</b>.
145 cell_unpack(cell_t
*dest
, const char *src
)
147 dest
->circ_id
= ntohs(*(uint16_t*)(src
));
148 dest
->command
= *(uint8_t*)(src
+2);
149 memcpy(dest
->payload
, src
+3, CELL_PAYLOAD_SIZE
);
152 /** Write the header of <b>cell</b> into the first VAR_CELL_HEADER_SIZE
153 * bytes of <b>hdr_out</b>. */
155 var_cell_pack_header(const var_cell_t
*cell
, char *hdr_out
)
157 set_uint16(hdr_out
, htons(cell
->circ_id
));
158 set_uint8(hdr_out
+2, cell
->command
);
159 set_uint16(hdr_out
+3, htons(cell
->payload_len
));
162 /** Allocate and return a new var_cell_t with <b>payload_len</b> bytes of
165 var_cell_new(uint16_t payload_len
)
167 var_cell_t
*cell
= tor_malloc(sizeof(var_cell_t
)+payload_len
-1);
168 cell
->payload_len
= payload_len
;
174 /** Release all space held by <b>cell</b>. */
176 var_cell_free(var_cell_t
*cell
)
181 /** We've received an EOF from <b>conn</b>. Mark it for close and return. */
183 connection_or_reached_eof(or_connection_t
*conn
)
185 log_info(LD_OR
,"OR connection reached EOF. Closing.");
186 connection_mark_for_close(TO_CONN(conn
));
190 /** Read conn's inbuf. If the http response from the proxy is all
191 * here, make sure it's good news, and begin the tls handshake. If
192 * it's bad news, close the connection and return -1. Else return 0
193 * and hope for better luck next time.
196 connection_or_read_proxy_response(or_connection_t
*or_conn
)
202 connection_t
*conn
= TO_CONN(or_conn
);
204 switch (fetch_from_buf_http(conn
->inbuf
,
205 &headers
, MAX_HEADERS_SIZE
,
206 NULL
, NULL
, 10000, 0)) {
207 case -1: /* overflow */
208 log_warn(LD_PROTOCOL
,
209 "Your https proxy sent back an oversized response. Closing.");
212 log_info(LD_OR
,"https proxy response not all here yet. Waiting.");
214 /* case 1, fall through */
217 if (parse_http_response(headers
, &status_code
, &date_header
,
218 NULL
, &reason
) < 0) {
220 "Unparseable headers from proxy (connecting to '%s'). Closing.",
225 if (!reason
) reason
= tor_strdup("[no reason given]");
227 if (status_code
== 200) {
229 "HTTPS connect to '%s' successful! (200 %s) Starting TLS.",
230 conn
->address
, escaped(reason
));
232 if (connection_tls_start_handshake(or_conn
, 0) < 0) {
233 /* TLS handshaking error of some kind. */
234 connection_mark_for_close(conn
);
240 /* else, bad news on the status code */
242 "The https proxy sent back an unexpected status code %d (%s). "
244 status_code
, escaped(reason
));
246 connection_mark_for_close(conn
);
250 /** Handle any new bytes that have come in on connection <b>conn</b>.
251 * If conn is in 'open' state, hand it to
252 * connection_or_process_cells_from_inbuf()
256 connection_or_process_inbuf(or_connection_t
*conn
)
260 switch (conn
->_base
.state
) {
261 case OR_CONN_STATE_PROXY_READING
:
262 return connection_or_read_proxy_response(conn
);
263 case OR_CONN_STATE_OPEN
:
264 case OR_CONN_STATE_OR_HANDSHAKING
:
265 return connection_or_process_cells_from_inbuf(conn
);
267 return 0; /* don't do anything */
271 /** When adding cells to an OR connection's outbuf, keep adding until the
272 * outbuf is at least this long, or we run out of cells. */
273 #define OR_CONN_HIGHWATER (32*1024)
275 /** Add cells to an OR connection's outbuf whenever the outbuf's data length
276 * drops below this size. */
277 #define OR_CONN_LOWWATER (16*1024)
279 /** Called whenever we have flushed some data on an or_conn: add more data
280 * from active circuits. */
282 connection_or_flushed_some(or_connection_t
*conn
)
284 size_t datalen
= buf_datalen(conn
->_base
.outbuf
);
285 /* If we're under the low water mark, add cells until we're just over the
286 * high water mark. */
287 if (datalen
< OR_CONN_LOWWATER
) {
288 ssize_t n
= (OR_CONN_HIGHWATER
- datalen
+ CELL_NETWORK_SIZE
-1)
290 time_t now
= approx_time();
291 while (conn
->active_circuits
&& n
> 0) {
293 flushed
= connection_or_flush_from_first_active_circuit(conn
, 1, now
);
300 /** Connection <b>conn</b> has finished writing and has no bytes left on
303 * Otherwise it's in state "open": stop writing and return.
305 * If <b>conn</b> is broken, mark it for close and return -1, else
309 connection_or_finished_flushing(or_connection_t
*conn
)
312 assert_connection_ok(TO_CONN(conn
),0);
314 switch (conn
->_base
.state
) {
315 case OR_CONN_STATE_PROXY_FLUSHING
:
316 log_debug(LD_OR
,"finished sending CONNECT to proxy.");
317 conn
->_base
.state
= OR_CONN_STATE_PROXY_READING
;
318 connection_stop_writing(TO_CONN(conn
));
320 case OR_CONN_STATE_OPEN
:
321 case OR_CONN_STATE_OR_HANDSHAKING
:
322 connection_stop_writing(TO_CONN(conn
));
325 log_err(LD_BUG
,"Called in unexpected state %d.", conn
->_base
.state
);
326 tor_fragile_assert();
332 /** Connected handler for OR connections: begin the TLS handshake.
335 connection_or_finished_connecting(or_connection_t
*or_conn
)
339 conn
= TO_CONN(or_conn
);
340 tor_assert(conn
->state
== OR_CONN_STATE_CONNECTING
);
342 log_debug(LD_OR
,"OR connect() to router at %s:%u finished.",
343 conn
->address
,conn
->port
);
344 control_event_bootstrap(BOOTSTRAP_STATUS_HANDSHAKE
, 0);
346 if (get_options()->HttpsProxy
) {
348 char *base64_authenticator
=NULL
;
349 const char *authenticator
= get_options()->HttpsProxyAuthenticator
;
352 base64_authenticator
= alloc_http_authenticator(authenticator
);
353 if (!base64_authenticator
)
354 log_warn(LD_OR
, "Encoding https authenticator failed");
356 if (base64_authenticator
) {
357 tor_snprintf(buf
, sizeof(buf
), "CONNECT %s:%d HTTP/1.1\r\n"
358 "Proxy-Authorization: Basic %s\r\n\r\n",
359 fmt_addr(&conn
->addr
),
360 conn
->port
, base64_authenticator
);
361 tor_free(base64_authenticator
);
363 tor_snprintf(buf
, sizeof(buf
), "CONNECT %s:%d HTTP/1.0\r\n\r\n",
364 fmt_addr(&conn
->addr
), conn
->port
);
366 connection_write_to_buf(buf
, strlen(buf
), conn
);
367 conn
->state
= OR_CONN_STATE_PROXY_FLUSHING
;
371 if (connection_tls_start_handshake(or_conn
, 0) < 0) {
372 /* TLS handshaking error of some kind. */
373 connection_mark_for_close(conn
);
379 /** If we don't necessarily know the router we're connecting to, but we
380 * have an addr/port/id_digest, then fill in as much as we can. Start
381 * by checking to see if this describes a router we know. */
383 connection_or_init_conn_from_address(or_connection_t
*conn
,
384 const tor_addr_t
*addr
, uint16_t port
,
385 const char *id_digest
,
388 or_options_t
*options
= get_options();
389 routerinfo_t
*r
= router_get_by_digest(id_digest
);
390 conn
->bandwidthrate
= (int)options
->BandwidthRate
;
391 conn
->read_bucket
= conn
->bandwidthburst
= (int)options
->BandwidthBurst
;
392 connection_or_set_identity_digest(conn
, id_digest
);
394 conn
->_base
.port
= port
;
395 tor_addr_copy(&conn
->_base
.addr
, addr
);
396 tor_addr_copy(&conn
->real_addr
, addr
);
398 /* XXXX proposal 118 will make this more complex. */
399 if (tor_addr_eq_ipv4h(&conn
->_base
.addr
, r
->addr
))
400 conn
->is_canonical
= 1;
402 /* Override the addr/port, so our log messages will make sense.
403 * This is dangerous, since if we ever try looking up a conn by
404 * its actual addr/port, we won't remember. Careful! */
405 /* XXXX arma: this is stupid, and it's the reason we need real_addr
406 * to track is_canonical properly. What requires it? */
407 /* XXXX <arma> i believe the reason we did this, originally, is because
408 * we wanted to log what OR a connection was to, and if we logged the
409 * right IP address and port 56244, that wouldn't be as helpful. now we
410 * log the "right" port too, so we know if it's moria1 or moria2.
412 tor_addr_from_ipv4h(&conn
->_base
.addr
, r
->addr
);
413 conn
->_base
.port
= r
->or_port
;
415 conn
->nickname
= tor_strdup(r
->nickname
);
416 tor_free(conn
->_base
.address
);
417 conn
->_base
.address
= tor_strdup(r
->address
);
420 /* If we're an authoritative directory server, we may know a
421 * nickname for this router. */
422 n
= dirserv_get_nickname_by_digest(id_digest
);
424 conn
->nickname
= tor_strdup(n
);
426 conn
->nickname
= tor_malloc(HEX_DIGEST_LEN
+2);
427 conn
->nickname
[0] = '$';
428 base16_encode(conn
->nickname
+1, HEX_DIGEST_LEN
+1,
429 conn
->identity_digest
, DIGEST_LEN
);
431 tor_free(conn
->_base
.address
);
432 conn
->_base
.address
= tor_dup_addr(addr
);
436 /** Return true iff <b>a</b> is "better" than <b>b</b> for new circuits.
438 * A more canonical connection is always better than a less canonical
439 * connection. That aside, a connection is better if it has circuits and the
440 * other does not, or if it was created more recently.
442 * Requires that both input connections are open; not is_bad_for_new_circs,
443 * and not impossibly non-canonical.
445 * If </b>forgive_new_connections</b> is true, then we do not call
446 * <b>a</b>better than <b>b</b> simply because b has no circuits,
447 * unless b is also relatively old.
450 connection_or_is_better(time_t now
,
451 const or_connection_t
*a
,
452 const or_connection_t
*b
,
453 int forgive_new_connections
)
456 /** Do not definitively deprecate a new connection with no circuits on it
457 * until this much time has passed. */
458 #define NEW_CONN_GRACE_PERIOD (15*60)
460 if (b
->is_canonical
&& !a
->is_canonical
)
461 return 0; /* A canonical connection is better than a non-canonical
462 * one, no matter how new it is or which has circuits. */
464 newer
= b
->_base
.timestamp_created
< a
->_base
.timestamp_created
;
467 /* We prefer canonical connections regardless of newness. */
468 (!b
->is_canonical
&& a
->is_canonical
) ||
469 /* If both have circuits we prefer the newer: */
470 (b
->n_circuits
&& a
->n_circuits
&& newer
) ||
471 /* If neither has circuits we prefer the newer: */
472 (!b
->n_circuits
&& !a
->n_circuits
&& newer
))
475 /* If one has no circuits and the other does... */
476 if (!b
->n_circuits
&& a
->n_circuits
) {
477 /* Then it's bad, unless it's in its grace period and we're forgiving. */
478 if (forgive_new_connections
&&
479 now
< b
->_base
.timestamp_created
+ NEW_CONN_GRACE_PERIOD
)
488 /** Return the OR connection we should use to extend a circuit to the router
489 * whose identity is <b>digest</b>, and whose address we believe (or have been
490 * told in an extend cell) is <b>target_addr</b>. If there is no good
491 * connection, set *<b>msg_out</b> to a message describing the connection's
492 * state and our next action, and set <b>launch_out</b> to a boolean for
493 * whether we should launch a new connection or not.
496 connection_or_get_for_extend(const char *digest
,
497 const tor_addr_t
*target_addr
,
498 const char **msg_out
,
501 or_connection_t
*conn
, *best
=NULL
;
502 int n_inprogress_goodaddr
= 0, n_old
= 0, n_noncanonical
= 0, n_possible
= 0;
503 time_t now
= approx_time();
506 tor_assert(launch_out
);
508 if (!orconn_identity_map
) {
509 *msg_out
= "Router not connected (nothing is). Connecting.";
514 conn
= digestmap_get(orconn_identity_map
, digest
);
516 for (; conn
; conn
= conn
->next_with_same_id
) {
517 tor_assert(conn
->_base
.magic
== OR_CONNECTION_MAGIC
);
518 tor_assert(conn
->_base
.type
== CONN_TYPE_OR
);
519 tor_assert(!memcmp(conn
->identity_digest
, digest
, DIGEST_LEN
));
520 if (conn
->_base
.marked_for_close
)
522 /* Never return a non-open connection. */
523 if (conn
->_base
.state
!= OR_CONN_STATE_OPEN
) {
524 /* If the address matches, don't launch a new connection for this
526 if (!tor_addr_compare(&conn
->real_addr
, target_addr
, CMP_EXACT
))
527 ++n_inprogress_goodaddr
;
530 /* Never return a connection that shouldn't be used for circs. */
531 if (conn
->is_bad_for_new_circs
) {
535 /* Never return a non-canonical connection using a recent link protocol
536 * if the address is not what we wanted.
538 * (For old link protocols, we can't rely on is_canonical getting
539 * set properly if we're talking to the right address, since we might
540 * have an out-of-date descriptor, and we will get no NETINFO cell to
541 * tell us about the right address.) */
542 if (!conn
->is_canonical
&& conn
->link_proto
>= 2 &&
543 tor_addr_compare(&conn
->real_addr
, target_addr
, CMP_EXACT
)) {
551 best
= conn
; /* If we have no 'best' so far, this one is good enough. */
555 if (connection_or_is_better(now
, conn
, best
, 0))
560 *msg_out
= "Connection is fine; using it.";
563 } else if (n_inprogress_goodaddr
) {
564 *msg_out
= "Connection in progress; waiting.";
567 } else if (n_old
|| n_noncanonical
) {
568 *msg_out
= "Connections all too old, or too non-canonical. "
569 " Launching a new one.";
573 *msg_out
= "Not connected. Connecting.";
579 /** How old do we let a connection to an OR get before deciding it's
580 * too old for new circuits? */
581 #define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)
583 /** Given the head of the linked list for all the or_connections with a given
584 * identity, set elements of that list as is_bad_for_new_circs() as
585 * appropriate. Helper for connection_or_set_bad_connections().
588 connection_or_group_set_badness(or_connection_t
*head
)
590 or_connection_t
*or_conn
= NULL
, *best
= NULL
;
591 int n_old
= 0, n_inprogress
= 0, n_canonical
= 0, n_other
= 0;
592 time_t now
= time(NULL
);
594 /* Pass 1: expire everything that's old, and see what the status of
595 * everything else is. */
596 for (or_conn
= head
; or_conn
; or_conn
= or_conn
->next_with_same_id
) {
597 if (or_conn
->_base
.marked_for_close
||
598 or_conn
->is_bad_for_new_circs
)
600 if (or_conn
->_base
.timestamp_created
+ TIME_BEFORE_OR_CONN_IS_TOO_OLD
603 "Marking OR conn to %s:%d as too old for new circuits "
604 "(fd %d, %d secs old).",
605 or_conn
->_base
.address
, or_conn
->_base
.port
, or_conn
->_base
.s
,
606 (int)(now
- or_conn
->_base
.timestamp_created
));
607 or_conn
->is_bad_for_new_circs
= 1;
610 if (or_conn
->is_bad_for_new_circs
) {
612 } else if (or_conn
->_base
.state
!= OR_CONN_STATE_OPEN
) {
614 } else if (or_conn
->is_canonical
) {
621 /* Pass 2: We know how about how good the best connection is.
622 * expire everything that's worse, and find the very best if we can. */
623 for (or_conn
= head
; or_conn
; or_conn
= or_conn
->next_with_same_id
) {
624 if (or_conn
->_base
.marked_for_close
||
625 or_conn
->is_bad_for_new_circs
)
626 continue; /* This one doesn't need to be marked bad. */
627 if (or_conn
->_base
.state
!= OR_CONN_STATE_OPEN
)
628 continue; /* Don't mark anything bad until we have seen what happens
629 * when the connection finishes. */
630 if (n_canonical
&& !or_conn
->is_canonical
) {
631 /* We have at least one open canonical connection to this router,
632 * and this one is open but not canonical. Mark it bad. */
634 "Marking OR conn to %s:%d as too old for new circuits: "
635 "(fd %d, %d secs old). It is not canonical, and we have "
636 "another connection to that OR that is.",
637 or_conn
->_base
.address
, or_conn
->_base
.port
, or_conn
->_base
.s
,
638 (int)(now
- or_conn
->_base
.timestamp_created
));
639 or_conn
->is_bad_for_new_circs
= 1;
643 if (!best
|| connection_or_is_better(now
, or_conn
, best
, 0))
650 /* Pass 3: One connection to OR is best. If it's canonical, mark as bad
651 * every other open connection. If it's non-canonical, mark as bad
652 * every other open connection to the same address.
654 * XXXX This isn't optimal; if we have connections to an OR at multiple
655 * addresses, we'd like to pick the best _for each address_, and mark as
656 * bad every open connection that isn't best for its address. But this
657 * can only occur in cases where the other OR is old (so we have no
658 * canonical connection to it), or where all the connections to the OR are
659 * at noncanonical addresses and we have no good direct connection (which
660 * means we aren't at risk of attaching circuits to it anyway). As
661 * 0.1.2.x dies out, the first case will go away, and the second one is
662 * "mostly harmless", so a fix can wait until somebody is bored.
664 for (or_conn
= head
; or_conn
; or_conn
= or_conn
->next_with_same_id
) {
665 if (or_conn
->_base
.marked_for_close
||
666 or_conn
->is_bad_for_new_circs
||
667 or_conn
->_base
.state
!= OR_CONN_STATE_OPEN
)
669 if (or_conn
!= best
&& connection_or_is_better(now
, best
, or_conn
, 1)) {
670 /* This isn't the best conn, _and_ the best conn is better than it,
671 even when we're being forgiving. */
672 if (best
->is_canonical
) {
674 "Marking OR conn to %s:%d as too old for new circuits: "
675 "(fd %d, %d secs old). We have a better canonical one "
676 "(fd %d; %d secs old).",
677 or_conn
->_base
.address
, or_conn
->_base
.port
, or_conn
->_base
.s
,
678 (int)(now
- or_conn
->_base
.timestamp_created
),
679 best
->_base
.s
, (int)(now
- best
->_base
.timestamp_created
));
680 or_conn
->is_bad_for_new_circs
= 1;
681 } else if (!tor_addr_compare(&or_conn
->real_addr
,
682 &best
->real_addr
, CMP_EXACT
)) {
684 "Marking OR conn to %s:%d as too old for new circuits: "
685 "(fd %d, %d secs old). We have a better one "
686 "(fd %d; %d secs old).",
687 or_conn
->_base
.address
, or_conn
->_base
.port
, or_conn
->_base
.s
,
688 (int)(now
- or_conn
->_base
.timestamp_created
),
689 best
->_base
.s
, (int)(now
- best
->_base
.timestamp_created
));
690 or_conn
->is_bad_for_new_circs
= 1;
696 /** Go through all the OR connections, and set the is_bad_for_new_circs
698 * - all connections that are too old.
699 * - all open non-canonical connections for which a canonical connection
700 * exists to the same router.
701 * - all open canonical connections for which a 'better' canonical
702 * connection exists to the same router.
703 * - all open non-canonical connections for which a 'better' non-canonical
704 * connection exists to the same router at the same address.
706 * See connection_or_is_better() for our idea of what makes one OR connection
707 * better than another.
710 connection_or_set_bad_connections(void)
712 if (!orconn_identity_map
)
715 DIGESTMAP_FOREACH(orconn_identity_map
, identity
, or_connection_t
*, conn
) {
716 connection_or_group_set_badness(conn
);
717 } DIGESTMAP_FOREACH_END
;
720 /** <b>conn</b> is in the 'connecting' state, and it failed to complete
721 * a TCP connection. Send notifications appropriately.
723 * <b>reason</b> specifies the or_conn_end_reason for the failure;
724 * <b>msg</b> specifies the strerror-style error message.
727 connection_or_connect_failed(or_connection_t
*conn
,
728 int reason
, const char *msg
)
730 control_event_or_conn_status(conn
, OR_CONN_EVENT_FAILED
, reason
);
731 if (!authdir_mode_tests_reachability(get_options()))
732 control_event_bootstrap_problem(msg
, reason
);
735 /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
736 * handshake with an OR with identity digest <b>id_digest</b>.
738 * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
739 * return that connection. If the connect() is in progress, set the
740 * new conn's state to 'connecting' and return it. If connect() succeeds,
741 * call connection_tls_start_handshake() on it.
743 * This function is called from router_retry_connections(), for
744 * ORs connecting to ORs, and circuit_establish_circuit(), for
745 * OPs connecting to ORs.
747 * Return the launched conn, or NULL if it failed.
750 connection_or_connect(const tor_addr_t
*_addr
, uint16_t port
,
751 const char *id_digest
)
753 or_connection_t
*conn
;
754 or_options_t
*options
= get_options();
755 int socket_error
= 0;
759 tor_assert(id_digest
);
760 tor_addr_copy(&addr
, _addr
);
762 if (server_mode(options
) && router_digest_is_me(id_digest
)) {
763 log_info(LD_PROTOCOL
,"Client asked me to connect to myself. Refusing.");
767 conn
= or_connection_new(AF_INET
);
769 /* set up conn so it's got all the data we need to remember */
770 connection_or_init_conn_from_address(conn
, &addr
, port
, id_digest
, 1);
771 conn
->_base
.state
= OR_CONN_STATE_CONNECTING
;
772 control_event_or_conn_status(conn
, OR_CONN_EVENT_LAUNCHED
, 0);
774 if (options
->HttpsProxy
) {
775 /* we shouldn't connect directly. use the https proxy instead. */
776 tor_addr_from_ipv4h(&addr
, options
->HttpsProxyAddr
);
777 port
= options
->HttpsProxyPort
;
780 switch (connection_connect(TO_CONN(conn
), conn
->_base
.address
,
781 &addr
, port
, &socket_error
)) {
783 /* If the connection failed immediately, and we're using
784 * an https proxy, our https proxy is down. Don't blame the
786 if (!options
->HttpsProxy
)
787 entry_guard_register_connect_status(conn
->identity_digest
,
789 connection_or_connect_failed(conn
,
790 errno_to_orconn_end_reason(socket_error
),
791 tor_socket_strerror(socket_error
));
792 connection_free(TO_CONN(conn
));
795 connection_watch_events(TO_CONN(conn
), EV_READ
| EV_WRITE
);
796 /* writable indicates finish, readable indicates broken link,
797 error indicates broken link on windows */
799 /* case 1: fall through */
802 if (connection_or_finished_connecting(conn
) < 0) {
803 /* already marked for close */
809 /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
810 * we initiated the connection, else it's 1.
812 * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
813 * pass <b>conn</b> to connection_tls_continue_handshake().
815 * Return -1 if <b>conn</b> is broken, else return 0.
818 connection_tls_start_handshake(or_connection_t
*conn
, int receiving
)
820 conn
->_base
.state
= OR_CONN_STATE_TLS_HANDSHAKING
;
821 conn
->tls
= tor_tls_new(conn
->_base
.s
, receiving
);
822 tor_tls_set_logged_address(conn
->tls
, escaped_safe_str(conn
->_base
.address
));
824 log_warn(LD_BUG
,"tor_tls_new failed. Closing.");
827 connection_start_reading(TO_CONN(conn
));
828 log_debug(LD_OR
,"starting TLS handshake on fd %d", conn
->_base
.s
);
829 note_crypto_pk_op(receiving
? TLS_HANDSHAKE_S
: TLS_HANDSHAKE_C
);
831 if (connection_tls_continue_handshake(conn
) < 0) {
837 /** Invoked on the server side from inside tor_tls_read() when the server
838 * gets a successful TLS renegotiation from the client. */
840 connection_or_tls_renegotiated_cb(tor_tls_t
*tls
, void *_conn
)
842 or_connection_t
*conn
= _conn
;
845 /* Don't invoke this again. */
846 tor_tls_set_renegotiate_callback(tls
, NULL
, NULL
);
847 tor_tls_block_renegotiation(tls
);
849 if (connection_tls_finish_handshake(conn
) < 0) {
850 /* XXXX_TLS double-check that it's ok to do this from inside read. */
851 /* XXXX_TLS double-check that this verifies certificates. */
852 connection_mark_for_close(TO_CONN(conn
));
856 /** Move forward with the tls handshake. If it finishes, hand
857 * <b>conn</b> to connection_tls_finish_handshake().
859 * Return -1 if <b>conn</b> is broken, else return 0.
862 connection_tls_continue_handshake(or_connection_t
*conn
)
865 check_no_tls_errors();
867 if (conn
->_base
.state
== OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING
) {
868 // log_notice(LD_OR, "Renegotiate with %p", conn->tls);
869 result
= tor_tls_renegotiate(conn
->tls
);
870 // log_notice(LD_OR, "Result: %d", result);
872 tor_assert(conn
->_base
.state
== OR_CONN_STATE_TLS_HANDSHAKING
);
873 // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
874 result
= tor_tls_handshake(conn
->tls
);
875 // log_notice(LD_OR, "Result: %d", result);
878 CASE_TOR_TLS_ERROR_ANY
:
879 log_info(LD_OR
,"tls error [%s]. breaking connection.",
880 tor_tls_err_to_string(result
));
883 if (! tor_tls_used_v1_handshake(conn
->tls
)) {
884 if (!tor_tls_is_server(conn
->tls
)) {
885 if (conn
->_base
.state
== OR_CONN_STATE_TLS_HANDSHAKING
) {
886 // log_notice(LD_OR,"Done. state was TLS_HANDSHAKING.");
887 conn
->_base
.state
= OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING
;
890 // log_notice(LD_OR,"Done. state was %d.", conn->_base.state);
892 /* improved handshake, but not a client. */
893 tor_tls_set_renegotiate_callback(conn
->tls
,
894 connection_or_tls_renegotiated_cb
,
896 conn
->_base
.state
= OR_CONN_STATE_TLS_SERVER_RENEGOTIATING
;
897 connection_stop_writing(TO_CONN(conn
));
898 connection_start_reading(TO_CONN(conn
));
902 return connection_tls_finish_handshake(conn
);
903 case TOR_TLS_WANTWRITE
:
904 connection_start_writing(TO_CONN(conn
));
905 log_debug(LD_OR
,"wanted write");
907 case TOR_TLS_WANTREAD
: /* handshaking conns are *always* reading */
908 log_debug(LD_OR
,"wanted read");
911 log_info(LD_OR
,"tls closed. breaking connection.");
917 /** Return 1 if we initiated this connection, or 0 if it started
918 * out as an incoming connection.
921 connection_or_nonopen_was_started_here(or_connection_t
*conn
)
923 tor_assert(conn
->_base
.type
== CONN_TYPE_OR
);
925 return 1; /* it's still in proxy states or something */
926 if (conn
->handshake_state
)
927 return conn
->handshake_state
->started_here
;
928 return !tor_tls_is_server(conn
->tls
);
931 /** <b>Conn</b> just completed its handshake. Return 0 if all is well, and
932 * return -1 if he is lying, broken, or otherwise something is wrong.
934 * If we initiated this connection (<b>started_here</b> is true), make sure
935 * the other side sent sent a correctly formed certificate. If I initiated the
936 * connection, make sure it's the right guy.
938 * Otherwise (if we _didn't_ initiate this connection), it's okay for
939 * the certificate to be weird or absent.
941 * If we return 0, and the certificate is as expected, write a hash of the
942 * identity key into digest_rcvd, which must have DIGEST_LEN space in it. (If
943 * we return -1 this buffer is undefined.) If the certificate is invalid
944 * or missing on an incoming connection, we return 0 and set digest_rcvd to
945 * DIGEST_LEN 0 bytes.
948 * 1) Set conn->circ_id_type according to tor-spec.txt.
949 * 2) If we're an authdirserver and we initiated the connection: drop all
950 * descriptors that claim to be on that IP/port but that aren't
951 * this guy; and note that this guy is reachable.
954 connection_or_check_valid_tls_handshake(or_connection_t
*conn
,
956 char *digest_rcvd_out
)
958 crypto_pk_env_t
*identity_rcvd
=NULL
;
959 or_options_t
*options
= get_options();
960 int severity
= server_mode(options
) ? LOG_PROTOCOL_WARN
: LOG_WARN
;
961 const char *safe_address
=
962 started_here
? conn
->_base
.address
: safe_str(conn
->_base
.address
);
963 const char *conn_type
= started_here
? "outgoing" : "incoming";
964 int has_cert
= 0, has_identity
=0;
966 check_no_tls_errors();
967 has_cert
= tor_tls_peer_has_cert(conn
->tls
);
968 if (started_here
&& !has_cert
) {
969 log_info(LD_PROTOCOL
,"Tried connecting to router at %s:%d, but it didn't "
970 "send a cert! Closing.",
971 safe_address
, conn
->_base
.port
);
973 } else if (!has_cert
) {
974 log_debug(LD_PROTOCOL
,"Got incoming connection with no certificate. "
977 check_no_tls_errors();
980 int v
= tor_tls_verify(started_here
?severity
:LOG_INFO
,
981 conn
->tls
, &identity_rcvd
);
982 if (started_here
&& v
<0) {
983 log_fn(severity
,LD_OR
,"Tried connecting to router at %s:%d: It"
984 " has a cert but it's invalid. Closing.",
985 safe_address
, conn
->_base
.port
);
988 log_info(LD_PROTOCOL
,"Incoming connection gave us an invalid cert "
991 log_debug(LD_OR
,"The certificate seems to be valid on %s connection "
992 "with %s:%d", conn_type
, safe_address
, conn
->_base
.port
);
994 check_no_tls_errors();
999 crypto_pk_get_digest(identity_rcvd
, digest_rcvd_out
);
1000 if (crypto_pk_cmp_keys(get_identity_key(), identity_rcvd
)<0) {
1001 conn
->circ_id_type
= CIRC_ID_TYPE_LOWER
;
1003 conn
->circ_id_type
= CIRC_ID_TYPE_HIGHER
;
1005 crypto_free_pk_env(identity_rcvd
);
1007 memset(digest_rcvd_out
, 0, DIGEST_LEN
);
1008 conn
->circ_id_type
= CIRC_ID_TYPE_NEITHER
;
1011 if (started_here
&& tor_digest_is_zero(conn
->identity_digest
)) {
1012 connection_or_set_identity_digest(conn
, digest_rcvd_out
);
1013 tor_free(conn
->nickname
);
1014 conn
->nickname
= tor_malloc(HEX_DIGEST_LEN
+2);
1015 conn
->nickname
[0] = '$';
1016 base16_encode(conn
->nickname
+1, HEX_DIGEST_LEN
+1,
1017 conn
->identity_digest
, DIGEST_LEN
);
1018 log_info(LD_OR
, "Connected to router %s at %s:%d without knowing "
1019 "its key. Hoping for the best.",
1020 conn
->nickname
, conn
->_base
.address
, conn
->_base
.port
);
1024 int as_advertised
= 1;
1025 tor_assert(has_cert
);
1026 tor_assert(has_identity
);
1027 if (memcmp(digest_rcvd_out
, conn
->identity_digest
, DIGEST_LEN
)) {
1028 /* I was aiming for a particular digest. I didn't get it! */
1029 char seen
[HEX_DIGEST_LEN
+1];
1030 char expected
[HEX_DIGEST_LEN
+1];
1031 base16_encode(seen
, sizeof(seen
), digest_rcvd_out
, DIGEST_LEN
);
1032 base16_encode(expected
, sizeof(expected
), conn
->identity_digest
,
1034 log_fn(severity
, LD_OR
,
1035 "Tried connecting to router at %s:%d, but identity key was not "
1036 "as expected: wanted %s but got %s.",
1037 conn
->_base
.address
, conn
->_base
.port
, expected
, seen
);
1038 entry_guard_register_connect_status(conn
->identity_digest
, 0, 1,
1040 control_event_or_conn_status(conn
, OR_CONN_EVENT_FAILED
,
1041 END_OR_CONN_REASON_OR_IDENTITY
);
1042 if (!authdir_mode_tests_reachability(options
))
1043 control_event_bootstrap_problem("foo", END_OR_CONN_REASON_OR_IDENTITY
);
1046 if (authdir_mode_tests_reachability(options
)) {
1047 /* We initiated this connection to address:port. Drop all routers
1048 * with the same address:port and a different key.
1050 dirserv_orconn_tls_done(conn
->_base
.address
, conn
->_base
.port
,
1051 digest_rcvd_out
, as_advertised
);
1059 /** The tls handshake is finished.
1061 * Make sure we are happy with the person we just handshaked with.
1063 * If he initiated the connection, make sure he's not already connected,
1064 * then initialize conn from the information in router.
1066 * If all is successful, call circuit_n_conn_done() to handle events
1067 * that have been pending on the <tls handshake completion. Also set the
1068 * directory to be dirty (only matters if I'm an authdirserver).
1071 connection_tls_finish_handshake(or_connection_t
*conn
)
1073 char digest_rcvd
[DIGEST_LEN
];
1074 int started_here
= connection_or_nonopen_was_started_here(conn
);
1076 log_debug(LD_OR
,"tls handshake with %s done. verifying.",
1077 safe_str(conn
->_base
.address
));
1079 directory_set_dirty();
1081 if (connection_or_check_valid_tls_handshake(conn
, started_here
,
1085 if (tor_tls_used_v1_handshake(conn
->tls
)) {
1086 conn
->link_proto
= 1;
1087 if (!started_here
) {
1088 connection_or_init_conn_from_address(conn
, &conn
->_base
.addr
,
1089 conn
->_base
.port
, digest_rcvd
, 0);
1091 tor_tls_block_renegotiation(conn
->tls
);
1092 return connection_or_set_state_open(conn
);
1094 conn
->_base
.state
= OR_CONN_STATE_OR_HANDSHAKING
;
1095 if (connection_init_or_handshake_state(conn
, started_here
) < 0)
1097 if (!started_here
) {
1098 connection_or_init_conn_from_address(conn
, &conn
->_base
.addr
,
1099 conn
->_base
.port
, digest_rcvd
, 0);
1101 return connection_or_send_versions(conn
);
1105 /** Allocate a new connection handshake state for the connection
1106 * <b>conn</b>. Return 0 on success, -1 on failure. */
1108 connection_init_or_handshake_state(or_connection_t
*conn
, int started_here
)
1110 or_handshake_state_t
*s
;
1111 s
= conn
->handshake_state
= tor_malloc_zero(sizeof(or_handshake_state_t
));
1112 s
->started_here
= started_here
? 1 : 0;
1116 /** Free all storage held by <b>state</b>. */
1118 or_handshake_state_free(or_handshake_state_t
*state
)
1121 memset(state
, 0xBE, sizeof(or_handshake_state_t
));
1125 /** Set <b>conn</b>'s state to OR_CONN_STATE_OPEN, and tell other subsystems
1126 * as appropriate. Called when we are done with all TLS and OR handshaking.
1129 connection_or_set_state_open(or_connection_t
*conn
)
1131 int started_here
= connection_or_nonopen_was_started_here(conn
);
1132 time_t now
= time(NULL
);
1133 conn
->_base
.state
= OR_CONN_STATE_OPEN
;
1134 control_event_or_conn_status(conn
, OR_CONN_EVENT_CONNECTED
, 0);
1137 rep_hist_note_connect_succeeded(conn
->identity_digest
, now
);
1138 if (entry_guard_register_connect_status(conn
->identity_digest
,
1140 /* Close any circuits pending on this conn. We leave it in state
1141 * 'open' though, because it didn't actually *fail* -- we just
1142 * chose not to use it. (Otherwise
1143 * connection_about_to_close_connection() will call a big pile of
1144 * functions to indicate we shouldn't try it again.) */
1145 log_debug(LD_OR
, "New entry guard was reachable, but closing this "
1146 "connection so we can retry the earlier entry guards.");
1147 circuit_n_conn_done(conn
, 0);
1150 router_set_status(conn
->identity_digest
, 1);
1152 /* only report it to the geoip module if it's not a known router */
1153 if (!router_get_by_digest(conn
->identity_digest
)) {
1154 if (tor_addr_family(&TO_CONN(conn
)->addr
) == AF_INET
) {
1155 /*XXXX IP6 support ipv6 geoip.*/
1156 uint32_t a
= tor_addr_to_ipv4h(&TO_CONN(conn
)->addr
);
1157 geoip_note_client_seen(GEOIP_CLIENT_CONNECT
, a
, now
);
1161 if (conn
->handshake_state
) {
1162 or_handshake_state_free(conn
->handshake_state
);
1163 conn
->handshake_state
= NULL
;
1165 connection_start_reading(TO_CONN(conn
));
1166 circuit_n_conn_done(conn
, 1); /* send the pending creates, if any. */
1171 /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
1172 * For cells that use or affect a circuit, this should only be called by
1173 * connection_or_flush_from_first_active_circuit().
1176 connection_or_write_cell_to_buf(const cell_t
*cell
, or_connection_t
*conn
)
1178 packed_cell_t networkcell
;
1183 cell_pack(&networkcell
, cell
);
1185 connection_write_to_buf(networkcell
.body
, CELL_NETWORK_SIZE
, TO_CONN(conn
));
1187 if (cell
->command
!= CELL_PADDING
)
1188 conn
->timestamp_last_added_nonpadding
= approx_time();
1191 /** Pack a variable-length <b>cell</b> into wire-format, and write it onto
1192 * <b>conn</b>'s outbuf. Right now, this <em>DOES NOT</em> support cells that
1196 connection_or_write_var_cell_to_buf(const var_cell_t
*cell
,
1197 or_connection_t
*conn
)
1199 char hdr
[VAR_CELL_HEADER_SIZE
];
1202 var_cell_pack_header(cell
, hdr
);
1203 connection_write_to_buf(hdr
, sizeof(hdr
), TO_CONN(conn
));
1204 connection_write_to_buf(cell
->payload
, cell
->payload_len
, TO_CONN(conn
));
1205 if (cell
->command
!= CELL_PADDING
)
1206 conn
->timestamp_last_added_nonpadding
= approx_time();
1209 /** See whether there's a variable-length cell waiting on <b>conn</b>'s
1210 * inbuf. Return values as for fetch_var_cell_from_buf(). */
1212 connection_fetch_var_cell_from_buf(or_connection_t
*conn
, var_cell_t
**out
)
1214 return fetch_var_cell_from_buf(conn
->_base
.inbuf
, out
, conn
->link_proto
);
1217 /** Process cells from <b>conn</b>'s inbuf.
1219 * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
1220 * and hand it to command_process_cell().
1225 connection_or_process_cells_from_inbuf(or_connection_t
*conn
)
1227 var_cell_t
*var_cell
;
1231 "%d: starting, inbuf_datalen %d (%d pending in tls object).",
1232 conn
->_base
.s
,(int)buf_datalen(conn
->_base
.inbuf
),
1233 tor_tls_get_pending_bytes(conn
->tls
));
1234 if (connection_fetch_var_cell_from_buf(conn
, &var_cell
)) {
1236 return 0; /* not yet. */
1237 command_process_var_cell(var_cell
, conn
);
1238 var_cell_free(var_cell
);
1240 char buf
[CELL_NETWORK_SIZE
];
1242 if (buf_datalen(conn
->_base
.inbuf
) < CELL_NETWORK_SIZE
) /* whole response
1244 return 0; /* not yet */
1246 connection_fetch_from_buf(buf
, CELL_NETWORK_SIZE
, TO_CONN(conn
));
1248 /* retrieve cell info from buf (create the host-order struct from the
1249 * network-order string) */
1250 cell_unpack(&cell
, buf
);
1252 command_process_cell(&cell
, conn
);
1257 /** Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
1258 * onto OR connection <b>conn</b>. Don't perform range-checking on reason:
1259 * we may want to propagate reasons from other cells.
1264 connection_or_send_destroy(circid_t circ_id
, or_connection_t
*conn
, int reason
)
1270 memset(&cell
, 0, sizeof(cell_t
));
1271 cell
.circ_id
= circ_id
;
1272 cell
.command
= CELL_DESTROY
;
1273 cell
.payload
[0] = (uint8_t) reason
;
1274 log_debug(LD_OR
,"Sending destroy (circID %d).", circ_id
);
1276 /* XXXX It's possible that under some circumstances, we want the destroy
1277 * to take precedence over other data waiting on the circuit's cell queue.
1280 connection_or_write_cell_to_buf(&cell
, conn
);
1284 /** Array of recognized link protocol versions. */
1285 static const uint16_t or_protocol_versions
[] = { 1, 2 };
1286 /** Number of versions in <b>or_protocol_versions</b>. */
1287 static const int n_or_protocol_versions
=
1288 (int)( sizeof(or_protocol_versions
)/sizeof(uint16_t) );
1290 /** Return true iff <b>v</b> is a link protocol version that this Tor
1291 * implementation believes it can support. */
1293 is_or_protocol_version_known(uint16_t v
)
1296 for (i
= 0; i
< n_or_protocol_versions
; ++i
) {
1297 if (or_protocol_versions
[i
] == v
)
1303 /** Send a VERSIONS cell on <b>conn</b>, telling the other host about the
1304 * link protocol versions that this Tor can support. */
1306 connection_or_send_versions(or_connection_t
*conn
)
1310 tor_assert(conn
->handshake_state
&&
1311 !conn
->handshake_state
->sent_versions_at
);
1312 cell
= var_cell_new(n_or_protocol_versions
* 2);
1313 cell
->command
= CELL_VERSIONS
;
1314 for (i
= 0; i
< n_or_protocol_versions
; ++i
) {
1315 uint16_t v
= or_protocol_versions
[i
];
1316 set_uint16(cell
->payload
+(2*i
), htons(v
));
1319 connection_or_write_var_cell_to_buf(cell
, conn
);
1320 conn
->handshake_state
->sent_versions_at
= time(NULL
);
1322 var_cell_free(cell
);
1326 /** Send a NETINFO cell on <b>conn</b>, telling the other server what we know
1327 * about their address, our address, and the current time. */
1329 connection_or_send_netinfo(or_connection_t
*conn
)
1332 time_t now
= time(NULL
);
1337 memset(&cell
, 0, sizeof(cell_t
));
1338 cell
.command
= CELL_NETINFO
;
1341 set_uint32(cell
.payload
, htonl((uint32_t)now
));
1343 /* Their address. */
1344 out
= cell
.payload
+ 4;
1345 len
= append_address_to_payload(out
, &conn
->_base
.addr
);
1351 if ((me
= router_get_my_routerinfo())) {
1353 *out
++ = 1; /* only one address is supported. */
1355 tor_addr_from_ipv4h(&my_addr
, me
->addr
);
1356 len
= append_address_to_payload(out
, &my_addr
);
1364 connection_or_write_cell_to_buf(&cell
, conn
);