1
//! Circuit-related types and helpers.
2
//!
3
//! This code is shared between the client and relay implementations.
4

            
5
pub(crate) mod cell_sender;
6
pub(crate) mod celltypes;
7
pub(crate) mod circ_sender;
8
pub(crate) mod circhop;
9
pub(crate) mod create;
10
pub(crate) mod metrics;
11
pub(crate) mod padding;
12
pub(crate) mod reactor;
13
pub(crate) mod syncview;
14
pub(crate) mod unique_id;
15

            
16
pub use crate::memquota::StreamAccount;
17
pub use syncview::CircHopSyncView;
18
pub use unique_id::UniqId;
19

            
20
use crate::ccparams::CongestionControlParams;
21
use crate::stream::flow_ctrl::params::FlowCtrlParameters;
22
use tor_cell::relaycell::extend::SubprotocolRequest;
23
use tor_error::ErrorKind;
24
use tor_protover::Protocols;
25

            
26
pub(crate) use circ_sender::{CircuitRxReceiver, CircuitRxSender};
27

            
28
/// Estimated upper bound for the likely number of hops.
29
pub(crate) const HOPS: usize = 6;
30

            
31
/// Description of the network's current rules for building circuits.
32
///
33
/// This type describes rules derived from the consensus,
34
/// and possibly amended by our own configuration.
35
///
36
/// Typically, this type created once for an entire circuit,
37
/// and any special per-hop information is derived
38
/// from each hop as a CircTarget.
39
/// Note however that callers _may_ provide different `CircParameters`
40
/// for different hops within a circuit if they have some reason to do so,
41
/// so we do not enforce that every hop in a circuit has the same `CircParameters`.
42
#[non_exhaustive]
43
#[derive(Clone, Debug)]
44
pub struct CircParameters {
45
    /// Whether we should include ed25519 identities when we send
46
    /// EXTEND2 cells.
47
    pub extend_by_ed25519_id: bool,
48
    /// Congestion control parameters for this circuit.
49
    pub ccontrol: CongestionControlParams,
50

            
51
    /// Flow control parameters to use for all streams on this circuit.
52
    // While flow control is a stream property and not a circuit property,
53
    // and it may seem better to pass the flow control parameters to for example `begin_stream()`,
54
    // it's included in [`CircParameters`] for the following reasons:
55
    //
56
    // - When endpoints (exits + hs) receive new stream requests, they need the flow control
57
    //   parameters immediately. It would be easy to pass flow control parameters when creating a
58
    //   stream, but it's not as easy to get flow control parameters when receiving a new stream
59
    //   request, unless those parameters are already available to the circuit (like
60
    //   `CircParameters` are).
61
    // - It's unclear if new streams on existing circuits should switch to new flow control
62
    //   parameters if the consensus changes. This behaviour doesn't appear to be specified. It
63
    //   might also leak information to the circuit's endpoint about when we downloaded new
64
    //   directory documents. So it seems best to stick with the same flow control parameters for
65
    //   the lifetime of the circuit.
66
    // - It doesn't belong in [`StreamParameters`] as `StreamParameters` is a set of preferences
67
    //   with defaults, and consensus parameters aren't preferences and don't have defaults.
68
    //   (Technically they have defaults, but `StreamParameters` isn't the place to set them.)
69
    pub flow_ctrl: FlowCtrlParameters,
70

            
71
    /// Maximum number of permitted incoming relay cells for each hop.
72
    ///
73
    /// If we would receive more relay cells than this from a single hop,
74
    /// we close the circuit with [`ExcessInboundCells`](crate::Error::ExcessInboundCells).
75
    ///
76
    /// If this value is None, then there is no limit to the number of inbound cells.
77
    ///
78
    /// Known limitation: If this value if `u32::MAX`,
79
    /// then a limit of `u32::MAX - 1` is enforced.
80
    pub n_incoming_cells_permitted: Option<u32>,
81

            
82
    /// Maximum number of permitted outgoing relay cells for each hop.
83
    ///
84
    /// If we would try to send more relay cells than this from a single hop,
85
    /// we close the circuit with [`ExcessOutboundCells`](crate::Error::ExcessOutboundCells).
86
    /// It is the circuit-user's responsibility to make sure that this does not happen.
87
    ///
88
    /// This setting is used to ensure that we do not violate a limit
89
    /// imposed by `n_incoming_cells_permitted`
90
    /// on the other side of a circuit.
91
    ///
92
    /// If this value is None, then there is no limit to the number of outbound cells.
93
    ///
94
    /// Known limitation: If this value if `u32::MAX`,
95
    /// then a limit of `u32::MAX - 1` is enforced.
96
    pub n_outgoing_cells_permitted: Option<u32>,
97
}
98

            
99
tor_protover::subprotocol_restricted_set! {
100
    /// The enabled/disabled status of subprotocols that are allowed to be requested through a
101
    /// subprotocol request during a circuit handshake.
102
    ///
103
    /// The allowed subprotocols are defined in:
104
    /// <https://spec.torproject.org/tor-spec/create-created-cells.html#subproto-request>
105
    #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
106
    pub(crate) struct HandshakeSubprotocols {
107
        RELAY_CRYPT_CGO,
108
    }
109
}
110

            
111
impl HandshakeSubprotocols {
112
    /// Build a [`HandshakeSubprotocols`] from a [`SubprotocolRequest`]
113
    /// provided during a circuit handshake.
114
    ///
115
    /// If the `SubprotocolRequest` contains subprotocols that aren't
116
    /// allowed to be requested through a subprotocol request,
117
    /// this returns an error containing the original `SubprotocolRequest`.
118
    //
119
    // It would be nice to return a list of only the invalid subprotocols,
120
    // but it seems a bit expensive to compute on the error path when we probably
121
    // want to fail quickly.
122
7
    pub(crate) fn try_from_request(
123
7
        protos: SubprotocolRequest,
124
7
    ) -> Result<Self, InvalidHandshakeSubprotocolError> {
125
        use std::sync::LazyLock;
126
        static ALL: LazyLock<Protocols> =
127
1
            LazyLock::new(|| Protocols::from(HandshakeSubprotocols::ALL));
128

            
129
7
        if !protos.contains_only(&ALL) {
130
2
            return Err(InvalidHandshakeSubprotocolError(protos));
131
5
        }
132

            
133
5
        Ok(Self {
134
5
            relay_crypt_cgo: protos.contains(tor_protover::named::RELAY_CRYPT_CGO),
135
5
        })
136
7
    }
137
}
138

            
139
/// The subprotocol request had subprotocols that are not all supported in circuit handshakes.
140
///
141
/// Contains the requested subprotocols (both valid and invalid).
142
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
143
#[error("Request included subprotocols that we do not support in circuit handshakes: {0:?}")]
144
pub(crate) struct InvalidHandshakeSubprotocolError(SubprotocolRequest);
145

            
146
impl tor_error::HasKind for InvalidHandshakeSubprotocolError {
147
    fn kind(&self) -> ErrorKind {
148
        ErrorKind::TorProtocolViolation
149
    }
150
}
151

            
152
#[cfg(test)]
153
pub(crate) mod test {
154
    use super::*;
155

            
156
    #[cfg(feature = "relay")]
157
    use crate::relay::{CircNetParameters, CongestionControlNetParams};
158

            
159
    pub(crate) use super::circ_sender::test::fake_mpsc;
160

            
161
    /// Return a new [`CircNetParameters`] using default values for unit tests. They are based on
162
    /// consensus defaults but should not be considered to be accurate from the one used on the
163
    /// production network.
164
    #[cfg(feature = "relay")]
165
    pub(crate) fn new_circ_net_params() -> CircNetParameters {
166
        CircNetParameters {
167
            cc: CongestionControlNetParams::defaults_for_tests(),
168
        }
169
    }
170

            
171
    #[test]
172
    fn handshake_subprotocols() {
173
        let empty_iter: [tor_protover::NumberedSubver; 0] = [];
174
        let request = SubprotocolRequest::from_iter(empty_iter);
175
        assert_eq!(
176
            HandshakeSubprotocols::try_from_request(request),
177
            Ok(HandshakeSubprotocols {
178
                relay_crypt_cgo: false,
179
            }),
180
        );
181

            
182
        let request = SubprotocolRequest::from_iter([tor_protover::named::RELAY_CRYPT_CGO]);
183
        assert_eq!(
184
            HandshakeSubprotocols::try_from_request(request),
185
            Ok(HandshakeSubprotocols {
186
                relay_crypt_cgo: true,
187
            }),
188
        );
189

            
190
        let request =
191
            SubprotocolRequest::from_iter([tor_protover::named::RELAY_NEGOTIATE_SUBPROTO]);
192
        assert!(HandshakeSubprotocols::try_from_request(request).is_err());
193

            
194
        let request = SubprotocolRequest::from_iter([
195
            tor_protover::named::RELAY_NEGOTIATE_SUBPROTO,
196
            tor_protover::named::RELAY_CRYPT_CGO,
197
        ]);
198
        assert!(HandshakeSubprotocols::try_from_request(request).is_err());
199
    }
200
}