Turn orconn watermarks into consensus parameters.
[tor.git] / src / core / or / connection_or.c
blobdb9f93e6f6453b0ea09e1c666757b4bc5fbe10c5
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-2021, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file connection_or.c
9 * \brief Functions to handle OR connections, TLS handshaking, and
10 * cells on the network.
12 * An or_connection_t is a subtype of connection_t (as implemented in
13 * connection.c) that uses a TLS connection to send and receive cells on the
14 * Tor network. (By sending and receiving cells connection_or.c, it cooperates
15 * with channeltls.c to implement a the channel interface of channel.c.)
17 * Every OR connection has an underlying tortls_t object (as implemented in
18 * tortls.c) which it uses as its TLS stream. It is responsible for
19 * sending and receiving cells over that TLS.
21 * This module also implements the client side of the v3 (and greater) Tor
22 * link handshake.
23 **/
24 #include "core/or/or.h"
25 #include "feature/client/bridges.h"
26 #include "lib/buf/buffers.h"
28 * Define this so we get channel internal functions, since we're implementing
29 * part of a subclass (channel_tls_t).
31 #define CHANNEL_OBJECT_PRIVATE
32 #define CONNECTION_OR_PRIVATE
33 #define ORCONN_EVENT_PRIVATE
34 #include "core/or/channel.h"
35 #include "core/or/channeltls.h"
36 #include "core/or/circuitbuild.h"
37 #include "core/or/circuitlist.h"
38 #include "core/or/circuitstats.h"
39 #include "core/or/command.h"
40 #include "app/config/config.h"
41 #include "core/mainloop/connection.h"
42 #include "core/or/connection_or.h"
43 #include "feature/relay/relay_handshake.h"
44 #include "feature/control/control_events.h"
45 #include "lib/crypt_ops/crypto_util.h"
46 #include "feature/dirauth/reachability.h"
47 #include "feature/client/entrynodes.h"
48 #include "lib/geoip/geoip.h"
49 #include "core/mainloop/mainloop.h"
50 #include "trunnel/netinfo.h"
51 #include "feature/nodelist/microdesc.h"
52 #include "feature/nodelist/networkstatus.h"
53 #include "feature/nodelist/nodelist.h"
54 #include "core/proto/proto_cell.h"
55 #include "core/or/reasons.h"
56 #include "core/or/relay.h"
57 #include "feature/rend/rendcommon.h"
58 #include "feature/stats/rephist.h"
59 #include "feature/relay/router.h"
60 #include "feature/relay/routerkeys.h"
61 #include "feature/relay/routermode.h"
62 #include "feature/nodelist/dirlist.h"
63 #include "feature/nodelist/routerlist.h"
64 #include "feature/relay/ext_orport.h"
65 #include "core/or/scheduler.h"
66 #include "feature/nodelist/torcert.h"
67 #include "core/or/channelpadding.h"
68 #include "core/or/congestion_control_common.h"
69 #include "feature/dirauth/authmode.h"
70 #include "feature/hs/hs_service.h"
72 #include "core/or/cell_st.h"
73 #include "core/or/cell_queue_st.h"
74 #include "core/or/or_connection_st.h"
75 #include "core/or/or_handshake_certs_st.h"
76 #include "core/or/or_handshake_state_st.h"
77 #include "app/config/or_state_st.h"
78 #include "feature/nodelist/routerinfo_st.h"
79 #include "core/or/var_cell_st.h"
80 #include "lib/crypt_ops/crypto_format.h"
82 #include "lib/tls/tortls.h"
84 #include "core/or/orconn_event.h"
86 static int connection_tls_finish_handshake(or_connection_t *conn);
87 static int connection_or_launch_v3_or_handshake(or_connection_t *conn);
88 static int connection_or_process_cells_from_inbuf(or_connection_t *conn);
89 static int connection_or_check_valid_tls_handshake(or_connection_t *conn,
90 int started_here,
91 char *digest_rcvd_out);
93 static void connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn);
95 static unsigned int
96 connection_or_is_bad_for_new_circs(or_connection_t *or_conn);
97 static void connection_or_mark_bad_for_new_circs(or_connection_t *or_conn);
99 static void connection_or_check_canonicity(or_connection_t *conn,
100 int started_here);
102 /**************************************************************/
105 * Cast a `connection_t *` to an `or_connection_t *`.
107 * Exit with an assertion failure if the input is not an `or_connnection_t`.
109 or_connection_t *
110 TO_OR_CONN(connection_t *c)
112 tor_assert(c->magic == OR_CONNECTION_MAGIC);
113 return DOWNCAST(or_connection_t, c);
117 * Cast a `const connection_t *` to a `const or_connection_t *`.
119 * Exit with an assertion failure if the input is not an `or_connnection_t`.
121 const or_connection_t *
122 CONST_TO_OR_CONN(const connection_t *c)
124 return TO_OR_CONN((connection_t *)c);
127 /** Clear clear conn->identity_digest and update other data
128 * structures as appropriate.*/
129 void
130 connection_or_clear_identity(or_connection_t *conn)
132 tor_assert(conn);
133 memset(conn->identity_digest, 0, DIGEST_LEN);
136 /** Clear all identities in OR conns.*/
137 void
138 connection_or_clear_identity_map(void)
140 smartlist_t *conns = get_connection_array();
141 SMARTLIST_FOREACH(conns, connection_t *, conn,
143 if (conn->type == CONN_TYPE_OR) {
144 connection_or_clear_identity(TO_OR_CONN(conn));
149 /** Change conn->identity_digest to digest, and add conn into
150 * the appropriate digest maps.
152 * NOTE that this function only allows two kinds of transitions: from
153 * unset identity to set identity, and from idempotent re-settings
154 * of the same identity. It's not allowed to clear an identity or to
155 * change an identity. Return 0 on success, and -1 if the transition
156 * is not allowed.
158 static void
159 connection_or_set_identity_digest(or_connection_t *conn,
160 const char *rsa_digest,
161 const ed25519_public_key_t *ed_id)
163 channel_t *chan = NULL;
164 tor_assert(conn);
165 tor_assert(rsa_digest);
167 if (conn->chan)
168 chan = TLS_CHAN_TO_BASE(conn->chan);
170 log_info(LD_HANDSHAKE, "Set identity digest for %s at %p: %s %s.",
171 connection_describe(TO_CONN(conn)),
172 conn,
173 hex_str(rsa_digest, DIGEST_LEN),
174 ed25519_fmt(ed_id));
175 log_info(LD_HANDSHAKE, " (Previously: %s %s)",
176 hex_str(conn->identity_digest, DIGEST_LEN),
177 chan ? ed25519_fmt(&chan->ed25519_identity) : "<null>");
179 const int rsa_id_was_set = ! tor_digest_is_zero(conn->identity_digest);
180 const int ed_id_was_set =
181 chan && !ed25519_public_key_is_zero(&chan->ed25519_identity);
182 const int rsa_changed =
183 tor_memneq(conn->identity_digest, rsa_digest, DIGEST_LEN);
184 const int ed_changed = ed_id_was_set &&
185 (!ed_id || !ed25519_pubkey_eq(ed_id, &chan->ed25519_identity));
187 tor_assert(!rsa_changed || !rsa_id_was_set);
188 tor_assert(!ed_changed || !ed_id_was_set);
190 if (!rsa_changed && !ed_changed)
191 return;
193 /* If the identity was set previously, remove the old mapping. */
194 if (rsa_id_was_set) {
195 connection_or_clear_identity(conn);
196 if (chan)
197 channel_clear_identity_digest(chan);
200 memcpy(conn->identity_digest, rsa_digest, DIGEST_LEN);
202 /* If we're initializing the IDs to zero, don't add a mapping yet. */
203 if (tor_digest_is_zero(rsa_digest) &&
204 (!ed_id || ed25519_public_key_is_zero(ed_id)))
205 return;
207 /* Deal with channels */
208 if (chan)
209 channel_set_identity_digest(chan, rsa_digest, ed_id);
213 * Return the Ed25519 identity of the peer for this connection (if any).
215 * Note that this ID may not be the _actual_ identity for the peer if
216 * authentication is not complete.
218 const struct ed25519_public_key_t *
219 connection_or_get_alleged_ed25519_id(const or_connection_t *conn)
221 if (conn && conn->chan) {
222 const channel_t *chan = NULL;
223 chan = TLS_CHAN_TO_BASE(conn->chan);
224 if (!ed25519_public_key_is_zero(&chan->ed25519_identity)) {
225 return &chan->ed25519_identity;
229 return NULL;
232 /**************************************************************/
234 /** Map from a string describing what a non-open OR connection was doing when
235 * failed, to an intptr_t describing the count of connections that failed that
236 * way. Note that the count is stored _as_ the pointer.
238 static strmap_t *broken_connection_counts;
240 /** If true, do not record information in <b>broken_connection_counts</b>. */
241 static int disable_broken_connection_counts = 0;
243 /** Record that an OR connection failed in <b>state</b>. */
244 static void
245 note_broken_connection(const char *state)
247 void *ptr;
248 intptr_t val;
249 if (disable_broken_connection_counts)
250 return;
252 if (!broken_connection_counts)
253 broken_connection_counts = strmap_new();
255 ptr = strmap_get(broken_connection_counts, state);
256 val = (intptr_t)ptr;
257 val++;
258 ptr = (void*)val;
259 strmap_set(broken_connection_counts, state, ptr);
262 /** Forget all recorded states for failed connections. If
263 * <b>stop_recording</b> is true, don't record any more. */
264 void
265 clear_broken_connection_map(int stop_recording)
267 if (broken_connection_counts)
268 strmap_free(broken_connection_counts, NULL);
269 broken_connection_counts = NULL;
270 if (stop_recording)
271 disable_broken_connection_counts = 1;
274 /** Write a detailed description the state of <b>orconn</b> into the
275 * <b>buflen</b>-byte buffer at <b>buf</b>. This description includes not
276 * only the OR-conn level state but also the TLS state. It's useful for
277 * diagnosing broken handshakes. */
278 static void
279 connection_or_get_state_description(or_connection_t *orconn,
280 char *buf, size_t buflen)
282 connection_t *conn = TO_CONN(orconn);
283 const char *conn_state;
284 char tls_state[256];
286 tor_assert(conn->type == CONN_TYPE_OR || conn->type == CONN_TYPE_EXT_OR);
288 conn_state = conn_state_to_string(conn->type, conn->state);
289 tor_tls_get_state_description(orconn->tls, tls_state, sizeof(tls_state));
291 tor_snprintf(buf, buflen, "%s with SSL state %s", conn_state, tls_state);
294 /** Record the current state of <b>orconn</b> as the state of a broken
295 * connection. */
296 static void
297 connection_or_note_state_when_broken(or_connection_t *orconn)
299 char buf[256];
300 if (disable_broken_connection_counts)
301 return;
302 connection_or_get_state_description(orconn, buf, sizeof(buf));
303 log_info(LD_HANDSHAKE,"Connection died in state '%s'", buf);
304 note_broken_connection(buf);
307 /** Helper type used to sort connection states and find the most frequent. */
308 typedef struct broken_state_count_t {
309 intptr_t count;
310 const char *state;
311 } broken_state_count_t;
313 /** Helper function used to sort broken_state_count_t by frequency. */
314 static int
315 broken_state_count_compare(const void **a_ptr, const void **b_ptr)
317 const broken_state_count_t *a = *a_ptr, *b = *b_ptr;
318 if (b->count < a->count)
319 return -1;
320 else if (b->count == a->count)
321 return 0;
322 else
323 return 1;
326 /** Upper limit on the number of different states to report for connection
327 * failure. */
328 #define MAX_REASONS_TO_REPORT 10
330 /** Report a list of the top states for failed OR connections at log level
331 * <b>severity</b>, in log domain <b>domain</b>. */
332 void
333 connection_or_report_broken_states(int severity, int domain)
335 int total = 0;
336 smartlist_t *items;
338 if (!broken_connection_counts || disable_broken_connection_counts)
339 return;
341 items = smartlist_new();
342 STRMAP_FOREACH(broken_connection_counts, state, void *, countptr) {
343 broken_state_count_t *c = tor_malloc(sizeof(broken_state_count_t));
344 c->count = (intptr_t)countptr;
345 total += (int)c->count;
346 c->state = state;
347 smartlist_add(items, c);
348 } STRMAP_FOREACH_END;
350 smartlist_sort(items, broken_state_count_compare);
352 tor_log(severity, domain, "%d connections have failed%s", total,
353 smartlist_len(items) > MAX_REASONS_TO_REPORT ? ". Top reasons:" : ":");
355 SMARTLIST_FOREACH_BEGIN(items, const broken_state_count_t *, c) {
356 if (c_sl_idx > MAX_REASONS_TO_REPORT)
357 break;
358 tor_log(severity, domain,
359 " %d connections died in state %s", (int)c->count, c->state);
360 } SMARTLIST_FOREACH_END(c);
362 SMARTLIST_FOREACH(items, broken_state_count_t *, c, tor_free(c));
363 smartlist_free(items);
367 * Helper function to publish an OR connection status event
369 * Publishes a messages to subscribers of ORCONN messages, and sends
370 * the control event.
372 void
373 connection_or_event_status(or_connection_t *conn, or_conn_status_event_t tp,
374 int reason)
376 orconn_status_msg_t *msg = tor_malloc(sizeof(*msg));
378 msg->gid = conn->base_.global_identifier;
379 msg->status = tp;
380 msg->reason = reason;
381 orconn_status_publish(msg);
382 control_event_or_conn_status(conn, tp, reason);
386 * Helper function to publish a state change message
388 * connection_or_change_state() calls this to notify subscribers about
389 * a change of an OR connection state.
391 static void
392 connection_or_state_publish(const or_connection_t *conn, uint8_t state)
394 orconn_state_msg_t *msg = tor_malloc(sizeof(*msg));
396 msg->gid = conn->base_.global_identifier;
397 if (conn->is_pt) {
398 /* Do extra decoding because conn->proxy_type indicates the proxy
399 * protocol that tor uses to talk with the transport plugin,
400 * instead of PROXY_PLUGGABLE. */
401 tor_assert_nonfatal(conn->proxy_type != PROXY_NONE);
402 msg->proxy_type = PROXY_PLUGGABLE;
403 } else {
404 msg->proxy_type = conn->proxy_type;
406 msg->state = state;
407 if (conn->chan) {
408 msg->chan = TLS_CHAN_TO_BASE(conn->chan)->global_identifier;
409 } else {
410 msg->chan = 0;
412 orconn_state_publish(msg);
415 /** Call this to change or_connection_t states, so the owning channel_tls_t can
416 * be notified.
419 MOCK_IMPL(void,
420 connection_or_change_state,(or_connection_t *conn, uint8_t state))
422 tor_assert(conn);
424 conn->base_.state = state;
426 connection_or_state_publish(conn, state);
427 if (conn->chan)
428 channel_tls_handle_state_change_on_orconn(conn->chan, conn, state);
431 /** Return the number of circuits using an or_connection_t; this used to
432 * be an or_connection_t field, but it got moved to channel_t and we
433 * shouldn't maintain two copies. */
435 MOCK_IMPL(int,
436 connection_or_get_num_circuits, (or_connection_t *conn))
438 tor_assert(conn);
440 if (conn->chan) {
441 return channel_num_circuits(TLS_CHAN_TO_BASE(conn->chan));
442 } else return 0;
445 /**************************************************************/
447 /** Pack the cell_t host-order structure <b>src</b> into network-order
448 * in the buffer <b>dest</b>. See tor-spec.txt for details about the
449 * wire format.
451 * Note that this function doesn't touch <b>dst</b>-\>next: the caller
452 * should set it or clear it as appropriate.
454 void
455 cell_pack(packed_cell_t *dst, const cell_t *src, int wide_circ_ids)
457 char *dest = dst->body;
458 if (wide_circ_ids) {
459 set_uint32(dest, htonl(src->circ_id));
460 dest += 4;
461 } else {
462 /* Clear the last two bytes of dest, in case we can accidentally
463 * send them to the network somehow. */
464 memset(dest+CELL_MAX_NETWORK_SIZE-2, 0, 2);
465 set_uint16(dest, htons(src->circ_id));
466 dest += 2;
468 set_uint8(dest, src->command);
469 memcpy(dest+1, src->payload, CELL_PAYLOAD_SIZE);
472 /** Unpack the network-order buffer <b>src</b> into a host-order
473 * cell_t structure <b>dest</b>.
475 static void
476 cell_unpack(cell_t *dest, const char *src, int wide_circ_ids)
478 if (wide_circ_ids) {
479 dest->circ_id = ntohl(get_uint32(src));
480 src += 4;
481 } else {
482 dest->circ_id = ntohs(get_uint16(src));
483 src += 2;
485 dest->command = get_uint8(src);
486 memcpy(dest->payload, src+1, CELL_PAYLOAD_SIZE);
489 /** Write the header of <b>cell</b> into the first VAR_CELL_MAX_HEADER_SIZE
490 * bytes of <b>hdr_out</b>. Returns number of bytes used. */
492 var_cell_pack_header(const var_cell_t *cell, char *hdr_out, int wide_circ_ids)
494 int r;
495 if (wide_circ_ids) {
496 set_uint32(hdr_out, htonl(cell->circ_id));
497 hdr_out += 4;
498 r = VAR_CELL_MAX_HEADER_SIZE;
499 } else {
500 set_uint16(hdr_out, htons(cell->circ_id));
501 hdr_out += 2;
502 r = VAR_CELL_MAX_HEADER_SIZE - 2;
504 set_uint8(hdr_out, cell->command);
505 set_uint16(hdr_out+1, htons(cell->payload_len));
506 return r;
509 /** Allocate and return a new var_cell_t with <b>payload_len</b> bytes of
510 * payload space. */
511 var_cell_t *
512 var_cell_new(uint16_t payload_len)
514 size_t size = offsetof(var_cell_t, payload) + payload_len;
515 var_cell_t *cell = tor_malloc_zero(size);
516 cell->payload_len = payload_len;
517 cell->command = 0;
518 cell->circ_id = 0;
519 return cell;
523 * Copy a var_cell_t
526 var_cell_t *
527 var_cell_copy(const var_cell_t *src)
529 var_cell_t *copy = NULL;
530 size_t size = 0;
532 if (src != NULL) {
533 size = offsetof(var_cell_t, payload) + src->payload_len;
534 copy = tor_malloc_zero(size);
535 copy->payload_len = src->payload_len;
536 copy->command = src->command;
537 copy->circ_id = src->circ_id;
538 memcpy(copy->payload, src->payload, copy->payload_len);
541 return copy;
544 /** Release all space held by <b>cell</b>. */
545 void
546 var_cell_free_(var_cell_t *cell)
548 tor_free(cell);
551 /** We've received an EOF from <b>conn</b>. Mark it for close and return. */
553 connection_or_reached_eof(or_connection_t *conn)
555 tor_assert(conn);
557 log_info(LD_OR,"OR connection reached EOF. Closing.");
558 connection_or_close_normally(conn, 1);
560 return 0;
563 /** Handle any new bytes that have come in on connection <b>conn</b>.
564 * If conn is in 'open' state, hand it to
565 * connection_or_process_cells_from_inbuf()
566 * (else do nothing).
569 connection_or_process_inbuf(or_connection_t *conn)
571 int ret = 0;
572 tor_assert(conn);
574 switch (conn->base_.state) {
575 case OR_CONN_STATE_PROXY_HANDSHAKING:
576 ret = connection_read_proxy_handshake(TO_CONN(conn));
578 /* start TLS after handshake completion, or deal with error */
579 if (ret == 1) {
580 tor_assert(TO_CONN(conn)->proxy_state == PROXY_CONNECTED);
581 if (buf_datalen(conn->base_.inbuf) != 0) {
582 log_fn(LOG_PROTOCOL_WARN, LD_NET, "Found leftover (%d bytes) "
583 "when transitioning from PROXY_HANDSHAKING state on %s: "
584 "closing.",
585 (int)buf_datalen(conn->base_.inbuf),
586 connection_describe(TO_CONN(conn)));
587 connection_or_close_for_error(conn, 0);
588 return -1;
590 if (connection_tls_start_handshake(conn, 0) < 0)
591 ret = -1;
592 /* Touch the channel's active timestamp if there is one */
593 if (conn->chan)
594 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
596 if (ret < 0) {
597 connection_or_close_for_error(conn, 0);
600 return ret;
601 case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
602 case OR_CONN_STATE_OPEN:
603 case OR_CONN_STATE_OR_HANDSHAKING_V2:
604 case OR_CONN_STATE_OR_HANDSHAKING_V3:
605 return connection_or_process_cells_from_inbuf(conn);
606 default:
607 break; /* don't do anything */
610 /* This check makes sure that we don't have any data on the inbuf if we're
611 * doing our TLS handshake: if we did, they were probably put there by a
612 * SOCKS proxy trying to trick us into accepting unauthenticated data.
614 if (buf_datalen(conn->base_.inbuf) != 0) {
615 log_fn(LOG_PROTOCOL_WARN, LD_NET, "Accumulated data (%d bytes) "
616 "on non-open %s; closing.",
617 (int)buf_datalen(conn->base_.inbuf),
618 connection_describe(TO_CONN(conn)));
619 connection_or_close_for_error(conn, 0);
620 ret = -1;
623 return ret;
626 /** Called whenever we have flushed some data on an or_conn: add more data
627 * from active circuits. */
629 connection_or_flushed_some(or_connection_t *conn)
631 size_t datalen;
633 /* Update the channel's active timestamp if there is one */
634 if (conn->chan)
635 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
637 /* If we're under the low water mark, add cells until we're just over the
638 * high water mark. */
639 datalen = connection_get_outbuf_len(TO_CONN(conn));
640 if (datalen < or_conn_lowwatermark()) {
641 /* Let the scheduler know */
642 scheduler_channel_wants_writes(TLS_CHAN_TO_BASE(conn->chan));
645 return 0;
648 /** This is for channeltls.c to ask how many cells we could accept if
649 * they were available. */
650 ssize_t
651 connection_or_num_cells_writeable(or_connection_t *conn)
653 size_t datalen, cell_network_size;
654 ssize_t n = 0;
656 tor_assert(conn);
659 * If we're under the high water mark, we're potentially
660 * writeable; note this is different from the calculation above
661 * used to trigger when to start writing after we've stopped.
663 datalen = connection_get_outbuf_len(TO_CONN(conn));
664 if (datalen < or_conn_highwatermark()) {
665 cell_network_size = get_cell_network_size(conn->wide_circ_ids);
666 n = CEIL_DIV(or_conn_highwatermark() - datalen, cell_network_size);
669 return n;
672 /** Connection <b>conn</b> has finished writing and has no bytes left on
673 * its outbuf.
675 * Otherwise it's in state "open": stop writing and return.
677 * If <b>conn</b> is broken, mark it for close and return -1, else
678 * return 0.
681 connection_or_finished_flushing(or_connection_t *conn)
683 tor_assert(conn);
684 assert_connection_ok(TO_CONN(conn),0);
686 switch (conn->base_.state) {
687 case OR_CONN_STATE_PROXY_HANDSHAKING:
688 /* PROXY_HAPROXY gets connected by receiving an ack. */
689 if (conn->proxy_type == PROXY_HAPROXY) {
690 tor_assert(TO_CONN(conn)->proxy_state == PROXY_HAPROXY_WAIT_FOR_FLUSH);
691 IF_BUG_ONCE(buf_datalen(TO_CONN(conn)->inbuf) != 0) {
692 /* This should be impossible; we're not even reading. */
693 connection_or_close_for_error(conn, 0);
694 return -1;
696 TO_CONN(conn)->proxy_state = PROXY_CONNECTED;
698 if (connection_tls_start_handshake(conn, 0) < 0) {
699 /* TLS handshaking error of some kind. */
700 connection_or_close_for_error(conn, 0);
701 return -1;
703 break;
705 break;
706 case OR_CONN_STATE_OPEN:
707 case OR_CONN_STATE_OR_HANDSHAKING_V2:
708 case OR_CONN_STATE_OR_HANDSHAKING_V3:
709 break;
710 default:
711 log_err(LD_BUG,"Called in unexpected state %d.", conn->base_.state);
712 tor_fragile_assert();
713 return -1;
716 /* Update the channel's active timestamp if there is one */
717 if (conn->chan)
718 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
720 return 0;
723 /** Connected handler for OR connections: begin the TLS handshake.
726 connection_or_finished_connecting(or_connection_t *or_conn)
728 const int proxy_type = or_conn->proxy_type;
729 connection_t *conn;
731 tor_assert(or_conn);
732 conn = TO_CONN(or_conn);
733 tor_assert(conn->state == OR_CONN_STATE_CONNECTING);
735 log_debug(LD_HANDSHAKE,"connect finished for %s",
736 connection_describe(conn));
738 if (proxy_type != PROXY_NONE) {
739 /* start proxy handshake */
740 if (connection_proxy_connect(conn, proxy_type) < 0) {
741 connection_or_close_for_error(or_conn, 0);
742 return -1;
745 connection_or_change_state(or_conn, OR_CONN_STATE_PROXY_HANDSHAKING);
746 connection_start_reading(conn);
748 return 0;
751 if (connection_tls_start_handshake(or_conn, 0) < 0) {
752 /* TLS handshaking error of some kind. */
753 connection_or_close_for_error(or_conn, 0);
754 return -1;
756 return 0;
759 /** Called when we're about to finally unlink and free an OR connection:
760 * perform necessary accounting and cleanup */
761 void
762 connection_or_about_to_close(or_connection_t *or_conn)
764 connection_t *conn = TO_CONN(or_conn);
766 /* Tell the controlling channel we're closed */
767 if (or_conn->chan) {
768 channel_closed(TLS_CHAN_TO_BASE(or_conn->chan));
770 * NULL this out because the channel might hang around a little
771 * longer before channel_run_cleanup() gets it.
773 or_conn->chan->conn = NULL;
774 or_conn->chan = NULL;
777 /* Remember why we're closing this connection. */
778 if (conn->state != OR_CONN_STATE_OPEN) {
779 /* now mark things down as needed */
780 if (connection_or_nonopen_was_started_here(or_conn)) {
781 const or_options_t *options = get_options();
782 connection_or_note_state_when_broken(or_conn);
783 /* Tell the new guard API about the channel failure */
784 entry_guard_chan_failed(TLS_CHAN_TO_BASE(or_conn->chan));
785 if (conn->state >= OR_CONN_STATE_TLS_HANDSHAKING) {
786 int reason = tls_error_to_orconn_end_reason(or_conn->tls_error);
787 connection_or_event_status(or_conn, OR_CONN_EVENT_FAILED,
788 reason);
789 if (!authdir_mode_tests_reachability(options)) {
790 const char *warning = NULL;
791 if (reason == END_OR_CONN_REASON_TLS_ERROR && or_conn->tls) {
792 warning = tor_tls_get_last_error_msg(or_conn->tls);
794 if (warning == NULL) {
795 warning = orconn_end_reason_to_control_string(reason);
797 control_event_bootstrap_prob_or(warning, reason, or_conn);
801 } else if (conn->hold_open_until_flushed) {
802 /* We only set hold_open_until_flushed when we're intentionally
803 * closing a connection. */
804 connection_or_event_status(or_conn, OR_CONN_EVENT_CLOSED,
805 tls_error_to_orconn_end_reason(or_conn->tls_error));
806 } else if (!tor_digest_is_zero(or_conn->identity_digest)) {
807 connection_or_event_status(or_conn, OR_CONN_EVENT_CLOSED,
808 tls_error_to_orconn_end_reason(or_conn->tls_error));
812 /** Return 1 if identity digest <b>id_digest</b> is known to be a
813 * currently or recently running relay. Otherwise return 0. */
815 connection_or_digest_is_known_relay(const char *id_digest)
817 if (router_get_consensus_status_by_id(id_digest))
818 return 1; /* It's in the consensus: "yes" */
819 if (router_get_by_id_digest(id_digest))
820 return 1; /* Not in the consensus, but we have a descriptor for
821 * it. Probably it was in a recent consensus. "Yes". */
822 return 0;
825 /** Set the per-conn read and write limits for <b>conn</b>. If it's a known
826 * relay, we will rely on the global read and write buckets, so give it
827 * per-conn limits that are big enough they'll never matter. But if it's
828 * not a known relay, first check if we set PerConnBwRate/Burst, then
829 * check if the consensus sets them, else default to 'big enough'.
831 * If <b>reset</b> is true, set the bucket to be full. Otherwise, just
832 * clip the bucket if it happens to be <em>too</em> full.
834 static void
835 connection_or_update_token_buckets_helper(or_connection_t *conn, int reset,
836 const or_options_t *options)
838 int rate, burst; /* per-connection rate limiting params */
839 if (connection_or_digest_is_known_relay(conn->identity_digest)) {
840 /* It's in the consensus, or we have a descriptor for it meaning it
841 * was probably in a recent consensus. It's a recognized relay:
842 * give it full bandwidth. */
843 rate = (int)options->BandwidthRate;
844 burst = (int)options->BandwidthBurst;
845 } else {
846 /* Not a recognized relay. Squeeze it down based on the suggested
847 * bandwidth parameters in the consensus, but allow local config
848 * options to override. */
849 rate = options->PerConnBWRate ? (int)options->PerConnBWRate :
850 networkstatus_get_param(NULL, "perconnbwrate",
851 (int)options->BandwidthRate, 1, INT32_MAX);
852 burst = options->PerConnBWBurst ? (int)options->PerConnBWBurst :
853 networkstatus_get_param(NULL, "perconnbwburst",
854 (int)options->BandwidthBurst, 1, INT32_MAX);
857 token_bucket_rw_adjust(&conn->bucket, rate, burst);
858 if (reset) {
859 token_bucket_rw_reset(&conn->bucket, monotime_coarse_get_stamp());
863 /** Either our set of relays or our per-conn rate limits have changed.
864 * Go through all the OR connections and update their token buckets to make
865 * sure they don't exceed their maximum values. */
866 void
867 connection_or_update_token_buckets(smartlist_t *conns,
868 const or_options_t *options)
870 SMARTLIST_FOREACH(conns, connection_t *, conn,
872 if (connection_speaks_cells(conn))
873 connection_or_update_token_buckets_helper(TO_OR_CONN(conn), 0, options);
877 /* Mark <b>or_conn</b> as canonical if <b>is_canonical</b> is set, and
878 * non-canonical otherwise. Adjust idle_timeout accordingly.
880 void
881 connection_or_set_canonical(or_connection_t *or_conn,
882 int is_canonical)
884 if (bool_eq(is_canonical, or_conn->is_canonical) &&
885 or_conn->idle_timeout != 0) {
886 /* Don't recalculate an existing idle_timeout unless the canonical
887 * status changed. */
888 return;
891 or_conn->is_canonical = !! is_canonical; /* force to a 1-bit boolean */
892 or_conn->idle_timeout = channelpadding_get_channel_idle_timeout(
893 TLS_CHAN_TO_BASE(or_conn->chan), is_canonical);
895 log_info(LD_CIRC,
896 "Channel %"PRIu64 " chose an idle timeout of %d.",
897 or_conn->chan ?
898 (TLS_CHAN_TO_BASE(or_conn->chan)->global_identifier):0,
899 or_conn->idle_timeout);
902 /** If we don't necessarily know the router we're connecting to, but we
903 * have an addr/port/id_digest, then fill in as much as we can. Start
904 * by checking to see if this describes a router we know.
905 * <b>started_here</b> is 1 if we are the initiator of <b>conn</b> and
906 * 0 if it's an incoming connection. */
907 void
908 connection_or_init_conn_from_address(or_connection_t *conn,
909 const tor_addr_t *addr, uint16_t port,
910 const char *id_digest,
911 const ed25519_public_key_t *ed_id,
912 int started_here)
914 log_debug(LD_HANDSHAKE, "init conn from address %s: %s, %s (%d)",
915 fmt_addr(addr),
916 hex_str((const char*)id_digest, DIGEST_LEN),
917 ed25519_fmt(ed_id),
918 started_here);
920 connection_or_set_identity_digest(conn, id_digest, ed_id);
921 connection_or_update_token_buckets_helper(conn, 1, get_options());
923 conn->base_.port = port;
924 tor_addr_copy(&conn->base_.addr, addr);
925 if (! conn->base_.address) {
926 conn->base_.address = tor_strdup(fmt_addr(addr));
929 connection_or_check_canonicity(conn, started_here);
932 /** Check whether the identity of <b>conn</b> matches a known node. If it
933 * does, check whether the address of conn matches the expected address, and
934 * update the connection's is_canonical flag, nickname, and address fields as
935 * appropriate. */
936 static void
937 connection_or_check_canonicity(or_connection_t *conn, int started_here)
939 (void) started_here;
941 const char *id_digest = conn->identity_digest;
942 const ed25519_public_key_t *ed_id = NULL;
943 if (conn->chan)
944 ed_id = & TLS_CHAN_TO_BASE(conn->chan)->ed25519_identity;
946 const node_t *r = node_get_by_id(id_digest);
947 if (r &&
948 node_supports_ed25519_link_authentication(r, 1) &&
949 ! node_ed25519_id_matches(r, ed_id)) {
950 /* If this node is capable of proving an ed25519 ID,
951 * we can't call this a canonical connection unless both IDs match. */
952 r = NULL;
955 if (r) {
956 tor_addr_port_t node_ipv4_ap;
957 tor_addr_port_t node_ipv6_ap;
958 node_get_prim_orport(r, &node_ipv4_ap);
959 node_get_pref_ipv6_orport(r, &node_ipv6_ap);
960 if (tor_addr_eq(&conn->base_.addr, &node_ipv4_ap.addr) ||
961 tor_addr_eq(&conn->base_.addr, &node_ipv6_ap.addr)) {
962 connection_or_set_canonical(conn, 1);
964 /* Choose the correct canonical address and port. */
965 tor_addr_port_t *node_ap;
966 if (tor_addr_family(&conn->base_.addr) == AF_INET) {
967 node_ap = &node_ipv4_ap;
968 } else {
969 node_ap = &node_ipv6_ap;
971 /* Remember the canonical addr/port so our log messages will make
972 sense. */
973 tor_addr_port_copy(&conn->canonical_orport, node_ap);
974 tor_free(conn->nickname);
975 conn->nickname = tor_strdup(node_get_nickname(r));
976 } else {
977 tor_free(conn->nickname);
978 conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
979 conn->nickname[0] = '$';
980 base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
981 conn->identity_digest, DIGEST_LEN);
985 * We have to tell channeltls.c to update the channel marks (local, in
986 * particular), since we may have changed the address.
989 if (conn->chan) {
990 channel_tls_update_marks(conn);
994 /** These just pass all the is_bad_for_new_circs manipulation on to
995 * channel_t */
997 static unsigned int
998 connection_or_is_bad_for_new_circs(or_connection_t *or_conn)
1000 tor_assert(or_conn);
1002 if (or_conn->chan)
1003 return channel_is_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan));
1004 else return 0;
1007 static void
1008 connection_or_mark_bad_for_new_circs(or_connection_t *or_conn)
1010 tor_assert(or_conn);
1012 if (or_conn->chan)
1013 channel_mark_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan));
1016 /** How old do we let a connection to an OR get before deciding it's
1017 * too old for new circuits? */
1018 #define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)
1020 /** Expire an or_connection if it is too old. Helper for
1021 * connection_or_group_set_badness_ and fast path for
1022 * channel_rsa_id_group_set_badness.
1024 * Returns 1 if the connection was already expired, else 0.
1027 connection_or_single_set_badness_(time_t now,
1028 or_connection_t *or_conn,
1029 int force)
1031 /* XXXX this function should also be about channels? */
1032 if (or_conn->base_.marked_for_close ||
1033 connection_or_is_bad_for_new_circs(or_conn))
1034 return 1;
1036 if (force ||
1037 or_conn->base_.timestamp_created + TIME_BEFORE_OR_CONN_IS_TOO_OLD
1038 < now) {
1039 log_info(LD_OR,
1040 "Marking %s as too old for new circuits "
1041 "(fd "TOR_SOCKET_T_FORMAT", %d secs old).",
1042 connection_describe(TO_CONN(or_conn)),
1043 or_conn->base_.s,
1044 (int)(now - or_conn->base_.timestamp_created));
1045 connection_or_mark_bad_for_new_circs(or_conn);
1048 return 0;
1051 /** Given a list of all the or_connections with a given
1052 * identity, set elements of that list as is_bad_for_new_circs as
1053 * appropriate. Helper for connection_or_set_bad_connections().
1055 * Specifically, we set the is_bad_for_new_circs flag on:
1056 * - all connections if <b>force</b> is true.
1057 * - all connections that are too old.
1058 * - all open non-canonical connections for which a canonical connection
1059 * exists to the same router.
1060 * - all open canonical connections for which a 'better' canonical
1061 * connection exists to the same router.
1062 * - all open non-canonical connections for which a 'better' non-canonical
1063 * connection exists to the same router at the same address.
1065 * See channel_is_better() in channel.c for our idea of what makes one OR
1066 * connection better than another.
1068 void
1069 connection_or_group_set_badness_(smartlist_t *group, int force)
1071 /* XXXX this function should be entirely about channels, not OR
1072 * XXXX connections. */
1074 or_connection_t *best = NULL;
1075 int n_old = 0, n_inprogress = 0, n_canonical = 0, n_other = 0;
1076 time_t now = time(NULL);
1078 /* Pass 1: expire everything that's old, and see what the status of
1079 * everything else is. */
1080 SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
1081 if (connection_or_single_set_badness_(now, or_conn, force))
1082 continue;
1084 if (connection_or_is_bad_for_new_circs(or_conn)) {
1085 ++n_old;
1086 } else if (or_conn->base_.state != OR_CONN_STATE_OPEN) {
1087 ++n_inprogress;
1088 } else if (or_conn->is_canonical) {
1089 ++n_canonical;
1090 } else {
1091 ++n_other;
1093 } SMARTLIST_FOREACH_END(or_conn);
1095 /* Pass 2: We know how about how good the best connection is.
1096 * expire everything that's worse, and find the very best if we can. */
1097 SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
1098 if (or_conn->base_.marked_for_close ||
1099 connection_or_is_bad_for_new_circs(or_conn))
1100 continue; /* This one doesn't need to be marked bad. */
1101 if (or_conn->base_.state != OR_CONN_STATE_OPEN)
1102 continue; /* Don't mark anything bad until we have seen what happens
1103 * when the connection finishes. */
1104 if (n_canonical && !or_conn->is_canonical) {
1105 /* We have at least one open canonical connection to this router,
1106 * and this one is open but not canonical. Mark it bad. */
1107 log_info(LD_OR,
1108 "Marking %s unsuitable for new circuits: "
1109 "(fd "TOR_SOCKET_T_FORMAT", %d secs old). It is not "
1110 "canonical, and we have another connection to that OR that is.",
1111 connection_describe(TO_CONN(or_conn)),
1112 or_conn->base_.s,
1113 (int)(now - or_conn->base_.timestamp_created));
1114 connection_or_mark_bad_for_new_circs(or_conn);
1115 continue;
1118 if (!best ||
1119 channel_is_better(TLS_CHAN_TO_BASE(or_conn->chan),
1120 TLS_CHAN_TO_BASE(best->chan))) {
1121 best = or_conn;
1123 } SMARTLIST_FOREACH_END(or_conn);
1125 if (!best)
1126 return;
1128 /* Pass 3: One connection to OR is best. If it's canonical, mark as bad
1129 * every other open connection. If it's non-canonical, mark as bad
1130 * every other open connection to the same address.
1132 * XXXX This isn't optimal; if we have connections to an OR at multiple
1133 * addresses, we'd like to pick the best _for each address_, and mark as
1134 * bad every open connection that isn't best for its address. But this
1135 * can only occur in cases where the other OR is old (so we have no
1136 * canonical connection to it), or where all the connections to the OR are
1137 * at noncanonical addresses and we have no good direct connection (which
1138 * means we aren't at risk of attaching circuits to it anyway). As
1139 * 0.1.2.x dies out, the first case will go away, and the second one is
1140 * "mostly harmless", so a fix can wait until somebody is bored.
1142 SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
1143 if (or_conn->base_.marked_for_close ||
1144 connection_or_is_bad_for_new_circs(or_conn) ||
1145 or_conn->base_.state != OR_CONN_STATE_OPEN)
1146 continue;
1147 if (or_conn != best &&
1148 channel_is_better(TLS_CHAN_TO_BASE(best->chan),
1149 TLS_CHAN_TO_BASE(or_conn->chan))) {
1150 /* This isn't the best conn, _and_ the best conn is better than it */
1151 if (best->is_canonical) {
1152 log_info(LD_OR,
1153 "Marking %s as unsuitable for new circuits: "
1154 "(fd "TOR_SOCKET_T_FORMAT", %d secs old). "
1155 "We have a better canonical one "
1156 "(fd "TOR_SOCKET_T_FORMAT"; %d secs old).",
1157 connection_describe(TO_CONN(or_conn)),
1158 or_conn->base_.s,
1159 (int)(now - or_conn->base_.timestamp_created),
1160 best->base_.s, (int)(now - best->base_.timestamp_created));
1161 connection_or_mark_bad_for_new_circs(or_conn);
1162 } else if (tor_addr_eq(&TO_CONN(or_conn)->addr,
1163 &TO_CONN(best)->addr)) {
1164 log_info(LD_OR,
1165 "Marking %s unsuitable for new circuits: "
1166 "(fd "TOR_SOCKET_T_FORMAT", %d secs old). We have a better "
1167 "one with the "
1168 "same address (fd "TOR_SOCKET_T_FORMAT"; %d secs old).",
1169 connection_describe(TO_CONN(or_conn)),
1170 or_conn->base_.s,
1171 (int)(now - or_conn->base_.timestamp_created),
1172 best->base_.s, (int)(now - best->base_.timestamp_created));
1173 connection_or_mark_bad_for_new_circs(or_conn);
1176 } SMARTLIST_FOREACH_END(or_conn);
1179 /* Lifetime of a connection failure. After that, we'll retry. This is in
1180 * seconds. */
1181 #define OR_CONNECT_FAILURE_LIFETIME 60
1182 /* The interval to use with when to clean up the failure cache. */
1183 #define OR_CONNECT_FAILURE_CLEANUP_INTERVAL 60
1185 /* When is the next time we have to cleanup the failure map. We keep this
1186 * because we clean it opportunistically. */
1187 static time_t or_connect_failure_map_next_cleanup_ts = 0;
1189 /* OR connection failure entry data structure. It is kept in the connection
1190 * failure map defined below and indexed by OR identity digest, address and
1191 * port.
1193 * We need to identify a connection failure with these three values because we
1194 * want to avoid to wrongfully block a relay if someone is trying to
1195 * extend to a known identity digest but with the wrong IP/port. For instance,
1196 * it can happen if a relay changed its port but the client still has an old
1197 * descriptor with the old port. We want to stop connecting to that
1198 * IP/port/identity all together, not only the relay identity. */
1199 typedef struct or_connect_failure_entry_t {
1200 HT_ENTRY(or_connect_failure_entry_t) node;
1201 /* Identity digest of the connection where it is connecting to. */
1202 uint8_t identity_digest[DIGEST_LEN];
1203 /* This is the connection address from the base connection_t. After the
1204 * connection is checked for canonicity, the base address should represent
1205 * what we know instead of where we are connecting to. This is what we need
1206 * so we can correlate known relays within the consensus. */
1207 tor_addr_t addr;
1208 uint16_t port;
1209 /* Last time we were unable to connect. */
1210 time_t last_failed_connect_ts;
1211 } or_connect_failure_entry_t;
1213 /* Map where we keep connection failure entries. They are indexed by addr,
1214 * port and identity digest. */
1215 static HT_HEAD(or_connect_failure_ht, or_connect_failure_entry_t)
1216 or_connect_failures_map = HT_INITIALIZER();
1218 /* Helper: Hashtable equal function. Return 1 if equal else 0. */
1219 static int
1220 or_connect_failure_ht_eq(const or_connect_failure_entry_t *a,
1221 const or_connect_failure_entry_t *b)
1223 return fast_memeq(a->identity_digest, b->identity_digest, DIGEST_LEN) &&
1224 tor_addr_eq(&a->addr, &b->addr) &&
1225 a->port == b->port;
1228 /* Helper: Return the hash for the hashtable of the given entry. For this
1229 * table, it is a combination of address, port and identity digest. */
1230 static unsigned int
1231 or_connect_failure_ht_hash(const or_connect_failure_entry_t *entry)
1233 size_t offset = 0, addr_size;
1234 const void *addr_ptr;
1235 /* Largest size is IPv6 and IPv4 is smaller so it is fine. */
1236 uint8_t data[16 + sizeof(uint16_t) + DIGEST_LEN];
1238 /* Get the right address bytes depending on the family. */
1239 switch (tor_addr_family(&entry->addr)) {
1240 case AF_INET:
1241 addr_size = 4;
1242 addr_ptr = &entry->addr.addr.in_addr.s_addr;
1243 break;
1244 case AF_INET6:
1245 addr_size = 16;
1246 addr_ptr = &entry->addr.addr.in6_addr.s6_addr;
1247 break;
1248 default:
1249 tor_assert_nonfatal_unreached();
1250 return 0;
1253 memcpy(data, addr_ptr, addr_size);
1254 offset += addr_size;
1255 memcpy(data + offset, entry->identity_digest, DIGEST_LEN);
1256 offset += DIGEST_LEN;
1257 set_uint16(data + offset, entry->port);
1258 offset += sizeof(uint16_t);
1260 return (unsigned int) siphash24g(data, offset);
1263 HT_PROTOTYPE(or_connect_failure_ht, or_connect_failure_entry_t, node,
1264 or_connect_failure_ht_hash, or_connect_failure_ht_eq);
1266 HT_GENERATE2(or_connect_failure_ht, or_connect_failure_entry_t, node,
1267 or_connect_failure_ht_hash, or_connect_failure_ht_eq,
1268 0.6, tor_reallocarray_, tor_free_);
1270 /* Initialize a given connect failure entry with the given identity_digest,
1271 * addr and port. All field are optional except ocf. */
1272 static void
1273 or_connect_failure_init(const char *identity_digest, const tor_addr_t *addr,
1274 uint16_t port, or_connect_failure_entry_t *ocf)
1276 tor_assert(ocf);
1277 if (identity_digest) {
1278 memcpy(ocf->identity_digest, identity_digest,
1279 sizeof(ocf->identity_digest));
1281 if (addr) {
1282 tor_addr_copy(&ocf->addr, addr);
1284 ocf->port = port;
1287 /* Return a newly allocated connection failure entry. It is initialized with
1288 * the given or_conn data. This can't fail. */
1289 static or_connect_failure_entry_t *
1290 or_connect_failure_new(const or_connection_t *or_conn)
1292 or_connect_failure_entry_t *ocf = tor_malloc_zero(sizeof(*ocf));
1293 or_connect_failure_init(or_conn->identity_digest, &TO_CONN(or_conn)->addr,
1294 TO_CONN(or_conn)->port, ocf);
1295 return ocf;
1298 /* Return a connection failure entry matching the given or_conn. NULL is
1299 * returned if not found. */
1300 static or_connect_failure_entry_t *
1301 or_connect_failure_find(const or_connection_t *or_conn)
1303 or_connect_failure_entry_t lookup;
1304 tor_assert(or_conn);
1305 or_connect_failure_init(or_conn->identity_digest, &TO_CONN(or_conn)->addr,
1306 TO_CONN(or_conn)->port, &lookup);
1307 return HT_FIND(or_connect_failure_ht, &or_connect_failures_map, &lookup);
1310 /* Note down in the connection failure cache that a failure occurred on the
1311 * given or_conn. */
1312 STATIC void
1313 note_or_connect_failed(const or_connection_t *or_conn)
1315 or_connect_failure_entry_t *ocf = NULL;
1317 tor_assert(or_conn);
1319 ocf = or_connect_failure_find(or_conn);
1320 if (ocf == NULL) {
1321 ocf = or_connect_failure_new(or_conn);
1322 HT_INSERT(or_connect_failure_ht, &or_connect_failures_map, ocf);
1324 ocf->last_failed_connect_ts = approx_time();
1327 /* Cleanup the connection failure cache and remove all entries below the
1328 * given cutoff. */
1329 static void
1330 or_connect_failure_map_cleanup(time_t cutoff)
1332 or_connect_failure_entry_t **ptr, **next, *entry;
1334 for (ptr = HT_START(or_connect_failure_ht, &or_connect_failures_map);
1335 ptr != NULL; ptr = next) {
1336 entry = *ptr;
1337 if (entry->last_failed_connect_ts <= cutoff) {
1338 next = HT_NEXT_RMV(or_connect_failure_ht, &or_connect_failures_map, ptr);
1339 tor_free(entry);
1340 } else {
1341 next = HT_NEXT(or_connect_failure_ht, &or_connect_failures_map, ptr);
1346 /* Return true iff the given OR connection can connect to its destination that
1347 * is the triplet identity_digest, address and port.
1349 * The or_conn MUST have gone through connection_or_check_canonicity() so the
1350 * base address is properly set to what we know or doesn't know. */
1351 STATIC int
1352 should_connect_to_relay(const or_connection_t *or_conn)
1354 time_t now, cutoff;
1355 time_t connect_failed_since_ts = 0;
1356 or_connect_failure_entry_t *ocf;
1358 tor_assert(or_conn);
1360 now = approx_time();
1361 cutoff = now - OR_CONNECT_FAILURE_LIFETIME;
1363 /* Opportunistically try to cleanup the failure cache. We do that at regular
1364 * interval so it doesn't grow too big. */
1365 if (or_connect_failure_map_next_cleanup_ts <= now) {
1366 or_connect_failure_map_cleanup(cutoff);
1367 or_connect_failure_map_next_cleanup_ts =
1368 now + OR_CONNECT_FAILURE_CLEANUP_INTERVAL;
1371 /* Look if we have failed previously to the same destination as this
1372 * OR connection. */
1373 ocf = or_connect_failure_find(or_conn);
1374 if (ocf) {
1375 connect_failed_since_ts = ocf->last_failed_connect_ts;
1377 /* If we do have an unable to connect timestamp and it is below cutoff, we
1378 * can connect. Or we have never failed before so let it connect. */
1379 if (connect_failed_since_ts > cutoff) {
1380 goto no_connect;
1383 /* Ok we can connect! */
1384 return 1;
1385 no_connect:
1386 return 0;
1389 /** <b>conn</b> is in the 'connecting' state, and it failed to complete
1390 * a TCP connection. Send notifications appropriately.
1392 * <b>reason</b> specifies the or_conn_end_reason for the failure;
1393 * <b>msg</b> specifies the strerror-style error message.
1395 void
1396 connection_or_connect_failed(or_connection_t *conn,
1397 int reason, const char *msg)
1399 connection_or_event_status(conn, OR_CONN_EVENT_FAILED, reason);
1400 if (!authdir_mode_tests_reachability(get_options()))
1401 control_event_bootstrap_prob_or(msg, reason, conn);
1402 note_or_connect_failed(conn);
1405 /** <b>conn</b> got an error in connection_handle_read_impl() or
1406 * connection_handle_write_impl() and is going to die soon.
1408 * <b>reason</b> specifies the or_conn_end_reason for the failure;
1409 * <b>msg</b> specifies the strerror-style error message.
1411 void
1412 connection_or_notify_error(or_connection_t *conn,
1413 int reason, const char *msg)
1415 channel_t *chan;
1417 tor_assert(conn);
1419 /* If we're connecting, call connect_failed() too */
1420 if (TO_CONN(conn)->state == OR_CONN_STATE_CONNECTING)
1421 connection_or_connect_failed(conn, reason, msg);
1423 /* Tell the controlling channel if we have one */
1424 if (conn->chan) {
1425 chan = TLS_CHAN_TO_BASE(conn->chan);
1426 /* Don't transition if we're already in closing, closed or error */
1427 if (!CHANNEL_CONDEMNED(chan)) {
1428 channel_close_for_error(chan);
1432 /* No need to mark for error because connection.c is about to do that */
1435 /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
1436 * handshake with an OR with identity digest <b>id_digest</b>. Optionally,
1437 * pass in a pointer to a channel using this connection.
1439 * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
1440 * return that connection. If the connect() is in progress, set the
1441 * new conn's state to 'connecting' and return it. If connect() succeeds,
1442 * call connection_tls_start_handshake() on it.
1444 * This function is called from router_retry_connections(), for
1445 * ORs connecting to ORs, and circuit_establish_circuit(), for
1446 * OPs connecting to ORs.
1448 * Return the launched conn, or NULL if it failed.
1451 MOCK_IMPL(or_connection_t *,
1452 connection_or_connect, (const tor_addr_t *_addr, uint16_t port,
1453 const char *id_digest,
1454 const ed25519_public_key_t *ed_id,
1455 channel_tls_t *chan))
1457 or_connection_t *conn;
1458 const or_options_t *options = get_options();
1459 int socket_error = 0;
1460 tor_addr_t addr;
1462 int r;
1463 tor_addr_t proxy_addr;
1464 uint16_t proxy_port;
1465 int proxy_type, is_pt = 0;
1467 tor_assert(_addr);
1468 tor_assert(id_digest);
1469 tor_addr_copy(&addr, _addr);
1471 if (server_mode(options) && router_digest_is_me(id_digest)) {
1472 log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
1473 return NULL;
1475 if (server_mode(options) && router_ed25519_id_is_me(ed_id)) {
1476 log_info(LD_PROTOCOL,"Client asked me to connect to myself by Ed25519 "
1477 "identity. Refusing.");
1478 return NULL;
1481 conn = or_connection_new(CONN_TYPE_OR, tor_addr_family(&addr));
1484 * Set up conn so it's got all the data we need to remember for channels
1486 * This stuff needs to happen before connection_or_init_conn_from_address()
1487 * so connection_or_set_identity_digest() and such know where to look to
1488 * keep the channel up to date.
1490 conn->chan = chan;
1491 chan->conn = conn;
1492 connection_or_init_conn_from_address(conn, &addr, port, id_digest, ed_id, 1);
1494 /* We have a proper OR connection setup, now check if we can connect to it
1495 * that is we haven't had a failure earlier. This is to avoid to try to
1496 * constantly connect to relays that we think are not reachable. */
1497 if (!should_connect_to_relay(conn)) {
1498 log_info(LD_GENERAL, "Can't connect to %s because we "
1499 "failed earlier. Refusing.",
1500 connection_describe_peer(TO_CONN(conn)));
1501 connection_free_(TO_CONN(conn));
1502 return NULL;
1505 conn->is_outgoing = 1;
1507 /* If we are using a proxy server, find it and use it. */
1508 r = get_proxy_addrport(&proxy_addr, &proxy_port, &proxy_type, &is_pt,
1509 TO_CONN(conn));
1510 if (r == 0) {
1511 conn->proxy_type = proxy_type;
1512 if (proxy_type != PROXY_NONE) {
1513 tor_addr_copy(&addr, &proxy_addr);
1514 port = proxy_port;
1515 conn->base_.proxy_state = PROXY_INFANT;
1516 conn->is_pt = is_pt;
1518 connection_or_change_state(conn, OR_CONN_STATE_CONNECTING);
1519 connection_or_event_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
1520 } else {
1521 /* This duplication of state change calls is necessary in case we
1522 * run into an error condition below */
1523 connection_or_change_state(conn, OR_CONN_STATE_CONNECTING);
1524 connection_or_event_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
1526 /* get_proxy_addrport() might fail if we have a Bridge line that
1527 references a transport, but no ClientTransportPlugin lines
1528 defining its transport proxy. If this is the case, let's try to
1529 output a useful log message to the user. */
1530 const char *transport_name =
1531 find_transport_name_by_bridge_addrport(&TO_CONN(conn)->addr,
1532 TO_CONN(conn)->port);
1534 if (transport_name) {
1535 log_warn(LD_GENERAL, "We were supposed to connect to bridge '%s' "
1536 "using pluggable transport '%s', but we can't find a pluggable "
1537 "transport proxy supporting '%s'. This can happen if you "
1538 "haven't provided a ClientTransportPlugin line, or if "
1539 "your pluggable transport proxy stopped running.",
1540 connection_describe_peer(TO_CONN(conn)),
1541 transport_name, transport_name);
1543 control_event_bootstrap_prob_or(
1544 "Can't connect to bridge",
1545 END_OR_CONN_REASON_PT_MISSING,
1546 conn);
1548 } else {
1549 log_warn(LD_GENERAL, "Tried to connect to %s through a proxy, but "
1550 "the proxy address could not be found.",
1551 connection_describe_peer(TO_CONN(conn)));
1554 connection_free_(TO_CONN(conn));
1555 return NULL;
1558 switch (connection_connect(TO_CONN(conn), conn->base_.address,
1559 &addr, port, &socket_error)) {
1560 case -1:
1561 /* We failed to establish a connection probably because of a local
1562 * error. No need to blame the guard in this case. Notify the networking
1563 * system of this failure. */
1564 connection_or_connect_failed(conn,
1565 errno_to_orconn_end_reason(socket_error),
1566 tor_socket_strerror(socket_error));
1567 connection_free_(TO_CONN(conn));
1568 return NULL;
1569 case 0:
1570 connection_watch_events(TO_CONN(conn), READ_EVENT | WRITE_EVENT);
1571 /* writable indicates finish, readable indicates broken link,
1572 error indicates broken link on windows */
1573 return conn;
1574 /* case 1: fall through */
1577 if (connection_or_finished_connecting(conn) < 0) {
1578 /* already marked for close */
1579 return NULL;
1581 return conn;
1584 /** Mark orconn for close and transition the associated channel, if any, to
1585 * the closing state.
1587 * It's safe to call this and connection_or_close_for_error() any time, and
1588 * channel layer will treat it as a connection closing for reasons outside
1589 * its control, like the remote end closing it. It can also be a local
1590 * reason that's specific to connection_t/or_connection_t rather than
1591 * the channel mechanism, such as expiration of old connections in
1592 * run_connection_housekeeping(). If you want to close a channel_t
1593 * from somewhere that logically works in terms of generic channels
1594 * rather than connections, use channel_mark_for_close(); see also
1595 * the comment on that function in channel.c.
1598 void
1599 connection_or_close_normally(or_connection_t *orconn, int flush)
1601 channel_t *chan = NULL;
1603 tor_assert(orconn);
1604 if (flush) connection_mark_and_flush_internal(TO_CONN(orconn));
1605 else connection_mark_for_close_internal(TO_CONN(orconn));
1606 if (orconn->chan) {
1607 chan = TLS_CHAN_TO_BASE(orconn->chan);
1608 /* Don't transition if we're already in closing, closed or error */
1609 if (!CHANNEL_CONDEMNED(chan)) {
1610 channel_close_from_lower_layer(chan);
1615 /** Mark orconn for close and transition the associated channel, if any, to
1616 * the error state.
1619 MOCK_IMPL(void,
1620 connection_or_close_for_error,(or_connection_t *orconn, int flush))
1622 channel_t *chan = NULL;
1624 tor_assert(orconn);
1625 if (flush) connection_mark_and_flush_internal(TO_CONN(orconn));
1626 else connection_mark_for_close_internal(TO_CONN(orconn));
1627 if (orconn->chan) {
1628 chan = TLS_CHAN_TO_BASE(orconn->chan);
1629 /* Don't transition if we're already in closing, closed or error */
1630 if (!CHANNEL_CONDEMNED(chan)) {
1631 channel_close_for_error(chan);
1636 /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
1637 * we initiated the connection, else it's 1.
1639 * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
1640 * pass <b>conn</b> to connection_tls_continue_handshake().
1642 * Return -1 if <b>conn</b> is broken, else return 0.
1644 MOCK_IMPL(int,
1645 connection_tls_start_handshake,(or_connection_t *conn, int receiving))
1647 channel_listener_t *chan_listener;
1648 channel_t *chan;
1650 /* Incoming connections will need a new channel passed to the
1651 * channel_tls_listener */
1652 if (receiving) {
1653 /* It shouldn't already be set */
1654 tor_assert(!(conn->chan));
1655 chan_listener = channel_tls_get_listener();
1656 if (!chan_listener) {
1657 chan_listener = channel_tls_start_listener();
1658 command_setup_listener(chan_listener);
1660 chan = channel_tls_handle_incoming(conn);
1661 channel_listener_queue_incoming(chan_listener, chan);
1664 connection_or_change_state(conn, OR_CONN_STATE_TLS_HANDSHAKING);
1665 tor_assert(!conn->tls);
1666 conn->tls = tor_tls_new(conn->base_.s, receiving);
1667 if (!conn->tls) {
1668 log_warn(LD_BUG,"tor_tls_new failed. Closing.");
1669 return -1;
1671 tor_tls_set_logged_address(conn->tls,
1672 connection_describe_peer(TO_CONN(conn)));
1674 connection_start_reading(TO_CONN(conn));
1675 log_debug(LD_HANDSHAKE,"starting TLS handshake on fd "TOR_SOCKET_T_FORMAT,
1676 conn->base_.s);
1678 if (connection_tls_continue_handshake(conn) < 0)
1679 return -1;
1681 return 0;
1684 /** Block all future attempts to renegotiate on 'conn' */
1685 void
1686 connection_or_block_renegotiation(or_connection_t *conn)
1688 tor_tls_t *tls = conn->tls;
1689 if (!tls)
1690 return;
1691 tor_tls_set_renegotiate_callback(tls, NULL, NULL);
1692 tor_tls_block_renegotiation(tls);
1695 /** Invoked on the server side from inside tor_tls_read() when the server
1696 * gets a successful TLS renegotiation from the client. */
1697 static void
1698 connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn)
1700 or_connection_t *conn = _conn;
1701 (void)tls;
1703 /* Don't invoke this again. */
1704 connection_or_block_renegotiation(conn);
1706 if (connection_tls_finish_handshake(conn) < 0) {
1707 /* XXXX_TLS double-check that it's ok to do this from inside read. */
1708 /* XXXX_TLS double-check that this verifies certificates. */
1709 connection_or_close_for_error(conn, 0);
1713 /** Move forward with the tls handshake. If it finishes, hand
1714 * <b>conn</b> to connection_tls_finish_handshake().
1716 * Return -1 if <b>conn</b> is broken, else return 0.
1719 connection_tls_continue_handshake(or_connection_t *conn)
1721 int result;
1722 check_no_tls_errors();
1724 tor_assert(conn->base_.state == OR_CONN_STATE_TLS_HANDSHAKING);
1725 // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
1726 result = tor_tls_handshake(conn->tls);
1727 // log_notice(LD_OR, "Result: %d", result);
1729 switch (result) {
1730 CASE_TOR_TLS_ERROR_ANY:
1731 conn->tls_error = result;
1732 log_info(LD_OR,"tls error [%s]. breaking connection.",
1733 tor_tls_err_to_string(result));
1734 return -1;
1735 case TOR_TLS_DONE:
1736 if (! tor_tls_used_v1_handshake(conn->tls)) {
1737 if (!tor_tls_is_server(conn->tls)) {
1738 tor_assert(conn->base_.state == OR_CONN_STATE_TLS_HANDSHAKING);
1739 return connection_or_launch_v3_or_handshake(conn);
1740 } else {
1741 /* v2/v3 handshake, but we are not a client. */
1742 log_debug(LD_OR, "Done with initial SSL handshake (server-side). "
1743 "Expecting renegotiation or VERSIONS cell");
1744 tor_tls_set_renegotiate_callback(conn->tls,
1745 connection_or_tls_renegotiated_cb,
1746 conn);
1747 connection_or_change_state(conn,
1748 OR_CONN_STATE_TLS_SERVER_RENEGOTIATING);
1749 connection_stop_writing(TO_CONN(conn));
1750 connection_start_reading(TO_CONN(conn));
1751 return 0;
1754 tor_assert(tor_tls_is_server(conn->tls));
1755 return connection_tls_finish_handshake(conn);
1756 case TOR_TLS_WANTWRITE:
1757 connection_start_writing(TO_CONN(conn));
1758 log_debug(LD_OR,"wanted write");
1759 return 0;
1760 case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
1761 log_debug(LD_OR,"wanted read");
1762 return 0;
1763 case TOR_TLS_CLOSE:
1764 conn->tls_error = result;
1765 log_info(LD_OR,"tls closed. breaking connection.");
1766 return -1;
1768 return 0;
1771 /** Return 1 if we initiated this connection, or 0 if it started
1772 * out as an incoming connection.
1775 connection_or_nonopen_was_started_here(or_connection_t *conn)
1777 tor_assert(conn->base_.type == CONN_TYPE_OR ||
1778 conn->base_.type == CONN_TYPE_EXT_OR);
1779 if (!conn->tls)
1780 return 1; /* it's still in proxy states or something */
1781 if (conn->handshake_state)
1782 return conn->handshake_state->started_here;
1783 return !tor_tls_is_server(conn->tls);
1786 /** <b>Conn</b> just completed its handshake. Return 0 if all is well, and
1787 * return -1 if they are lying, broken, or otherwise something is wrong.
1789 * If we initiated this connection (<b>started_here</b> is true), make sure
1790 * the other side sent a correctly formed certificate. If I initiated the
1791 * connection, make sure it's the right relay by checking the certificate.
1793 * Otherwise (if we _didn't_ initiate this connection), it's okay for
1794 * the certificate to be weird or absent.
1796 * If we return 0, and the certificate is as expected, write a hash of the
1797 * identity key into <b>digest_rcvd_out</b>, which must have DIGEST_LEN
1798 * space in it.
1799 * If the certificate is invalid or missing on an incoming connection,
1800 * we return 0 and set <b>digest_rcvd_out</b> to DIGEST_LEN NUL bytes.
1801 * (If we return -1, the contents of this buffer are undefined.)
1803 * As side effects,
1804 * 1) Set conn->circ_id_type according to tor-spec.txt.
1805 * 2) If we're an authdirserver and we initiated the connection: drop all
1806 * descriptors that claim to be on that IP/port but that aren't
1807 * this relay; and note that this relay is reachable.
1808 * 3) If this is a bridge and we didn't configure its identity
1809 * fingerprint, remember the keyid we just learned.
1811 static int
1812 connection_or_check_valid_tls_handshake(or_connection_t *conn,
1813 int started_here,
1814 char *digest_rcvd_out)
1816 crypto_pk_t *identity_rcvd=NULL;
1817 const or_options_t *options = get_options();
1818 int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
1819 const char *conn_type = started_here ? "outgoing" : "incoming";
1820 int has_cert = 0;
1822 check_no_tls_errors();
1823 has_cert = tor_tls_peer_has_cert(conn->tls);
1824 if (started_here && !has_cert) {
1825 log_info(LD_HANDSHAKE,"Tried connecting to router at %s, but it didn't "
1826 "send a cert! Closing.",
1827 connection_describe_peer(TO_CONN(conn)));
1828 return -1;
1829 } else if (!has_cert) {
1830 log_debug(LD_HANDSHAKE,"Got incoming connection with no certificate. "
1831 "That's ok.");
1833 check_no_tls_errors();
1835 if (has_cert) {
1836 int v = tor_tls_verify(started_here?severity:LOG_INFO,
1837 conn->tls, &identity_rcvd);
1838 if (started_here && v<0) {
1839 log_fn(severity,LD_HANDSHAKE,"Tried connecting to router at %s: It"
1840 " has a cert but it's invalid. Closing.",
1841 connection_describe_peer(TO_CONN(conn)));
1842 return -1;
1843 } else if (v<0) {
1844 log_info(LD_HANDSHAKE,"Incoming connection gave us an invalid cert "
1845 "chain; ignoring.");
1846 } else {
1847 log_debug(LD_HANDSHAKE,
1848 "The certificate seems to be valid on %s connection "
1849 "with %s", conn_type,
1850 connection_describe_peer(TO_CONN(conn)));
1852 check_no_tls_errors();
1855 if (identity_rcvd) {
1856 if (crypto_pk_get_digest(identity_rcvd, digest_rcvd_out) < 0) {
1857 crypto_pk_free(identity_rcvd);
1858 return -1;
1860 } else {
1861 memset(digest_rcvd_out, 0, DIGEST_LEN);
1864 tor_assert(conn->chan);
1865 channel_set_circid_type(TLS_CHAN_TO_BASE(conn->chan), identity_rcvd, 1);
1867 crypto_pk_free(identity_rcvd);
1869 if (started_here) {
1870 /* A TLS handshake can't teach us an Ed25519 ID, so we set it to NULL
1871 * here. */
1872 log_debug(LD_HANDSHAKE, "Calling client_learned_peer_id from "
1873 "check_valid_tls_handshake");
1874 return connection_or_client_learned_peer_id(conn,
1875 (const uint8_t*)digest_rcvd_out,
1876 NULL);
1879 return 0;
1882 /** Called when we (as a connection initiator) have definitively,
1883 * authenticatedly, learned that ID of the Tor instance on the other
1884 * side of <b>conn</b> is <b>rsa_peer_id</b> and optionally <b>ed_peer_id</b>.
1885 * For v1 and v2 handshakes,
1886 * this is right after we get a certificate chain in a TLS handshake
1887 * or renegotiation. For v3+ handshakes, this is right after we get a
1888 * certificate chain in a CERTS cell.
1890 * If we did not know the ID before, record the one we got.
1892 * If we wanted an ID, but we didn't get the one we expected, log a message
1893 * and return -1.
1894 * On relays:
1895 * - log a protocol warning whenever the fingerprints don't match;
1896 * On clients:
1897 * - if a relay's fingerprint doesn't match, log a warning;
1898 * - if we don't have updated relay fingerprints from a recent consensus, and
1899 * a fallback directory mirror's hard-coded fingerprint has changed, log an
1900 * info explaining that we will try another fallback.
1902 * If we're testing reachability, remember what we learned.
1904 * Return 0 on success, -1 on failure.
1907 connection_or_client_learned_peer_id(or_connection_t *conn,
1908 const uint8_t *rsa_peer_id,
1909 const ed25519_public_key_t *ed_peer_id)
1911 const or_options_t *options = get_options();
1912 channel_tls_t *chan_tls = conn->chan;
1913 channel_t *chan = channel_tls_to_base(chan_tls);
1914 int changed_identity = 0;
1915 tor_assert(chan);
1917 const int expected_rsa_key =
1918 ! tor_digest_is_zero(conn->identity_digest);
1919 const int expected_ed_key =
1920 ! ed25519_public_key_is_zero(&chan->ed25519_identity);
1922 log_info(LD_HANDSHAKE, "learned peer id for %s at %p: %s, %s",
1923 connection_describe(TO_CONN(conn)),
1924 conn,
1925 hex_str((const char*)rsa_peer_id, DIGEST_LEN),
1926 ed25519_fmt(ed_peer_id));
1928 if (! expected_rsa_key && ! expected_ed_key) {
1929 log_info(LD_HANDSHAKE, "(we had no ID in mind when we made this "
1930 "connection.");
1931 connection_or_set_identity_digest(conn,
1932 (const char*)rsa_peer_id, ed_peer_id);
1933 tor_free(conn->nickname);
1934 conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
1935 conn->nickname[0] = '$';
1936 base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
1937 conn->identity_digest, DIGEST_LEN);
1938 log_info(LD_HANDSHAKE, "Connected to router at %s without knowing "
1939 "its key. Hoping for the best.",
1940 connection_describe_peer(TO_CONN(conn)));
1941 /* if it's a bridge and we didn't know its identity fingerprint, now
1942 * we do -- remember it for future attempts. */
1943 learned_router_identity(&conn->base_.addr, conn->base_.port,
1944 (const char*)rsa_peer_id, ed_peer_id);
1945 changed_identity = 1;
1948 const int rsa_mismatch = expected_rsa_key &&
1949 tor_memneq(rsa_peer_id, conn->identity_digest, DIGEST_LEN);
1950 /* It only counts as an ed25519 mismatch if we wanted an ed25519 identity
1951 * and didn't get it. It's okay if we get one that we didn't ask for. */
1952 const int ed25519_mismatch =
1953 expected_ed_key &&
1954 (ed_peer_id == NULL ||
1955 ! ed25519_pubkey_eq(&chan->ed25519_identity, ed_peer_id));
1957 if (rsa_mismatch || ed25519_mismatch) {
1958 /* I was aiming for a particular digest. I didn't get it! */
1959 char seen_rsa[HEX_DIGEST_LEN+1];
1960 char expected_rsa[HEX_DIGEST_LEN+1];
1961 char seen_ed[ED25519_BASE64_LEN+1];
1962 char expected_ed[ED25519_BASE64_LEN+1];
1963 base16_encode(seen_rsa, sizeof(seen_rsa),
1964 (const char*)rsa_peer_id, DIGEST_LEN);
1965 base16_encode(expected_rsa, sizeof(expected_rsa), conn->identity_digest,
1966 DIGEST_LEN);
1967 if (ed_peer_id) {
1968 ed25519_public_to_base64(seen_ed, ed_peer_id);
1969 } else {
1970 strlcpy(seen_ed, "no ed25519 key", sizeof(seen_ed));
1972 if (! ed25519_public_key_is_zero(&chan->ed25519_identity)) {
1973 ed25519_public_to_base64(expected_ed, &chan->ed25519_identity);
1974 } else {
1975 strlcpy(expected_ed, "no ed25519 key", sizeof(expected_ed));
1977 const int using_hardcoded_fingerprints =
1978 !networkstatus_get_reasonably_live_consensus(time(NULL),
1979 usable_consensus_flavor());
1980 const int is_fallback_fingerprint = router_digest_is_fallback_dir(
1981 conn->identity_digest);
1982 const int is_authority_fingerprint = router_digest_is_trusted_dir(
1983 conn->identity_digest);
1984 const int non_anonymous_mode =
1985 hs_service_non_anonymous_mode_enabled(options);
1986 int severity;
1987 const char *extra_log = "";
1989 /* Relays and Single Onion Services make direct connections using
1990 * untrusted authentication keys. */
1991 if (server_mode(options) || non_anonymous_mode) {
1992 severity = LOG_PROTOCOL_WARN;
1993 } else {
1994 if (using_hardcoded_fingerprints) {
1995 /* We need to do the checks in this order, because the list of
1996 * fallbacks includes the list of authorities */
1997 if (is_authority_fingerprint) {
1998 severity = LOG_WARN;
1999 } else if (is_fallback_fingerprint) {
2000 /* we expect a small number of fallbacks to change from their
2001 * hard-coded fingerprints over the life of a release */
2002 severity = LOG_INFO;
2003 extra_log = " Tor will try a different fallback.";
2004 } else {
2005 /* it's a bridge, it's either a misconfiguration, or unexpected */
2006 severity = LOG_WARN;
2008 } else {
2009 /* a relay has changed its fingerprint from the one in the consensus */
2010 severity = LOG_WARN;
2014 log_fn(severity, LD_HANDSHAKE,
2015 "Tried connecting to router at %s, but RSA + ed25519 identity "
2016 "keys were not as expected: wanted %s + %s but got %s + %s.%s",
2017 connection_describe_peer(TO_CONN(conn)),
2018 expected_rsa, expected_ed, seen_rsa, seen_ed, extra_log);
2020 /* Tell the new guard API about the channel failure */
2021 entry_guard_chan_failed(TLS_CHAN_TO_BASE(conn->chan));
2022 connection_or_event_status(conn, OR_CONN_EVENT_FAILED,
2023 END_OR_CONN_REASON_OR_IDENTITY);
2024 if (!authdir_mode_tests_reachability(options))
2025 control_event_bootstrap_prob_or(
2026 "Unexpected identity in router certificate",
2027 END_OR_CONN_REASON_OR_IDENTITY,
2028 conn);
2029 return -1;
2032 if (!expected_ed_key && ed_peer_id) {
2033 log_info(LD_HANDSHAKE, "(We had no Ed25519 ID in mind when we made this "
2034 "connection.)");
2035 connection_or_set_identity_digest(conn,
2036 (const char*)rsa_peer_id, ed_peer_id);
2037 changed_identity = 1;
2040 if (changed_identity) {
2041 /* If we learned an identity for this connection, then we might have
2042 * just discovered it to be canonical. */
2043 connection_or_check_canonicity(conn, conn->handshake_state->started_here);
2044 if (conn->tls)
2045 tor_tls_set_logged_address(conn->tls,
2046 connection_describe_peer(TO_CONN(conn)));
2049 if (authdir_mode_tests_reachability(options)) {
2050 // We don't want to use canonical_orport here -- we want the address
2051 // that we really used.
2052 dirserv_orconn_tls_done(&conn->base_.addr, conn->base_.port,
2053 (const char*)rsa_peer_id, ed_peer_id);
2056 return 0;
2059 /** Return when we last used this channel for client activity (origin
2060 * circuits). This is called from connection.c, since client_used is now one
2061 * of the timestamps in channel_t */
2063 time_t
2064 connection_or_client_used(or_connection_t *conn)
2066 tor_assert(conn);
2068 if (conn->chan) {
2069 return channel_when_last_client(TLS_CHAN_TO_BASE(conn->chan));
2070 } else return 0;
2073 /** The v1/v2 TLS handshake is finished.
2075 * Make sure we are happy with the peer we just handshaked with.
2077 * If they initiated the connection, make sure they're not already connected,
2078 * then initialize conn from the information in router.
2080 * If all is successful, call circuit_n_conn_done() to handle events
2081 * that have been pending on the <tls handshake completion. Also set the
2082 * directory to be dirty (only matters if I'm an authdirserver).
2084 * If this is a v2 TLS handshake, send a versions cell.
2086 static int
2087 connection_tls_finish_handshake(or_connection_t *conn)
2089 char digest_rcvd[DIGEST_LEN];
2090 int started_here = connection_or_nonopen_was_started_here(conn);
2092 tor_assert(!started_here);
2094 log_debug(LD_HANDSHAKE,"%s tls handshake on %s done, using "
2095 "ciphersuite %s. verifying.",
2096 started_here?"outgoing":"incoming",
2097 connection_describe_peer(TO_CONN(conn)),
2098 tor_tls_get_ciphersuite_name(conn->tls));
2100 if (connection_or_check_valid_tls_handshake(conn, started_here,
2101 digest_rcvd) < 0)
2102 return -1;
2104 circuit_build_times_network_is_live(get_circuit_build_times_mutable());
2106 if (tor_tls_used_v1_handshake(conn->tls)) {
2107 conn->link_proto = 1;
2108 connection_or_init_conn_from_address(conn, &conn->base_.addr,
2109 conn->base_.port, digest_rcvd,
2110 NULL, 0);
2111 tor_tls_block_renegotiation(conn->tls);
2112 rep_hist_note_negotiated_link_proto(1, started_here);
2113 return connection_or_set_state_open(conn);
2114 } else {
2115 connection_or_change_state(conn, OR_CONN_STATE_OR_HANDSHAKING_V2);
2116 if (connection_init_or_handshake_state(conn, started_here) < 0)
2117 return -1;
2118 connection_or_init_conn_from_address(conn, &conn->base_.addr,
2119 conn->base_.port, digest_rcvd,
2120 NULL, 0);
2121 return connection_or_send_versions(conn, 0);
2126 * Called as client when initial TLS handshake is done, and we notice
2127 * that we got a v3-handshake signalling certificate from the server.
2128 * Set up structures, do bookkeeping, and send the versions cell.
2129 * Return 0 on success and -1 on failure.
2131 static int
2132 connection_or_launch_v3_or_handshake(or_connection_t *conn)
2134 tor_assert(connection_or_nonopen_was_started_here(conn));
2136 circuit_build_times_network_is_live(get_circuit_build_times_mutable());
2138 connection_or_change_state(conn, OR_CONN_STATE_OR_HANDSHAKING_V3);
2139 if (connection_init_or_handshake_state(conn, 1) < 0)
2140 return -1;
2142 return connection_or_send_versions(conn, 1);
2145 /** Allocate a new connection handshake state for the connection
2146 * <b>conn</b>. Return 0 on success, -1 on failure. */
2148 connection_init_or_handshake_state(or_connection_t *conn, int started_here)
2150 or_handshake_state_t *s;
2151 if (conn->handshake_state) {
2152 log_warn(LD_BUG, "Duplicate call to connection_init_or_handshake_state!");
2153 return 0;
2155 s = conn->handshake_state = tor_malloc_zero(sizeof(or_handshake_state_t));
2156 s->started_here = started_here ? 1 : 0;
2157 s->digest_sent_data = 1;
2158 s->digest_received_data = 1;
2159 if (! started_here && get_current_link_cert_cert()) {
2160 s->own_link_cert = tor_cert_dup(get_current_link_cert_cert());
2162 s->certs = or_handshake_certs_new();
2163 s->certs->started_here = s->started_here;
2164 return 0;
2167 /** Free all storage held by <b>state</b>. */
2168 void
2169 or_handshake_state_free_(or_handshake_state_t *state)
2171 if (!state)
2172 return;
2173 crypto_digest_free(state->digest_sent);
2174 crypto_digest_free(state->digest_received);
2175 or_handshake_certs_free(state->certs);
2176 tor_cert_free(state->own_link_cert);
2177 memwipe(state, 0xBE, sizeof(or_handshake_state_t));
2178 tor_free(state);
2182 * Remember that <b>cell</b> has been transmitted (if <b>incoming</b> is
2183 * false) or received (if <b>incoming</b> is true) during a V3 handshake using
2184 * <b>state</b>.
2186 * (We don't record the cell, but we keep a digest of everything sent or
2187 * received during the v3 handshake, and the client signs it in an
2188 * authenticate cell.)
2190 void
2191 or_handshake_state_record_cell(or_connection_t *conn,
2192 or_handshake_state_t *state,
2193 const cell_t *cell,
2194 int incoming)
2196 size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
2197 crypto_digest_t *d, **dptr;
2198 packed_cell_t packed;
2199 if (incoming) {
2200 if (!state->digest_received_data)
2201 return;
2202 } else {
2203 if (!state->digest_sent_data)
2204 return;
2206 if (!incoming) {
2207 log_warn(LD_BUG, "We shouldn't be sending any non-variable-length cells "
2208 "while making a handshake digest. But we think we are sending "
2209 "one with type %d.", (int)cell->command);
2211 dptr = incoming ? &state->digest_received : &state->digest_sent;
2212 if (! *dptr)
2213 *dptr = crypto_digest256_new(DIGEST_SHA256);
2215 d = *dptr;
2216 /* Re-packing like this is a little inefficient, but we don't have to do
2217 this very often at all. */
2218 cell_pack(&packed, cell, conn->wide_circ_ids);
2219 crypto_digest_add_bytes(d, packed.body, cell_network_size);
2220 memwipe(&packed, 0, sizeof(packed));
2223 /** Remember that a variable-length <b>cell</b> has been transmitted (if
2224 * <b>incoming</b> is false) or received (if <b>incoming</b> is true) during a
2225 * V3 handshake using <b>state</b>.
2227 * (We don't record the cell, but we keep a digest of everything sent or
2228 * received during the v3 handshake, and the client signs it in an
2229 * authenticate cell.)
2231 void
2232 or_handshake_state_record_var_cell(or_connection_t *conn,
2233 or_handshake_state_t *state,
2234 const var_cell_t *cell,
2235 int incoming)
2237 crypto_digest_t *d, **dptr;
2238 int n;
2239 char buf[VAR_CELL_MAX_HEADER_SIZE];
2240 if (incoming) {
2241 if (!state->digest_received_data)
2242 return;
2243 } else {
2244 if (!state->digest_sent_data)
2245 return;
2247 dptr = incoming ? &state->digest_received : &state->digest_sent;
2248 if (! *dptr)
2249 *dptr = crypto_digest256_new(DIGEST_SHA256);
2251 d = *dptr;
2253 n = var_cell_pack_header(cell, buf, conn->wide_circ_ids);
2254 crypto_digest_add_bytes(d, buf, n);
2255 crypto_digest_add_bytes(d, (const char *)cell->payload, cell->payload_len);
2257 memwipe(buf, 0, sizeof(buf));
2260 /** Set <b>conn</b>'s state to OR_CONN_STATE_OPEN, and tell other subsystems
2261 * as appropriate. Called when we are done with all TLS and OR handshaking.
2264 connection_or_set_state_open(or_connection_t *conn)
2266 connection_or_change_state(conn, OR_CONN_STATE_OPEN);
2267 connection_or_event_status(conn, OR_CONN_EVENT_CONNECTED, 0);
2269 /* Link protocol 3 appeared in Tor 0.2.3.6-alpha, so any connection
2270 * that uses an earlier link protocol should not be treated as a relay. */
2271 if (conn->link_proto < 3) {
2272 channel_mark_client(TLS_CHAN_TO_BASE(conn->chan));
2275 or_handshake_state_free(conn->handshake_state);
2276 conn->handshake_state = NULL;
2277 connection_start_reading(TO_CONN(conn));
2279 return 0;
2282 /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
2283 * For cells that use or affect a circuit, this should only be called by
2284 * connection_or_flush_from_first_active_circuit().
2286 void
2287 connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
2289 packed_cell_t networkcell;
2290 size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
2292 tor_assert(cell);
2293 tor_assert(conn);
2295 cell_pack(&networkcell, cell, conn->wide_circ_ids);
2297 /* We need to count padding cells from this non-packed code path
2298 * since they are sent via chan->write_cell() (which is not packed) */
2299 rep_hist_padding_count_write(PADDING_TYPE_TOTAL);
2300 if (cell->command == CELL_PADDING)
2301 rep_hist_padding_count_write(PADDING_TYPE_CELL);
2303 connection_buf_add(networkcell.body, cell_network_size, TO_CONN(conn));
2305 /* Touch the channel's active timestamp if there is one */
2306 if (conn->chan) {
2307 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2309 if (TLS_CHAN_TO_BASE(conn->chan)->padding_enabled) {
2310 rep_hist_padding_count_write(PADDING_TYPE_ENABLED_TOTAL);
2311 if (cell->command == CELL_PADDING)
2312 rep_hist_padding_count_write(PADDING_TYPE_ENABLED_CELL);
2316 if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
2317 or_handshake_state_record_cell(conn, conn->handshake_state, cell, 0);
2320 /** Pack a variable-length <b>cell</b> into wire-format, and write it onto
2321 * <b>conn</b>'s outbuf. Right now, this <em>DOES NOT</em> support cells that
2322 * affect a circuit.
2324 MOCK_IMPL(void,
2325 connection_or_write_var_cell_to_buf,(const var_cell_t *cell,
2326 or_connection_t *conn))
2328 int n;
2329 char hdr[VAR_CELL_MAX_HEADER_SIZE];
2330 tor_assert(cell);
2331 tor_assert(conn);
2332 n = var_cell_pack_header(cell, hdr, conn->wide_circ_ids);
2333 connection_buf_add(hdr, n, TO_CONN(conn));
2334 connection_buf_add((char*)cell->payload,
2335 cell->payload_len, TO_CONN(conn));
2336 if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
2337 or_handshake_state_record_var_cell(conn, conn->handshake_state, cell, 0);
2339 rep_hist_padding_count_write(PADDING_TYPE_TOTAL);
2340 /* Touch the channel's active timestamp if there is one */
2341 if (conn->chan)
2342 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2345 /** See whether there's a variable-length cell waiting on <b>or_conn</b>'s
2346 * inbuf. Return values as for fetch_var_cell_from_buf(). */
2347 static int
2348 connection_fetch_var_cell_from_buf(or_connection_t *or_conn, var_cell_t **out)
2350 connection_t *conn = TO_CONN(or_conn);
2351 return fetch_var_cell_from_buf(conn->inbuf, out, or_conn->link_proto);
2354 /** Process cells from <b>conn</b>'s inbuf.
2356 * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
2357 * and hand it to command_process_cell().
2359 * Always return 0.
2361 static int
2362 connection_or_process_cells_from_inbuf(or_connection_t *conn)
2364 var_cell_t *var_cell;
2367 * Note on memory management for incoming cells: below the channel layer,
2368 * we shouldn't need to consider its internal queueing/copying logic. It
2369 * is safe to pass cells to it on the stack or on the heap, but in the
2370 * latter case we must be sure we free them later.
2372 * The incoming cell queue code in channel.c will (in the common case)
2373 * decide it can pass them to the upper layer immediately, in which case
2374 * those functions may run directly on the cell pointers we pass here, or
2375 * it may decide to queue them, in which case it will allocate its own
2376 * buffer and copy the cell.
2379 while (1) {
2380 log_debug(LD_OR,
2381 TOR_SOCKET_T_FORMAT": starting, inbuf_datalen %d "
2382 "(%d pending in tls object).",
2383 conn->base_.s,(int)connection_get_inbuf_len(TO_CONN(conn)),
2384 tor_tls_get_pending_bytes(conn->tls));
2385 if (connection_fetch_var_cell_from_buf(conn, &var_cell)) {
2386 if (!var_cell)
2387 return 0; /* not yet. */
2389 /* Touch the channel's active timestamp if there is one */
2390 if (conn->chan)
2391 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2393 circuit_build_times_network_is_live(get_circuit_build_times_mutable());
2394 channel_tls_handle_var_cell(var_cell, conn);
2395 var_cell_free(var_cell);
2396 } else {
2397 const int wide_circ_ids = conn->wide_circ_ids;
2398 size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
2399 char buf[CELL_MAX_NETWORK_SIZE];
2400 cell_t cell;
2401 if (connection_get_inbuf_len(TO_CONN(conn))
2402 < cell_network_size) /* whole response available? */
2403 return 0; /* not yet */
2405 /* Touch the channel's active timestamp if there is one */
2406 if (conn->chan)
2407 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2409 circuit_build_times_network_is_live(get_circuit_build_times_mutable());
2410 connection_buf_get_bytes(buf, cell_network_size, TO_CONN(conn));
2412 /* retrieve cell info from buf (create the host-order struct from the
2413 * network-order string) */
2414 cell_unpack(&cell, buf, wide_circ_ids);
2416 channel_tls_handle_cell(&cell, conn);
2421 /** Array of recognized link protocol versions. */
2422 static const uint16_t or_protocol_versions[] = { 1, 2, 3, 4, 5 };
2423 /** Number of versions in <b>or_protocol_versions</b>. */
2424 static const int n_or_protocol_versions =
2425 (int)( sizeof(or_protocol_versions)/sizeof(uint16_t) );
2427 /** Return true iff <b>v</b> is a link protocol version that this Tor
2428 * implementation believes it can support. */
2430 is_or_protocol_version_known(uint16_t v)
2432 int i;
2433 for (i = 0; i < n_or_protocol_versions; ++i) {
2434 if (or_protocol_versions[i] == v)
2435 return 1;
2437 return 0;
2440 /** Send a VERSIONS cell on <b>conn</b>, telling the other host about the
2441 * link protocol versions that this Tor can support.
2443 * If <b>v3_plus</b>, this is part of a V3 protocol handshake, so only
2444 * allow protocol version v3 or later. If not <b>v3_plus</b>, this is
2445 * not part of a v3 protocol handshake, so don't allow protocol v3 or
2446 * later.
2449 connection_or_send_versions(or_connection_t *conn, int v3_plus)
2451 var_cell_t *cell;
2452 int i;
2453 int n_versions = 0;
2454 const int min_version = v3_plus ? 3 : 0;
2455 const int max_version = v3_plus ? UINT16_MAX : 2;
2456 tor_assert(conn->handshake_state &&
2457 !conn->handshake_state->sent_versions_at);
2458 cell = var_cell_new(n_or_protocol_versions * 2);
2459 cell->command = CELL_VERSIONS;
2460 for (i = 0; i < n_or_protocol_versions; ++i) {
2461 uint16_t v = or_protocol_versions[i];
2462 if (v < min_version || v > max_version)
2463 continue;
2464 set_uint16(cell->payload+(2*n_versions), htons(v));
2465 ++n_versions;
2467 cell->payload_len = n_versions * 2;
2469 connection_or_write_var_cell_to_buf(cell, conn);
2470 conn->handshake_state->sent_versions_at = time(NULL);
2472 var_cell_free(cell);
2473 return 0;
2476 static netinfo_addr_t *
2477 netinfo_addr_from_tor_addr(const tor_addr_t *tor_addr)
2479 sa_family_t addr_family = tor_addr_family(tor_addr);
2481 if (BUG(addr_family != AF_INET && addr_family != AF_INET6))
2482 return NULL;
2484 netinfo_addr_t *netinfo_addr = netinfo_addr_new();
2486 if (addr_family == AF_INET) {
2487 netinfo_addr_set_addr_type(netinfo_addr, NETINFO_ADDR_TYPE_IPV4);
2488 netinfo_addr_set_len(netinfo_addr, 4);
2489 netinfo_addr_set_addr_ipv4(netinfo_addr, tor_addr_to_ipv4h(tor_addr));
2490 } else if (addr_family == AF_INET6) {
2491 netinfo_addr_set_addr_type(netinfo_addr, NETINFO_ADDR_TYPE_IPV6);
2492 netinfo_addr_set_len(netinfo_addr, 16);
2493 uint8_t *ipv6_buf = netinfo_addr_getarray_addr_ipv6(netinfo_addr);
2494 const uint8_t *in6_addr = tor_addr_to_in6_addr8(tor_addr);
2495 memcpy(ipv6_buf, in6_addr, 16);
2498 return netinfo_addr;
2501 /** Send a NETINFO cell on <b>conn</b>, telling the other server what we know
2502 * about their address, our address, and the current time. */
2503 MOCK_IMPL(int,
2504 connection_or_send_netinfo,(or_connection_t *conn))
2506 cell_t cell;
2507 time_t now = time(NULL);
2508 const routerinfo_t *me;
2509 int r = -1;
2511 tor_assert(conn->handshake_state);
2513 if (conn->handshake_state->sent_netinfo) {
2514 log_warn(LD_BUG, "Attempted to send an extra netinfo cell on a connection "
2515 "where we already sent one.");
2516 return 0;
2519 memset(&cell, 0, sizeof(cell_t));
2520 cell.command = CELL_NETINFO;
2522 netinfo_cell_t *netinfo_cell = netinfo_cell_new();
2524 /* Timestamp, if we're a relay. */
2525 if (public_server_mode(get_options()) || ! conn->is_outgoing)
2526 netinfo_cell_set_timestamp(netinfo_cell, (uint32_t)now);
2528 /* Their address. */
2529 const tor_addr_t *remote_tor_addr = &TO_CONN(conn)->addr;
2530 /* We can safely use TO_CONN(conn)->addr here, since we no longer replace
2531 * it with a canonical address. */
2532 netinfo_addr_t *their_addr = netinfo_addr_from_tor_addr(remote_tor_addr);
2534 netinfo_cell_set_other_addr(netinfo_cell, their_addr);
2536 /* My address -- only include it if I'm a public relay, or if I'm a
2537 * bridge and this is an incoming connection. If I'm a bridge and this
2538 * is an outgoing connection, act like a normal client and omit it. */
2539 if ((public_server_mode(get_options()) || !conn->is_outgoing) &&
2540 (me = router_get_my_routerinfo())) {
2541 uint8_t n_my_addrs = 1 + !tor_addr_is_null(&me->ipv6_addr);
2542 netinfo_cell_set_n_my_addrs(netinfo_cell, n_my_addrs);
2544 netinfo_cell_add_my_addrs(netinfo_cell,
2545 netinfo_addr_from_tor_addr(&me->ipv4_addr));
2547 if (!tor_addr_is_null(&me->ipv6_addr)) {
2548 netinfo_cell_add_my_addrs(netinfo_cell,
2549 netinfo_addr_from_tor_addr(&me->ipv6_addr));
2553 const char *errmsg = NULL;
2554 if ((errmsg = netinfo_cell_check(netinfo_cell))) {
2555 log_warn(LD_OR, "Failed to validate NETINFO cell with error: %s",
2556 errmsg);
2557 goto cleanup;
2560 if (netinfo_cell_encode(cell.payload, CELL_PAYLOAD_SIZE,
2561 netinfo_cell) < 0) {
2562 log_warn(LD_OR, "Failed generating NETINFO cell");
2563 goto cleanup;
2566 conn->handshake_state->digest_sent_data = 0;
2567 conn->handshake_state->sent_netinfo = 1;
2568 connection_or_write_cell_to_buf(&cell, conn);
2570 r = 0;
2571 cleanup:
2572 netinfo_cell_free(netinfo_cell);
2574 return r;