Tor 0.4.9.13
Loading...
Searching...
No Matches
connection_or.c
Go to the documentation of this file.
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 */
6
7/**
8 * \file connection_or.c
9 * \brief Functions to handle OR connections, TLS handshaking, and
10 * cells on the network.
11 *
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.)
16 *
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.
20 *
21 * This module also implements the client side of the v3 (and greater) Tor
22 * link handshake.
23 **/
24#include "core/or/or.h"
26#include "lib/buf/buffers.h"
27/*
28 * Define this so we get channel internal functions, since we're implementing
29 * part of a subclass (channel_tls_t).
30 */
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"
37#include "core/or/circuitlist.h"
39#include "core/or/command.h"
40#include "app/config/config.h"
48#include "lib/geoip/geoip.h"
50#include "trunnel/netinfo.h"
55#include "core/or/reasons.h"
56#include "core/or/relay.h"
65#include "core/or/scheduler.h"
67#include "core/or/channelpadding.h"
71
72#include "core/or/cell_st.h"
79#include "core/or/var_cell_st.h"
81
82#include "lib/tls/tortls.h"
83
85
88
89static unsigned int
91static void connection_or_mark_bad_for_new_circs(or_connection_t *or_conn);
92
94 int started_here);
95
96/**************************************************************/
97
98/**
99 * Cast a `connection_t *` to an `or_connection_t *`.
100 *
101 * Exit with an assertion failure if the input is not an `or_connection_t`.
102 **/
105{
106 tor_assert(c->magic == OR_CONNECTION_MAGIC);
107 return DOWNCAST(or_connection_t, c);
108}
109
110/**
111 * Cast a `const connection_t *` to a `const or_connection_t *`.
112 *
113 * Exit with an assertion failure if the input is not an `or_connection_t`.
114 **/
115const or_connection_t *
117{
118 return TO_OR_CONN((connection_t *)c);
119}
120
121/** Clear clear conn->identity_digest and update other data
122 * structures as appropriate.*/
123void
125{
126 tor_assert(conn);
127 memset(conn->identity_digest, 0, DIGEST_LEN);
128}
129
130/** Clear all identities in OR conns.*/
131void
133{
135 SMARTLIST_FOREACH(conns, connection_t *, conn,
136 {
137 if (conn->type == CONN_TYPE_OR) {
139 }
140 });
141}
142
143/** Change conn->identity_digest to digest, and add conn into
144 * the appropriate digest maps.
145 *
146 * NOTE that this function only allows two kinds of transitions: from
147 * unset identity to set identity, and from idempotent re-settings
148 * of the same identity. It's not allowed to clear an identity or to
149 * change an identity. Return 0 on success, and -1 if the transition
150 * is not allowed.
151 **/
152static void
154 const char *rsa_digest,
155 const ed25519_public_key_t *ed_id)
156{
157 channel_t *chan = NULL;
158 tor_assert(conn);
159 tor_assert(rsa_digest);
160
161 if (conn->chan)
162 chan = TLS_CHAN_TO_BASE(conn->chan);
163
164 log_info(LD_HANDSHAKE, "Set identity digest for %s at %p: %s %s.",
166 conn,
167 hex_str(rsa_digest, DIGEST_LEN),
168 ed25519_fmt(ed_id));
169 log_info(LD_HANDSHAKE, " (Previously: %s %s)",
171 chan ? ed25519_fmt(&chan->ed25519_identity) : "<null>");
172
173 const int rsa_id_was_set = ! tor_digest_is_zero(conn->identity_digest);
174 const int ed_id_was_set =
176 const int new_ed_id_is_set =
177 (ed_id && !ed25519_public_key_is_zero(ed_id));
178 const int rsa_changed =
179 tor_memneq(conn->identity_digest, rsa_digest, DIGEST_LEN);
180 const int ed_changed = bool_neq(ed_id_was_set, new_ed_id_is_set) ||
181 (ed_id_was_set && new_ed_id_is_set && chan &&
182 !ed25519_pubkey_eq(ed_id, &chan->ed25519_identity));
183
184 if (BUG(rsa_changed && rsa_id_was_set))
185 return;
186 if (BUG(ed_changed && ed_id_was_set))
187 return;
188
189 if (!rsa_changed && !ed_changed)
190 return;
191
192 /* If the identity was set previously, remove the old mapping. */
193 if (rsa_id_was_set) {
195 if (chan)
197 }
198
199 memcpy(conn->identity_digest, rsa_digest, DIGEST_LEN);
200
201 /* If we're initializing the IDs to zero, don't add a mapping yet. */
202 if (tor_digest_is_zero(rsa_digest) && !new_ed_id_is_set)
203 return;
204
205 /* Deal with channels */
206 if (chan)
207 channel_set_identity_digest(chan, rsa_digest, ed_id);
208}
209
210/**
211 * Return the Ed25519 identity of the peer for this connection (if any).
212 *
213 * Note that this ID may not be the _actual_ identity for the peer if
214 * authentication is not complete.
215 **/
216const struct ed25519_public_key_t *
218{
219 if (conn && conn->chan) {
220 const channel_t *chan = NULL;
221 chan = TLS_CHAN_TO_BASE(conn->chan);
223 return &chan->ed25519_identity;
224 }
225 }
226
227 return NULL;
228}
229
230/**************************************************************/
231
232/** Map from a string describing what a non-open OR connection was doing when
233 * failed, to an intptr_t describing the count of connections that failed that
234 * way. Note that the count is stored _as_ the pointer.
235 */
237
238/** If true, do not record information in <b>broken_connection_counts</b>. */
240
241/** Record that an OR connection failed in <b>state</b>. */
242static void
243note_broken_connection(const char *state)
244{
245 void *ptr;
246 intptr_t val;
248 return;
249
251 broken_connection_counts = strmap_new();
252
253 ptr = strmap_get(broken_connection_counts, state);
254 val = (intptr_t)ptr;
255 val++;
256 ptr = (void*)val;
257 strmap_set(broken_connection_counts, state, ptr);
258}
259
260/** Forget all recorded states for failed connections. If
261 * <b>stop_recording</b> is true, don't record any more. */
262void
264{
266 strmap_free(broken_connection_counts, NULL);
268 if (stop_recording)
270}
271
272/** Write a detailed description the state of <b>orconn</b> into the
273 * <b>buflen</b>-byte buffer at <b>buf</b>. This description includes not
274 * only the OR-conn level state but also the TLS state. It's useful for
275 * diagnosing broken handshakes. */
276static void
278 char *buf, size_t buflen)
279{
280 connection_t *conn = TO_CONN(orconn);
281 const char *conn_state;
282 char tls_state[256];
283
284 tor_assert(conn->type == CONN_TYPE_OR || conn->type == CONN_TYPE_EXT_OR);
285
286 conn_state = conn_state_to_string(conn->type, conn->state);
287 tor_tls_get_state_description(orconn->tls, tls_state, sizeof(tls_state));
288
289 tor_snprintf(buf, buflen, "%s with SSL state %s", conn_state, tls_state);
290}
291
292/** Record the current state of <b>orconn</b> as the state of a broken
293 * connection. */
294static void
296{
297 char buf[256];
299 return;
300 connection_or_get_state_description(orconn, buf, sizeof(buf));
301 log_info(LD_HANDSHAKE,"Connection died in state '%s'", buf);
303}
304
305/** Helper type used to sort connection states and find the most frequent. */
306typedef struct broken_state_count_t {
307 intptr_t count;
308 const char *state;
310
311/** Helper function used to sort broken_state_count_t by frequency. */
312static int
313broken_state_count_compare(const void **a_ptr, const void **b_ptr)
314{
315 const broken_state_count_t *a = *a_ptr, *b = *b_ptr;
316 if (b->count < a->count)
317 return -1;
318 else if (b->count == a->count)
319 return 0;
320 else
321 return 1;
322}
323
324/** Upper limit on the number of different states to report for connection
325 * failure. */
326#define MAX_REASONS_TO_REPORT 10
327
328/** Report a list of the top states for failed OR connections at log level
329 * <b>severity</b>, in log domain <b>domain</b>. */
330void
331connection_or_report_broken_states(int severity, int domain)
332{
333 int total = 0;
334 smartlist_t *items;
335
337 return;
338
339 items = smartlist_new();
340 STRMAP_FOREACH(broken_connection_counts, state, void *, countptr) {
341 broken_state_count_t *c = tor_malloc(sizeof(broken_state_count_t));
342 c->count = (intptr_t)countptr;
343 total += (int)c->count;
344 c->state = state;
345 smartlist_add(items, c);
346 } STRMAP_FOREACH_END;
347
349
350 tor_log(severity, domain, "%d connections have failed%s", total,
351 smartlist_len(items) > MAX_REASONS_TO_REPORT ? ". Top reasons:" : ":");
352
354 if (c_sl_idx > MAX_REASONS_TO_REPORT)
355 break;
356 tor_log(severity, domain,
357 " %d connections died in state %s", (int)c->count, c->state);
358 } SMARTLIST_FOREACH_END(c);
359
361 smartlist_free(items);
362}
363
364/**
365 * Helper function to publish an OR connection status event
366 *
367 * Publishes a messages to subscribers of ORCONN messages, and sends
368 * the control event.
369 **/
370void
372 int reason)
373{
374 orconn_status_msg_t *msg = tor_malloc(sizeof(*msg));
375
376 msg->gid = conn->base_.global_identifier;
377 msg->status = tp;
378 msg->reason = reason;
379 orconn_status_publish(msg);
380 control_event_or_conn_status(conn, tp, reason);
381}
382
383/**
384 * Helper function to publish a state change message
385 *
386 * connection_or_change_state() calls this to notify subscribers about
387 * a change of an OR connection state.
388 **/
389static void
391{
392 orconn_state_msg_t *msg = tor_malloc(sizeof(*msg));
393
394 msg->gid = conn->base_.global_identifier;
395 if (conn->is_pt) {
396 /* Do extra decoding because conn->proxy_type indicates the proxy
397 * protocol that tor uses to talk with the transport plugin,
398 * instead of PROXY_PLUGGABLE. */
399 tor_assert_nonfatal(conn->proxy_type != PROXY_NONE);
400 msg->proxy_type = PROXY_PLUGGABLE;
401 } else {
402 msg->proxy_type = conn->proxy_type;
403 }
404 msg->state = state;
405 if (conn->chan) {
406 msg->chan = TLS_CHAN_TO_BASE(conn->chan)->global_identifier;
407 } else {
408 msg->chan = 0;
409 }
410 orconn_state_publish(msg);
411}
412
413/** Call this to change or_connection_t states, so the owning channel_tls_t can
414 * be notified.
415 */
416MOCK_IMPL(void,
418{
419 tor_assert(conn);
420
421 conn->base_.state = state;
422
423 connection_or_state_publish(conn, state);
424 if (conn->chan)
426}
427
428/** Return the number of circuits using an or_connection_t; this used to
429 * be an or_connection_t field, but it got moved to channel_t and we
430 * shouldn't maintain two copies. */
431MOCK_IMPL(int,
433{
434 tor_assert(conn);
435
436 if (conn->chan) {
437 return channel_num_circuits(TLS_CHAN_TO_BASE(conn->chan));
438 } else return 0;
439}
440
441/**************************************************************/
442
443/** Pack the cell_t host-order structure <b>src</b> into network-order
444 * in the buffer <b>dest</b>. See tor-spec.txt for details about the
445 * wire format.
446 *
447 * Note that this function doesn't touch <b>dst</b>->next: the caller
448 * should set it or clear it as appropriate.
449 */
450void
451cell_pack(packed_cell_t *dst, const cell_t *src, int wide_circ_ids)
452{
453 char *dest = dst->body;
454 if (wide_circ_ids) {
455 set_uint32(dest, htonl(src->circ_id));
456 dest += 4;
457 } else {
458 /* Clear the last two bytes of dest, in case we can accidentally
459 * send them to the network somehow. */
460 memset(dest+CELL_MAX_NETWORK_SIZE-2, 0, 2);
461 set_uint16(dest, htons(src->circ_id));
462 dest += 2;
463 }
464 set_uint8(dest, src->command);
465 memcpy(dest+1, src->payload, CELL_PAYLOAD_SIZE);
466}
467
468/** Unpack the network-order buffer <b>src</b> into a host-order
469 * cell_t structure <b>dest</b>.
470 */
471static void
472cell_unpack(cell_t *dest, const char *src, int wide_circ_ids)
473{
474 if (wide_circ_ids) {
475 dest->circ_id = ntohl(get_uint32(src));
476 src += 4;
477 } else {
478 dest->circ_id = ntohs(get_uint16(src));
479 src += 2;
480 }
481 dest->command = get_uint8(src);
482 memcpy(dest->payload, src+1, CELL_PAYLOAD_SIZE);
483}
484
485/** Write the header of <b>cell</b> into the first VAR_CELL_MAX_HEADER_SIZE
486 * bytes of <b>hdr_out</b>. Returns number of bytes used. */
487int
488var_cell_pack_header(const var_cell_t *cell, char *hdr_out, int wide_circ_ids)
489{
490 int r;
491 if (wide_circ_ids) {
492 set_uint32(hdr_out, htonl(cell->circ_id));
493 hdr_out += 4;
495 } else {
496 set_uint16(hdr_out, htons(cell->circ_id));
497 hdr_out += 2;
499 }
500 set_uint8(hdr_out, cell->command);
501 set_uint16(hdr_out+1, htons(cell->payload_len));
502 return r;
503}
504
505/** Allocate and return a new var_cell_t with <b>payload_len</b> bytes of
506 * payload space. */
508var_cell_new(uint16_t payload_len)
509{
510 size_t size = offsetof(var_cell_t, payload) + payload_len;
511 var_cell_t *cell = tor_malloc_zero(size);
512 cell->payload_len = payload_len;
513 cell->command = 0;
514 cell->circ_id = 0;
515 return cell;
516}
517
518/**
519 * Copy a var_cell_t
520 */
523{
524 var_cell_t *copy = NULL;
525 size_t size = 0;
526
527 if (src != NULL) {
528 size = offsetof(var_cell_t, payload) + src->payload_len;
529 copy = tor_malloc_zero(size);
530 copy->payload_len = src->payload_len;
531 copy->command = src->command;
532 copy->circ_id = src->circ_id;
533 memcpy(copy->payload, src->payload, copy->payload_len);
534 }
535
536 return copy;
537}
538
539/** Release all space held by <b>cell</b>. */
540void
542{
543 tor_free(cell);
544}
545
546/** We've received an EOF from <b>conn</b>. Mark it for close and return. */
547int
549{
550 tor_assert(conn);
551
552 log_info(LD_OR,"OR connection reached EOF. Closing.");
553 /* EOF is treated as a channel error, with queued output still flushed.
554 * Error-close attributes guard failure only during eligible establishment;
555 * an established or previously cancelled connection cannot blame its
556 * guard. */
558
559 return 0;
560}
561
562/** Handle any new bytes that have come in on connection <b>conn</b>.
563 * If conn is in 'open' state, hand it to
564 * connection_or_process_cells_from_inbuf()
565 * (else do nothing).
566 */
567int
569{
570 int ret = 0;
571 tor_assert(conn);
572
573 switch (conn->base_.state) {
576
577 /* start TLS after handshake completion, or deal with error */
578 if (ret == 1) {
579 tor_assert(TO_CONN(conn)->proxy_state == PROXY_CONNECTED);
580 if (buf_datalen(conn->base_.inbuf) != 0) {
581 log_fn(LOG_PROTOCOL_WARN, LD_NET, "Found leftover (%d bytes) "
582 "when transitioning from PROXY_HANDSHAKING state on %s: "
583 "closing.",
584 (int)buf_datalen(conn->base_.inbuf),
587 return -1;
588 }
589 if (connection_tls_start_handshake(conn, 0) < 0)
590 ret = -1;
591 /* Touch the channel's active timestamp if there is one */
592 if (conn->chan)
593 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
594 }
595 if (ret < 0) {
597 }
598
599 return ret;
604 default:
605 break; /* don't do anything */
606 }
607
608 /* This check makes sure that we don't have any data on the inbuf if we're
609 * doing our TLS handshake: if we did, they were probably put there by a
610 * SOCKS proxy trying to trick us into accepting unauthenticated data.
611 */
612 if (buf_datalen(conn->base_.inbuf) != 0) {
613 log_fn(LOG_PROTOCOL_WARN, LD_NET, "Accumulated data (%d bytes) "
614 "on non-open %s; closing.",
615 (int)buf_datalen(conn->base_.inbuf),
618 ret = -1;
619 }
620
621 return ret;
622}
623
624/** Called whenever we have flushed some data on an or_conn: add more data
625 * from active circuits. */
626int
628{
629 size_t datalen;
630
631 /* Update the channel's active timestamp if there is one */
632 if (conn->chan)
633 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
634
635 /* If we're under the low water mark, add cells until we're just over the
636 * high water mark. */
637 datalen = connection_get_outbuf_len(TO_CONN(conn));
638 if (datalen < or_conn_lowwatermark()) {
639 /* Let the scheduler know */
640 scheduler_channel_wants_writes(TLS_CHAN_TO_BASE(conn->chan));
641 }
642
643 return 0;
644}
645
646/** This is for channeltls.c to ask how many cells we could accept if
647 * they were available. */
648ssize_t
650{
651 size_t datalen, cell_network_size;
652 ssize_t n = 0;
653
654 tor_assert(conn);
655
656 /*
657 * If we're under the high water mark, we're potentially
658 * writeable; note this is different from the calculation above
659 * used to trigger when to start writing after we've stopped.
660 */
661 datalen = connection_get_outbuf_len(TO_CONN(conn));
662 if (datalen < or_conn_highwatermark()) {
663 cell_network_size = get_cell_network_size(conn->wide_circ_ids);
664 n = CEIL_DIV(or_conn_highwatermark() - datalen, cell_network_size);
665 }
666
667 return n;
668}
669
670/** Connection <b>conn</b> has finished writing and has no bytes left on
671 * its outbuf.
672 *
673 * Otherwise it's in state "open": stop writing and return.
674 *
675 * If <b>conn</b> is broken, mark it for close and return -1, else
676 * return 0.
677 */
678int
680{
681 tor_assert(conn);
683
684 switch (conn->base_.state) {
686 /* PROXY_HAPROXY gets connected by receiving an ack. */
687 if (conn->proxy_type == PROXY_HAPROXY) {
688 tor_assert(TO_CONN(conn)->proxy_state == PROXY_HAPROXY_WAIT_FOR_FLUSH);
689 IF_BUG_ONCE(buf_datalen(TO_CONN(conn)->inbuf) != 0) {
690 /* This should be impossible; we're not even reading. */
692 return -1;
693 }
694 TO_CONN(conn)->proxy_state = PROXY_CONNECTED;
695
696 if (connection_tls_start_handshake(conn, 0) < 0) {
697 /* TLS handshaking error of some kind. */
699 return -1;
700 }
701 break;
702 }
703 break;
706 break;
707 default:
708 log_err(LD_BUG,"Called in unexpected state %d.", conn->base_.state);
710 return -1;
711 }
712
713 /* Update the channel's active timestamp if there is one */
714 if (conn->chan)
715 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
716
717 return 0;
718}
719
720/** Connected handler for OR connections: begin the TLS handshake.
721 */
722int
724{
725 const int proxy_type = or_conn->proxy_type;
726 connection_t *conn;
727
728 tor_assert(or_conn);
729 conn = TO_CONN(or_conn);
731
732 log_debug(LD_HANDSHAKE,"connect finished for %s",
733 connection_describe(conn));
734
735 if (proxy_type != PROXY_NONE) {
736 /* start proxy handshake */
737 if (connection_proxy_connect(conn, proxy_type) < 0) {
739 return -1;
740 }
741
744
745 return 0;
746 }
747
748 if (connection_tls_start_handshake(or_conn, 0) < 0) {
749 /* TLS handshaking error of some kind. */
751 return -1;
752 }
753 return 0;
754}
755
756/** Called when we're about to finally unlink and free an OR connection:
757 * perform necessary accounting and cleanup */
758void
760{
761 connection_t *conn = TO_CONN(or_conn);
762
763 /* Tell the controlling channel we're closed */
764 if (or_conn->chan) {
765 channel_closed(TLS_CHAN_TO_BASE(or_conn->chan));
766 /*
767 * NULL this out because the channel might hang around a little
768 * longer before channel_run_cleanup() gets it.
769 */
770 or_conn->chan->conn = NULL;
771 or_conn->chan = NULL;
772 }
773
774 /* Remember why we're closing this connection. */
775 if (conn->state != OR_CONN_STATE_OPEN) {
776 /* now mark things down as needed */
778 const or_options_t *options = get_options();
781 int reason = tls_error_to_orconn_end_reason(or_conn->tls_error);
782 connection_or_event_status(or_conn, OR_CONN_EVENT_FAILED,
783 reason);
784 if (!authdir_mode_tests_reachability(options)) {
785 const char *warning = NULL;
786 if (reason == END_OR_CONN_REASON_TLS_ERROR && or_conn->tls) {
787 warning = tor_tls_get_last_error_msg(or_conn->tls);
788 }
789 if (warning == NULL) {
790 warning = orconn_end_reason_to_control_string(reason);
791 }
792 control_event_bootstrap_prob_or(warning, reason, or_conn);
793 }
794 }
795 }
796 } else if (conn->hold_open_until_flushed) {
797 /* We only set hold_open_until_flushed when we're intentionally
798 * closing a connection. */
799 connection_or_event_status(or_conn, OR_CONN_EVENT_CLOSED,
801 } else if (!tor_digest_is_zero(or_conn->identity_digest)) {
802 connection_or_event_status(or_conn, OR_CONN_EVENT_CLOSED,
804 } else {
805 /* Normal close, we notify of a done connection. */
806 connection_or_event_status(or_conn, OR_CONN_EVENT_CLOSED,
807 END_OR_CONN_REASON_DONE);
808 }
809}
810
811/** Return 1 if identity digest <b>id_digest</b> is known to be a
812 * currently or recently running relay. Otherwise return 0. */
813int
815{
817 return 1; /* It's in the consensus: "yes" */
818 if (router_get_by_id_digest(id_digest))
819 return 1; /* Not in the consensus, but we have a descriptor for
820 * it. Probably it was in a recent consensus. "Yes". */
821 return 0;
822}
823
824/** Set the per-conn read and write limits for <b>conn</b>. If it's a known
825 * relay, we will rely on the global read and write buckets, so give it
826 * per-conn limits that are big enough they'll never matter. But if it's
827 * not a known relay, first check if we set PerConnBwRate/Burst, then
828 * check if the consensus sets them, else default to 'big enough'.
829 *
830 * If <b>reset</b> is true, set the bucket to be full. Otherwise, just
831 * clip the bucket if it happens to be <em>too</em> full.
832 */
833static void
835 const or_options_t *options)
836{
837 int rate, burst; /* per-connection rate limiting params */
839 /* It's in the consensus, or we have a descriptor for it meaning it
840 * was probably in a recent consensus. It's a recognized relay:
841 * give it full bandwidth. */
842 rate = (int)options->BandwidthRate;
843 burst = (int)options->BandwidthBurst;
844 } else {
845 /* Not a recognized relay. Squeeze it down based on the suggested
846 * bandwidth parameters in the consensus, but allow local config
847 * options to override. */
848 rate = options->PerConnBWRate ? (int)options->PerConnBWRate :
849 networkstatus_get_param(NULL, "perconnbwrate",
850 (int)options->BandwidthRate, 1, INT32_MAX);
851 burst = options->PerConnBWBurst ? (int)options->PerConnBWBurst :
852 networkstatus_get_param(NULL, "perconnbwburst",
853 (int)options->BandwidthBurst, 1, INT32_MAX);
854 }
855
856 token_bucket_rw_adjust(&conn->bucket, rate, burst);
857 if (reset) {
859 }
860}
861
862/** Either our set of relays or our per-conn rate limits have changed.
863 * Go through all the OR connections and update their token buckets to make
864 * sure they don't exceed their maximum values. */
865void
867 const or_options_t *options)
868{
869 SMARTLIST_FOREACH(conns, connection_t *, conn,
870 {
871 if (connection_speaks_cells(conn))
873 });
874}
875
876/* Mark <b>or_conn</b> as canonical if <b>is_canonical</b> is set, and
877 * non-canonical otherwise. Adjust idle_timeout accordingly.
878 */
879void
880connection_or_set_canonical(or_connection_t *or_conn,
881 int is_canonical)
882{
883 if (bool_eq(is_canonical, or_conn->is_canonical) &&
884 or_conn->idle_timeout != 0) {
885 /* Don't recalculate an existing idle_timeout unless the canonical
886 * status changed. */
887 return;
888 }
889
890 or_conn->is_canonical = !! is_canonical; /* force to a 1-bit boolean */
892 TLS_CHAN_TO_BASE(or_conn->chan), is_canonical);
893
894 log_info(LD_CIRC,
895 "Channel %"PRIu64 " chose an idle timeout of %d.",
896 or_conn->chan ?
897 (TLS_CHAN_TO_BASE(or_conn->chan)->global_identifier):0,
898 or_conn->idle_timeout);
899}
900
901/** If we don't necessarily know the router we're connecting to, but we
902 * have an addr/port/id_digest, then fill in as much as we can. Start
903 * by checking to see if this describes a router we know.
904 * <b>started_here</b> is 1 if we are the initiator of <b>conn</b> and
905 * 0 if it's an incoming connection. */
906void
908 const tor_addr_t *addr, uint16_t port,
909 const char *id_digest,
910 const ed25519_public_key_t *ed_id,
911 int started_here)
912{
913 log_debug(LD_HANDSHAKE, "init conn from address %s: %s, %s (%d)",
914 fmt_addr(addr),
915 hex_str((const char*)id_digest, DIGEST_LEN),
916 ed25519_fmt(ed_id),
917 started_here);
918
919 connection_or_set_identity_digest(conn, id_digest, ed_id);
921
922 conn->base_.port = port;
923 tor_addr_copy(&conn->base_.addr, addr);
924 if (! conn->base_.address) {
925 conn->base_.address = tor_strdup(fmt_addr(addr));
926 }
927
928 connection_or_check_canonicity(conn, started_here);
929}
930
931/** Check whether the identity of <b>conn</b> matches a known node. If it
932 * does, check whether the address of conn matches the expected address, and
933 * update the connection's is_canonical flag, nickname, and address fields as
934 * appropriate. */
935static void
937{
938 (void) started_here;
939
940 const char *id_digest = conn->identity_digest;
941 const ed25519_public_key_t *ed_id = NULL;
942 if (conn->chan)
943 ed_id = & TLS_CHAN_TO_BASE(conn->chan)->ed25519_identity;
944
945 const node_t *r = node_get_by_id(id_digest);
946 if (r &&
948 ! node_ed25519_id_matches(r, ed_id)) {
949 /* If this node is capable of proving an ed25519 ID,
950 * we can't call this a canonical connection unless both IDs match. */
951 r = NULL;
952 }
953
954 if (r) {
955 tor_addr_port_t node_ipv4_ap;
956 tor_addr_port_t node_ipv6_ap;
957 node_get_prim_orport(r, &node_ipv4_ap);
958 node_get_pref_ipv6_orport(r, &node_ipv6_ap);
959 if (tor_addr_eq(&conn->base_.addr, &node_ipv4_ap.addr) ||
960 tor_addr_eq(&conn->base_.addr, &node_ipv6_ap.addr)) {
961 connection_or_set_canonical(conn, 1);
962 }
963 /* Choose the correct canonical address and port. */
964 tor_addr_port_t *node_ap;
965 if (tor_addr_family(&conn->base_.addr) == AF_INET) {
966 node_ap = &node_ipv4_ap;
967 } else {
968 node_ap = &node_ipv6_ap;
969 }
970 /* Remember the canonical addr/port so our log messages will make
971 sense. */
972 tor_addr_port_copy(&conn->canonical_orport, node_ap);
973 tor_free(conn->nickname);
974 conn->nickname = tor_strdup(node_get_nickname(r));
975 } else {
976 tor_free(conn->nickname);
977 conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
978 conn->nickname[0] = '$';
981 }
982
983 /*
984 * We have to tell channeltls.c to update the channel marks (local, in
985 * particular), since we may have changed the address.
986 */
987
988 if (conn->chan) {
990 }
991}
992
993/** These just pass all the is_bad_for_new_circs manipulation on to
994 * channel_t */
995
996static unsigned int
998{
999 tor_assert(or_conn);
1000
1001 if (or_conn->chan)
1002 return channel_is_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan));
1003 else return 0;
1004}
1005
1006static void
1007connection_or_mark_bad_for_new_circs(or_connection_t *or_conn)
1008{
1009 tor_assert(or_conn);
1010
1011 if (or_conn->chan)
1012 channel_mark_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan));
1013}
1014
1015/** How old do we let a connection to an OR get before deciding it's
1016 * too old for new circuits? */
1017#define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)
1018
1019/** Expire an or_connection if it is too old. Helper for
1020 * connection_or_group_set_badness_ and fast path for
1021 * channel_rsa_id_group_set_badness.
1022 *
1023 * Returns 1 if the connection was already expired, else 0.
1024 */
1025int
1027 or_connection_t *or_conn,
1028 int force)
1029{
1030 /* XXXX this function should also be about channels? */
1031 if (or_conn->base_.marked_for_close ||
1033 return 1;
1034
1035 if (force ||
1037 < now) {
1038 log_info(LD_OR,
1039 "Marking %s as too old for new circuits "
1040 "(fd "TOR_SOCKET_T_FORMAT", %d secs old).",
1041 connection_describe(TO_CONN(or_conn)),
1042 or_conn->base_.s,
1043 (int)(now - or_conn->base_.timestamp_created));
1044 connection_or_mark_bad_for_new_circs(or_conn);
1045 }
1046
1047 return 0;
1048}
1049
1050/** Given a list of all the or_connections with a given
1051 * identity, set elements of that list as is_bad_for_new_circs as
1052 * appropriate. Helper for connection_or_set_bad_connections().
1053 *
1054 * Specifically, we set the is_bad_for_new_circs flag on:
1055 * - all connections if <b>force</b> is true.
1056 * - all connections that are too old.
1057 * - all open non-canonical connections for which a canonical connection
1058 * exists to the same router.
1059 * - all open canonical connections for which a 'better' canonical
1060 * connection exists to the same router.
1061 * - all open non-canonical connections for which a 'better' non-canonical
1062 * connection exists to the same router at the same address.
1063 *
1064 * See channel_is_better() in channel.c for our idea of what makes one OR
1065 * connection better than another.
1066 */
1067void
1069{
1070 /* XXXX this function should be entirely about channels, not OR
1071 * XXXX connections. */
1072
1073 or_connection_t *best = NULL;
1074 int n_canonical = 0;
1075 time_t now = time(NULL);
1076
1077 /* Pass 1: expire everything that's old, and see what the status of
1078 * everything else is. */
1079 SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
1080 if (connection_or_single_set_badness_(now, or_conn, force))
1081 continue;
1082
1083 if (or_conn->is_canonical) {
1084 ++n_canonical;
1085 }
1086 } SMARTLIST_FOREACH_END(or_conn);
1087
1088 /* Pass 2: We know how about how good the best connection is.
1089 * expire everything that's worse, and find the very best if we can. */
1090 SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
1091 if (or_conn->base_.marked_for_close ||
1093 continue; /* This one doesn't need to be marked bad. */
1094 if (or_conn->base_.state != OR_CONN_STATE_OPEN)
1095 continue; /* Don't mark anything bad until we have seen what happens
1096 * when the connection finishes. */
1097 if (n_canonical && !or_conn->is_canonical) {
1098 /* We have at least one open canonical connection to this router,
1099 * and this one is open but not canonical. Mark it bad. */
1100 log_info(LD_OR,
1101 "Marking %s unsuitable for new circuits: "
1102 "(fd "TOR_SOCKET_T_FORMAT", %d secs old). It is not "
1103 "canonical, and we have another connection to that OR that is.",
1104 connection_describe(TO_CONN(or_conn)),
1105 or_conn->base_.s,
1106 (int)(now - or_conn->base_.timestamp_created));
1107 connection_or_mark_bad_for_new_circs(or_conn);
1108 continue;
1109 }
1110
1111 if (!best ||
1112 channel_is_better(TLS_CHAN_TO_BASE(or_conn->chan),
1113 TLS_CHAN_TO_BASE(best->chan))) {
1114 best = or_conn;
1115 }
1116 } SMARTLIST_FOREACH_END(or_conn);
1117
1118 if (!best)
1119 return;
1120
1121 /* Pass 3: One connection to OR is best. If it's canonical, mark as bad
1122 * every other open connection. If it's non-canonical, mark as bad
1123 * every other open connection to the same address.
1124 *
1125 * XXXX This isn't optimal; if we have connections to an OR at multiple
1126 * addresses, we'd like to pick the best _for each address_, and mark as
1127 * bad every open connection that isn't best for its address. But this
1128 * can only occur in cases where the other OR is old (so we have no
1129 * canonical connection to it), or where all the connections to the OR are
1130 * at noncanonical addresses and we have no good direct connection (which
1131 * means we aren't at risk of attaching circuits to it anyway). As
1132 * 0.1.2.x dies out, the first case will go away, and the second one is
1133 * "mostly harmless", so a fix can wait until somebody is bored.
1134 */
1135 SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
1136 if (or_conn->base_.marked_for_close ||
1138 or_conn->base_.state != OR_CONN_STATE_OPEN)
1139 continue;
1140 if (or_conn != best &&
1141 channel_is_better(TLS_CHAN_TO_BASE(best->chan),
1142 TLS_CHAN_TO_BASE(or_conn->chan))) {
1143 /* This isn't the best conn, _and_ the best conn is better than it */
1144 if (best->is_canonical) {
1145 log_info(LD_OR,
1146 "Marking %s as unsuitable for new circuits: "
1147 "(fd "TOR_SOCKET_T_FORMAT", %d secs old). "
1148 "We have a better canonical one "
1149 "(fd "TOR_SOCKET_T_FORMAT"; %d secs old).",
1150 connection_describe(TO_CONN(or_conn)),
1151 or_conn->base_.s,
1152 (int)(now - or_conn->base_.timestamp_created),
1153 best->base_.s, (int)(now - best->base_.timestamp_created));
1154 connection_or_mark_bad_for_new_circs(or_conn);
1155 } else if (tor_addr_eq(&TO_CONN(or_conn)->addr,
1156 &TO_CONN(best)->addr)) {
1157 log_info(LD_OR,
1158 "Marking %s unsuitable for new circuits: "
1159 "(fd "TOR_SOCKET_T_FORMAT", %d secs old). We have a better "
1160 "one with the "
1161 "same address (fd "TOR_SOCKET_T_FORMAT"; %d secs old).",
1162 connection_describe(TO_CONN(or_conn)),
1163 or_conn->base_.s,
1164 (int)(now - or_conn->base_.timestamp_created),
1165 best->base_.s, (int)(now - best->base_.timestamp_created));
1166 connection_or_mark_bad_for_new_circs(or_conn);
1167 }
1168 }
1169 } SMARTLIST_FOREACH_END(or_conn);
1170}
1171
1172/* Lifetime of a connection failure. After that, we'll retry. This is in
1173 * seconds. */
1174#define OR_CONNECT_FAILURE_LIFETIME 60
1175/* The interval to use with when to clean up the failure cache. */
1176#define OR_CONNECT_FAILURE_CLEANUP_INTERVAL 60
1177
1178/* When is the next time we have to cleanup the failure map. We keep this
1179 * because we clean it opportunistically. */
1180static time_t or_connect_failure_map_next_cleanup_ts = 0;
1181
1182/* OR connection failure entry data structure. It is kept in the connection
1183 * failure map defined below and indexed by OR identity digest, address and
1184 * port.
1185 *
1186 * We need to identify a connection failure with these three values because we
1187 * want to avoid to wrongfully block a relay if someone is trying to
1188 * extend to a known identity digest but with the wrong IP/port. For instance,
1189 * it can happen if a relay changed its port but the client still has an old
1190 * descriptor with the old port. We want to stop connecting to that
1191 * IP/port/identity all together, not only the relay identity. */
1193 HT_ENTRY(or_connect_failure_entry_t) node;
1194 /* Identity digest of the connection where it is connecting to. */
1195 uint8_t identity_digest[DIGEST_LEN];
1196 /* This is the connection address from the base connection_t. After the
1197 * connection is checked for canonicity, the base address should represent
1198 * what we know instead of where we are connecting to. This is what we need
1199 * so we can correlate known relays within the consensus. */
1200 tor_addr_t addr;
1201 uint16_t port;
1202 /* Last time we were unable to connect. */
1203 time_t last_failed_connect_ts;
1205
1206/* Map where we keep connection failure entries. They are indexed by addr,
1207 * port and identity digest. */
1208static HT_HEAD(or_connect_failure_ht, or_connect_failure_entry_t)
1209 or_connect_failures_map = HT_INITIALIZER();
1210
1211/* Helper: Hashtable equal function. Return 1 if equal else 0. */
1212static int
1213or_connect_failure_ht_eq(const or_connect_failure_entry_t *a,
1215{
1216 return fast_memeq(a->identity_digest, b->identity_digest, DIGEST_LEN) &&
1217 tor_addr_eq(&a->addr, &b->addr) &&
1218 a->port == b->port;
1219}
1220
1221/* Helper: Return the hash for the hashtable of the given entry. For this
1222 * table, it is a combination of address, port and identity digest. */
1223static unsigned int
1224or_connect_failure_ht_hash(const or_connect_failure_entry_t *entry)
1225{
1226 size_t offset = 0, addr_size;
1227 const void *addr_ptr;
1228 /* Largest size is IPv6 and IPv4 is smaller so it is fine. */
1229 uint8_t data[16 + sizeof(uint16_t) + DIGEST_LEN];
1230
1231 /* Get the right address bytes depending on the family. */
1232 switch (tor_addr_family(&entry->addr)) {
1233 case AF_INET:
1234 addr_size = 4;
1235 addr_ptr = &entry->addr.addr.in_addr.s_addr;
1236 break;
1237 case AF_INET6:
1238 addr_size = 16;
1239 addr_ptr = &entry->addr.addr.in6_addr.s6_addr;
1240 break;
1241 default:
1243 return 0;
1244 }
1245
1246 memcpy(data, addr_ptr, addr_size);
1247 offset += addr_size;
1248 memcpy(data + offset, entry->identity_digest, DIGEST_LEN);
1249 offset += DIGEST_LEN;
1250 set_uint16(data + offset, entry->port);
1251 offset += sizeof(uint16_t);
1252
1253 return (unsigned int) siphash24g(data, offset);
1254}
1255
1256HT_PROTOTYPE(or_connect_failure_ht, or_connect_failure_entry_t, node,
1257 or_connect_failure_ht_hash, or_connect_failure_ht_eq);
1258
1259HT_GENERATE2(or_connect_failure_ht, or_connect_failure_entry_t, node,
1260 or_connect_failure_ht_hash, or_connect_failure_ht_eq,
1262
1263/* Initialize a given connect failure entry with the given identity_digest,
1264 * addr and port. All field are optional except ocf. */
1265static void
1266or_connect_failure_init(const char *identity_digest, const tor_addr_t *addr,
1267 uint16_t port, or_connect_failure_entry_t *ocf)
1268{
1269 tor_assert(ocf);
1270 if (identity_digest) {
1271 memcpy(ocf->identity_digest, identity_digest,
1272 sizeof(ocf->identity_digest));
1273 }
1274 if (addr) {
1275 tor_addr_copy(&ocf->addr, addr);
1276 }
1277 ocf->port = port;
1278}
1279
1280/* Return a newly allocated connection failure entry. It is initialized with
1281 * the given or_conn data. This can't fail. */
1283or_connect_failure_new(const or_connection_t *or_conn)
1284{
1285 or_connect_failure_entry_t *ocf = tor_malloc_zero(sizeof(*ocf));
1286 or_connect_failure_init(or_conn->identity_digest, &TO_CONN(or_conn)->addr,
1287 TO_CONN(or_conn)->port, ocf);
1288 return ocf;
1289}
1290
1291/* Return a connection failure entry matching the given or_conn. NULL is
1292 * returned if not found. */
1294or_connect_failure_find(const or_connection_t *or_conn)
1295{
1297 tor_assert(or_conn);
1298 or_connect_failure_init(or_conn->identity_digest, &TO_CONN(or_conn)->addr,
1299 TO_CONN(or_conn)->port, &lookup);
1300 return HT_FIND(or_connect_failure_ht, &or_connect_failures_map, &lookup);
1301}
1302
1303/* Note down in the connection failure cache that a failure occurred on the
1304 * given or_conn. */
1305STATIC void
1306note_or_connect_failed(const or_connection_t *or_conn)
1307{
1308 or_connect_failure_entry_t *ocf = NULL;
1309
1310 tor_assert(or_conn);
1311
1313 /* Don't cache connection failures for connections we initiated ourself.
1314 * If these direct connections fail, we're supposed to recognize that
1315 * the destination is down and stop trying. See ticket 40499. */
1316 return;
1317 }
1318
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);
1323 }
1324 ocf->last_failed_connect_ts = approx_time();
1325}
1326
1327/* Cleanup the connection failure cache and remove all entries below the
1328 * given cutoff. */
1329static void
1330or_connect_failure_map_cleanup(time_t cutoff)
1331{
1332 or_connect_failure_entry_t **ptr, **next, *entry;
1333
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);
1342 }
1343 }
1344}
1345
1346/* Return true iff the given OR connection can connect to its destination that
1347 * is the triplet identity_digest, address and port.
1348 *
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. */
1351STATIC int
1352should_connect_to_relay(const or_connection_t *or_conn)
1353{
1354 time_t now, cutoff;
1355 time_t connect_failed_since_ts = 0;
1357
1358 tor_assert(or_conn);
1359
1360 now = approx_time();
1361 cutoff = now - OR_CONNECT_FAILURE_LIFETIME;
1362
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;
1369 }
1370
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;
1376 }
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;
1381 }
1382
1383 /* Ok we can connect! */
1384 return 1;
1385 no_connect:
1386 return 0;
1387}
1388
1389/** Finalizes an opening attempt at an OR error boundary, EOF, timeout, or
1390 * immediate connect failure. Normal closure and explicit exceptions consume
1391 * permission without blame; successful opening does so before callbacks. */
1392void
1394{
1395 if (!conn->chan)
1396 return;
1397 channel_t *chan = TLS_CHAN_TO_BASE(conn->chan);
1398 if (!conn->is_outgoing || conn->base_.marked_for_close ||
1399 conn->base_.state == OR_CONN_STATE_OPEN) {
1400 /* Incoming, closed, or established connections cannot fail this attempt.
1401 * Clearing the association prevents later notifications from using it. */
1403 return;
1404 }
1405 switch (conn->base_.state) {
1412 break;
1413 default:
1414 /* No establishment is in progress in this state. Clearing stale blame
1415 * permission prevents its use after a later state transition. */
1417 break;
1418 }
1419}
1420
1421/** <b>conn</b> is in the 'connecting' state, and it failed to complete
1422 * a TCP connection. Send notifications appropriately.
1423 *
1424 * <b>reason</b> specifies the or_conn_end_reason for the failure;
1425 * <b>msg</b> specifies the strerror-style error message.
1426 */
1427void
1429 int reason, const char *msg)
1430{
1431 connection_or_event_status(conn, OR_CONN_EVENT_FAILED, reason);
1432 if (!authdir_mode_tests_reachability(get_options()))
1433 control_event_bootstrap_prob_or(msg, reason, conn);
1434 note_or_connect_failed(conn);
1435}
1436
1437/** <b>conn</b> got an error in connection_handle_read_impl() or
1438 * connection_handle_write_impl() and is going to die soon.
1439 *
1440 * <b>reason</b> specifies the or_conn_end_reason for the failure;
1441 * <b>msg</b> specifies the strerror-style error message.
1442 */
1443void
1445 int reason, const char *msg)
1446{
1447 channel_t *chan;
1448
1449 tor_assert(conn);
1451
1452 /* If we're connecting, call connect_failed() too */
1453 if (TO_CONN(conn)->state == OR_CONN_STATE_CONNECTING)
1454 connection_or_connect_failed(conn, reason, msg);
1455
1456 /* Tell the controlling channel if we have one */
1457 if (conn->chan) {
1458 chan = TLS_CHAN_TO_BASE(conn->chan);
1459 /* Don't transition if we're already in closing, closed or error */
1460 if (!CHANNEL_CONDEMNED(chan)) {
1462 }
1463 }
1464
1465 /* No need to mark for error because connection.c is about to do that */
1466}
1467
1468/** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
1469 * handshake with an OR with identity digest <b>id_digest</b>. Optionally,
1470 * pass in a pointer to a channel using this connection.
1471 *
1472 * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
1473 * return that connection. If the connect() is in progress, set the
1474 * new conn's state to 'connecting' and return it. If connect() succeeds,
1475 * call connection_tls_start_handshake() on it.
1476 *
1477 * This function is called from router_retry_connections(), for
1478 * ORs connecting to ORs, and circuit_establish_circuit(), for
1479 * OPs connecting to ORs.
1480 *
1481 * Return the launched conn, or NULL if it failed.
1482 */
1484connection_or_connect, (const tor_addr_t *_addr, uint16_t port,
1485 const char *id_digest,
1486 const ed25519_public_key_t *ed_id,
1487 channel_tls_t *chan, bool for_origin_circ))
1488{
1489 or_connection_t *conn;
1490 const or_options_t *options = get_options();
1491 int socket_error = 0;
1492 tor_addr_t addr;
1493
1494 int r;
1495 tor_addr_t proxy_addr;
1496 uint16_t proxy_port;
1497 int proxy_type, is_pt = 0;
1498
1499 tor_assert(_addr);
1500 tor_assert(id_digest);
1501 tor_addr_copy(&addr, _addr);
1502
1503 if (server_mode(options) && router_digest_is_me(id_digest)) {
1504 log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
1505 return NULL;
1506 }
1507 if (server_mode(options) && router_ed25519_id_is_me(ed_id)) {
1508 log_info(LD_PROTOCOL,"Client asked me to connect to myself by Ed25519 "
1509 "identity. Refusing.");
1510 return NULL;
1511 }
1512
1514 /* Origin provenance is set before socket work so synchronous failures use
1515 * the same bootstrap reporting and cache policy as asynchronous failures.
1516 * This is independent of guard selection; fallbacks are origin launches too.
1517 * should_connect_to_relay() still honors existing cached failures. */
1518 conn->potentially_used_for_bootstrapping = for_origin_circ;
1519
1520 /*
1521 * Set up conn so it's got all the data we need to remember for channels
1522 *
1523 * This stuff needs to happen before connection_or_init_conn_from_address()
1524 * so connection_or_set_identity_digest() and such know where to look to
1525 * keep the channel up to date.
1526 */
1527 conn->chan = chan;
1528 chan->conn = conn;
1529 connection_or_init_conn_from_address(conn, &addr, port, id_digest, ed_id, 1);
1530
1531 /* We have a proper OR connection setup, now check if we can connect to it
1532 * that is we haven't had a failure earlier. This is to avoid to try to
1533 * constantly connect to relays that we think are not reachable. */
1534 if (!should_connect_to_relay(conn)) {
1535 log_info(LD_GENERAL, "Can't connect to %s because we "
1536 "failed earlier. Refusing.",
1539 return NULL;
1540 }
1541
1542 conn->is_outgoing = 1;
1543
1544 /* If we are using a proxy server, find it and use it. */
1545 r = get_proxy_addrport(&proxy_addr, &proxy_port, &proxy_type, &is_pt,
1546 TO_CONN(conn));
1547 if (r == 0) {
1548 conn->proxy_type = proxy_type;
1549 if (proxy_type != PROXY_NONE) {
1550 tor_addr_copy(&addr, &proxy_addr);
1551 port = proxy_port;
1552 conn->base_.proxy_state = PROXY_INFANT;
1553 conn->is_pt = is_pt;
1554 }
1556 connection_or_event_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
1557 } else {
1558 /* Missing proxy/PT configuration prevented any socket connection attempt.
1559 * This discards guard attribution permission before state/status
1560 * callbacks, so later error handling cannot blame the guard for this
1561 * setup error. */
1562 channel_note_establishment_cancelled(TLS_CHAN_TO_BASE(chan));
1563 /* This duplication of state change calls is necessary in case we
1564 * run into an error condition below */
1566 connection_or_event_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
1567
1568 /* get_proxy_addrport() might fail if we have a Bridge line that
1569 references a transport, but no ClientTransportPlugin lines
1570 defining its transport proxy. If this is the case, let's try to
1571 output a useful log message to the user. */
1572 const char *transport_name =
1574 TO_CONN(conn)->port);
1575
1576 if (transport_name) {
1577 log_warn(LD_GENERAL, "We were supposed to connect to bridge '%s' "
1578 "using pluggable transport '%s', but we can't find a pluggable "
1579 "transport proxy supporting '%s'. This can happen if you "
1580 "haven't provided a ClientTransportPlugin line, or if "
1581 "your pluggable transport proxy stopped running.",
1583 transport_name, transport_name);
1584
1586 "Can't connect to bridge",
1587 END_OR_CONN_REASON_PT_MISSING,
1588 conn);
1589
1590 } else {
1591 log_warn(LD_GENERAL, "Tried to connect to %s through a proxy, but "
1592 "the proxy address could not be found.",
1594 }
1595
1597 return NULL;
1598 }
1599
1600 switch (connection_connect(TO_CONN(conn), conn->base_.address,
1601 &addr, port, &socket_error)) {
1602 case -1:
1603 /* connection_connect() calls connection_connect_sockaddr(), which calls
1604 * connection_or_note_establishment_failure() on an immediate
1605 * tor_connect_socket() error other than EINPROGRESS. Any eligible
1606 * guard-blaming attribution has therefore already been reported.
1607 * Cancel any remaining guard-blaming attribution for local setup errors
1608 * before connection_or_connect_failed() and connection_free_() can
1609 * reenter error handling. Cancellation does not undo a reported guard
1610 * failure; connection failure notifications and failure-cache accounting
1611 * still follow in both cases. */
1612 channel_note_establishment_cancelled(TLS_CHAN_TO_BASE(chan));
1614 errno_to_orconn_end_reason(socket_error),
1615 tor_socket_strerror(socket_error));
1617 return NULL;
1618 case 0:
1620 /* writable indicates finish, readable indicates broken link,
1621 error indicates broken link on windows */
1622 return conn;
1623 /* case 1: fall through */
1624 }
1625
1626 if (connection_or_finished_connecting(conn) < 0) {
1627 /* already marked for close */
1628 return NULL;
1629 }
1630 return conn;
1631}
1632
1633/** Mark orconn for close and transition the associated channel, if any, to
1634 * the closing state.
1635 *
1636 * It's safe to call this and connection_or_close_for_error() any time, and
1637 * channel layer will treat it as a connection closing for reasons outside
1638 * its control, like the remote end closing it. It can also be a local
1639 * reason that's specific to connection_t/or_connection_t rather than
1640 * the channel mechanism, such as expiration of old connections in
1641 * run_connection_housekeeping(). If you want to close a channel_t
1642 * from somewhere that logically works in terms of generic channels
1643 * rather than connections, use channel_mark_for_close(); see also
1644 * the comment on that function in channel.c.
1645 */
1646void
1648{
1649 channel_t *chan = NULL;
1650
1651 tor_assert(orconn);
1652 /* Both connection_mark_for_close_internal() and
1653 * connection_mark_and_flush_internal() call
1654 * connection_mark_for_close_internal_(), which validates the connection,
1655 * then cancels guard-blaming attribution before close bookkeeping or
1656 * flushing. On a duplicate close, the first marking already cancelled that
1657 * attribution; the guard handle must never be reinstalled. */
1658 if (flush) connection_mark_and_flush_internal(TO_CONN(orconn));
1659 else connection_mark_for_close_internal(TO_CONN(orconn));
1660 if (orconn->chan) {
1661 chan = TLS_CHAN_TO_BASE(orconn->chan);
1662 /* Don't transition if we're already in closing, closed or error */
1663 if (!CHANNEL_CONDEMNED(chan)) {
1665 }
1666 }
1667}
1668
1669/** Mark orconn for close and transition the associated channel, if any, to
1670 * the error state. During selected outgoing establishment, any such error
1671 * counts, including local TLS setup, protocol, and internal-state failures.
1672 * OOS eviction and output-queue failure explicitly cancel permission at their
1673 * callers: those are Tor-directed disposal, potentially caused by other work.
1674 * These exceptions live at the disposal sites; this function does not
1675 * classify individual error causes. Normal close, prior cancellation, and
1676 * successful open never regain attribution permission.
1677 */
1678MOCK_IMPL(void,
1680{
1681 channel_t *chan = NULL;
1682
1683 tor_assert(orconn);
1684 assert_connection_ok(TO_CONN(orconn), 0);
1686 if (flush) connection_mark_and_flush_internal(TO_CONN(orconn));
1687 else connection_mark_for_close_internal(TO_CONN(orconn));
1688 if (orconn->chan) {
1689 chan = TLS_CHAN_TO_BASE(orconn->chan);
1690 /* Don't transition if we're already in closing, closed or error */
1691 if (!CHANNEL_CONDEMNED(chan)) {
1693 }
1694 }
1695}
1696
1697/** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
1698 * we initiated the connection, else it's 1.
1699 *
1700 * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
1701 * pass <b>conn</b> to connection_tls_continue_handshake().
1702 *
1703 * Return -1 if <b>conn</b> is broken, else return 0.
1704 */
1705MOCK_IMPL(int,
1707{
1708 channel_listener_t *chan_listener;
1709 channel_t *chan;
1710
1711 /* Incoming connections will need a new channel passed to the
1712 * channel_tls_listener */
1713 if (receiving) {
1714 /* It shouldn't already be set */
1715 tor_assert(!(conn->chan));
1716 chan_listener = channel_tls_get_listener();
1717 if (!chan_listener) {
1718 chan_listener = channel_tls_start_listener();
1719 command_setup_listener(chan_listener);
1720 }
1721 chan = channel_tls_handle_incoming(conn);
1722 channel_listener_queue_incoming(chan_listener, chan);
1723 }
1724
1726 tor_assert(!conn->tls);
1727 conn->tls = tor_tls_new(conn->base_.s, receiving);
1728 if (!conn->tls) {
1729 log_warn(LD_BUG,"tor_tls_new failed. Closing.");
1730 return -1;
1731 }
1734
1736 log_debug(LD_HANDSHAKE,"starting TLS handshake on fd "TOR_SOCKET_T_FORMAT,
1737 conn->base_.s);
1738
1740 return -1;
1741
1742 return 0;
1743}
1744
1745/** Move forward with the tls handshake. If it finishes, hand
1746 * <b>conn</b> to connection_tls_finish_handshake().
1747 *
1748 * Return -1 if <b>conn</b> is broken, else return 0.
1749 */
1750int
1752{
1753 int result;
1754 check_no_tls_errors();
1755
1757 // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
1758 result = tor_tls_handshake(conn->tls);
1759 // log_notice(LD_OR, "Result: %d", result);
1760
1761 switch (result) {
1763 conn->tls_error = result;
1764 log_info(LD_OR,"tls error [%s]. breaking connection.",
1765 tor_tls_err_to_string(result));
1766 return -1;
1767 case TOR_TLS_DONE:
1768 {
1769 if (!tor_tls_is_server(conn->tls)) {
1772 } else {
1773 /* v3+ handshake, but we are not a client. */
1774 log_debug(LD_OR, "Done with initial SSL handshake (server-side). "
1775 "Expecting VERSIONS cell");
1776 /* Note: We could instead just send a VERSIONS cell now,
1777 * since the V2 handshake is no longer a thing.
1778 * But that would require re-plumbing this state machine. */
1783 return 0;
1784 }
1785 }
1786 case TOR_TLS_WANTWRITE:
1788 log_debug(LD_OR,"wanted write");
1789 return 0;
1790 case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
1791 log_debug(LD_OR,"wanted read");
1792 return 0;
1793 case TOR_TLS_CLOSE:
1794 conn->tls_error = result;
1795 log_info(LD_OR,"tls closed. breaking connection.");
1796 return -1;
1797 }
1798 return 0;
1799}
1800
1801/** Return 1 if we initiated this connection, or 0 if it started
1802 * out as an incoming connection.
1803 */
1804int
1806{
1807 tor_assert(conn->base_.type == CONN_TYPE_OR ||
1808 conn->base_.type == CONN_TYPE_EXT_OR);
1809 if (!conn->tls)
1810 return 1; /* it's still in proxy states or something */
1811 if (conn->handshake_state)
1812 return conn->handshake_state->started_here;
1813 return !tor_tls_is_server(conn->tls);
1814}
1815
1816/** Called when we (as a connection initiator) have definitively,
1817 * authenticatedly, learned that ID of the Tor instance on the other
1818 * side of <b>conn</b> is <b>rsa_peer_id</b> and optionally <b>ed_peer_id</b>.
1819 * For v1 and v2 handshakes,
1820 * this is right after we get a certificate chain in a TLS handshake
1821 * or renegotiation. For v3+ handshakes, this is right after we get a
1822 * certificate chain in a CERTS cell.
1823 *
1824 * If we did not know the ID before, record the one we got.
1825 *
1826 * If we wanted an ID, but we didn't get the one we expected, log a message
1827 * and return -1.
1828 * On relays:
1829 * - log a protocol warning whenever the fingerprints don't match;
1830 * On clients:
1831 * - if a relay's fingerprint doesn't match, log a warning;
1832 * - if we don't have updated relay fingerprints from a recent consensus, and
1833 * a fallback directory mirror's hard-coded fingerprint has changed, log an
1834 * info explaining that we will try another fallback.
1835 *
1836 * If we're testing reachability, remember what we learned.
1837 *
1838 * Return 0 on success, -1 on failure.
1839 */
1840int
1842 const uint8_t *rsa_peer_id,
1843 const ed25519_public_key_t *ed_peer_id)
1844{
1845 const or_options_t *options = get_options();
1846 channel_tls_t *chan_tls = conn->chan;
1847 channel_t *chan = channel_tls_to_base(chan_tls);
1848 int changed_identity = 0;
1849 tor_assert(chan);
1850
1851 const int expected_rsa_key =
1853 const int expected_ed_key =
1855
1856 log_info(LD_HANDSHAKE, "learned peer id for %s at %p: %s, %s",
1858 conn,
1859 hex_str((const char*)rsa_peer_id, DIGEST_LEN),
1860 ed25519_fmt(ed_peer_id));
1861
1862 if (! expected_rsa_key && ! expected_ed_key) {
1863 log_info(LD_HANDSHAKE, "(we had no ID in mind when we made this "
1864 "connection.");
1866 (const char*)rsa_peer_id, ed_peer_id);
1867 tor_free(conn->nickname);
1868 conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
1869 conn->nickname[0] = '$';
1872 log_info(LD_HANDSHAKE, "Connected to router at %s without knowing "
1873 "its key. Hoping for the best.",
1875 /* if it's a bridge and we didn't know its identity fingerprint, now
1876 * we do -- remember it for future attempts. */
1877 learned_router_identity(&conn->base_.addr, conn->base_.port,
1878 (const char*)rsa_peer_id, ed_peer_id);
1879 changed_identity = 1;
1880 }
1881
1882 const int rsa_mismatch = expected_rsa_key &&
1883 tor_memneq(rsa_peer_id, conn->identity_digest, DIGEST_LEN);
1884 /* It only counts as an ed25519 mismatch if we wanted an ed25519 identity
1885 * and didn't get it. It's okay if we get one that we didn't ask for. */
1886 const int ed25519_mismatch =
1887 expected_ed_key &&
1888 (ed_peer_id == NULL ||
1889 ! ed25519_pubkey_eq(&chan->ed25519_identity, ed_peer_id));
1890
1891 if (rsa_mismatch || ed25519_mismatch) {
1892 /* I was aiming for a particular digest. I didn't get it! */
1893 char seen_rsa[HEX_DIGEST_LEN+1];
1894 char expected_rsa[HEX_DIGEST_LEN+1];
1895 char seen_ed[ED25519_BASE64_LEN+1];
1896 char expected_ed[ED25519_BASE64_LEN+1];
1897 base16_encode(seen_rsa, sizeof(seen_rsa),
1898 (const char*)rsa_peer_id, DIGEST_LEN);
1899 base16_encode(expected_rsa, sizeof(expected_rsa), conn->identity_digest,
1900 DIGEST_LEN);
1901 if (ed_peer_id) {
1902 ed25519_public_to_base64(seen_ed, ed_peer_id);
1903 } else {
1904 strlcpy(seen_ed, "no ed25519 key", sizeof(seen_ed));
1905 }
1907 ed25519_public_to_base64(expected_ed, &chan->ed25519_identity);
1908 } else {
1909 strlcpy(expected_ed, "no ed25519 key", sizeof(expected_ed));
1910 }
1911 const int using_hardcoded_fingerprints =
1914 const int is_fallback_fingerprint = router_digest_is_fallback_dir(
1915 conn->identity_digest);
1916 const int is_authority_fingerprint = router_digest_is_trusted_dir(
1917 conn->identity_digest);
1918 const int non_anonymous_mode =
1919 hs_service_non_anonymous_mode_enabled(options);
1920 int severity;
1921 const char *extra_log = "";
1922
1923 /* Relays and Single Onion Services make direct connections using
1924 * untrusted authentication keys. */
1925 if (server_mode(options) || non_anonymous_mode) {
1926 severity = LOG_PROTOCOL_WARN;
1927 } else {
1928 if (using_hardcoded_fingerprints) {
1929 /* We need to do the checks in this order, because the list of
1930 * fallbacks includes the list of authorities */
1931 if (is_authority_fingerprint) {
1932 severity = LOG_WARN;
1933 } else if (is_fallback_fingerprint) {
1934 /* we expect a small number of fallbacks to change from their
1935 * hard-coded fingerprints over the life of a release */
1936 severity = LOG_INFO;
1937 extra_log = " Tor will try a different fallback.";
1938 } else {
1939 /* it's a bridge, it's either a misconfiguration, or unexpected */
1940 severity = LOG_WARN;
1941 }
1942 } else {
1943 /* a relay has changed its fingerprint from the one in the consensus */
1944 severity = LOG_WARN;
1945 }
1946 }
1947
1948 log_fn(severity, LD_HANDSHAKE,
1949 "Tried connecting to router at %s, but RSA + ed25519 identity "
1950 "keys were not as expected: wanted %s + %s but got %s + %s.%s",
1952 expected_rsa, expected_ed, seen_rsa, seen_ed, extra_log);
1953
1954 connection_or_event_status(conn, OR_CONN_EVENT_FAILED,
1955 END_OR_CONN_REASON_OR_IDENTITY);
1956 if (!authdir_mode_tests_reachability(options))
1958 "Unexpected identity in router certificate",
1959 END_OR_CONN_REASON_OR_IDENTITY,
1960 conn);
1961 return -1;
1962 }
1963
1964 if (!expected_ed_key && ed_peer_id) {
1965 log_info(LD_HANDSHAKE, "(We had no Ed25519 ID in mind when we made this "
1966 "connection.)");
1968 (const char*)rsa_peer_id, ed_peer_id);
1969 changed_identity = 1;
1970 }
1971
1972 if (changed_identity) {
1973 /* If we learned an identity for this connection, then we might have
1974 * just discovered it to be canonical. */
1976 if (conn->tls)
1979 }
1980
1981 if (authdir_mode_tests_reachability(options)) {
1982 // We don't want to use canonical_orport here -- we want the address
1983 // that we really used.
1984 dirserv_orconn_tls_done(&conn->base_.addr, conn->base_.port,
1985 (const char*)rsa_peer_id, ed_peer_id);
1986 }
1987
1988 return 0;
1989}
1990
1991/** Return when we last used this channel for client activity (origin
1992 * circuits). This is called from connection.c, since client_used is now one
1993 * of the timestamps in channel_t */
1994time_t
1996{
1997 tor_assert(conn);
1998
1999 if (conn->chan) {
2000 return channel_when_last_client(TLS_CHAN_TO_BASE(conn->chan));
2001 } else return 0;
2002}
2003
2004/**
2005 * Called as client when initial TLS handshake is done, and we notice
2006 * that we got a v3-handshake signalling certificate from the server.
2007 * Set up structures, do bookkeeping, and send the versions cell.
2008 * Return 0 on success and -1 on failure.
2009 */
2010static int
2023
2024/** Allocate a new connection handshake state for the connection
2025 * <b>conn</b>. Return 0 on success, -1 on failure. */
2026int
2028{
2030 if (conn->handshake_state) {
2031 log_warn(LD_BUG, "Duplicate call to connection_init_or_handshake_state!");
2032 return 0;
2033 }
2034 s = conn->handshake_state = tor_malloc_zero(sizeof(or_handshake_state_t));
2035 s->started_here = started_here ? 1 : 0;
2036 s->digest_sent_data = 1;
2037 s->digest_received_data = 1;
2038 if (! started_here && get_current_link_cert_cert()) {
2039 s->own_link_cert = tor_cert_dup(get_current_link_cert_cert());
2040 }
2043 return 0;
2044}
2045
2046/** Free all storage held by <b>state</b>. */
2047void
2049{
2050 if (!state)
2051 return;
2053 crypto_digest_free(state->digest_received);
2054 or_handshake_certs_free(state->certs);
2055 tor_cert_free(state->own_link_cert);
2056 memwipe(state, 0xBE, sizeof(or_handshake_state_t));
2057 tor_free(state);
2058}
2059
2060/**
2061 * Remember that <b>cell</b> has been transmitted (if <b>incoming</b> is
2062 * false) or received (if <b>incoming</b> is true) during a V3 handshake using
2063 * <b>state</b>.
2064 *
2065 * (We don't record the cell, but we keep a digest of everything sent or
2066 * received during the v3 handshake, and the client signs it in an
2067 * authenticate cell.)
2068 */
2069void
2071 or_handshake_state_t *state,
2072 const cell_t *cell,
2073 int incoming)
2074{
2075 size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
2076 crypto_digest_t *d, **dptr;
2077 packed_cell_t packed;
2078 if (incoming) {
2079 if (!state->digest_received_data)
2080 return;
2081 } else {
2082 if (!state->digest_sent_data)
2083 return;
2084 }
2085 if (!incoming) {
2086 log_warn(LD_BUG, "We shouldn't be sending any non-variable-length cells "
2087 "while making a handshake digest. But we think we are sending "
2088 "one with type %d.", (int)cell->command);
2089 }
2090 dptr = incoming ? &state->digest_received : &state->digest_sent;
2091 if (! *dptr)
2092 *dptr = crypto_digest256_new(DIGEST_SHA256);
2093
2094 d = *dptr;
2095 /* Re-packing like this is a little inefficient, but we don't have to do
2096 this very often at all. */
2097 cell_pack(&packed, cell, conn->wide_circ_ids);
2098 crypto_digest_add_bytes(d, packed.body, cell_network_size);
2099 memwipe(&packed, 0, sizeof(packed));
2100}
2101
2102/** Remember that a variable-length <b>cell</b> has been transmitted (if
2103 * <b>incoming</b> is false) or received (if <b>incoming</b> is true) during a
2104 * V3 handshake using <b>state</b>.
2105 *
2106 * (We don't record the cell, but we keep a digest of everything sent or
2107 * received during the v3 handshake, and the client signs it in an
2108 * authenticate cell.)
2109 */
2110void
2112 or_handshake_state_t *state,
2113 const var_cell_t *cell,
2114 int incoming)
2115{
2116 crypto_digest_t *d, **dptr;
2117 int n;
2118 char buf[VAR_CELL_MAX_HEADER_SIZE];
2119 if (incoming) {
2120 if (!state->digest_received_data)
2121 return;
2122 } else {
2123 if (!state->digest_sent_data)
2124 return;
2125 }
2126 dptr = incoming ? &state->digest_received : &state->digest_sent;
2127 if (! *dptr)
2128 *dptr = crypto_digest256_new(DIGEST_SHA256);
2129
2130 d = *dptr;
2131
2132 n = var_cell_pack_header(cell, buf, conn->wide_circ_ids);
2133 crypto_digest_add_bytes(d, buf, n);
2134 crypto_digest_add_bytes(d, (const char *)cell->payload, cell->payload_len);
2135
2136 memwipe(buf, 0, sizeof(buf));
2137}
2138
2139/** Set <b>conn</b>'s state to OR_CONN_STATE_OPEN, and tell other subsystems
2140 * as appropriate. Called when we are done with all TLS and OR handshaking.
2141 */
2142int
2144{
2145 tor_assert(conn);
2146 /* Handshaking succeeded. This clears attribution before OR status callbacks
2147 * can reenter error handling, even while the channel still appears
2148 * OPENING. */
2149 if (conn->chan)
2150 channel_note_establishment_cancelled(TLS_CHAN_TO_BASE(conn->chan));
2152 connection_or_event_status(conn, OR_CONN_EVENT_CONNECTED, 0);
2153
2154 /* Link protocol 3 appeared in Tor 0.2.3.6-alpha, so any connection
2155 * that uses an earlier link protocol should not be treated as a relay. */
2156 if (conn->link_proto < 3) {
2157 channel_mark_client(TLS_CHAN_TO_BASE(conn->chan));
2158 }
2159
2160 or_handshake_state_free(conn->handshake_state);
2161 conn->handshake_state = NULL;
2163
2164 return 0;
2165}
2166
2167/** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
2168 * For cells that use or affect a circuit, this should only be called by
2169 * connection_or_flush_from_first_active_circuit().
2170 */
2171void
2173{
2174 packed_cell_t networkcell;
2175 size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
2176
2177 tor_assert(cell);
2178 tor_assert(conn);
2179
2180 cell_pack(&networkcell, cell, conn->wide_circ_ids);
2181
2182 /* We need to count padding cells from this non-packed code path
2183 * since they are sent via chan->write_cell() (which is not packed) */
2185 if (cell->command == CELL_PADDING)
2187
2188 connection_buf_add(networkcell.body, cell_network_size, TO_CONN(conn));
2189
2190 /* Touch the channel's active timestamp if there is one */
2191 if (conn->chan) {
2192 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2193
2194 if (TLS_CHAN_TO_BASE(conn->chan)->padding_enabled) {
2196 if (cell->command == CELL_PADDING)
2198 }
2199 }
2200
2201 if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
2202 or_handshake_state_record_cell(conn, conn->handshake_state, cell, 0);
2203}
2204
2205/** Pack a variable-length <b>cell</b> into wire-format, and write it onto
2206 * <b>conn</b>'s outbuf. Right now, this <em>DOES NOT</em> support cells that
2207 * affect a circuit.
2208 */
2209MOCK_IMPL(void,
2212{
2213 int n;
2214 char hdr[VAR_CELL_MAX_HEADER_SIZE];
2215 tor_assert(cell);
2216 tor_assert(conn);
2217 n = var_cell_pack_header(cell, hdr, conn->wide_circ_ids);
2218 connection_buf_add(hdr, n, TO_CONN(conn));
2219 connection_buf_add((char*)cell->payload,
2220 cell->payload_len, TO_CONN(conn));
2221 if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
2223
2225 /* Touch the channel's active timestamp if there is one */
2226 if (conn->chan)
2227 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2228}
2229
2230/** See whether there's a variable-length cell waiting on <b>or_conn</b>'s
2231 * inbuf. Return values as for fetch_var_cell_from_buf(). */
2232static int
2234{
2235 connection_t *conn = TO_CONN(or_conn);
2236 return fetch_var_cell_from_buf(conn->inbuf, out, or_conn->link_proto);
2237}
2238
2239/** Process cells from <b>conn</b>'s inbuf.
2240 *
2241 * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
2242 * and hand it to command_process_cell().
2243 *
2244 * Always return 0.
2245 */
2246static int
2248{
2249 var_cell_t *var_cell;
2250
2251 /*
2252 * Note on memory management for incoming cells: below the channel layer,
2253 * we shouldn't need to consider its internal queueing/copying logic. It
2254 * is safe to pass cells to it on the stack or on the heap, but in the
2255 * latter case we must be sure we free them later.
2256 *
2257 * The incoming cell queue code in channel.c will (in the common case)
2258 * decide it can pass them to the upper layer immediately, in which case
2259 * those functions may run directly on the cell pointers we pass here, or
2260 * it may decide to queue them, in which case it will allocate its own
2261 * buffer and copy the cell.
2262 */
2263
2264 while (1) {
2265 log_debug(LD_OR,
2266 TOR_SOCKET_T_FORMAT": starting, inbuf_datalen %d "
2267 "(%d pending in tls object).",
2268 conn->base_.s,(int)connection_get_inbuf_len(TO_CONN(conn)),
2270 if (connection_fetch_var_cell_from_buf(conn, &var_cell)) {
2271 if (!var_cell)
2272 return 0; /* not yet. */
2273
2274 /* Touch the channel's active timestamp if there is one */
2275 if (conn->chan)
2276 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2277
2279 channel_tls_handle_var_cell(var_cell, conn);
2280 var_cell_free(var_cell);
2281 } else {
2282 const int wide_circ_ids = conn->wide_circ_ids;
2283 size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
2284 char buf[CELL_MAX_NETWORK_SIZE];
2285 cell_t cell;
2286 if (connection_get_inbuf_len(TO_CONN(conn))
2287 < cell_network_size) /* whole response available? */
2288 return 0; /* not yet */
2289
2290 /* Touch the channel's active timestamp if there is one */
2291 if (conn->chan)
2292 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2293
2295 connection_buf_get_bytes(buf, cell_network_size, TO_CONN(conn));
2296
2297 /* retrieve cell info from buf (create the host-order struct from the
2298 * network-order string) */
2299 cell_unpack(&cell, buf, wide_circ_ids);
2300
2301 channel_tls_handle_cell(&cell, conn);
2302 }
2303 }
2304}
2305
2306/** Array of supported link protocol versions. */
2307static const uint16_t or_protocol_versions[] = { 3, 4, 5 };
2308/** Number of versions in <b>or_protocol_versions</b>. */
2309static const int n_or_protocol_versions =
2310 (int)( sizeof(or_protocol_versions)/sizeof(uint16_t) );
2311
2312/** Return true iff <b>v</b> is a link protocol version that this Tor
2313 * implementation believes it can support. */
2314int
2316{
2317 int i;
2318 for (i = 0; i < n_or_protocol_versions; ++i) {
2319 if (or_protocol_versions[i] == v)
2320 return 1;
2321 }
2322 return 0;
2323}
2324
2325/** Send a VERSIONS cell on <b>conn</b>, telling the other host about the
2326 * link protocol versions that this Tor can support.
2327 *
2328 * If <b>v3_plus</b>, this is part of a V3 protocol handshake, so only
2329 * allow protocol version v3 or later. If not <b>v3_plus</b>, this is
2330 * not part of a v3 protocol handshake, so don't allow protocol v3 or
2331 * later.
2332 **/
2333int
2335{
2336 var_cell_t *cell;
2337 int i;
2338 int n_versions = 0;
2339 const int min_version = v3_plus ? 3 : 0;
2340 const int max_version = v3_plus ? UINT16_MAX : 2;
2344 cell->command = CELL_VERSIONS;
2345 for (i = 0; i < n_or_protocol_versions; ++i) {
2346 uint16_t v = or_protocol_versions[i];
2347 if (v < min_version || v > max_version)
2348 continue;
2349 set_uint16(cell->payload+(2*n_versions), htons(v));
2350 ++n_versions;
2351 }
2352 cell->payload_len = n_versions * 2;
2353
2355 conn->handshake_state->sent_versions_at = time(NULL);
2356
2357 var_cell_free(cell);
2358 return 0;
2359}
2360
2361static netinfo_addr_t *
2362netinfo_addr_from_tor_addr(const tor_addr_t *tor_addr)
2363{
2364 sa_family_t addr_family = tor_addr_family(tor_addr);
2365
2366 if (BUG(addr_family != AF_INET && addr_family != AF_INET6))
2367 return NULL;
2368
2369 netinfo_addr_t *netinfo_addr = netinfo_addr_new();
2370
2371 if (addr_family == AF_INET) {
2372 netinfo_addr_set_addr_type(netinfo_addr, NETINFO_ADDR_TYPE_IPV4);
2373 netinfo_addr_set_len(netinfo_addr, 4);
2374 netinfo_addr_set_addr_ipv4(netinfo_addr, tor_addr_to_ipv4h(tor_addr));
2375 } else if (addr_family == AF_INET6) {
2376 netinfo_addr_set_addr_type(netinfo_addr, NETINFO_ADDR_TYPE_IPV6);
2377 netinfo_addr_set_len(netinfo_addr, 16);
2378 uint8_t *ipv6_buf = netinfo_addr_getarray_addr_ipv6(netinfo_addr);
2379 const uint8_t *in6_addr = tor_addr_to_in6_addr8(tor_addr);
2380 memcpy(ipv6_buf, in6_addr, 16);
2381 }
2382
2383 return netinfo_addr;
2384}
2385
2386/** Send a NETINFO cell on <b>conn</b>, telling the other server what we know
2387 * about their address, our address, and the current time. */
2388MOCK_IMPL(int,
2390{
2391 cell_t cell;
2392 time_t now = time(NULL);
2393 const routerinfo_t *me;
2394 int r = -1;
2395
2397
2398 if (conn->handshake_state->sent_netinfo) {
2399 log_warn(LD_BUG, "Attempted to send an extra netinfo cell on a connection "
2400 "where we already sent one.");
2401 return 0;
2402 }
2403
2404 memset(&cell, 0, sizeof(cell_t));
2405 cell.command = CELL_NETINFO;
2406
2407 netinfo_cell_t *netinfo_cell = netinfo_cell_new();
2408
2409 /* Timestamp, if we're a relay. */
2410 if (public_server_mode(get_options()) || ! conn->is_outgoing)
2411 netinfo_cell_set_timestamp(netinfo_cell, (uint32_t)now);
2412
2413 /* Their address. */
2414 const tor_addr_t *remote_tor_addr = &TO_CONN(conn)->addr;
2415 /* We can safely use TO_CONN(conn)->addr here, since we no longer replace
2416 * it with a canonical address. */
2417 netinfo_addr_t *their_addr = netinfo_addr_from_tor_addr(remote_tor_addr);
2418
2419 netinfo_cell_set_other_addr(netinfo_cell, their_addr);
2420
2421 /* My address -- only include it if I'm a public relay, or if I'm a
2422 * bridge and this is an incoming connection. If I'm a bridge and this
2423 * is an outgoing connection, act like a normal client and omit it. */
2424 if ((public_server_mode(get_options()) || !conn->is_outgoing) &&
2425 (me = router_get_my_routerinfo())) {
2426 uint8_t n_my_addrs = 1 + !tor_addr_is_null(&me->ipv6_addr);
2427 netinfo_cell_set_n_my_addrs(netinfo_cell, n_my_addrs);
2428
2429 netinfo_cell_add_my_addrs(netinfo_cell,
2430 netinfo_addr_from_tor_addr(&me->ipv4_addr));
2431
2432 if (!tor_addr_is_null(&me->ipv6_addr)) {
2433 netinfo_cell_add_my_addrs(netinfo_cell,
2434 netinfo_addr_from_tor_addr(&me->ipv6_addr));
2435 }
2436 }
2437
2438 const char *errmsg = NULL;
2439 if ((errmsg = netinfo_cell_check(netinfo_cell))) {
2440 log_warn(LD_OR, "Failed to validate NETINFO cell with error: %s",
2441 errmsg);
2442 goto cleanup;
2443 }
2444
2445 if (netinfo_cell_encode(cell.payload, CELL_PAYLOAD_SIZE,
2446 netinfo_cell) < 0) {
2447 log_warn(LD_OR, "Failed generating NETINFO cell");
2448 goto cleanup;
2449 }
2450
2452 conn->handshake_state->sent_netinfo = 1;
2454
2455 r = 0;
2456 cleanup:
2457 netinfo_cell_free(netinfo_cell);
2458
2459 return r;
2460}
void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
Definition address.c:933
int tor_addr_is_null(const tor_addr_t *addr)
Definition address.c:780
void tor_addr_port_copy(tor_addr_port_t *dest, const tor_addr_port_t *source)
Definition address.c:2121
static sa_family_t tor_addr_family(const tor_addr_t *a)
Definition address.h:189
static uint32_t tor_addr_to_ipv4h(const tor_addr_t *a)
Definition address.h:162
#define tor_addr_to_in6_addr8(x)
Definition address.h:137
#define fmt_addr(a)
Definition address.h:241
#define tor_addr_eq(a, b)
Definition address.h:282
time_t approx_time(void)
Definition approx_time.c:32
Header file for directory authority mode.
const char * hex_str(const char *from, size_t fromlen)
Definition binascii.c:34
void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition binascii.c:478
void learned_router_identity(const tor_addr_t *addr, uint16_t port, const char *digest, const ed25519_public_key_t *ed_id)
Definition bridges.c:448
const char * find_transport_name_by_bridge_addrport(const tor_addr_t *addr, uint16_t port)
Definition bridges.c:642
Header file for circuitbuild.c.
size_t buf_datalen(const buf_t *buf)
Definition buffers.c:394
Header file for buffers.c.
static void set_uint16(void *cp, uint16_t v)
Definition bytes.h:78
static uint16_t get_uint16(const void *cp)
Definition bytes.h:42
static void set_uint32(void *cp, uint32_t v)
Definition bytes.h:87
static uint8_t get_uint8(const void *cp)
Definition bytes.h:23
static void set_uint8(void *cp, uint8_t v)
Definition bytes.h:31
static uint32_t get_uint32(const void *cp)
Definition bytes.h:54
Cell queue structures.
Fixed-size cell structure.
void channel_timestamp_active(channel_t *chan)
Definition channel.c:3216
int channel_is_better(channel_t *a, channel_t *b)
Definition channel.c:2413
int channel_is_bad_for_new_circs(channel_t *chan)
Definition channel.c:2959
void channel_set_identity_digest(channel_t *chan, const char *identity_digest, const ed25519_public_key_t *ed_identity)
Definition channel.c:1391
void channel_mark_client(channel_t *chan)
Definition channel.c:3000
void channel_closed(channel_t *chan)
Definition channel.c:1326
void channel_note_establishment_failure(channel_t *chan)
Definition channel.c:1304
void channel_close_from_lower_layer(channel_t *chan)
Definition channel.c:1229
void channel_listener_queue_incoming(channel_listener_t *listener, channel_t *incoming)
Definition channel.c:1994
time_t channel_when_last_client(channel_t *chan)
Definition channel.c:3336
void channel_mark_bad_for_new_circs(channel_t *chan)
Definition channel.c:2972
void channel_close_for_error(channel_t *chan)
Definition channel.c:1257
void channel_clear_identity_digest(channel_t *chan)
Definition channel.c:1362
unsigned int channel_num_circuits(channel_t *chan)
Definition channel.c:3410
void channel_note_establishment_cancelled(channel_t *chan)
Definition channel.c:1290
Header file for channel.c.
unsigned int channelpadding_get_channel_idle_timeout(const channel_t *chan, int is_canonical)
void channel_tls_handle_var_cell(var_cell_t *var_cell, or_connection_t *conn)
channel_listener_t * channel_tls_start_listener(void)
Definition channeltls.c:296
void channel_tls_handle_state_change_on_orconn(channel_tls_t *chan, or_connection_t *conn, uint8_t state)
void channel_tls_handle_cell(cell_t *cell, or_connection_t *conn)
channel_listener_t * channel_tls_get_listener(void)
Definition channeltls.c:284
void channel_tls_update_marks(or_connection_t *conn)
channel_t * channel_tls_handle_incoming(or_connection_t *orconn)
Definition channeltls.c:359
channel_t * channel_tls_to_base(channel_tls_t *tlschan)
Definition channeltls.c:440
Header file for channeltls.c.
Header file for circuitbuild.c.
Header file for circuitlist.c.
circuit_build_times_t * get_circuit_build_times_mutable(void)
void circuit_build_times_network_is_live(circuit_build_times_t *cbt)
Header file for circuitstats.c.
void command_setup_listener(channel_listener_t *listener)
Definition command.c:725
Header file for command.c.
uint32_t monotime_coarse_get_stamp(void)
const or_options_t * get_options(void)
Definition config.c:949
Header file for config.c.
Public APIs for congestion control.
static uint32_t or_conn_highwatermark(void)
static uint32_t or_conn_lowwatermark(void)
int connection_buf_get_bytes(char *string, size_t len, connection_t *conn)
int get_proxy_addrport(tor_addr_t *addr, uint16_t *port, int *proxy_type, int *is_pt_out, const connection_t *conn)
int connection_proxy_connect(connection_t *conn, int type)
void assert_connection_ok(connection_t *conn, time_t now)
int connection_read_proxy_handshake(connection_t *conn)
const char * connection_describe_peer(const connection_t *conn)
Definition connection.c:523
or_connection_t * or_connection_new(int type, int socket_family)
Definition connection.c:571
const char * connection_describe(const connection_t *conn)
Definition connection.c:538
void connection_free_(connection_t *conn)
Definition connection.c:965
int connection_connect(connection_t *conn, const char *address, const tor_addr_t *addr, uint16_t port, int *socket_error)
const char * conn_state_to_string(int type, int state)
Definition connection.c:301
Header file for connection.c.
#define CONN_TYPE_OR
Definition connection.h:44
#define CONN_TYPE_EXT_OR
Definition connection.h:71
void connection_or_event_status(or_connection_t *conn, or_conn_status_event_t tp, int reason)
or_connection_t * TO_OR_CONN(connection_t *c)
int is_or_protocol_version_known(uint16_t v)
int connection_or_set_state_open(or_connection_t *conn)
int connection_or_reached_eof(or_connection_t *conn)
static const int n_or_protocol_versions
int connection_tls_continue_handshake(or_connection_t *conn)
static void connection_or_set_identity_digest(or_connection_t *conn, const char *rsa_digest, const ed25519_public_key_t *ed_id)
void connection_or_notify_error(or_connection_t *conn, int reason, const char *msg)
void connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
int connection_or_process_inbuf(or_connection_t *conn)
static int connection_fetch_var_cell_from_buf(or_connection_t *or_conn, var_cell_t **out)
void connection_or_note_establishment_failure(or_connection_t *conn)
void connection_or_clear_identity(or_connection_t *conn)
int connection_or_send_versions(or_connection_t *conn, int v3_plus)
int connection_or_client_learned_peer_id(or_connection_t *conn, const uint8_t *rsa_peer_id, const ed25519_public_key_t *ed_peer_id)
static void connection_or_update_token_buckets_helper(or_connection_t *conn, int reset, const or_options_t *options)
time_t connection_or_client_used(or_connection_t *conn)
void cell_pack(packed_cell_t *dst, const cell_t *src, int wide_circ_ids)
static void connection_or_note_state_when_broken(or_connection_t *orconn)
var_cell_t * var_cell_new(uint16_t payload_len)
void or_handshake_state_free_(or_handshake_state_t *state)
void or_handshake_state_record_var_cell(or_connection_t *conn, or_handshake_state_t *state, const var_cell_t *cell, int incoming)
int var_cell_pack_header(const var_cell_t *cell, char *hdr_out, int wide_circ_ids)
int connection_or_finished_flushing(or_connection_t *conn)
static unsigned int connection_or_is_bad_for_new_circs(or_connection_t *or_conn)
void clear_broken_connection_map(int stop_recording)
static void cell_unpack(cell_t *dest, const char *src, int wide_circ_ids)
void connection_or_connect_failed(or_connection_t *conn, int reason, const char *msg)
static int connection_or_process_cells_from_inbuf(or_connection_t *conn)
int connection_or_send_netinfo(or_connection_t *conn)
void var_cell_free_(var_cell_t *cell)
int connection_or_single_set_badness_(time_t now, or_connection_t *or_conn, int force)
int connection_tls_start_handshake(or_connection_t *conn, int receiving)
void connection_or_change_state(or_connection_t *conn, uint8_t state)
void or_handshake_state_record_cell(or_connection_t *conn, or_handshake_state_t *state, const cell_t *cell, int incoming)
var_cell_t * var_cell_copy(const var_cell_t *src)
static int connection_or_launch_v3_or_handshake(or_connection_t *conn)
static void note_broken_connection(const char *state)
void connection_or_report_broken_states(int severity, int domain)
static void connection_or_check_canonicity(or_connection_t *conn, int started_here)
int connection_or_digest_is_known_relay(const char *id_digest)
#define MAX_REASONS_TO_REPORT
void connection_or_init_conn_from_address(or_connection_t *conn, const tor_addr_t *addr, uint16_t port, const char *id_digest, const ed25519_public_key_t *ed_id, int started_here)
static const uint16_t or_protocol_versions[]
int connection_or_get_num_circuits(or_connection_t *conn)
int connection_or_flushed_some(or_connection_t *conn)
const struct ed25519_public_key_t * connection_or_get_alleged_ed25519_id(const or_connection_t *conn)
int connection_or_nonopen_was_started_here(or_connection_t *conn)
static int disable_broken_connection_counts
void connection_or_close_for_error(or_connection_t *orconn, int flush)
const or_connection_t * CONST_TO_OR_CONN(const connection_t *c)
static strmap_t * broken_connection_counts
void connection_or_update_token_buckets(smartlist_t *conns, const or_options_t *options)
or_connection_t * connection_or_connect(const tor_addr_t *_addr, uint16_t port, const char *id_digest, const ed25519_public_key_t *ed_id, channel_tls_t *chan, bool for_origin_circ)
static void connection_or_get_state_description(or_connection_t *orconn, char *buf, size_t buflen)
void connection_or_group_set_badness_(smartlist_t *group, int force)
int connection_or_finished_connecting(or_connection_t *or_conn)
void connection_or_about_to_close(or_connection_t *or_conn)
static int broken_state_count_compare(const void **a_ptr, const void **b_ptr)
ssize_t connection_or_num_cells_writeable(or_connection_t *conn)
int connection_init_or_handshake_state(or_connection_t *conn, int started_here)
void connection_or_clear_identity_map(void)
void connection_or_close_normally(or_connection_t *orconn, int flush)
static void connection_or_state_publish(const or_connection_t *conn, uint8_t state)
void connection_or_write_var_cell_to_buf(const var_cell_t *cell, or_connection_t *conn)
#define TIME_BEFORE_OR_CONN_IS_TOO_OLD
Header file for connection_or.c.
void control_event_bootstrap_prob_or(const char *warn, int reason, or_connection_t *or_conn)
int control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp, int reason)
Header file for control_events.c.
#define HEX_DIGEST_LEN
#define crypto_digest_free(d)
crypto_digest_t * crypto_digest256_new(digest_algorithm_t algorithm)
void crypto_digest_add_bytes(crypto_digest_t *digest, const char *data, size_t len)
int ed25519_public_key_is_zero(const ed25519_public_key_t *pubkey)
int ed25519_pubkey_eq(const ed25519_public_key_t *key1, const ed25519_public_key_t *key2)
void ed25519_public_to_base64(char *output, const ed25519_public_key_t *pkey)
const char * ed25519_fmt(const ed25519_public_key_t *pkey)
Header for crypto_format.c.
void memwipe(void *mem, uint8_t byte, size_t sz)
Definition crypto_util.c:55
Common functions for cryptographic routines.
#define fast_memeq(a, b, c)
Definition di_ops.h:35
#define tor_memneq(a, b, sz)
Definition di_ops.h:21
#define DIGEST_LEN
int router_digest_is_fallback_dir(const char *digest)
Definition dirlist.c:205
Header file for dirlist.c.
Header file for circuitbuild.c.
Header for ext_orport.c.
Header file for geoip.c.
Header file containing service data for the HS subsystem.
uint16_t sa_family_t
Definition inaddr_st.h:77
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition log.c:591
#define log_fn(severity, domain, args,...)
Definition log.h:283
#define LD_PROTOCOL
Definition log.h:72
#define LD_OR
Definition log.h:92
#define LD_BUG
Definition log.h:86
#define LD_HANDSHAKE
Definition log.h:101
#define LD_NET
Definition log.h:66
#define LD_GENERAL
Definition log.h:62
#define LD_CIRC
Definition log.h:82
#define LOG_WARN
Definition log.h:53
#define LOG_INFO
Definition log.h:45
#define bool_neq(a, b)
Definition logic.h:18
#define bool_eq(a, b)
Definition logic.h:16
void connection_watch_events(connection_t *conn, watchable_events_t events)
Definition mainloop.c:486
void connection_start_reading(connection_t *conn)
Definition mainloop.c:636
void connection_start_writing(connection_t *conn)
Definition mainloop.c:709
smartlist_t * get_connection_array(void)
Definition mainloop.c:444
void connection_stop_writing(connection_t *conn)
Definition mainloop.c:686
Header file for mainloop.c.
@ WRITE_EVENT
Definition mainloop.h:38
@ READ_EVENT
Definition mainloop.h:37
void * tor_reallocarray_(void *ptr, size_t sz1, size_t sz2)
Definition malloc.c:146
void tor_free_(void *mem)
Definition malloc.c:227
#define tor_free(p)
Definition malloc.h:56
int usable_consensus_flavor(void)
Definition microdesc.c:1088
Header file for microdesc.c.
networkstatus_t * networkstatus_get_reasonably_live_consensus(time_t now, int flavor)
const routerstatus_t * router_get_consensus_status_by_id(const char *digest)
int32_t networkstatus_get_param(const networkstatus_t *ns, const char *param_name, int32_t default_val, int32_t min_val, int32_t max_val)
Header file for networkstatus.c.
void node_get_prim_orport(const node_t *node, tor_addr_port_t *ap_out)
Definition nodelist.c:1855
const node_t * node_get_by_id(const char *identity_digest)
Definition nodelist.c:226
const char * node_get_nickname(const node_t *node)
Definition nodelist.c:1484
bool node_supports_ed25519_link_authentication(const node_t *node, bool compatible_with_us)
Definition nodelist.c:1260
int node_ed25519_id_matches(const node_t *node, const ed25519_public_key_t *id)
Definition nodelist.c:1220
void node_get_pref_ipv6_orport(const node_t *node, tor_addr_port_t *ap_out)
Definition nodelist.c:1891
Header file for nodelist.c.
Master header file for Tor-specific functionality.
#define CELL_PAYLOAD_SIZE
Definition or.h:529
#define VAR_CELL_MAX_HEADER_SIZE
Definition or.h:535
#define CELL_MAX_NETWORK_SIZE
Definition or.h:532
#define TO_CONN(c)
Definition or.h:709
#define DOWNCAST(to, ptr)
Definition or.h:109
OR connection structure.
OR handshake certs structure.
OR handshake state structure.
The or_state_t structure, which represents Tor's state file.
Header file for orconn_event.c.
#define OR_CONN_STATE_SERVER_VERSIONS_WAIT
or_conn_status_event_t
#define OR_CONN_STATE_CONNECTING
#define OR_CONN_STATE_PROXY_HANDSHAKING
#define OR_CONN_STATE_TLS_HANDSHAKING
#define OR_CONN_STATE_OR_HANDSHAKING_V3
#define OR_CONN_STATE_OPEN
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition printf.c:27
int fetch_var_cell_from_buf(buf_t *buf, var_cell_t **out, int linkproto)
Definition proto_cell.c:57
Header for proto_cell.c.
Header file for reachability.c.
int tls_error_to_orconn_end_reason(int e)
Definition reasons.c:267
int errno_to_orconn_end_reason(int e)
Definition reasons.c:295
const char * orconn_end_reason_to_control_string(int r)
Definition reasons.c:229
Header file for reasons.c.
Header file for relay.c.
Header for feature/relay/relay_handshake.c.
Header file for rendcommon.c.
void rep_hist_padding_count_write(padding_type_t type)
Definition rephist.c:2816
Header file for rephist.c.
@ PADDING_TYPE_ENABLED_CELL
Definition rephist.h:158
@ PADDING_TYPE_TOTAL
Definition rephist.h:154
@ PADDING_TYPE_ENABLED_TOTAL
Definition rephist.h:156
@ PADDING_TYPE_CELL
Definition rephist.h:152
int router_digest_is_me(const char *digest)
Definition router.c:1755
const routerinfo_t * router_get_my_routerinfo(void)
Definition router.c:1817
Header file for router.c.
Router descriptor structure.
Header for routerkeys.c.
const routerinfo_t * router_get_by_id_digest(const char *digest)
Definition routerlist.c:778
Header file for routerlist.c.
Header file for routermode.c.
void scheduler_channel_wants_writes(channel_t *chan)
Definition scheduler.c:673
Header file for scheduler*.c.
void smartlist_sort(smartlist_t *sl, int(*compare)(const void **a, const void **b))
Definition smartlist.c:334
smartlist_t * smartlist_new(void)
void smartlist_add(smartlist_t *sl, void *element)
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
#define SMARTLIST_FOREACH(sl, type, var, cmd)
uint8_t payload[CELL_PAYLOAD_SIZE]
Definition cell_st.h:21
uint8_t command
Definition cell_st.h:19
circid_t circ_id
Definition cell_st.h:18
struct ed25519_public_key_t ed25519_identity
Definition channel.h:389
unsigned int proxy_state
struct buf_t * inbuf
unsigned int hold_open_until_flushed
unsigned int type
uint32_t magic
uint64_t global_identifier
uint16_t marked_for_close
tor_socket_t s
time_t timestamp_created
tor_addr_t addr
token_bucket_rw_t bucket
channel_tls_t * chan
unsigned int potentially_used_for_bootstrapping
char identity_digest[DIGEST_LEN]
unsigned int is_outgoing
or_handshake_state_t * handshake_state
unsigned int is_pt
tor_addr_port_t canonical_orport
struct tor_tls_t * tls
unsigned int is_canonical
unsigned int proxy_type
struct tor_cert_st * own_link_cert
crypto_digest_t * digest_sent
or_handshake_certs_t * certs
uint64_t BandwidthRate
uint64_t PerConnBWBurst
uint64_t PerConnBWRate
uint64_t BandwidthBurst
char body[CELL_MAX_NETWORK_SIZE]
tor_addr_t ipv6_addr
tor_addr_t ipv4_addr
uint8_t command
Definition var_cell_st.h:18
uint16_t payload_len
Definition var_cell_st.h:22
circid_t circ_id
Definition var_cell_st.h:20
uint8_t payload[FLEXIBLE_ARRAY_MEMBER]
Definition var_cell_st.h:24
#define STATIC
Definition testsupport.h:32
#define MOCK_IMPL(rv, funcname, arglist)
void token_bucket_rw_adjust(token_bucket_rw_t *bucket, uint32_t rate, uint32_t burst)
void token_bucket_rw_reset(token_bucket_rw_t *bucket, uint32_t now_ts_stamp)
tor_cert_t * tor_cert_dup(const tor_cert_t *cert)
Definition torcert.c:294
or_handshake_certs_t * or_handshake_certs_new(void)
Definition torcert.c:471
Header for torcert.c.
int tor_tls_is_server(tor_tls_t *tls)
Definition tortls.c:365
void tor_tls_set_logged_address(tor_tls_t *tls, const char *address)
Definition tortls.c:355
const char * tor_tls_err_to_string(int err)
Definition tortls.c:142
Headers for tortls.c.
#define CASE_TOR_TLS_ERROR_ANY
Definition tortls.h:62
int tor_tls_get_pending_bytes(tor_tls_t *tls)
Definition tortls_nss.c:596
int tor_tls_handshake(tor_tls_t *tls)
Definition tortls_nss.c:578
tor_tls_t * tor_tls_new(tor_socket_t sock, int is_server)
Definition tortls_nss.c:386
const char * tor_tls_get_last_error_msg(const tor_tls_t *tls)
Definition tortls_nss.c:374
void tor_tls_get_state_description(tor_tls_t *tls, char *buf, size_t sz)
Definition tortls_nss.c:323
#define tor_assert_nonfatal_unreached()
Definition util_bug.h:177
#define tor_assert(expr)
Definition util_bug.h:103
#define tor_fragile_assert()
Definition util_bug.h:278
#define IF_BUG_ONCE(cond)
Definition util_bug.h:254
int tor_digest_is_zero(const char *digest)
Definition util_string.c:98
Variable-length cell structure.
#define ED25519_BASE64_LEN