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-2009, 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 /** Handle any new bytes that have come in on connection <b>conn</b>.
191 * If conn is in 'open' state, hand it to
192 * connection_or_process_cells_from_inbuf()
196 connection_or_process_inbuf(or_connection_t
*conn
)
201 switch (conn
->_base
.state
) {
202 case OR_CONN_STATE_PROXY_HANDSHAKING
:
203 ret
= connection_read_proxy_handshake(TO_CONN(conn
));
205 /* start TLS after handshake completion, or deal with error */
207 tor_assert(TO_CONN(conn
)->proxy_state
== PROXY_CONNECTED
);
208 if (connection_tls_start_handshake(conn
, 0) < 0)
212 connection_mark_for_close(TO_CONN(conn
));
216 case OR_CONN_STATE_OPEN
:
217 case OR_CONN_STATE_OR_HANDSHAKING
:
218 return connection_or_process_cells_from_inbuf(conn
);
220 return 0; /* don't do anything */
224 /** When adding cells to an OR connection's outbuf, keep adding until the
225 * outbuf is at least this long, or we run out of cells. */
226 #define OR_CONN_HIGHWATER (32*1024)
228 /** Add cells to an OR connection's outbuf whenever the outbuf's data length
229 * drops below this size. */
230 #define OR_CONN_LOWWATER (16*1024)
232 /** Called whenever we have flushed some data on an or_conn: add more data
233 * from active circuits. */
235 connection_or_flushed_some(or_connection_t
*conn
)
237 size_t datalen
= buf_datalen(conn
->_base
.outbuf
);
238 /* If we're under the low water mark, add cells until we're just over the
239 * high water mark. */
240 if (datalen
< OR_CONN_LOWWATER
) {
241 ssize_t n
= (OR_CONN_HIGHWATER
- datalen
+ CELL_NETWORK_SIZE
-1)
243 time_t now
= approx_time();
244 while (conn
->active_circuits
&& n
> 0) {
246 flushed
= connection_or_flush_from_first_active_circuit(conn
, 1, now
);
253 /** Connection <b>conn</b> has finished writing and has no bytes left on
256 * Otherwise it's in state "open": stop writing and return.
258 * If <b>conn</b> is broken, mark it for close and return -1, else
262 connection_or_finished_flushing(or_connection_t
*conn
)
265 assert_connection_ok(TO_CONN(conn
),0);
267 switch (conn
->_base
.state
) {
268 case OR_CONN_STATE_PROXY_HANDSHAKING
:
269 case OR_CONN_STATE_OPEN
:
270 case OR_CONN_STATE_OR_HANDSHAKING
:
271 connection_stop_writing(TO_CONN(conn
));
274 log_err(LD_BUG
,"Called in unexpected state %d.", conn
->_base
.state
);
275 tor_fragile_assert();
281 /** Connected handler for OR connections: begin the TLS handshake.
284 connection_or_finished_connecting(or_connection_t
*or_conn
)
289 conn
= TO_CONN(or_conn
);
290 tor_assert(conn
->state
== OR_CONN_STATE_CONNECTING
);
292 log_debug(LD_OR
,"OR connect() to router at %s:%u finished.",
293 conn
->address
,conn
->port
);
294 control_event_bootstrap(BOOTSTRAP_STATUS_HANDSHAKE
, 0);
296 proxy_type
= PROXY_NONE
;
298 if (get_options()->HttpsProxy
)
299 proxy_type
= PROXY_CONNECT
;
300 else if (get_options()->Socks4Proxy
)
301 proxy_type
= PROXY_SOCKS4
;
302 else if (get_options()->Socks5Proxy
)
303 proxy_type
= PROXY_SOCKS5
;
305 if (proxy_type
!= PROXY_NONE
) {
306 /* start proxy handshake */
307 if (connection_proxy_connect(conn
, proxy_type
) < 0) {
308 connection_mark_for_close(conn
);
312 connection_start_reading(conn
);
313 conn
->state
= OR_CONN_STATE_PROXY_HANDSHAKING
;
317 if (connection_tls_start_handshake(or_conn
, 0) < 0) {
318 /* TLS handshaking error of some kind. */
319 connection_mark_for_close(conn
);
325 /** If we don't necessarily know the router we're connecting to, but we
326 * have an addr/port/id_digest, then fill in as much as we can. Start
327 * by checking to see if this describes a router we know. */
329 connection_or_init_conn_from_address(or_connection_t
*conn
,
330 const tor_addr_t
*addr
, uint16_t port
,
331 const char *id_digest
,
334 or_options_t
*options
= get_options();
335 routerinfo_t
*r
= router_get_by_digest(id_digest
);
336 conn
->bandwidthrate
= (int)options
->BandwidthRate
;
337 conn
->read_bucket
= conn
->bandwidthburst
= (int)options
->BandwidthBurst
;
338 connection_or_set_identity_digest(conn
, id_digest
);
340 conn
->_base
.port
= port
;
341 tor_addr_copy(&conn
->_base
.addr
, addr
);
342 tor_addr_copy(&conn
->real_addr
, addr
);
344 /* XXXX proposal 118 will make this more complex. */
345 if (tor_addr_eq_ipv4h(&conn
->_base
.addr
, r
->addr
))
346 conn
->is_canonical
= 1;
348 /* Override the addr/port, so our log messages will make sense.
349 * This is dangerous, since if we ever try looking up a conn by
350 * its actual addr/port, we won't remember. Careful! */
351 /* XXXX arma: this is stupid, and it's the reason we need real_addr
352 * to track is_canonical properly. What requires it? */
353 /* XXXX <arma> i believe the reason we did this, originally, is because
354 * we wanted to log what OR a connection was to, and if we logged the
355 * right IP address and port 56244, that wouldn't be as helpful. now we
356 * log the "right" port too, so we know if it's moria1 or moria2.
358 tor_addr_from_ipv4h(&conn
->_base
.addr
, r
->addr
);
359 conn
->_base
.port
= r
->or_port
;
361 conn
->nickname
= tor_strdup(r
->nickname
);
362 tor_free(conn
->_base
.address
);
363 conn
->_base
.address
= tor_strdup(r
->address
);
366 /* If we're an authoritative directory server, we may know a
367 * nickname for this router. */
368 n
= dirserv_get_nickname_by_digest(id_digest
);
370 conn
->nickname
= tor_strdup(n
);
372 conn
->nickname
= tor_malloc(HEX_DIGEST_LEN
+2);
373 conn
->nickname
[0] = '$';
374 base16_encode(conn
->nickname
+1, HEX_DIGEST_LEN
+1,
375 conn
->identity_digest
, DIGEST_LEN
);
377 tor_free(conn
->_base
.address
);
378 conn
->_base
.address
= tor_dup_addr(addr
);
382 /** Return true iff <b>a</b> is "better" than <b>b</b> for new circuits.
384 * A more canonical connection is always better than a less canonical
385 * connection. That aside, a connection is better if it has circuits and the
386 * other does not, or if it was created more recently.
388 * Requires that both input connections are open; not is_bad_for_new_circs,
389 * and not impossibly non-canonical.
391 * If </b>forgive_new_connections</b> is true, then we do not call
392 * <b>a</b>better than <b>b</b> simply because b has no circuits,
393 * unless b is also relatively old.
396 connection_or_is_better(time_t now
,
397 const or_connection_t
*a
,
398 const or_connection_t
*b
,
399 int forgive_new_connections
)
402 /** Do not definitively deprecate a new connection with no circuits on it
403 * until this much time has passed. */
404 #define NEW_CONN_GRACE_PERIOD (15*60)
406 if (b
->is_canonical
&& !a
->is_canonical
)
407 return 0; /* A canonical connection is better than a non-canonical
408 * one, no matter how new it is or which has circuits. */
410 newer
= b
->_base
.timestamp_created
< a
->_base
.timestamp_created
;
413 /* We prefer canonical connections regardless of newness. */
414 (!b
->is_canonical
&& a
->is_canonical
) ||
415 /* If both have circuits we prefer the newer: */
416 (b
->n_circuits
&& a
->n_circuits
&& newer
) ||
417 /* If neither has circuits we prefer the newer: */
418 (!b
->n_circuits
&& !a
->n_circuits
&& newer
))
421 /* If one has no circuits and the other does... */
422 if (!b
->n_circuits
&& a
->n_circuits
) {
423 /* Then it's bad, unless it's in its grace period and we're forgiving. */
424 if (forgive_new_connections
&&
425 now
< b
->_base
.timestamp_created
+ NEW_CONN_GRACE_PERIOD
)
434 /** Return the OR connection we should use to extend a circuit to the router
435 * whose identity is <b>digest</b>, and whose address we believe (or have been
436 * told in an extend cell) is <b>target_addr</b>. If there is no good
437 * connection, set *<b>msg_out</b> to a message describing the connection's
438 * state and our next action, and set <b>launch_out</b> to a boolean for
439 * whether we should launch a new connection or not.
442 connection_or_get_for_extend(const char *digest
,
443 const tor_addr_t
*target_addr
,
444 const char **msg_out
,
447 or_connection_t
*conn
, *best
=NULL
;
448 int n_inprogress_goodaddr
= 0, n_old
= 0, n_noncanonical
= 0, n_possible
= 0;
449 time_t now
= approx_time();
452 tor_assert(launch_out
);
454 if (!orconn_identity_map
) {
455 *msg_out
= "Router not connected (nothing is). Connecting.";
460 conn
= digestmap_get(orconn_identity_map
, digest
);
462 for (; conn
; conn
= conn
->next_with_same_id
) {
463 tor_assert(conn
->_base
.magic
== OR_CONNECTION_MAGIC
);
464 tor_assert(conn
->_base
.type
== CONN_TYPE_OR
);
465 tor_assert(!memcmp(conn
->identity_digest
, digest
, DIGEST_LEN
));
466 if (conn
->_base
.marked_for_close
)
468 /* Never return a non-open connection. */
469 if (conn
->_base
.state
!= OR_CONN_STATE_OPEN
) {
470 /* If the address matches, don't launch a new connection for this
472 if (!tor_addr_compare(&conn
->real_addr
, target_addr
, CMP_EXACT
))
473 ++n_inprogress_goodaddr
;
476 /* Never return a connection that shouldn't be used for circs. */
477 if (conn
->is_bad_for_new_circs
) {
481 /* Never return a non-canonical connection using a recent link protocol
482 * if the address is not what we wanted.
484 * (For old link protocols, we can't rely on is_canonical getting
485 * set properly if we're talking to the right address, since we might
486 * have an out-of-date descriptor, and we will get no NETINFO cell to
487 * tell us about the right address.) */
488 if (!conn
->is_canonical
&& conn
->link_proto
>= 2 &&
489 tor_addr_compare(&conn
->real_addr
, target_addr
, CMP_EXACT
)) {
497 best
= conn
; /* If we have no 'best' so far, this one is good enough. */
501 if (connection_or_is_better(now
, conn
, best
, 0))
506 *msg_out
= "Connection is fine; using it.";
509 } else if (n_inprogress_goodaddr
) {
510 *msg_out
= "Connection in progress; waiting.";
513 } else if (n_old
|| n_noncanonical
) {
514 *msg_out
= "Connections all too old, or too non-canonical. "
515 " Launching a new one.";
519 *msg_out
= "Not connected. Connecting.";
525 /** How old do we let a connection to an OR get before deciding it's
526 * too old for new circuits? */
527 #define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)
529 /** Given the head of the linked list for all the or_connections with a given
530 * identity, set elements of that list as is_bad_for_new_circs() as
531 * appropriate. Helper for connection_or_set_bad_connections().
534 connection_or_group_set_badness(or_connection_t
*head
)
536 or_connection_t
*or_conn
= NULL
, *best
= NULL
;
537 int n_old
= 0, n_inprogress
= 0, n_canonical
= 0, n_other
= 0;
538 time_t now
= time(NULL
);
540 /* Pass 1: expire everything that's old, and see what the status of
541 * everything else is. */
542 for (or_conn
= head
; or_conn
; or_conn
= or_conn
->next_with_same_id
) {
543 if (or_conn
->_base
.marked_for_close
||
544 or_conn
->is_bad_for_new_circs
)
546 if (or_conn
->_base
.timestamp_created
+ TIME_BEFORE_OR_CONN_IS_TOO_OLD
549 "Marking OR conn to %s:%d as too old for new circuits "
550 "(fd %d, %d secs old).",
551 or_conn
->_base
.address
, or_conn
->_base
.port
, or_conn
->_base
.s
,
552 (int)(now
- or_conn
->_base
.timestamp_created
));
553 or_conn
->is_bad_for_new_circs
= 1;
556 if (or_conn
->is_bad_for_new_circs
) {
558 } else if (or_conn
->_base
.state
!= OR_CONN_STATE_OPEN
) {
560 } else if (or_conn
->is_canonical
) {
567 /* Pass 2: We know how about how good the best connection is.
568 * expire everything that's worse, and find the very best if we can. */
569 for (or_conn
= head
; or_conn
; or_conn
= or_conn
->next_with_same_id
) {
570 if (or_conn
->_base
.marked_for_close
||
571 or_conn
->is_bad_for_new_circs
)
572 continue; /* This one doesn't need to be marked bad. */
573 if (or_conn
->_base
.state
!= OR_CONN_STATE_OPEN
)
574 continue; /* Don't mark anything bad until we have seen what happens
575 * when the connection finishes. */
576 if (n_canonical
&& !or_conn
->is_canonical
) {
577 /* We have at least one open canonical connection to this router,
578 * and this one is open but not canonical. Mark it bad. */
580 "Marking OR conn to %s:%d as too old for new circuits: "
581 "(fd %d, %d secs old). It is not canonical, and we have "
582 "another connection to that OR that is.",
583 or_conn
->_base
.address
, or_conn
->_base
.port
, or_conn
->_base
.s
,
584 (int)(now
- or_conn
->_base
.timestamp_created
));
585 or_conn
->is_bad_for_new_circs
= 1;
589 if (!best
|| connection_or_is_better(now
, or_conn
, best
, 0))
596 /* Pass 3: One connection to OR is best. If it's canonical, mark as bad
597 * every other open connection. If it's non-canonical, mark as bad
598 * every other open connection to the same address.
600 * XXXX This isn't optimal; if we have connections to an OR at multiple
601 * addresses, we'd like to pick the best _for each address_, and mark as
602 * bad every open connection that isn't best for its address. But this
603 * can only occur in cases where the other OR is old (so we have no
604 * canonical connection to it), or where all the connections to the OR are
605 * at noncanonical addresses and we have no good direct connection (which
606 * means we aren't at risk of attaching circuits to it anyway). As
607 * 0.1.2.x dies out, the first case will go away, and the second one is
608 * "mostly harmless", so a fix can wait until somebody is bored.
610 for (or_conn
= head
; or_conn
; or_conn
= or_conn
->next_with_same_id
) {
611 if (or_conn
->_base
.marked_for_close
||
612 or_conn
->is_bad_for_new_circs
||
613 or_conn
->_base
.state
!= OR_CONN_STATE_OPEN
)
615 if (or_conn
!= best
&& connection_or_is_better(now
, best
, or_conn
, 1)) {
616 /* This isn't the best conn, _and_ the best conn is better than it,
617 even when we're being forgiving. */
618 if (best
->is_canonical
) {
620 "Marking OR conn to %s:%d as too old for new circuits: "
621 "(fd %d, %d secs old). We have a better canonical one "
622 "(fd %d; %d secs old).",
623 or_conn
->_base
.address
, or_conn
->_base
.port
, or_conn
->_base
.s
,
624 (int)(now
- or_conn
->_base
.timestamp_created
),
625 best
->_base
.s
, (int)(now
- best
->_base
.timestamp_created
));
626 or_conn
->is_bad_for_new_circs
= 1;
627 } else if (!tor_addr_compare(&or_conn
->real_addr
,
628 &best
->real_addr
, CMP_EXACT
)) {
630 "Marking OR conn to %s:%d as too old for new circuits: "
631 "(fd %d, %d secs old). We have a better one "
632 "(fd %d; %d secs old).",
633 or_conn
->_base
.address
, or_conn
->_base
.port
, or_conn
->_base
.s
,
634 (int)(now
- or_conn
->_base
.timestamp_created
),
635 best
->_base
.s
, (int)(now
- best
->_base
.timestamp_created
));
636 or_conn
->is_bad_for_new_circs
= 1;
642 /** Go through all the OR connections, and set the is_bad_for_new_circs
644 * - all connections that are too old.
645 * - all open non-canonical connections for which a canonical connection
646 * exists to the same router.
647 * - all open canonical connections for which a 'better' canonical
648 * connection exists to the same router.
649 * - all open non-canonical connections for which a 'better' non-canonical
650 * connection exists to the same router at the same address.
652 * See connection_or_is_better() for our idea of what makes one OR connection
653 * better than another.
656 connection_or_set_bad_connections(void)
658 if (!orconn_identity_map
)
661 DIGESTMAP_FOREACH(orconn_identity_map
, identity
, or_connection_t
*, conn
) {
662 connection_or_group_set_badness(conn
);
663 } DIGESTMAP_FOREACH_END
;
666 /** <b>conn</b> is in the 'connecting' state, and it failed to complete
667 * a TCP connection. Send notifications appropriately.
669 * <b>reason</b> specifies the or_conn_end_reason for the failure;
670 * <b>msg</b> specifies the strerror-style error message.
673 connection_or_connect_failed(or_connection_t
*conn
,
674 int reason
, const char *msg
)
676 control_event_or_conn_status(conn
, OR_CONN_EVENT_FAILED
, reason
);
677 if (!authdir_mode_tests_reachability(get_options()))
678 control_event_bootstrap_problem(msg
, reason
);
681 /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
682 * handshake with an OR with identity digest <b>id_digest</b>.
684 * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
685 * return that connection. If the connect() is in progress, set the
686 * new conn's state to 'connecting' and return it. If connect() succeeds,
687 * call connection_tls_start_handshake() on it.
689 * This function is called from router_retry_connections(), for
690 * ORs connecting to ORs, and circuit_establish_circuit(), for
691 * OPs connecting to ORs.
693 * Return the launched conn, or NULL if it failed.
696 connection_or_connect(const tor_addr_t
*_addr
, uint16_t port
,
697 const char *id_digest
)
699 or_connection_t
*conn
;
700 or_options_t
*options
= get_options();
701 int socket_error
= 0;
706 tor_assert(id_digest
);
707 tor_addr_copy(&addr
, _addr
);
709 if (server_mode(options
) && router_digest_is_me(id_digest
)) {
710 log_info(LD_PROTOCOL
,"Client asked me to connect to myself. Refusing.");
714 conn
= or_connection_new(AF_INET
);
716 /* set up conn so it's got all the data we need to remember */
717 connection_or_init_conn_from_address(conn
, &addr
, port
, id_digest
, 1);
718 conn
->_base
.state
= OR_CONN_STATE_CONNECTING
;
719 control_event_or_conn_status(conn
, OR_CONN_EVENT_LAUNCHED
, 0);
721 /* use a proxy server if available */
722 if (options
->HttpsProxy
) {
724 tor_addr_copy(&addr
, &options
->HttpsProxyAddr
);
725 port
= options
->HttpsProxyPort
;
726 } else if (options
->Socks4Proxy
) {
728 tor_addr_copy(&addr
, &options
->Socks4ProxyAddr
);
729 port
= options
->Socks4ProxyPort
;
730 } else if (options
->Socks5Proxy
) {
732 tor_addr_copy(&addr
, &options
->Socks5ProxyAddr
);
733 port
= options
->Socks5ProxyPort
;
736 switch (connection_connect(TO_CONN(conn
), conn
->_base
.address
,
737 &addr
, port
, &socket_error
)) {
739 /* If the connection failed immediately, and we're using
740 * a proxy, our proxy is down. Don't blame the Tor server. */
742 entry_guard_register_connect_status(conn
->identity_digest
,
744 connection_or_connect_failed(conn
,
745 errno_to_orconn_end_reason(socket_error
),
746 tor_socket_strerror(socket_error
));
747 connection_free(TO_CONN(conn
));
750 connection_watch_events(TO_CONN(conn
), READ_EVENT
| WRITE_EVENT
);
751 /* writable indicates finish, readable indicates broken link,
752 error indicates broken link on windows */
754 /* case 1: fall through */
757 if (connection_or_finished_connecting(conn
) < 0) {
758 /* already marked for close */
764 /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
765 * we initiated the connection, else it's 1.
767 * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
768 * pass <b>conn</b> to connection_tls_continue_handshake().
770 * Return -1 if <b>conn</b> is broken, else return 0.
773 connection_tls_start_handshake(or_connection_t
*conn
, int receiving
)
775 conn
->_base
.state
= OR_CONN_STATE_TLS_HANDSHAKING
;
776 conn
->tls
= tor_tls_new(conn
->_base
.s
, receiving
);
777 tor_tls_set_logged_address(conn
->tls
, escaped_safe_str(conn
->_base
.address
));
779 log_warn(LD_BUG
,"tor_tls_new failed. Closing.");
782 connection_start_reading(TO_CONN(conn
));
783 log_debug(LD_OR
,"starting TLS handshake on fd %d", conn
->_base
.s
);
784 note_crypto_pk_op(receiving
? TLS_HANDSHAKE_S
: TLS_HANDSHAKE_C
);
786 if (connection_tls_continue_handshake(conn
) < 0) {
792 /** Invoked on the server side from inside tor_tls_read() when the server
793 * gets a successful TLS renegotiation from the client. */
795 connection_or_tls_renegotiated_cb(tor_tls_t
*tls
, void *_conn
)
797 or_connection_t
*conn
= _conn
;
800 /* Don't invoke this again. */
801 tor_tls_set_renegotiate_callback(tls
, NULL
, NULL
);
803 if (connection_tls_finish_handshake(conn
) < 0) {
804 /* XXXX_TLS double-check that it's ok to do this from inside read. */
805 /* XXXX_TLS double-check that this verifies certificates. */
806 connection_mark_for_close(TO_CONN(conn
));
810 /** Move forward with the tls handshake. If it finishes, hand
811 * <b>conn</b> to connection_tls_finish_handshake().
813 * Return -1 if <b>conn</b> is broken, else return 0.
816 connection_tls_continue_handshake(or_connection_t
*conn
)
819 check_no_tls_errors();
821 if (conn
->_base
.state
== OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING
) {
822 // log_notice(LD_OR, "Renegotiate with %p", conn->tls);
823 result
= tor_tls_renegotiate(conn
->tls
);
824 // log_notice(LD_OR, "Result: %d", result);
826 tor_assert(conn
->_base
.state
== OR_CONN_STATE_TLS_HANDSHAKING
);
827 // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
828 result
= tor_tls_handshake(conn
->tls
);
829 // log_notice(LD_OR, "Result: %d", result);
832 CASE_TOR_TLS_ERROR_ANY
:
833 log_info(LD_OR
,"tls error [%s]. breaking connection.",
834 tor_tls_err_to_string(result
));
837 if (! tor_tls_used_v1_handshake(conn
->tls
)) {
838 if (!tor_tls_is_server(conn
->tls
)) {
839 if (conn
->_base
.state
== OR_CONN_STATE_TLS_HANDSHAKING
) {
840 // log_notice(LD_OR,"Done. state was TLS_HANDSHAKING.");
841 conn
->_base
.state
= OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING
;
844 // log_notice(LD_OR,"Done. state was %d.", conn->_base.state);
846 /* improved handshake, but not a client. */
847 tor_tls_set_renegotiate_callback(conn
->tls
,
848 connection_or_tls_renegotiated_cb
,
850 conn
->_base
.state
= OR_CONN_STATE_TLS_SERVER_RENEGOTIATING
;
851 connection_stop_writing(TO_CONN(conn
));
852 connection_start_reading(TO_CONN(conn
));
856 return connection_tls_finish_handshake(conn
);
857 case TOR_TLS_WANTWRITE
:
858 connection_start_writing(TO_CONN(conn
));
859 log_debug(LD_OR
,"wanted write");
861 case TOR_TLS_WANTREAD
: /* handshaking conns are *always* reading */
862 log_debug(LD_OR
,"wanted read");
865 log_info(LD_OR
,"tls closed. breaking connection.");
871 /** Return 1 if we initiated this connection, or 0 if it started
872 * out as an incoming connection.
875 connection_or_nonopen_was_started_here(or_connection_t
*conn
)
877 tor_assert(conn
->_base
.type
== CONN_TYPE_OR
);
879 return 1; /* it's still in proxy states or something */
880 if (conn
->handshake_state
)
881 return conn
->handshake_state
->started_here
;
882 return !tor_tls_is_server(conn
->tls
);
885 /** <b>Conn</b> just completed its handshake. Return 0 if all is well, and
886 * return -1 if he is lying, broken, or otherwise something is wrong.
888 * If we initiated this connection (<b>started_here</b> is true), make sure
889 * the other side sent sent a correctly formed certificate. If I initiated the
890 * connection, make sure it's the right guy.
892 * Otherwise (if we _didn't_ initiate this connection), it's okay for
893 * the certificate to be weird or absent.
895 * If we return 0, and the certificate is as expected, write a hash of the
896 * identity key into digest_rcvd, which must have DIGEST_LEN space in it. (If
897 * we return -1 this buffer is undefined.) If the certificate is invalid
898 * or missing on an incoming connection, we return 0 and set digest_rcvd to
899 * DIGEST_LEN 0 bytes.
902 * 1) Set conn->circ_id_type according to tor-spec.txt.
903 * 2) If we're an authdirserver and we initiated the connection: drop all
904 * descriptors that claim to be on that IP/port but that aren't
905 * this guy; and note that this guy is reachable.
908 connection_or_check_valid_tls_handshake(or_connection_t
*conn
,
910 char *digest_rcvd_out
)
912 crypto_pk_env_t
*identity_rcvd
=NULL
;
913 or_options_t
*options
= get_options();
914 int severity
= server_mode(options
) ? LOG_PROTOCOL_WARN
: LOG_WARN
;
915 const char *safe_address
=
916 started_here
? conn
->_base
.address
: safe_str(conn
->_base
.address
);
917 const char *conn_type
= started_here
? "outgoing" : "incoming";
918 int has_cert
= 0, has_identity
=0;
920 check_no_tls_errors();
921 has_cert
= tor_tls_peer_has_cert(conn
->tls
);
922 if (started_here
&& !has_cert
) {
923 log_info(LD_PROTOCOL
,"Tried connecting to router at %s:%d, but it didn't "
924 "send a cert! Closing.",
925 safe_address
, conn
->_base
.port
);
927 } else if (!has_cert
) {
928 log_debug(LD_PROTOCOL
,"Got incoming connection with no certificate. "
931 check_no_tls_errors();
934 int v
= tor_tls_verify(started_here
?severity
:LOG_INFO
,
935 conn
->tls
, &identity_rcvd
);
936 if (started_here
&& v
<0) {
937 log_fn(severity
,LD_OR
,"Tried connecting to router at %s:%d: It"
938 " has a cert but it's invalid. Closing.",
939 safe_address
, conn
->_base
.port
);
942 log_info(LD_PROTOCOL
,"Incoming connection gave us an invalid cert "
945 log_debug(LD_OR
,"The certificate seems to be valid on %s connection "
946 "with %s:%d", conn_type
, safe_address
, conn
->_base
.port
);
948 check_no_tls_errors();
953 crypto_pk_get_digest(identity_rcvd
, digest_rcvd_out
);
954 if (crypto_pk_cmp_keys(get_identity_key(), identity_rcvd
)<0) {
955 conn
->circ_id_type
= CIRC_ID_TYPE_LOWER
;
957 conn
->circ_id_type
= CIRC_ID_TYPE_HIGHER
;
959 crypto_free_pk_env(identity_rcvd
);
961 memset(digest_rcvd_out
, 0, DIGEST_LEN
);
962 conn
->circ_id_type
= CIRC_ID_TYPE_NEITHER
;
965 if (started_here
&& tor_digest_is_zero(conn
->identity_digest
)) {
966 connection_or_set_identity_digest(conn
, digest_rcvd_out
);
967 tor_free(conn
->nickname
);
968 conn
->nickname
= tor_malloc(HEX_DIGEST_LEN
+2);
969 conn
->nickname
[0] = '$';
970 base16_encode(conn
->nickname
+1, HEX_DIGEST_LEN
+1,
971 conn
->identity_digest
, DIGEST_LEN
);
972 log_info(LD_OR
, "Connected to router %s at %s:%d without knowing "
973 "its key. Hoping for the best.",
974 conn
->nickname
, conn
->_base
.address
, conn
->_base
.port
);
978 int as_advertised
= 1;
979 tor_assert(has_cert
);
980 tor_assert(has_identity
);
981 if (memcmp(digest_rcvd_out
, conn
->identity_digest
, DIGEST_LEN
)) {
982 /* I was aiming for a particular digest. I didn't get it! */
983 char seen
[HEX_DIGEST_LEN
+1];
984 char expected
[HEX_DIGEST_LEN
+1];
985 base16_encode(seen
, sizeof(seen
), digest_rcvd_out
, DIGEST_LEN
);
986 base16_encode(expected
, sizeof(expected
), conn
->identity_digest
,
988 log_fn(severity
, LD_OR
,
989 "Tried connecting to router at %s:%d, but identity key was not "
990 "as expected: wanted %s but got %s.",
991 conn
->_base
.address
, conn
->_base
.port
, expected
, seen
);
992 entry_guard_register_connect_status(conn
->identity_digest
, 0, 1,
994 control_event_or_conn_status(conn
, OR_CONN_EVENT_FAILED
,
995 END_OR_CONN_REASON_OR_IDENTITY
);
996 if (!authdir_mode_tests_reachability(options
))
997 control_event_bootstrap_problem("foo", END_OR_CONN_REASON_OR_IDENTITY
);
1000 if (authdir_mode_tests_reachability(options
)) {
1001 /* We initiated this connection to address:port. Drop all routers
1002 * with the same address:port and a different key.
1004 dirserv_orconn_tls_done(conn
->_base
.address
, conn
->_base
.port
,
1005 digest_rcvd_out
, as_advertised
);
1013 /** The tls handshake is finished.
1015 * Make sure we are happy with the person we just handshaked with.
1017 * If he initiated the connection, make sure he's not already connected,
1018 * then initialize conn from the information in router.
1020 * If all is successful, call circuit_n_conn_done() to handle events
1021 * that have been pending on the <tls handshake completion. Also set the
1022 * directory to be dirty (only matters if I'm an authdirserver).
1025 connection_tls_finish_handshake(or_connection_t
*conn
)
1027 char digest_rcvd
[DIGEST_LEN
];
1028 int started_here
= connection_or_nonopen_was_started_here(conn
);
1030 log_debug(LD_OR
,"tls handshake with %s done. verifying.",
1031 safe_str(conn
->_base
.address
));
1033 directory_set_dirty();
1035 if (connection_or_check_valid_tls_handshake(conn
, started_here
,
1039 circuit_build_times_network_is_live(&circ_times
);
1041 if (tor_tls_used_v1_handshake(conn
->tls
)) {
1042 conn
->link_proto
= 1;
1043 if (!started_here
) {
1044 connection_or_init_conn_from_address(conn
, &conn
->_base
.addr
,
1045 conn
->_base
.port
, digest_rcvd
, 0);
1047 return connection_or_set_state_open(conn
);
1049 conn
->_base
.state
= OR_CONN_STATE_OR_HANDSHAKING
;
1050 if (connection_init_or_handshake_state(conn
, started_here
) < 0)
1052 if (!started_here
) {
1053 connection_or_init_conn_from_address(conn
, &conn
->_base
.addr
,
1054 conn
->_base
.port
, digest_rcvd
, 0);
1056 return connection_or_send_versions(conn
);
1060 /** Allocate a new connection handshake state for the connection
1061 * <b>conn</b>. Return 0 on success, -1 on failure. */
1063 connection_init_or_handshake_state(or_connection_t
*conn
, int started_here
)
1065 or_handshake_state_t
*s
;
1066 s
= conn
->handshake_state
= tor_malloc_zero(sizeof(or_handshake_state_t
));
1067 s
->started_here
= started_here
? 1 : 0;
1071 /** Free all storage held by <b>state</b>. */
1073 or_handshake_state_free(or_handshake_state_t
*state
)
1076 memset(state
, 0xBE, sizeof(or_handshake_state_t
));
1080 /** Set <b>conn</b>'s state to OR_CONN_STATE_OPEN, and tell other subsystems
1081 * as appropriate. Called when we are done with all TLS and OR handshaking.
1084 connection_or_set_state_open(or_connection_t
*conn
)
1086 int started_here
= connection_or_nonopen_was_started_here(conn
);
1087 time_t now
= time(NULL
);
1088 conn
->_base
.state
= OR_CONN_STATE_OPEN
;
1089 control_event_or_conn_status(conn
, OR_CONN_EVENT_CONNECTED
, 0);
1092 circuit_build_times_network_is_live(&circ_times
);
1093 rep_hist_note_connect_succeeded(conn
->identity_digest
, now
);
1094 if (entry_guard_register_connect_status(conn
->identity_digest
,
1096 /* Close any circuits pending on this conn. We leave it in state
1097 * 'open' though, because it didn't actually *fail* -- we just
1098 * chose not to use it. (Otherwise
1099 * connection_about_to_close_connection() will call a big pile of
1100 * functions to indicate we shouldn't try it again.) */
1101 log_debug(LD_OR
, "New entry guard was reachable, but closing this "
1102 "connection so we can retry the earlier entry guards.");
1103 circuit_n_conn_done(conn
, 0);
1106 router_set_status(conn
->identity_digest
, 1);
1108 /* only report it to the geoip module if it's not a known router */
1109 if (!router_get_by_digest(conn
->identity_digest
)) {
1110 if (tor_addr_family(&TO_CONN(conn
)->addr
) == AF_INET
) {
1111 /*XXXX IP6 support ipv6 geoip.*/
1112 uint32_t a
= tor_addr_to_ipv4h(&TO_CONN(conn
)->addr
);
1113 geoip_note_client_seen(GEOIP_CLIENT_CONNECT
, a
, now
);
1117 if (conn
->handshake_state
) {
1118 or_handshake_state_free(conn
->handshake_state
);
1119 conn
->handshake_state
= NULL
;
1121 connection_start_reading(TO_CONN(conn
));
1122 circuit_n_conn_done(conn
, 1); /* send the pending creates, if any. */
1127 /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
1128 * For cells that use or affect a circuit, this should only be called by
1129 * connection_or_flush_from_first_active_circuit().
1132 connection_or_write_cell_to_buf(const cell_t
*cell
, or_connection_t
*conn
)
1134 packed_cell_t networkcell
;
1139 cell_pack(&networkcell
, cell
);
1141 connection_write_to_buf(networkcell
.body
, CELL_NETWORK_SIZE
, TO_CONN(conn
));
1143 if (cell
->command
!= CELL_PADDING
)
1144 conn
->timestamp_last_added_nonpadding
= approx_time();
1147 /** Pack a variable-length <b>cell</b> into wire-format, and write it onto
1148 * <b>conn</b>'s outbuf. Right now, this <em>DOES NOT</em> support cells that
1152 connection_or_write_var_cell_to_buf(const var_cell_t
*cell
,
1153 or_connection_t
*conn
)
1155 char hdr
[VAR_CELL_HEADER_SIZE
];
1158 var_cell_pack_header(cell
, hdr
);
1159 connection_write_to_buf(hdr
, sizeof(hdr
), TO_CONN(conn
));
1160 connection_write_to_buf(cell
->payload
, cell
->payload_len
, TO_CONN(conn
));
1161 if (cell
->command
!= CELL_PADDING
)
1162 conn
->timestamp_last_added_nonpadding
= approx_time();
1165 /** See whether there's a variable-length cell waiting on <b>conn</b>'s
1166 * inbuf. Return values as for fetch_var_cell_from_buf(). */
1168 connection_fetch_var_cell_from_buf(or_connection_t
*conn
, var_cell_t
**out
)
1170 return fetch_var_cell_from_buf(conn
->_base
.inbuf
, out
, conn
->link_proto
);
1173 /** Process cells from <b>conn</b>'s inbuf.
1175 * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
1176 * and hand it to command_process_cell().
1181 connection_or_process_cells_from_inbuf(or_connection_t
*conn
)
1183 var_cell_t
*var_cell
;
1187 "%d: starting, inbuf_datalen %d (%d pending in tls object).",
1188 conn
->_base
.s
,(int)buf_datalen(conn
->_base
.inbuf
),
1189 tor_tls_get_pending_bytes(conn
->tls
));
1190 if (connection_fetch_var_cell_from_buf(conn
, &var_cell
)) {
1192 return 0; /* not yet. */
1193 circuit_build_times_network_is_live(&circ_times
);
1194 command_process_var_cell(var_cell
, conn
);
1195 var_cell_free(var_cell
);
1197 char buf
[CELL_NETWORK_SIZE
];
1199 if (buf_datalen(conn
->_base
.inbuf
) < CELL_NETWORK_SIZE
) /* whole response
1201 return 0; /* not yet */
1203 circuit_build_times_network_is_live(&circ_times
);
1204 connection_fetch_from_buf(buf
, CELL_NETWORK_SIZE
, TO_CONN(conn
));
1206 /* retrieve cell info from buf (create the host-order struct from the
1207 * network-order string) */
1208 cell_unpack(&cell
, buf
);
1210 command_process_cell(&cell
, conn
);
1215 /** Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
1216 * onto OR connection <b>conn</b>. Don't perform range-checking on reason:
1217 * we may want to propagate reasons from other cells.
1222 connection_or_send_destroy(circid_t circ_id
, or_connection_t
*conn
, int reason
)
1228 memset(&cell
, 0, sizeof(cell_t
));
1229 cell
.circ_id
= circ_id
;
1230 cell
.command
= CELL_DESTROY
;
1231 cell
.payload
[0] = (uint8_t) reason
;
1232 log_debug(LD_OR
,"Sending destroy (circID %d).", circ_id
);
1234 /* XXXX It's possible that under some circumstances, we want the destroy
1235 * to take precedence over other data waiting on the circuit's cell queue.
1238 connection_or_write_cell_to_buf(&cell
, conn
);
1242 /** Array of recognized link protocol versions. */
1243 static const uint16_t or_protocol_versions
[] = { 1, 2 };
1244 /** Number of versions in <b>or_protocol_versions</b>. */
1245 static const int n_or_protocol_versions
=
1246 (int)( sizeof(or_protocol_versions
)/sizeof(uint16_t) );
1248 /** Return true iff <b>v</b> is a link protocol version that this Tor
1249 * implementation believes it can support. */
1251 is_or_protocol_version_known(uint16_t v
)
1254 for (i
= 0; i
< n_or_protocol_versions
; ++i
) {
1255 if (or_protocol_versions
[i
] == v
)
1261 /** Send a VERSIONS cell on <b>conn</b>, telling the other host about the
1262 * link protocol versions that this Tor can support. */
1264 connection_or_send_versions(or_connection_t
*conn
)
1268 tor_assert(conn
->handshake_state
&&
1269 !conn
->handshake_state
->sent_versions_at
);
1270 cell
= var_cell_new(n_or_protocol_versions
* 2);
1271 cell
->command
= CELL_VERSIONS
;
1272 for (i
= 0; i
< n_or_protocol_versions
; ++i
) {
1273 uint16_t v
= or_protocol_versions
[i
];
1274 set_uint16(cell
->payload
+(2*i
), htons(v
));
1277 connection_or_write_var_cell_to_buf(cell
, conn
);
1278 conn
->handshake_state
->sent_versions_at
= time(NULL
);
1280 var_cell_free(cell
);
1284 /** Send a NETINFO cell on <b>conn</b>, telling the other server what we know
1285 * about their address, our address, and the current time. */
1287 connection_or_send_netinfo(or_connection_t
*conn
)
1290 time_t now
= time(NULL
);
1295 memset(&cell
, 0, sizeof(cell_t
));
1296 cell
.command
= CELL_NETINFO
;
1299 set_uint32(cell
.payload
, htonl((uint32_t)now
));
1301 /* Their address. */
1302 out
= cell
.payload
+ 4;
1303 len
= append_address_to_payload(out
, &conn
->_base
.addr
);
1309 if ((me
= router_get_my_routerinfo())) {
1311 *out
++ = 1; /* only one address is supported. */
1313 tor_addr_from_ipv4h(&my_addr
, me
->addr
);
1314 len
= append_address_to_payload(out
, &my_addr
);
1322 connection_or_write_cell_to_buf(&cell
, conn
);