1
//! Module exposing structures relating to a reactor's view of a circuit hop.
2

            
3
// TODO(relay): don't import from the client module
4
use crate::client::circuit::handshake::RelayCryptLayerProtocol;
5

            
6
use crate::ccparams::CongestionControlParams;
7
use crate::circuit::CircParameters;
8
use crate::congestion::{CongestionControl, sendme};
9
use crate::memquota::{SpecificAccount, StreamAccount};
10
use crate::stream::CloseStreamBehavior;
11
use crate::stream::SEND_WINDOW_INIT;
12
use crate::stream::StreamMpscSender;
13
use crate::stream::cmdcheck::{AnyCmdChecker, StreamStatus};
14
use crate::stream::flow_ctrl::params::FlowCtrlParameters;
15
use crate::stream::flow_ctrl::state::{
16
    FlowCtrlHooks, StreamFlowCtrl, StreamRateLimit, WithSidechannelMitigations,
17
};
18
use crate::stream::flow_ctrl::xon_xoff::reader::DrainRateRequest;
19
use crate::stream::queue::{StreamQueueReceiver, stream_queue};
20
use crate::streammap::{
21
    self, EndSentStreamEnt, OpenStreamEnt, ShouldSendEnd, StreamEntMut, StreamMap,
22
};
23
use crate::util::notify::{NotifyReceiver, NotifySender};
24
use crate::{Error, HopNum, Result};
25

            
26
use derive_deftly::Deftly;
27
use postage::watch;
28
use safelog::sensitive as sv;
29
use tracing::{debug, trace};
30

            
31
use tor_cell::chancell::{BoxedCellBody, CircId};
32
use tor_cell::relaycell::extend::{CcRequest, CircRequestExt};
33
use tor_cell::relaycell::flow_ctrl::{Xoff, Xon, XonKBpsEwma};
34
use tor_cell::relaycell::msg::AnyRelayMsg;
35
use tor_cell::relaycell::{
36
    AnyRelayMsgOuter, RelayCellDecoder, RelayCellDecoderResult, RelayCellFormat, RelayCmd,
37
    StreamId, UnparsedRelayMsg,
38
};
39
use tor_error::{Bug, ErrorKind, HasKind, internal, into_internal};
40
use tor_memquota::derive_deftly_template_HasMemoryCost;
41
use tor_memquota::mq_queue::{ChannelSpec as _, MpscSpec};
42
use tor_protover::named;
43
use tor_rtcompat::DynTimeProvider;
44

            
45
use std::num::NonZeroU32;
46
use std::pin::Pin;
47
use std::result::Result as StdResult;
48
use std::sync::{Arc, Mutex};
49
use web_time_compat::Instant;
50

            
51
#[cfg(test)]
52
use tor_cell::relaycell::msg::SendmeTag;
53

            
54
#[cfg(feature = "relay")]
55
use {
56
    crate::ccparams::{Algorithm, AlgorithmDiscriminants},
57
    crate::circuit::HandshakeSubprotocols,
58
    crate::relay::{CircNetParameters, CongestionControlNetParams},
59
};
60

            
61
use cfg_if::cfg_if;
62

            
63
/// The size of the stream's outbound RELAY message queue.
64
// TODO(tuning): figure out if this is a good size for this buffer
65
const CIRCUIT_BUFFER_SIZE: usize = 128;
66

            
67
/// Type of negotiation that we'll be performing as we establish a hop.
68
///
69
/// Determines what flavor of extensions we can send and receive, which in turn
70
/// limits the hop settings we can negotiate.
71
///
72
// TODO-CGO: This is likely to be refactored when we finally add support for
73
// HsV3+CGO, which will require refactoring
74
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
75
pub(crate) enum HopNegotiationType {
76
    /// We're using a handshake in which extension-based negotiation cannot occur.
77
    None,
78
    /// We're using the HsV3-ntor handshake, in which the client can send extensions,
79
    /// but the server cannot.
80
    ///
81
    /// As a special case, the default relay encryption protocol is the hsv3
82
    /// variant of Tor1.
83
    //
84
    // We would call this "HalfDuplex" or something, but we do not expect to add
85
    // any more handshakes of this type.
86
    HsV3,
87
    /// We're using a handshake in which both client and relay can send extensions.
88
    Full,
89
}
90

            
91
/// The settings we use for single hop of a circuit.
92
///
93
/// Unlike [`CircParameters`], this type is crate-internal.
94
/// We construct it based on our settings from the circuit,
95
/// and from the hop's actual capabilities.
96
/// Then, we negotiate with the hop as part of circuit
97
/// creation/extension to determine the actual settings that will be in use.
98
/// Finally, we use those settings to construct the negotiated circuit hop.
99
//
100
// TODO: Relays should probably derive an instance of this type too, as
101
// part of the circuit creation handshake.
102
#[derive(Clone, Debug)]
103
pub(crate) struct HopSettings {
104
    /// The negotiated congestion control settings for this hop .
105
    pub(crate) ccontrol: CongestionControlParams,
106

            
107
    /// Flow control parameters that will be used for streams on this hop.
108
    pub(crate) flow_ctrl_params: FlowCtrlParameters,
109

            
110
    /// Maximum number of permitted incoming relay cells for this hop.
111
    pub(crate) n_incoming_cells_permitted: Option<u32>,
112

            
113
    /// Maximum number of permitted outgoing relay cells for this hop.
114
    pub(crate) n_outgoing_cells_permitted: Option<u32>,
115

            
116
    /// The relay cell encryption algorithm and cell format for this hop.
117
    relay_crypt_protocol: RelayCryptLayerProtocol,
118
}
119

            
120
impl HopSettings {
121
    /// Construct a new `HopSettings` based on `params` (a set of circuit parameters)
122
    /// and `caps` (a set of protocol capabilities for a circuit target).
123
    ///
124
    /// The resulting settings will represent what the client would prefer to negotiate
125
    /// (determined by `params`),
126
    /// as modified by what the target relay is believed to support (represented by `caps`).
127
    ///
128
    /// This represents the `HopSettings` in a pre-negotiation state:
129
    /// the circuit negotiation process will modify it.
130
    #[allow(clippy::unnecessary_wraps)] // likely to become fallible in the future.
131
573
    pub(crate) fn from_params_and_caps(
132
573
        hoptype: HopNegotiationType,
133
573
        params: &CircParameters,
134
573
        caps: &tor_protover::Protocols,
135
573
    ) -> Result<Self> {
136
573
        let mut ccontrol = params.ccontrol.clone();
137
573
        match ccontrol.alg() {
138
375
            crate::ccparams::Algorithm::FixedWindow(_) => {}
139
            crate::ccparams::Algorithm::Vegas(_) => {
140
                // If the target doesn't support FLOWCTRL_CC, we can't use Vegas.
141
198
                if !caps.supports_named_subver(named::FLOWCTRL_CC) {
142
                    ccontrol.use_fallback_alg();
143
198
                }
144
            }
145
        };
146
573
        if hoptype == HopNegotiationType::None {
147
50
            ccontrol.use_fallback_alg();
148
523
        }
149
573
        let ccontrol = ccontrol; // drop mut
150

            
151
        // Negotiate CGO if it is supported, if CC is also supported,
152
        // and if CGO is available on this relay.
153
573
        let relay_crypt_protocol = match hoptype {
154
50
            HopNegotiationType::None => RelayCryptLayerProtocol::Tor1(RelayCellFormat::V0),
155
            HopNegotiationType::HsV3 => {
156
                cfg_if! {
157
                    if #[cfg(feature = "hs-common")] {
158
                        if ccontrol.alg().compatible_with_cgo() && caps.supports_named_subver(named::RELAY_CRYPT_CGO) {
159
                            RelayCryptLayerProtocol::Cgo
160
                        } else {
161
                            RelayCryptLayerProtocol::HsV3(RelayCellFormat::V0)
162
                        }
163
                    } else {
164
                        return Err(
165
                            tor_error::internal!("Unexpectedly tried to negotiate HsV3 without support!").into(),
166
                        );
167
                    }
168
                }
169
            }
170
            HopNegotiationType::Full => {
171
                #[allow(clippy::overly_complex_bool_expr)]
172
523
                if ccontrol.alg().compatible_with_cgo()
173
198
                    && caps.supports_named_subver(named::RELAY_NEGOTIATE_SUBPROTO)
174
                    && caps.supports_named_subver(named::RELAY_CRYPT_CGO)
175
                {
176
                    RelayCryptLayerProtocol::Cgo
177
                } else {
178
523
                    RelayCryptLayerProtocol::Tor1(RelayCellFormat::V0)
179
                }
180
            }
181
        };
182

            
183
573
        Ok(Self {
184
573
            ccontrol,
185
573
            flow_ctrl_params: params.flow_ctrl.clone(),
186
573
            relay_crypt_protocol,
187
573
            n_incoming_cells_permitted: params.n_incoming_cells_permitted,
188
573
            n_outgoing_cells_permitted: params.n_outgoing_cells_permitted,
189
573
        })
190
573
    }
