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 */
7 const char connection_or_c_id
[] =
11 * \file connection_or.c
12 * \brief Functions to handle OR connections, TLS handshaking, and
13 * cells on the network.
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
,
23 static int connection_or_check_valid_tls_handshake(or_connection_t
*conn
,
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. */
37 connection_or_remove_from_identity_map(or_connection_t
*conn
)
41 if (!orconn_identity_map
)
43 tmp
= digestmap_get(orconn_identity_map
, conn
->identity_digest
);
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");
53 if (conn
->next_with_same_id
)
54 digestmap_set(orconn_identity_map
, conn
->identity_digest
,
55 conn
->next_with_same_id
);
57 digestmap_remove(orconn_identity_map
, conn
->identity_digest
);
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
;
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.*/
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
;
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. */
95 connection_or_set_identity_digest(or_connection_t
*conn
, const char *digest
)
101 if (!orconn_identity_map
)
102 orconn_identity_map
= digestmap_new();
103 if (!memcmp(conn
->identity_digest
, digest
, DIGEST_LEN
))
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
))
116 tmp
= digestmap_set(orconn_identity_map
, digest
, conn
);
117 conn
->next_with_same_id
= tmp
;
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
);
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
132 * Note that this function doesn't touch <b>dst</b>-\>next: the caller
133 * should set it or clear it as appropriate.
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>.
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>. */
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
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
;
177 /** Release all space held by <b>cell</b>. */
179 var_cell_free(var_cell_t
*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
));
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.
199 connection_or_read_proxy_response(or_connection_t
*or_conn
)
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.");
215 log_info(LD_OR
,"https proxy response not all here yet. Waiting.");
217 /* case 1, fall through */
220 if (parse_http_response(headers
, &status_code
, &date_header
,
221 NULL
, &reason
) < 0) {
223 "Unparseable headers from proxy (connecting to '%s'). Closing.",
228 if (!reason
) reason
= tor_strdup("[no reason given]");
230 if (status_code
== 200) {
232 "HTTPS connect to '%s' successful! (200 %s) Starting TLS.",
233 conn
->address
, escaped(reason
));
235 if (connection_tls_start_handshake(or_conn
, 0) < 0) {
236 /* TLS handshaking error of some kind. */
237 connection_mark_for_close(conn
);
243 /* else, bad news on the status code */
245 "The https proxy sent back an unexpected status code %d (%s). "
247 status_code
, escaped(reason
));
249 connection_mark_for_close(conn
);
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()
259 connection_or_process_inbuf(or_connection_t
*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
);
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 /* If we're under the low water mark, add cells until we're just over the
289 * high water mark. */
290 if (datalen
< OR_CONN_LOWWATER
) {
291 ssize_t n
= (OR_CONN_HIGHWATER
- datalen
+ CELL_NETWORK_SIZE
-1)
293 time_t now
= approx_time();
294 while (conn
->active_circuits
&& n
> 0) {
296 flushed
= connection_or_flush_from_first_active_circuit(conn
, 1, now
);
303 /** Connection <b>conn</b> has finished writing and has no bytes left on
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
312 connection_or_finished_flushing(or_connection_t
*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
));
323 case OR_CONN_STATE_OPEN
:
324 case OR_CONN_STATE_OR_HANDSHAKING
:
325 connection_stop_writing(TO_CONN(conn
));
328 log_err(LD_BUG
,"Called in unexpected state %d.", conn
->_base
.state
);
329 tor_fragile_assert();
335 /** Connected handler for OR connections: begin the TLS handshake.
338 connection_or_finished_connecting(or_connection_t
*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
) {
351 char *base64_authenticator
=NULL
;
352 const char *authenticator
= get_options()->HttpsProxyAuthenticator
;
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
);
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
;
374 if (connection_tls_start_handshake(or_conn
, 0) < 0) {
375 /* TLS handshaking error of some kind. */
376 connection_mark_for_close(conn
);
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. */
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
,
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
);
401 /* XXXX proposal 118 will make this more complex. */
402 if (tor_addr_eq_ipv4h(&conn
->_base
.addr
, r
->addr
))
403 conn
->is_canonical
= 1;
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 /* XXXX 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
);
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
);
427 conn
->nickname
= tor_strdup(n
);
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 true iff <b>a</b> is "better" than <b>b</b> for new circuits.
441 * A more canonical connection is always better than a less canonical
442 * connection. That aside, a connection is better if it has circuits and the
443 * other does not, or if it was created more recently.
445 * Requires that both input connections are open; not is_bad_for_new_circs,
446 * and not impossibly non-canonical.
449 connection_or_is_better(const or_connection_t
*a
,
450 const or_connection_t
*b
)
454 if (b
->is_canonical
&& !a
->is_canonical
)
455 return 0; /* A canonical connection is better than a non-canonical
456 * one, no matter how new it is or which has circuits. */
458 newer
= b
->_base
.timestamp_created
< a
->_base
.timestamp_created
;
461 /* We prefer canonical connections regardless of newness. */
462 (!b
->is_canonical
&& a
->is_canonical
) ||
463 /* If both have circuits we prefer the newer: */
464 (b
->n_circuits
&& a
->n_circuits
&& newer
) ||
465 /* If neither has circuits we prefer the newer: */
466 (!b
->n_circuits
&& !a
->n_circuits
&& newer
) ||
467 /* If only one has circuits, use that. */
468 (!b
->n_circuits
&& a
->n_circuits
);
471 /** Return the OR connection we should use to extend a circuit to the router
472 * whose identity is <b>digest</b>, and whose address we believe (or have been
473 * told in an extend cell) is <b>target_addr</b>. If there is no good
474 * connection, set *<b>msg_out</b> to a message describing the connection's
475 * state and our next action, and set <b>launch_out</b> to a boolean for
476 * whether we should launch a new connection or not.
479 connection_or_get_for_extend(const char *digest
,
480 const tor_addr_t
*target_addr
,
481 const char **msg_out
,
484 or_connection_t
*conn
, *best
=NULL
;
485 int n_inprogress_goodaddr
= 0, n_old
= 0, n_noncanonical
= 0, n_possible
= 0;
488 tor_assert(launch_out
);
490 if (!orconn_identity_map
) {
491 *msg_out
= "Router not connected (nothing is). Connecting.";
496 conn
= digestmap_get(orconn_identity_map
, digest
);
498 for (; conn
; conn
= conn
->next_with_same_id
) {
499 tor_assert(conn
->_base
.magic
== OR_CONNECTION_MAGIC
);
500 tor_assert(conn
->_base
.type
== CONN_TYPE_OR
);
501 tor_assert(!memcmp(conn
->identity_digest
, digest
, DIGEST_LEN
));
502 if (conn
->_base
.marked_for_close
)
504 /* Never return a non-open connection. */
505 if (conn
->_base
.state
!= OR_CONN_STATE_OPEN
) {
506 /* If the address matches, don't launch a new connection for this
508 if (!tor_addr_compare(&conn
->real_addr
, target_addr
, CMP_EXACT
))
509 ++n_inprogress_goodaddr
;
512 /* Never return a connection that shouldn't be used for circs. */
513 if (conn
->is_bad_for_new_circs
) {
517 /* Never return a non-canonical connection using a recent link protocol
518 * if the address is not what we wanted.
520 * (For old link protocols, we can't rely on is_canonical getting
521 * set properly if we're talking to the right address, since we might
522 * have an out-of-date descriptor, and we will get no NETINFO cell to
523 * tell us about the right address.) */
524 if (!conn
->is_canonical
&& conn
->link_proto
>= 2 &&
525 tor_addr_compare(&conn
->real_addr
, target_addr
, CMP_EXACT
)) {
533 best
= conn
; /* If we have no 'best' so far, this one is good enough. */
537 if (connection_or_is_better(conn
, best
))
542 *msg_out
= "Connection is fine; using it.";
545 } else if (n_inprogress_goodaddr
) {
546 *msg_out
= "Connection in progress; waiting.";
549 } else if (n_old
|| n_noncanonical
) {
550 *msg_out
= "Connections all too old, or too non-canonical. "
551 " Launching a new one.";
555 *msg_out
= "Not connected. Connecting.";
561 /** How old do we let a connection to an OR get before deciding it's
562 * too old for new circuits? */
563 #define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)
565 /** Given the head of the linked list for all the or_connections with a given
566 * identity, set elements of that list as is_bad_for_new_circs() as
567 * appropriate. Helper for connection_or_set_bad_connections().
570 connection_or_group_set_badness(or_connection_t
*head
)
572 or_connection_t
*or_conn
= NULL
, *best
= NULL
;
573 int n_old
= 0, n_inprogress
= 0, n_canonical
= 0, n_other
= 0;
574 time_t now
= time(NULL
);
576 /* Pass 1: expire everything that's old, and see what the status of
577 * everything else is. */
578 for (or_conn
= head
; or_conn
; or_conn
= or_conn
->next_with_same_id
) {
579 if (or_conn
->_base
.marked_for_close
||
580 or_conn
->is_bad_for_new_circs
)
582 if (or_conn
->_base
.timestamp_created
+ TIME_BEFORE_OR_CONN_IS_TOO_OLD
585 "Marking OR conn to %s:%d as too old for new circuits "
586 "(fd %d, %d secs old).",
587 or_conn
->_base
.address
, or_conn
->_base
.port
, or_conn
->_base
.s
,
588 (int)(now
- or_conn
->_base
.timestamp_created
));
589 or_conn
->is_bad_for_new_circs
= 1;
592 if (or_conn
->is_bad_for_new_circs
) {
594 } else if (or_conn
->_base
.state
!= OR_CONN_STATE_OPEN
) {
596 } else if (or_conn
->is_canonical
) {
603 /* Pass 2: We know how about how good the best connection is.
604 * expire everything that's worse, and find the very best if we can. */
605 for (or_conn
= head
; or_conn
; or_conn
= or_conn
->next_with_same_id
) {
606 if (or_conn
->_base
.marked_for_close
||
607 or_conn
->is_bad_for_new_circs
)
608 continue; /* This one doesn't need to be marked bad. */
609 if (or_conn
->_base
.state
!= OR_CONN_STATE_OPEN
)
610 continue; /* Don't mark anything bad until we have seen what happens
611 * when the connection finishes. */
612 if (n_canonical
&& !or_conn
->is_canonical
) {
613 /* We have at least one open canonical connection to this router,
614 * and this one is open but not canonical. Mark it bad. */
616 "Marking OR conn to %s:%d as too old for new circuits: "
617 "(fd %d, %d secs old). It is not canonical, and we have "
618 "another connection to that OR that is.",
619 or_conn
->_base
.address
, or_conn
->_base
.port
, or_conn
->_base
.s
,
620 (int)(now
- or_conn
->_base
.timestamp_created
));
621 or_conn
->is_bad_for_new_circs
= 1;
625 if (!best
|| connection_or_is_better(or_conn
, best
))
632 /* Pass 3: One connection to OR is best. If it's canonical, mark as bad
633 * every other open connection. If it's non-canonical, mark as bad
634 * every other open connection to the same address.
638 for (or_conn
= head
; or_conn
; or_conn
= or_conn
->next_with_same_id
) {
639 if (or_conn
->_base
.marked_for_close
||
640 or_conn
->is_bad_for_new_circs
||
641 or_conn
->_base
.state
!= OR_CONN_STATE_OPEN
)
643 if (or_conn
!= best
) {
644 if (best
->is_canonical
) {
646 "Marking OR conn to %s:%d as too old for new circuits: "
647 "(fd %d, %d secs old). We have a better canonical one "
648 "(fd %d; %d secs old).",
649 or_conn
->_base
.address
, or_conn
->_base
.port
, or_conn
->_base
.s
,
650 (int)(now
- or_conn
->_base
.timestamp_created
),
651 best
->_base
.s
, (int)(now
- best
->_base
.timestamp_created
));
652 or_conn
->is_bad_for_new_circs
= 1;
653 } else if (!tor_addr_compare(&or_conn
->real_addr
,
654 &best
->real_addr
, CMP_EXACT
)) {
656 "Marking OR conn to %s:%d as too old for new circuits: "
657 "(fd %d, %d secs old). We have a better one "
658 "(fd %d; %d secs old).",
659 or_conn
->_base
.address
, or_conn
->_base
.port
, or_conn
->_base
.s
,
660 (int)(now
- or_conn
->_base
.timestamp_created
),
661 best
->_base
.s
, (int)(now
- best
->_base
.timestamp_created
));
662 or_conn
->is_bad_for_new_circs
= 1;
668 /** Go through all the OR connections, and set the is_bad_for_new_circs
670 * - all connections that are too old.
671 * - all open non-canonical connections for which a canonical connection
672 * exists to the same router.
673 * - all open canonical connections for which a 'better' canonical
674 * connection exists to the same router.
675 * - all open non-canonical connections for which a 'better' non-canonical
676 * connection exists to the same router at the same address.
678 * See connection_or_is_better() for our idea of what makes one OR connection
679 * better than another.
682 connection_or_set_bad_connections(void)
684 if (!orconn_identity_map
)
687 DIGESTMAP_FOREACH(orconn_identity_map
, identity
, or_connection_t
*, conn
) {
688 connection_or_group_set_badness(conn
);
689 } DIGESTMAP_FOREACH_END
;
692 /** <b>conn</b> is in the 'connecting' state, and it failed to complete
693 * a TCP connection. Send notifications appropriately.
695 * <b>reason</b> specifies the or_conn_end_reason for the failure;
696 * <b>msg</b> specifies the strerror-style error message.
699 connection_or_connect_failed(or_connection_t
*conn
,
700 int reason
, const char *msg
)
702 control_event_or_conn_status(conn
, OR_CONN_EVENT_FAILED
, reason
);
703 if (!authdir_mode_tests_reachability(get_options()))
704 control_event_bootstrap_problem(msg
, reason
);
707 /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
708 * handshake with an OR with identity digest <b>id_digest</b>.
710 * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
711 * return that connection. If the connect() is in progress, set the
712 * new conn's state to 'connecting' and return it. If connect() succeeds,
713 * call connection_tls_start_handshake() on it.
715 * This function is called from router_retry_connections(), for
716 * ORs connecting to ORs, and circuit_establish_circuit(), for
717 * OPs connecting to ORs.
719 * Return the launched conn, or NULL if it failed.
722 connection_or_connect(const tor_addr_t
*_addr
, uint16_t port
,
723 const char *id_digest
)
725 or_connection_t
*conn
;
726 or_options_t
*options
= get_options();
727 int socket_error
= 0;
731 tor_assert(id_digest
);
732 tor_addr_copy(&addr
, _addr
);
734 if (server_mode(options
) && router_digest_is_me(id_digest
)) {
735 log_info(LD_PROTOCOL
,"Client asked me to connect to myself. Refusing.");
739 conn
= or_connection_new(AF_INET
);
741 /* set up conn so it's got all the data we need to remember */
742 connection_or_init_conn_from_address(conn
, &addr
, port
, id_digest
, 1);
743 conn
->_base
.state
= OR_CONN_STATE_CONNECTING
;
744 control_event_or_conn_status(conn
, OR_CONN_EVENT_LAUNCHED
, 0);
746 if (options
->HttpsProxy
) {
747 /* we shouldn't connect directly. use the https proxy instead. */
748 tor_addr_from_ipv4h(&addr
, options
->HttpsProxyAddr
);
749 port
= options
->HttpsProxyPort
;
752 switch (connection_connect(TO_CONN(conn
), conn
->_base
.address
,
753 &addr
, port
, &socket_error
)) {
755 /* If the connection failed immediately, and we're using
756 * an https proxy, our https proxy is down. Don't blame the
758 if (!options
->HttpsProxy
) {
759 entry_guard_register_connect_status(conn
->identity_digest
, 0,
761 router_set_status(conn
->identity_digest
, 0);
763 connection_or_connect_failed(conn
,
764 errno_to_orconn_end_reason(socket_error
),
765 tor_socket_strerror(socket_error
));
766 connection_free(TO_CONN(conn
));
769 connection_watch_events(TO_CONN(conn
), EV_READ
| EV_WRITE
);
770 /* writable indicates finish, readable indicates broken link,
771 error indicates broken link on windows */
773 /* case 1: fall through */
776 if (connection_or_finished_connecting(conn
) < 0) {
777 /* already marked for close */
783 /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
784 * we initiated the connection, else it's 1.
786 * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
787 * pass <b>conn</b> to connection_tls_continue_handshake().
789 * Return -1 if <b>conn</b> is broken, else return 0.
792 connection_tls_start_handshake(or_connection_t
*conn
, int receiving
)
794 conn
->_base
.state
= OR_CONN_STATE_TLS_HANDSHAKING
;
795 conn
->tls
= tor_tls_new(conn
->_base
.s
, receiving
);
796 tor_tls_set_logged_address(conn
->tls
, escaped_safe_str(conn
->_base
.address
));
798 log_warn(LD_BUG
,"tor_tls_new failed. Closing.");
801 connection_start_reading(TO_CONN(conn
));
802 log_debug(LD_OR
,"starting TLS handshake on fd %d", conn
->_base
.s
);
803 note_crypto_pk_op(receiving
? TLS_HANDSHAKE_S
: TLS_HANDSHAKE_C
);
805 if (connection_tls_continue_handshake(conn
) < 0) {
811 /** Invoked on the server side from inside tor_tls_read() when the server
812 * gets a successful TLS renegotiation from the client. */
814 connection_or_tls_renegotiated_cb(tor_tls_t
*tls
, void *_conn
)
816 or_connection_t
*conn
= _conn
;
819 /* Don't invoke this again. */
820 tor_tls_set_renegotiate_callback(tls
, NULL
, NULL
);
822 if (connection_tls_finish_handshake(conn
) < 0) {
823 /* XXXX_TLS double-check that it's ok to do this from inside read. */
824 /* XXXX_TLS double-check that this verifies certificates. */
825 connection_mark_for_close(TO_CONN(conn
));
829 /** Move forward with the tls handshake. If it finishes, hand
830 * <b>conn</b> to connection_tls_finish_handshake().
832 * Return -1 if <b>conn</b> is broken, else return 0.
835 connection_tls_continue_handshake(or_connection_t
*conn
)
838 check_no_tls_errors();
840 if (conn
->_base
.state
== OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING
) {
841 // log_notice(LD_OR, "Renegotiate with %p", conn->tls);
842 result
= tor_tls_renegotiate(conn
->tls
);
843 // log_notice(LD_OR, "Result: %d", result);
845 tor_assert(conn
->_base
.state
== OR_CONN_STATE_TLS_HANDSHAKING
);
846 // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
847 result
= tor_tls_handshake(conn
->tls
);
848 // log_notice(LD_OR, "Result: %d", result);
851 CASE_TOR_TLS_ERROR_ANY
:
852 log_info(LD_OR
,"tls error [%s]. breaking connection.",
853 tor_tls_err_to_string(result
));
856 if (! tor_tls_used_v1_handshake(conn
->tls
)) {
857 if (!tor_tls_is_server(conn
->tls
)) {
858 if (conn
->_base
.state
== OR_CONN_STATE_TLS_HANDSHAKING
) {
859 // log_notice(LD_OR,"Done. state was TLS_HANDSHAKING.");
860 conn
->_base
.state
= OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING
;
863 // log_notice(LD_OR,"Done. state was %d.", conn->_base.state);
865 /* improved handshake, but not a client. */
866 tor_tls_set_renegotiate_callback(conn
->tls
,
867 connection_or_tls_renegotiated_cb
,
869 conn
->_base
.state
= OR_CONN_STATE_TLS_SERVER_RENEGOTIATING
;
870 connection_stop_writing(TO_CONN(conn
));
871 connection_start_reading(TO_CONN(conn
));
875 return connection_tls_finish_handshake(conn
);
876 case TOR_TLS_WANTWRITE
:
877 connection_start_writing(TO_CONN(conn
));
878 log_debug(LD_OR
,"wanted write");
880 case TOR_TLS_WANTREAD
: /* handshaking conns are *always* reading */
881 log_debug(LD_OR
,"wanted read");
884 log_info(LD_OR
,"tls closed. breaking connection.");
890 /** Return 1 if we initiated this connection, or 0 if it started
891 * out as an incoming connection.
894 connection_or_nonopen_was_started_here(or_connection_t
*conn
)
896 tor_assert(conn
->_base
.type
== CONN_TYPE_OR
);
898 return 1; /* it's still in proxy states or something */
899 if (conn
->handshake_state
)
900 return conn
->handshake_state
->started_here
;
901 return !tor_tls_is_server(conn
->tls
);
904 /** <b>Conn</b> just completed its handshake. Return 0 if all is well, and
905 * return -1 if he is lying, broken, or otherwise something is wrong.
907 * If we initiated this connection (<b>started_here</b> is true), make sure
908 * the other side sent sent a correctly formed certificate. If I initiated the
909 * connection, make sure it's the right guy.
911 * Otherwise (if we _didn't_ initiate this connection), it's okay for
912 * the certificate to be weird or absent.
914 * If we return 0, and the certificate is as expected, write a hash of the
915 * identity key into digest_rcvd, which must have DIGEST_LEN space in it. (If
916 * we return -1 this buffer is undefined.) If the certificate is invalid
917 * or missing on an incoming connection, we return 0 and set digest_rcvd to
918 * DIGEST_LEN 0 bytes.
921 * 1) Set conn->circ_id_type according to tor-spec.txt.
922 * 2) If we're an authdirserver and we initiated the connection: drop all
923 * descriptors that claim to be on that IP/port but that aren't
924 * this guy; and note that this guy is reachable.
927 connection_or_check_valid_tls_handshake(or_connection_t
*conn
,
929 char *digest_rcvd_out
)
931 crypto_pk_env_t
*identity_rcvd
=NULL
;
932 or_options_t
*options
= get_options();
933 int severity
= server_mode(options
) ? LOG_PROTOCOL_WARN
: LOG_WARN
;
934 const char *safe_address
=
935 started_here
? conn
->_base
.address
: safe_str(conn
->_base
.address
);
936 const char *conn_type
= started_here
? "outgoing" : "incoming";
937 int has_cert
= 0, has_identity
=0;
939 check_no_tls_errors();
940 has_cert
= tor_tls_peer_has_cert(conn
->tls
);
941 if (started_here
&& !has_cert
) {
942 log_info(LD_PROTOCOL
,"Tried connecting to router at %s:%d, but it didn't "
943 "send a cert! Closing.",
944 safe_address
, conn
->_base
.port
);
946 } else if (!has_cert
) {
947 log_debug(LD_PROTOCOL
,"Got incoming connection with no certificate. "
950 check_no_tls_errors();
953 int v
= tor_tls_verify(started_here
?severity
:LOG_INFO
,
954 conn
->tls
, &identity_rcvd
);
955 if (started_here
&& v
<0) {
956 log_fn(severity
,LD_OR
,"Tried connecting to router at %s:%d: It"
957 " has a cert but it's invalid. Closing.",
958 safe_address
, conn
->_base
.port
);
961 log_info(LD_PROTOCOL
,"Incoming connection gave us an invalid cert "
964 log_debug(LD_OR
,"The certificate seems to be valid on %s connection "
965 "with %s:%d", conn_type
, safe_address
, conn
->_base
.port
);
967 check_no_tls_errors();
972 crypto_pk_get_digest(identity_rcvd
, digest_rcvd_out
);
973 if (crypto_pk_cmp_keys(get_identity_key(), identity_rcvd
)<0) {
974 conn
->circ_id_type
= CIRC_ID_TYPE_LOWER
;
976 conn
->circ_id_type
= CIRC_ID_TYPE_HIGHER
;
978 crypto_free_pk_env(identity_rcvd
);
980 memset(digest_rcvd_out
, 0, DIGEST_LEN
);
981 conn
->circ_id_type
= CIRC_ID_TYPE_NEITHER
;
984 if (started_here
&& tor_digest_is_zero(conn
->identity_digest
)) {
985 connection_or_set_identity_digest(conn
, digest_rcvd_out
);
986 tor_free(conn
->nickname
);
987 conn
->nickname
= tor_malloc(HEX_DIGEST_LEN
+2);
988 conn
->nickname
[0] = '$';
989 base16_encode(conn
->nickname
+1, HEX_DIGEST_LEN
+1,
990 conn
->identity_digest
, DIGEST_LEN
);
991 log_info(LD_OR
, "Connected to router %s at %s:%d without knowing "
992 "its key. Hoping for the best.",
993 conn
->nickname
, conn
->_base
.address
, conn
->_base
.port
);
997 int as_advertised
= 1;
998 tor_assert(has_cert
);
999 tor_assert(has_identity
);
1000 if (memcmp(digest_rcvd_out
, conn
->identity_digest
, DIGEST_LEN
)) {
1001 /* I was aiming for a particular digest. I didn't get it! */
1002 char seen
[HEX_DIGEST_LEN
+1];
1003 char expected
[HEX_DIGEST_LEN
+1];
1004 base16_encode(seen
, sizeof(seen
), digest_rcvd_out
, DIGEST_LEN
);
1005 base16_encode(expected
, sizeof(expected
), conn
->identity_digest
,
1007 log_fn(severity
, LD_OR
,
1008 "Tried connecting to router at %s:%d, but identity key was not "
1009 "as expected: wanted %s but got %s.",
1010 conn
->_base
.address
, conn
->_base
.port
, expected
, seen
);
1011 entry_guard_register_connect_status(conn
->identity_digest
,0,time(NULL
));
1012 router_set_status(conn
->identity_digest
, 0);
1013 control_event_or_conn_status(conn
, OR_CONN_EVENT_FAILED
,
1014 END_OR_CONN_REASON_OR_IDENTITY
);
1015 if (!authdir_mode_tests_reachability(options
))
1016 control_event_bootstrap_problem("foo", END_OR_CONN_REASON_OR_IDENTITY
);
1019 if (authdir_mode_tests_reachability(options
)) {
1020 /* We initiated this connection to address:port. Drop all routers
1021 * with the same address:port and a different key.
1023 dirserv_orconn_tls_done(conn
->_base
.address
, conn
->_base
.port
,
1024 digest_rcvd_out
, as_advertised
);
1032 /** The tls handshake is finished.
1034 * Make sure we are happy with the person we just handshaked with.
1036 * If he initiated the connection, make sure he's not already connected,
1037 * then initialize conn from the information in router.
1039 * If all is successful, call circuit_n_conn_done() to handle events
1040 * that have been pending on the <tls handshake completion. Also set the
1041 * directory to be dirty (only matters if I'm an authdirserver).
1044 connection_tls_finish_handshake(or_connection_t
*conn
)
1046 char digest_rcvd
[DIGEST_LEN
];
1047 int started_here
= connection_or_nonopen_was_started_here(conn
);
1049 log_debug(LD_OR
,"tls handshake with %s done. verifying.",
1050 safe_str(conn
->_base
.address
));
1052 directory_set_dirty();
1054 if (connection_or_check_valid_tls_handshake(conn
, started_here
,
1058 if (tor_tls_used_v1_handshake(conn
->tls
)) {
1059 conn
->link_proto
= 1;
1060 if (!started_here
) {
1061 connection_or_init_conn_from_address(conn
, &conn
->_base
.addr
,
1062 conn
->_base
.port
, digest_rcvd
, 0);
1064 return connection_or_set_state_open(conn
);
1066 conn
->_base
.state
= OR_CONN_STATE_OR_HANDSHAKING
;
1067 if (connection_init_or_handshake_state(conn
, started_here
) < 0)
1069 if (!started_here
) {
1070 connection_or_init_conn_from_address(conn
, &conn
->_base
.addr
,
1071 conn
->_base
.port
, digest_rcvd
, 0);
1073 return connection_or_send_versions(conn
);
1077 /** Allocate a new connection handshake state for the connection
1078 * <b>conn</b>. Return 0 on success, -1 on failure. */
1080 connection_init_or_handshake_state(or_connection_t
*conn
, int started_here
)
1082 or_handshake_state_t
*s
;
1083 s
= conn
->handshake_state
= tor_malloc_zero(sizeof(or_handshake_state_t
));
1084 s
->started_here
= started_here
? 1 : 0;
1088 /** Free all storage held by <b>state</b>. */
1090 or_handshake_state_free(or_handshake_state_t
*state
)
1093 memset(state
, 0xBE, sizeof(or_handshake_state_t
));
1097 /** Set <b>conn</b>'s state to OR_CONN_STATE_OPEN, and tell other subsystems
1098 * as appropriate. Called when we are done with all TLS and OR handshaking.
1101 connection_or_set_state_open(or_connection_t
*conn
)
1103 int started_here
= connection_or_nonopen_was_started_here(conn
);
1104 time_t now
= time(NULL
);
1105 conn
->_base
.state
= OR_CONN_STATE_OPEN
;
1106 control_event_or_conn_status(conn
, OR_CONN_EVENT_CONNECTED
, 0);
1109 rep_hist_note_connect_succeeded(conn
->identity_digest
, now
);
1110 if (entry_guard_register_connect_status(conn
->identity_digest
,
1112 /* Close any circuits pending on this conn. We leave it in state
1113 * 'open' though, because it didn't actually *fail* -- we just
1114 * chose not to use it. (Otherwise
1115 * connection_about_to_close_connection() will call a big pile of
1116 * functions to indicate we shouldn't try it again.) */
1117 log_debug(LD_OR
, "New entry guard was reachable, but closing this "
1118 "connection so we can retry the earlier entry guards.");
1119 circuit_n_conn_done(conn
, 0);
1122 router_set_status(conn
->identity_digest
, 1);
1124 /* only report it to the geoip module if it's not a known router */
1125 if (!router_get_by_digest(conn
->identity_digest
)) {
1126 if (tor_addr_family(&TO_CONN(conn
)->addr
) == AF_INET
) {
1127 /*XXXX IP6 support ipv6 geoip.*/
1128 uint32_t a
= tor_addr_to_ipv4h(&TO_CONN(conn
)->addr
);
1129 geoip_note_client_seen(GEOIP_CLIENT_CONNECT
, a
, now
);
1133 if (conn
->handshake_state
) {
1134 or_handshake_state_free(conn
->handshake_state
);
1135 conn
->handshake_state
= NULL
;
1137 connection_start_reading(TO_CONN(conn
));
1138 circuit_n_conn_done(conn
, 1); /* send the pending creates, if any. */
1143 /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
1144 * For cells that use or affect a circuit, this should only be called by
1145 * connection_or_flush_from_first_active_circuit().
1148 connection_or_write_cell_to_buf(const cell_t
*cell
, or_connection_t
*conn
)
1150 packed_cell_t networkcell
;
1155 cell_pack(&networkcell
, cell
);
1157 connection_write_to_buf(networkcell
.body
, CELL_NETWORK_SIZE
, TO_CONN(conn
));
1159 if (cell
->command
!= CELL_PADDING
)
1160 conn
->timestamp_last_added_nonpadding
= approx_time();
1163 /** Pack a variable-length <b>cell</b> into wire-format, and write it onto
1164 * <b>conn</b>'s outbuf. Right now, this <em>DOES NOT</em> support cells that
1168 connection_or_write_var_cell_to_buf(const var_cell_t
*cell
,
1169 or_connection_t
*conn
)
1171 char hdr
[VAR_CELL_HEADER_SIZE
];
1174 var_cell_pack_header(cell
, hdr
);
1175 connection_write_to_buf(hdr
, sizeof(hdr
), TO_CONN(conn
));
1176 connection_write_to_buf(cell
->payload
, cell
->payload_len
, TO_CONN(conn
));
1177 if (cell
->command
!= CELL_PADDING
)
1178 conn
->timestamp_last_added_nonpadding
= approx_time();
1181 /** See whether there's a variable-length cell waiting on <b>conn</b>'s
1182 * inbuf. Return values as for fetch_var_cell_from_buf(). */
1184 connection_fetch_var_cell_from_buf(or_connection_t
*conn
, var_cell_t
**out
)
1186 return fetch_var_cell_from_buf(conn
->_base
.inbuf
, out
, conn
->link_proto
);
1189 /** Process cells from <b>conn</b>'s inbuf.
1191 * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
1192 * and hand it to command_process_cell().
1197 connection_or_process_cells_from_inbuf(or_connection_t
*conn
)
1199 var_cell_t
*var_cell
;
1203 "%d: starting, inbuf_datalen %d (%d pending in tls object).",
1204 conn
->_base
.s
,(int)buf_datalen(conn
->_base
.inbuf
),
1205 tor_tls_get_pending_bytes(conn
->tls
));
1206 if (connection_fetch_var_cell_from_buf(conn
, &var_cell
)) {
1208 return 0; /* not yet. */
1209 command_process_var_cell(var_cell
, conn
);
1210 var_cell_free(var_cell
);
1212 char buf
[CELL_NETWORK_SIZE
];
1214 if (buf_datalen(conn
->_base
.inbuf
) < CELL_NETWORK_SIZE
) /* whole response
1216 return 0; /* not yet */
1218 connection_fetch_from_buf(buf
, CELL_NETWORK_SIZE
, TO_CONN(conn
));
1220 /* retrieve cell info from buf (create the host-order struct from the
1221 * network-order string) */
1222 cell_unpack(&cell
, buf
);
1224 command_process_cell(&cell
, conn
);
1229 /** Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
1230 * onto OR connection <b>conn</b>. Don't perform range-checking on reason:
1231 * we may want to propagate reasons from other cells.
1236 connection_or_send_destroy(circid_t circ_id
, or_connection_t
*conn
, int reason
)
1242 memset(&cell
, 0, sizeof(cell_t
));
1243 cell
.circ_id
= circ_id
;
1244 cell
.command
= CELL_DESTROY
;
1245 cell
.payload
[0] = (uint8_t) reason
;
1246 log_debug(LD_OR
,"Sending destroy (circID %d).", circ_id
);
1248 /* XXXX It's possible that under some circumstances, we want the destroy
1249 * to take precedence over other data waiting on the circuit's cell queue.
1252 connection_or_write_cell_to_buf(&cell
, conn
);
1256 /** Array of recognized link protocol versions. */
1257 static const uint16_t or_protocol_versions
[] = { 1, 2 };
1258 /** Number of versions in <b>or_protocol_versions</b>. */
1259 static const int n_or_protocol_versions
=
1260 (int)( sizeof(or_protocol_versions
)/sizeof(uint16_t) );
1262 /** Return true iff <b>v</b> is a link protocol version that this Tor
1263 * implementation believes it can support. */
1265 is_or_protocol_version_known(uint16_t v
)
1268 for (i
= 0; i
< n_or_protocol_versions
; ++i
) {
1269 if (or_protocol_versions
[i
] == v
)
1275 /** Send a VERSIONS cell on <b>conn</b>, telling the other host about the
1276 * link protocol versions that this Tor can support. */
1278 connection_or_send_versions(or_connection_t
*conn
)
1282 tor_assert(conn
->handshake_state
&&
1283 !conn
->handshake_state
->sent_versions_at
);
1284 cell
= var_cell_new(n_or_protocol_versions
* 2);
1285 cell
->command
= CELL_VERSIONS
;
1286 for (i
= 0; i
< n_or_protocol_versions
; ++i
) {
1287 uint16_t v
= or_protocol_versions
[i
];
1288 set_uint16(cell
->payload
+(2*i
), htons(v
));
1291 connection_or_write_var_cell_to_buf(cell
, conn
);
1292 conn
->handshake_state
->sent_versions_at
= time(NULL
);
1294 var_cell_free(cell
);
1298 /** Send a NETINFO cell on <b>conn</b>, telling the other server what we know
1299 * about their address, our address, and the current time. */
1301 connection_or_send_netinfo(or_connection_t
*conn
)
1304 time_t now
= time(NULL
);
1309 memset(&cell
, 0, sizeof(cell_t
));
1310 cell
.command
= CELL_NETINFO
;
1313 set_uint32(cell
.payload
, htonl((uint32_t)now
));
1315 /* Their address. */
1316 out
= cell
.payload
+ 4;
1317 len
= append_address_to_payload(out
, &conn
->_base
.addr
);
1323 if ((me
= router_get_my_routerinfo())) {
1325 *out
++ = 1; /* only one address is supported. */
1327 tor_addr_from_ipv4h(&my_addr
, me
->addr
);
1328 len
= append_address_to_payload(out
, &my_addr
);
1336 connection_or_write_cell_to_buf(&cell
, conn
);