191

            
192
    /// Build a [`HopSettings`] from the parameters requested during a circuit handshake.
193
    //
194
    // We disable `unused` warnings at the root of tor-proto,
195
    // but it's nice to have here so we re-enable it.
196
    #[warn(unused)]
197
    #[cfg(feature = "relay")]
198
8
    pub(crate) fn from_handshake_params(
199
8
        circ_net_params: CircNetParameters,
200
8
        cc_algorithm: AlgorithmDiscriminants,
201
8
        subprotos_requested: HandshakeSubprotocols,
202
8
    ) -> StdResult<Self, HandshakeParamsError> {
203
        // Unpack everything to make sure that we aren't missing anything
204
        // (otherwise clippy would warn).
205
        let CircNetParameters {
206
            cc:
207
                CongestionControlNetParams {
208
                    fixed_window,
209
                    vegas_exit,
210
                    cwnd,
211
                    rtt,
212
                    flow_ctrl,
213
                },
214
8
        } = circ_net_params;
215

            
216
8
        let HandshakeSubprotocols { relay_crypt_cgo } = subprotos_requested;
217

            
218
        // TODO: We have similar logic in and around `HopSettings` that deals with determining the
219
        // crypt protocol and cc algorithm to use. We might want to try to dedup some of this, or
220
        // make it more self-contained. This is a bit tricky though since the code is used in
221
        // different situations and the inputs are not the same.
222
8
        let (cc_algorithm, relay_crypt_protocol) = match (cc_algorithm, relay_crypt_cgo) {
223
8
            (AlgorithmDiscriminants::FixedWindow, false) => (
224
8
                Algorithm::FixedWindow(fixed_window),
225
8
                RelayCryptLayerProtocol::Tor1(RelayCellFormat::V0),
226
8
            ),
227
            (AlgorithmDiscriminants::FixedWindow, true) => {
228
                return Err(HandshakeParamsError::IncompatibleParams(
229
                    "requested CGO but not congestion control",
230
                ));
231
            }
232
            (AlgorithmDiscriminants::Vegas, false) => (
233
                Algorithm::Vegas(vegas_exit),
234
                RelayCryptLayerProtocol::Tor1(RelayCellFormat::V0),
235
            ),
236
            (AlgorithmDiscriminants::Vegas, true) => {
237
                (Algorithm::Vegas(vegas_exit), RelayCryptLayerProtocol::Cgo)
238
            }
239
        };
240

            
241
        // TODO(arti#2442): The builder pattern here seems like a footgun.
242
8
        let ccontrol = CongestionControlParams::builder()
243
8
            .alg(cc_algorithm)
244
8
            .fixed_window_params(fixed_window)
245
8
            .cwnd_params(cwnd)
246
8
            .rtt_params(rtt)
247
8
            .build()
248
8
            .map_err(into_internal!("Could not build `CongestionControlParams`"))?;
249

            
250
8
        Ok(Self {
251
8
            ccontrol,
252
8
            flow_ctrl_params: flow_ctrl,
253
8
            relay_crypt_protocol,
254
8
            n_incoming_cells_permitted: None,
255
8
            n_outgoing_cells_permitted: None,
256
8
        })
257
8
    }
258

            
259
    /// Return the negotiated relay crypto protocol.
260
631
    pub(crate) fn relay_crypt_protocol(&self) -> RelayCryptLayerProtocol {
261
631
        self.relay_crypt_protocol
262
631
    }
263

            
264
    /// Return the client circuit-creation extensions that we should use in order to negotiate
265
    /// these circuit hop parameters.
266
    #[allow(clippy::unnecessary_wraps)]
267
25
    pub(crate) fn circuit_request_extensions(&self) -> Result<Vec<CircRequestExt>> {
268
        // allow 'unused_mut' because of the combinations of `cfg` conditions below
269
        #[allow(unused_mut)]
270
25
        let mut client_extensions = Vec::new();
271

            
272
        #[allow(unused, unused_mut)]
273
25
        let mut cc_extension_set = false;
274

            
275
25
        if self.ccontrol.is_enabled() {
276
6
            client_extensions.push(CircRequestExt::CcRequest(CcRequest::default()));
277
6
            cc_extension_set = true;
278
19
        }
279

            
280
        // See whether we need to send a list of required protocol capabilities.
281
        // These aren't "negotiated" per se; they're simply demanded.
282
        // The relay will refuse the circuit if it doesn't support all of them,
283
        // and if any of them isn't supported in the SubprotocolRequest extension.
284
        //
285
        // (In other words, don't add capabilities here just because you want the
286
        // relay to have them! They must be explicitly listed as supported for use
287
        // with this extension. For the current list, see
288
        // https://spec.torproject.org/tor-spec/create-created-cells.html#subproto-request)
289
        //
290
        // TODO: Should this use `HandshakeSubprotocols` so that the above comment has some
291
        // compile-time checks?
292
        #[allow(unused_mut)]
293
25
        let mut required_protocol_capabilities: Vec<tor_protover::NamedSubver> = Vec::new();
294

            
295
25
        if matches!(self.relay_crypt_protocol(), RelayCryptLayerProtocol::Cgo) {
296
            if !cc_extension_set {
297
                return Err(tor_error::internal!("Tried to negotiate CGO without CC.").into());
298
            }
299
            required_protocol_capabilities.push(tor_protover::named::RELAY_CRYPT_CGO);
300
25
        }
301

            
302
25
        if !required_protocol_capabilities.is_empty() {
303
            client_extensions.push(CircRequestExt::SubprotocolRequest(
304
                required_protocol_capabilities.into_iter().collect(),
305
            ));
306
25
        }
307

            
308
25
        Ok(client_extensions)
309
25
    }
310
}
311

            
312
#[cfg(test)]
313
impl std::default::Default for CircParameters {
314
176
    fn default() -> Self {
315
176
        Self {
316
176
            extend_by_ed25519_id: true,
317
176
            ccontrol: crate::congestion::test_utils::params::build_cc_fixed_params(),
318
176
            flow_ctrl: FlowCtrlParameters::defaults_for_tests(),
319
176
            n_incoming_cells_permitted: None,
320
176
            n_outgoing_cells_permitted: None,
321
176
        }
322
176
    }
323
}
324

            
325
/// An error that can occur when building a [`HopSettings`] using parameters requested during a
326
/// circuit handshake.
327
#[derive(Clone, Debug, thiserror::Error)]
328
pub(crate) enum HandshakeParamsError {
329
    /// The provided parameters are incompatible with each other.
330
    #[error("The provided handshake parameters are incompatible with each other: {0}")]
331
    IncompatibleParams(&'static str),
332
    /// An internal error.
333
    #[error("Internal error")]
334
    Internal(#[from] tor_error::Bug),
335
}
336

            
337
impl HasKind for HandshakeParamsError {
338
    fn kind(&self) -> ErrorKind {
339
        match self {
340
            Self::IncompatibleParams(_) => ErrorKind::TorProtocolViolation,
341
            Self::Internal(_) => ErrorKind::Internal,
342
        }
343
    }
344
}
345

            
346
impl CircParameters {
347
    /// Constructor
348
708
    pub fn new(
349
708
        extend_by_ed25519_id: bool,
350
708
        ccontrol: CongestionControlParams,
351
708
        flow_ctrl: FlowCtrlParameters,
352
708
    ) -> Self {
353
708
        Self {
354
708
            extend_by_ed25519_id,
355
708
            ccontrol,
356
708
            flow_ctrl,
357
708
            n_incoming_cells_permitted: None,
358
708
            n_outgoing_cells_permitted: None,
359
708
        }
360
708
    }
361
}
362

            
363
/// Instructions for sending a RELAY cell.
364
///
365
/// This instructs a circuit reactor to send a RELAY cell to a given target
366
/// (a hop, if we are a client, or the client, if we are a relay).
367
#[derive(educe::Educe)]
368
#[educe(Debug)]
369
pub(crate) struct SendRelayCell {
370
    /// The hop number, or `None` if we are a relay.
371
    pub(crate) hop: Option<HopNum>,
372
    /// Whether to use a RELAY_EARLY cell.
373
    pub(crate) early: bool,
374
    /// The cell to send.
375
    pub(crate) cell: AnyRelayMsgOuter,
376
}
377

            
378
/// The inbound state of a hop.
379
pub(crate) struct CircHopInbound {
380
    /// Decodes relay cells received from this hop.
381
    decoder: RelayCellDecoder,
382
    /// Remaining permitted incoming relay cells from this hop, plus 1.
383
    ///
384
    /// (In other words, `None` represents no limit,
385
    /// `Some(1)` represents an exhausted limit,
386
    /// and `Some(n)` means that n-1 more cells may be received.)
387
    ///
388
    /// If this ever decrements from Some(1), then the circuit must be torn down with an error.
389
    n_incoming_cells_permitted: Option<NonZeroU32>,
390
}
391

            
392
/// The outbound state of a hop.
393
pub(crate) struct CircHopOutbound {
394
    /// Congestion control object.
395
    ///
396
    /// This object is also in charge of handling circuit level SENDME logic for this hop.
397
    ccontrol: Arc<Mutex<CongestionControl>>,
398
    /// Map from stream IDs to streams.
399
    ///
400
    /// We store this with the reactor instead of the circuit, since the
401
    /// reactor needs it for every incoming cell on a stream, whereas
402
    /// the circuit only needs it when allocating new streams.
403
    ///
404
    /// NOTE: this is behind a mutex because the client reactor polls the `StreamMap`s
405
    /// of all hops concurrently, in a `FuturesUnordered`. Without the mutex,
406
    /// this wouldn't be possible, because it would mean holding multiple
407
    /// mutable references to `self` (the reactor). Note, however,
408
    /// that there should never be any contention on this mutex:
409
    /// we never create more than one
410
    /// `CircHopList::ready_streams_iterator()` stream
411
    /// at a time, and we never clone/lock the hop's `StreamMap` outside of it.
412
    ///
413
    /// Additionally, the stream map of the last hop (join point) of a conflux tunnel
414
    /// is shared with all the circuits in the tunnel.
415
    map: Arc<Mutex<StreamMap>>,
416
    /// Format to use for relay cells.
417
    //
418
    // When we have packed/fragmented cells, this may be replaced by a RelayCellEncoder.
419
    relay_format: RelayCellFormat,
420
    /// Flow control parameters for new streams.
421
    flow_ctrl_params: Arc<FlowCtrlParameters>,
422
    /// Remaining permitted outgoing relay cells from this hop, plus 1.
423
    ///
424
    /// If this ever decrements from Some(1), then the circuit must be torn down with an error.
425
    n_outgoing_cells_permitted: Option<NonZeroU32>,
426
}
427

            
428
impl CircHopInbound {
429
    /// Create a new [`CircHopInbound`].
430
549
    pub(crate) fn new(decoder: RelayCellDecoder, settings: &HopSettings) -> Self {
431
549
        Self {
432
549
            decoder,
433
549
            n_incoming_cells_permitted: settings.n_incoming_cells_permitted.map(cvt),
434
549
        }
435
549
    }
436

            
437
    /// Parse a RELAY or RELAY_EARLY cell body.
438
    ///
439
    /// Requires that the cryptographic checks on the message have already been
440
    /// performed
441
278
    pub(crate) fn decode(&self, cell: BoxedCellBody) -> Result<RelayCellDecoderResult> {
442
278
        self.decoder
443
278
            .decode(cell)
444
            .map_err(|e| Error::from_bytes_err(e, "relay cell"))
445
278
    }
446

            
447
    /// Decrement the limit of inbound cells that may be received from this hop; give
448
    /// an error if it would reach zero.
449
278
    pub(crate) fn decrement_cell_limit(&mut self) -> Result<()> {
450
278
        try_decrement_cell_limit(&mut self.n_incoming_cells_permitted)
451
            .map_err(|_| Error::ExcessInboundCells)
452
278
    }
453
}
454

            
455
impl CircHopOutbound {
456
    /// Create a new [`CircHopOutbound`].
457
525
    pub(crate) fn new(
458
525
        ccontrol: Arc<Mutex<CongestionControl>>,
459
525
        relay_format: RelayCellFormat,
460
525
        flow_ctrl_params: Arc<FlowCtrlParameters>,
461
525
        settings: &HopSettings,
462
525
    ) -> Self {
463
525
        Self {
464
525
            ccontrol,
465
525
            map: Arc::new(Mutex::new(StreamMap::new())),
466
525
            relay_format,
467
525
            flow_ctrl_params,
468
525
            n_outgoing_cells_permitted: settings.n_outgoing_cells_permitted.map(cvt),
469
525
        }
470
525
    }
471

            
472
    /// Start a stream. Creates an entry in the stream map with the given channels, and sends the
473
    /// `message` to the provided hop.
474
48
    pub(crate) fn begin_stream(
475
48
        &mut self,
476
48
        hop: Option<HopNum>,
477
48
        message: AnyRelayMsg,
478
48
        time_prov: &DynTimeProvider,
479
48
        cmd_checker: AnyCmdChecker,
480
48
        memquota: &StreamAccount,
481
48
    ) -> Result<(SendRelayCell, StreamId, ReactorStreamComponents)> {
482
        // TODO: This has a lot of duplicated code with `Self::add_ent_with_id()`.
483

            
484
        // A channel for the reactor to inform the writer of a new rate limit.
485
48
        let (rate_limit_tx, rate_limit_rx) = watch::channel_with(StreamRateLimit::MAX);
486

            
487
        // A channel for the reactor to request a new drain rate from the reader.
488
        // Typically this notification will be sent after an XOFF is sent so that the reader can
489
        // send us a new drain rate when the stream data queue becomes empty.
490
48
        let mut drain_rate_request_tx = NotifySender::new_typed();
491
48
        let drain_rate_request_rx = drain_rate_request_tx.subscribe();
492

            
493
48
        let flow_ctrl = self.build_flow_ctrl(
494
48
            // We are starting the stream,
495
48
            // so we're a client and want flow control sidechannel mitigations.
496
48
            WithSidechannelMitigations::Enabled,
497
48
            rate_limit_tx,
498
48
            drain_rate_request_tx,
499
48
        );
500

            
501
48
        let stream_queue_max_len = flow_ctrl.inbound_queue_max_len();
502

            
503
        // A queue for inbound RELAY messages.
504
48
        let (sender, receiver) = stream_queue(stream_queue_max_len, memquota, time_prov)?;
505

            
506
        // A queue for outbound RELAY messages.
507
48
        let (msg_tx, msg_rx) = MpscSpec::new(CIRCUIT_BUFFER_SIZE)
508
48
            .new_mq(time_prov.clone(), memquota.as_raw_account())?;
509

            
510
48
        let r = self.map.lock().expect("lock poisoned").add_ent(
511
48
            sender,
512
48
            msg_rx,
513
48
            flow_ctrl,
514
48
            cmd_checker,
515
48
        )?;
516
48
        let cell = AnyRelayMsgOuter::new(Some(r), message);
517

            
518
48
        let stream_components = ReactorStreamComponents {
519
48
            stream_inbound_rx: receiver,
520
48
            stream_outbound_tx: msg_tx,
521
48
            rate_limit_rx,
522
48
            drain_rate_request_rx,
523
48
        };
524

            
525
48
        Ok((
526
48
            SendRelayCell {
527
48
                hop,
528
48
                early: false,
529
48
                cell,
530
48
            },
531
48
            r,
532
48
            stream_components,
533
48
        ))
534
48
    }
535

            
536
    /// Close the stream associated with `id` because the stream was dropped.
537
    ///
538
    /// If we have not already received an END cell on this stream, send one.
539
    /// If no END cell is specified, an END cell with the reason byte set to
540
    /// REASON_MISC will be sent.
541
    ///
542
    // Note(relay): `circ_uniq_id` is an opaque displayable type
543
    // because relays use a different circuit ID type
544
    // than clients. Eventually, we should probably make
545
    // them both use the same ID type, or have a nicer approach here
546
    #[allow(clippy::too_many_arguments)]
547
38
    pub(crate) fn close_stream(
548
38
        &mut self,
549
38
        circ_uniq_id: impl std::fmt::Display,
550
38
        circ_id: CircId,
551
38
        id: StreamId,
552
38
        hop: Option<HopNum>,
553
38
        message: CloseStreamBehavior,
554
38
        why: streammap::TerminateReason,
555
38
        expiry: Instant,
556
38
    ) -> Result<Option<SendRelayCell>> {
557
38
        let should_send_end = self
558
38
            .map
559
38
            .lock()
560
38
            .expect("lock poisoned")
561
38
            .terminate(id, why, expiry)?;
562
38
        trace!(
563
            circ_uniq_id = %circ_uniq_id,
564
            circ_id = %circ_id,
565
            stream_id = %id,
566
            should_send_end = ?should_send_end,
567
            "Ending stream",
568
        );
569
        // TODO: I am about 80% sure that we only send an END cell if
570
        // we didn't already get an END cell.  But I should double-check!
571
38
        let end_message = match should_send_end {
572
38
            ShouldSendEnd::Send => match message {
573
36
                CloseStreamBehavior::SendEnd(end_message) => end_message.into(),
574
2
                CloseStreamBehavior::SendResolved(resolved_message) => resolved_message.into(),
575
                CloseStreamBehavior::SendNothing => return Ok(None),
576
            },
577
            ShouldSendEnd::DontSend => return Ok(None),
578
        };
579

            
580
38
        let end_cell = AnyRelayMsgOuter::new(Some(id), end_message);
581
38
        let cell = SendRelayCell {
582
38
            hop,
583
38
            early: false,
584
38
            cell: end_cell,
585
38
        };
586

            
587
38
        Ok(Some(cell))
588
38
    }
589

            
590
    /// Check if we should send an XON message.
591
    ///
592
    /// If we should, then returns the XON message that should be sent.
593
    pub(crate) fn maybe_send_xon(
594
        &mut self,
595
        rate: XonKBpsEwma,
596
        id: StreamId,
597
    ) -> Result<Option<Xon>> {
598
        // the call below will return an error if XON/XOFF aren't supported,
599
        // so we check for support here
600
        if !self
601
            .ccontrol()
602
            .lock()
603
            .expect("poisoned lock")
604
            .uses_xon_xoff()
605
        {
606
            return Ok(None);
607
        }
608

            
609
        let mut map = self.map.lock().expect("lock poisoned");
610
        let Some(StreamEntMut::Open(ent)) = map.get_mut(id) else {
611
            // stream went away
612
            return Ok(None);
613
        };
614

            
615
        ent.maybe_send_xon(rate)
616
    }
617

            
618
    /// Check if we should send an XOFF message.
619
    ///
620
    /// If we should, then returns the XOFF message that should be sent.
621
110
    pub(crate) fn maybe_send_xoff(&mut self, id: StreamId) -> Result<Option<Xoff>> {
622
        // the call below will return an error if XON/XOFF aren't supported,
623
        // so we check for support here
624
110
        if !self
625
110
            .ccontrol()
626
110
            .lock()
627
110
            .expect("poisoned lock")
628
110
            .uses_xon_xoff()
629
        {
630
70
            return Ok(None);
631
40
        }
632

            
633
40
        let mut map = self.map.lock().expect("lock poisoned");
634
40
        let Some(StreamEntMut::Open(ent)) = map.get_mut(id) else {
635
            // stream went away
636
6
            return Ok(None);
637
        };
638

            
639
34
        ent.maybe_send_xoff()
640
110
    }
641

            
642
    /// Return the format that is used for relay cells sent to this hop.
643
    ///
644
    /// For the most part, this format isn't necessary to interact with a CircHop;
645
    /// it becomes relevant when we are deciding _what_ we can encode for the hop.
646
2377
    pub(crate) fn relay_cell_format(&self) -> RelayCellFormat {
647
2377
        self.relay_format
648
2377
    }
649

            
650
    /// Delegate to CongestionControl, for testing purposes
651
    #[cfg(test)]
652
10
    pub(crate) fn send_window_and_expected_tags(&self) -> (u32, Vec<SendmeTag>) {
653
10
        self.ccontrol()
654
10
            .lock()
655
10
            .expect("poisoned lock")
656
10
            .send_window_and_expected_tags()
657
10
    }
658

            
659
    /// Return the number of open streams on this hop.
660
    ///
661
    /// WARNING: because this locks the stream map mutex,
662
    /// it should never be called from a context where that mutex is already locked.
663
52
    pub(crate) fn n_open_streams(&self) -> usize {
664
52
        self.map.lock().expect("lock poisoned").n_open_streams()
665
52
    }
666

            
667
    /// Return a reference to our CongestionControl object.
668
13874
    pub(crate) fn ccontrol(&self) -> &Arc<Mutex<CongestionControl>> {
669
13874
        &self.ccontrol
670
13874
    }
671

            
672
    /// We're about to send `msg`.
673
    ///
674
    /// See [`OpenStreamEnt::about_to_send`](crate::streammap::OpenStreamEnt::about_to_send).
675
    //
676
    // TODO prop340: This should take a cell or similar, not a message.
677
    //
678
    // Note(relay): `circ_uniq_id` is an opaque displayable type
679
    // because relays use a different circuit ID type
680
    // than clients. Eventually, we should probably make
681
    // them both use the same ID type, or have a nicer approach here
682
2079
    pub(crate) fn about_to_send(
683
2079
        &mut self,
684
2079
        circ_uniq_id: impl std::fmt::Display,
685
2079
        circ_id: CircId,
686
2079
        stream_id: StreamId,
687
2079
        msg: &AnyRelayMsg,
688
2079
    ) -> Result<()> {
689
2079
        let mut hop_map = self.map.lock().expect("lock poisoned");
690
2079
        let Some(StreamEntMut::Open(ent)) = hop_map.get_mut(stream_id) else {
691
            // This can happen when we have outgoing data queued when we received an END.
692
            // We shouldn't return an error here since it would close the circuit along with all
693
            // other streams, and instead we just let the caller send this message anyways.
694
            // Also the caller only calls `about_to_send()` for DATA cells,
695
            // which means that other non-DATA cells don't hit this code path and are always sent,
696
            // and so we should handle all cell types consistently.
697
            // TODO: We should drop the message and not send it,
698
            // but the caller of `about_to_send()` isn't designed to handle fallible sends
699
            // so it would need some refactoring to handle this.
700
            debug!(
701
                circ_uniq_id = %circ_uniq_id,
702
                circ_id = %circ_id,
703
                stream_id = %stream_id,
704
                "sending a relay cell for non-existent or non-open stream!",
705
            );
706
            return Ok(());
707
        };
708

            
709
2079
        ent.about_to_send(msg)
710
2079
    }
711

            
712
    /// Add an entry to this map using the specified StreamId.
713
    #[cfg(any(feature = "hs-service", feature = "relay"))]
714
26
    pub(crate) fn add_ent_with_id(
715
26
        &self,
716
26
        time_prov: &DynTimeProvider,
717
26
        stream_id: StreamId,
718
26
        cmd_checker: AnyCmdChecker,
719
26
        with_sidechannel_mitigations: WithSidechannelMitigations,
720
26
        memquota: &StreamAccount,
721
26
    ) -> Result<ReactorStreamComponents> {
722
        // TODO: This has a lot of duplicated code with `Self::begin_stream()`.
723

            
724
        // A channel for the reactor to inform the writer of a new rate limit.
725
26
        let (rate_limit_tx, rate_limit_rx) = watch::channel_with(StreamRateLimit::MAX);
726

            
727
        // A channel for the reactor to request a new drain rate from the reader.
728
        // Typically this notification will be sent after an XOFF is sent so that the reader can
729
        // send us a new drain rate when the stream data queue becomes empty.
730
26
        let mut drain_rate_request_tx = NotifySender::new_typed();
731
26
        let drain_rate_request_rx = drain_rate_request_tx.subscribe();
732

            
733
26
        let flow_ctrl = self.build_flow_ctrl(
734
26
            with_sidechannel_mitigations,
735
26
            rate_limit_tx,
736
26
            drain_rate_request_tx,
737
26
        );
738

            
739
26
        let stream_queue_max_len = flow_ctrl.inbound_queue_max_len();
740

            
741
        // A queue for inbound RELAY messages.
742
26
        let (sender, receiver) = stream_queue(stream_queue_max_len, memquota, time_prov)?;
743

            
744
        // A queue for outbound RELAY messages.
745
26
        let (msg_tx, msg_rx) = MpscSpec::new(CIRCUIT_BUFFER_SIZE)
746
26
            .new_mq(time_prov.clone(), memquota.as_raw_account())?;
747

            
748
26
        let mut hop_map = self.map.lock().expect("lock poisoned");
749
26
        hop_map.add_ent_with_id(sender, msg_rx, flow_ctrl, stream_id, cmd_checker)?;
750

            
751
26
        Ok(ReactorStreamComponents {
752
26
            stream_inbound_rx: receiver,
753
26
            stream_outbound_tx: msg_tx,
754
26
            rate_limit_rx,
755
26
            drain_rate_request_rx,
756
26
        })
757
26
    }
758

            
759
    /// Builds the reactor's flow control handler for a new stream.
760
74
    fn build_flow_ctrl(
761
74
        &self,
762
74
        with_sidechannel_mitigations: WithSidechannelMitigations,
763
74
        rate_limit_updater: watch::Sender<StreamRateLimit>,
764
74
        drain_rate_requester: NotifySender<DrainRateRequest>,
765
74
    ) -> StreamFlowCtrl {
766
74
        let params = Arc::clone(&self.flow_ctrl_params);
767

            
768
74
        if self
769
74
            .ccontrol()
770
74
            .lock()
771
74
            .expect("poisoned lock")
772
74
            .uses_stream_sendme()
773
        {
774
60
            let window = sendme::StreamSendWindow::new(SEND_WINDOW_INIT);
775
60
            StreamFlowCtrl::new_window(window)
776
        } else {
777
14
            StreamFlowCtrl::new_xon_xoff(
778
14
                params,
779
14
                with_sidechannel_mitigations,
780
14
                rate_limit_updater,
781
14
                drain_rate_requester,
782
14
            )
783
        }
784
74
    }
785

            
786
    /// Deliver `msg` to the specified open stream entry `ent`.
787
108
    fn deliver_msg_to_stream(
788
108
        streamid: StreamId,
789
108
        ent: &mut OpenStreamEnt,
790
108
        cell_counts_toward_windows: bool,
791
108
        msg: UnparsedRelayMsg,
792
108
    ) -> Result<bool> {
793
        use tor_async_utils::SinkTrySend as _;
794
        use tor_async_utils::SinkTrySendError as _;
795

            
796
        // The stream for this message exists, and is open.
797

            
798
        // We need to handle SENDME/XON/XOFF messages here, not in the stream's recv() method, or
799
        // else we'd never notice them if the stream isn't reading.
800
108
        match msg.cmd() {
801
            RelayCmd::SENDME => {
802
2
                ent.put_for_incoming_sendme(msg)?;
803
2
                return Ok(false);
804
            }
805
            RelayCmd::XON => {
806
                ent.handle_incoming_xon(msg)?;
807
                return Ok(false);
808
            }
809
            RelayCmd::XOFF => {
810
                ent.handle_incoming_xoff(msg)?;
811
                return Ok(false);
812
            }
813
106
            _ => {}
814
        }
815

            
816
106
        let message_closes_stream = ent.cmd_checker.check_msg(&msg)? == StreamStatus::Closed;
817

            
818
106
        if let Err(e) = Pin::new(&mut ent.sink).try_send(msg) {
819
            if e.is_full() {
820
                return Err(internal!(
821
                    "Stream (ID {}) uses an unbounded queue, but apparently it's full?",
822
                    sv(streamid),
823
                )
824
                .into());
825
            }
826
            if e.is_disconnected() && cell_counts_toward_windows {
827
                // the other side of the stream has gone away; remember
828
                // that we received a cell that we couldn't queue for it.
829
                //
830
                // Later this value will be recorded in a half-stream.
831
                ent.dropped += 1;
832
            }
833
106
        }
834

            
835
106
        Ok(message_closes_stream)
836
108
    }
837

            
838
    /// Note that we received an END message (or other message indicating the end of
839
    /// the stream) on the stream with `id`.
840
    ///
841
    /// See [`StreamMap::ending_msg_received`](crate::streammap::StreamMap::ending_msg_received).
842
    #[cfg(feature = "hs-service")]
843
    pub(crate) fn ending_msg_received(&self, stream_id: StreamId) -> Result<()> {
844
        let mut hop_map = self.map.lock().expect("lock poisoned");
845

            
846
        hop_map.ending_msg_received(stream_id)?;
847

            
848
        Ok(())
849
    }
850

            
851
    /// Handle `msg`, delivering it to the stream with the specified `streamid` if appropriate.
852
    ///
853
    /// Returns back the provided `msg`, if the message is an incoming stream request
854
    /// that needs to be handled by the calling code.
855
    ///
856
    // TODO: the above is a bit of a code smell -- we should try to avoid passing the msg
857
    // back and forth like this.
858
148
    pub(crate) fn handle_msg<F>(
859
148
        &self,
860
148
        possible_proto_violation_err: F,
861
148
        cell_counts_toward_windows: bool,
862
148
        streamid: StreamId,
863
148
        msg: UnparsedRelayMsg,
864
148
        now: Instant,
865
148
    ) -> Result<Option<UnparsedRelayMsg>>
866
148
    where
867
148
        F: FnOnce(StreamId) -> Error,
868
    {
869
148
        let mut hop_map = self.map.lock().expect("lock poisoned");
870

            
871
148
        match hop_map.get_mut(streamid) {
872
            Some(StreamEntMut::Open(ent)) => {
873
                let message_closes_stream =
874
108
                    Self::deliver_msg_to_stream(streamid, ent, cell_counts_toward_windows, msg)?;
875

            
876
108
                if message_closes_stream {
877
12
                    hop_map.ending_msg_received(streamid)?;
878
96
                }
879
            }
880
10
            Some(StreamEntMut::EndSent(EndSentStreamEnt { expiry, .. })) if now >= *expiry => {
881
2
                return Err(possible_proto_violation_err(streamid));
882
            }
883
            Some(StreamEntMut::EndSent(_))
884
8
                if matches!(
885
8
                    msg.cmd(),
886
                    RelayCmd::BEGIN | RelayCmd::BEGIN_DIR | RelayCmd::RESOLVE
887
                ) =>
888
            {
889
                // If the other side is sending us a BEGIN but hasn't yet acknowledged our END
890
                // message, just remove the old stream from the map and stop waiting for a
891
                // response
892
6
                hop_map.ending_msg_received(streamid)?;
893
6
                return Ok(Some(msg));
894
            }
895
            Some(StreamEntMut::EndSent(EndSentStreamEnt { half_stream, .. })) => {
896
                // We sent an end but maybe the other side hasn't heard.
897

            
898
2
                match half_stream.handle_msg(msg)? {
899
2
                    StreamStatus::Open => {}
900
                    StreamStatus::Closed => {
901
                        hop_map.ending_msg_received(streamid)?;
902
                    }
903
                }
904
            }
905
30
            None if matches!(
906
30
                msg.cmd(),
907
                RelayCmd::BEGIN | RelayCmd::BEGIN_DIR | RelayCmd::RESOLVE
908
            ) =>
909
            {
910
28
                return Ok(Some(msg));
911
            }
912
            _ => {
913
                // No stream wants this message, or ever did.
914
2
                return Err(possible_proto_violation_err(streamid));
915
            }
916
        }
917

            
918
110
        Ok(None)
919
148
    }
920

            
921
    /// Get the stream map of this hop.
922
19835
    pub(crate) fn stream_map(&self) -> &Arc<Mutex<StreamMap>> {
923
19835
        &self.map
924
19835
    }
925

            
926
    /// Set the stream map of this hop to `map`.
927
    ///
928
    /// Returns an error if the existing stream map of the hop has any open stream.
929
52
    pub(crate) fn set_stream_map(&mut self, map: Arc<Mutex<StreamMap>>) -> StdResult<(), Bug> {
930
52
        if self.n_open_streams() != 0 {
931
            return Err(internal!("Tried to discard existing open streams?!"));
932
52
        }
933

            
934
52
        self.map = map;
935

            
936
52
        Ok(())
937
52
    }
938

            
939
    /// Decrement the limit of outbound cells that may be sent to this hop; give
940
    /// an error if it would reach zero.
941
2303
    pub(crate) fn decrement_cell_limit(&mut self) -> Result<()> {
942
2303
        try_decrement_cell_limit(&mut self.n_outgoing_cells_permitted)
943
            .map_err(|_| Error::ExcessOutboundCells)
944
2303
    }
945
}
946

            
947
/// If `val` is `Some(1)`, return Err(());
948
/// otherwise decrement it (if it is Some) and return Ok(()).
949
#[inline]
950
2581
fn try_decrement_cell_limit(val: &mut Option<NonZeroU32>) -> StdResult<(), ()> {
951
    // This is a bit verbose, but I've confirmed that it optimizes nicely.
952
2581
    match val {
953
        Some(x) => {
954
            let z = u32::from(*x);
955
            if z == 1 {
956
                Err(())
957
            } else {
958
                *x = (z - 1).try_into().expect("NonZeroU32 was zero?!");
959
                Ok(())
960
            }
961
        }
962
2581
        None => Ok(()),
963
    }
964
2581
}
965

            
966
/// Convert a limit from the form used in a HopSettings to that used here.
967
/// (The format we use here is more compact.)
968
fn cvt(limit: u32) -> NonZeroU32 {
969
    // See "known limitations" comment on n_incoming_cells_permitted.
970
    limit
971
        .saturating_add(1)
972
        .try_into()
973
        .expect("Adding one left it as zero?")
974
}
975

            
976
/// A collection of components that can be used to interact with the reactor's view of a Tor stream.
977
//
978
// TODO: We also have a `StreamComponents` type that is used and built outside of the reactor.
979
// It's maybe confusing to have these similar type names, so a better name would be nice.
980
//
981
// TODO(arti#2068): The components we return should maybe depend on what type of flow control is
982
// used, so in the future we might want to make some of these fields optional.
983
#[derive(Debug, Deftly)]
984
#[derive_deftly(HasMemoryCost)]
985
pub(crate) struct ReactorStreamComponents {
986
    /// An MPSC receiver for inbound messages that arrive on the stream.
987
    #[deftly(has_memory_cost(indirect_size = "0"))] // estimate
988
    pub(crate) stream_inbound_rx: StreamQueueReceiver,
989

            
990
    /// An MPSC sender for outbound messages to be sent on the stream.
991
    #[deftly(has_memory_cost(indirect_size = "size_of::<AnyRelayMsg>()"))] // estimate
992
    pub(crate) stream_outbound_tx: StreamMpscSender<AnyRelayMsg>,
993

            
994
    /// A mechanism to allow the stream's writer to receive rate limit updates from the reactor.
995
    // The `watch::Sender` owns the indirect data.
996
    #[deftly(has_memory_cost(indirect_size = "0"))]
997
    pub(crate) rate_limit_rx: watch::Receiver<StreamRateLimit>,
998

            
999
    /// A mechanism to allow the stream's reader to receive drain rate update requests from the
    /// reactor.
    #[deftly(has_memory_cost(indirect_size = "0"))]
    pub(crate) drain_rate_request_rx: NotifyReceiver<DrainRateRequest>,
}