1
//! Channel for sending messages to [`StreamReactor`].
2

            
3
// TODO(DEDUP): this will replace CircHopList when we rewrite the client reactor
4
// to use the new reactor architecture
5
mod circhop;
6

            
7
use crate::circuit::UniqId;
8
use crate::circuit::circhop::{CircHopOutbound, HopSettings};
9
use crate::circuit::metrics::CircuitMetrics;
10
use crate::circuit::reactor::stream::{CtrlMsg, ReadyStreamMsg, StreamHandler, StreamReactor};
11
use crate::congestion::{CongestionControl, CongestionSignals};
12
use crate::crypto::cell::RelayCellBody;
13
use crate::memquota::CircuitAccount;
14
use crate::util::err::ReactorError;
15
use crate::{Error, HopNum, Result};
16
use circhop::CircHopList;
17

            
18
#[cfg(any(feature = "hs-service", feature = "relay"))]
19
use {
20
    crate::stream::CloseStreamBehavior, crate::stream::incoming::IncomingStreamRequestHandler,
21
    tor_cell::relaycell::StreamId,
22
};
23

            
24
use tor_cell::chancell::CircId;
25
use tor_cell::relaycell::msg::{Sendme, SendmeTag};
26
use tor_cell::relaycell::{AnyRelayMsgOuter, RelayCellDecoderResult, RelayCellFormat};
27
use tor_error::internal;
28
use tor_rtcompat::{DynTimeProvider, Runtime};
29

            
30
use futures::SinkExt;
31
use futures::channel::mpsc;
32

            
33
use std::result::Result as StdResult;
34
use std::sync::{Arc, Mutex, RwLock};
35

            
36
/// The state of a circuit.
37
///
38
/// This contains the per-hop state (e.g. congestion control information),
39
/// and a handle to the stream reactor of the hop.
40
///
41
/// The stream reactor of the hop is launched lazily,
42
/// when the first [`CtrlMsg`] is sent via [`CircuitState::send`].
43
///
44
/// This is owned by the decrypting reactor.
45
pub(crate) struct CircuitState<R: Runtime> {
46
    /// A handle to the runtime.
47
    runtime: R,
48
    /// Context used when spawning a stream reactor.
49
    ctx: StreamReactorContext,
50
    /// Sender for sending messages to the encrypting reactor.
51
    ///
52
    /// The receiver is in encrypting reactor.
53
    ///
54
    /// A clone of this is passed to each spawned StreamReactor
55
    enc_tx: mpsc::Sender<ReadyStreamMsg>,
56
    /// The shared parts of the circuit state.
57
    ///
58
    /// The encrypting reactor has a clone of this.
59
    shared: Arc<CircuitStateShared>,
60
    /// Memory quota account
61
    memquota: CircuitAccount,
62
}
63

            
64
/// The shared parts of a [`CircuitState`].
65
///
66
/// Currently, this is used by the encrypting reactor,
67
/// which needs access to the congestion control objects.
68
/// The encrypting reactor only ever *reads* from this
69
/// (it never mutates the circ hop list).
70
pub(crate) struct CircuitStateShared {
71
    /// The underlying senders, indexed by [`HopNum`].
72
    ///
73
    /// Relays have at most one stream reactor per circuit.
74
    /// Clients have at most one stream reactor per circuit hop.
75
    hops: RwLock<CircHopList>,
76
}
77

            
78
impl CircuitStateShared {
79
    /// Return the RelayCellFormat and CC state of a given hop.
80
6
    pub(crate) fn hop_info(
81
6
        &self,
82
6
        hopnum: Option<HopNum>,
83
6
    ) -> Result<(RelayCellFormat, Arc<Mutex<CongestionControl>>)> {
84
6
        let hops = self.hops.read().expect("poisoned lock");
85
6
        let hop = hops.get(hopnum)?;
86
6
        let relay_cell_format = hop.settings.relay_crypt_protocol().relay_cell_format();
87
6
        let ccontrol = Arc::clone(&hop.ccontrol);
88

            
89
6
        Ok((relay_cell_format, ccontrol))
90
6
    }
91

            
92
    /// Update the congestion control state of the specified hop
93
    /// that we received a SENDME along with possible congestion signals.
94
    pub(crate) fn note_sendme_received(
95
        &self,
96
        hopnum: Option<HopNum>,
97
        runtime: &DynTimeProvider,
98
        tag: SendmeTag,
99
        signals: CongestionSignals,
100
    ) -> Result<()> {
101
        let hops = self.hops.read().expect("poisoned lock");
102
        let hop = hops.get(hopnum)?;
103

            
104
        // Update the CC object that we received a SENDME along
105
        // with possible congestion signals.
106
        hop.ccontrol
107
            .lock()
108
            .expect("poisoned lock")
109
            .note_sendme_received(runtime, tag, signals)?;
110

            
111
        Ok(())
112
    }
113

            
114
    /// Try to parse a RELAY or RELAY_EARLY cell body.
115
    ///
116
    /// Relays pass `None` for the hopnum.
117
28
    pub(crate) fn decode(
118
28
        &self,
119
28
        hopnum: Option<HopNum>,
120
28
        body: RelayCellBody,
121
28
    ) -> Result<RelayCellDecoderResult> {
122
28
        let hops = self.hops.read().expect("poisoned lock");
123
28
        hops.get(hopnum)?.inbound.decode(body.into())
124
28
    }
125

            
126
    /// Note that we have received a RELAY cell.
127
    ///
128
    /// Returns whether we need to send back a SENDME.
129
    ///
130
    /// Updates the padding and CC state.
131
28
    pub(crate) fn note_relay_cell_received(
132
28
        &self,
133
28
        hopnum: Option<HopNum>,
134
28
        c_t_w: bool,
135
28
        tag: SendmeTag,
136
28
    ) -> Result<Option<AnyRelayMsgOuter>> {
137
28
        let mut hops = self.hops.write().expect("poisoned lock");
138
28
        let hop = hops.get_mut(hopnum)?;
139

            
140
        // Check whether we are allowed to receive more data for this circuit hop.
141
28
        hop.inbound.decrement_cell_limit()?;
142

            
143
        // Decrement the circuit sendme windows, and see if we need to
144
        // send a sendme cell.
145
28
        let send_circ_sendme = if c_t_w {
146
4
            hop.ccontrol
147
4
                .lock()
148
4
                .expect("poisoned lock")
149
4
                .note_data_received()?
150
        } else {
151
24
            false
152
        };
153

            
154
        // If we do need to send a circuit-level SENDME cell, do so.
155
28
        if send_circ_sendme {
156
            // This always sends a V1 (tagged) sendme cell, and thereby assumes
157
            // that SendmeEmitMinVersion is no more than 1.  If the authorities
158
            // every increase that parameter to a higher number, this will
159
            // become incorrect.  (Higher numbers are not currently defined.)
160
            let sendme = Sendme::from(tag);
161
            Ok(Some(AnyRelayMsgOuter::new(None, sendme.into())))
162
        } else {
163
28
            Ok(None)
164
        }
165
28
    }
166
}
167

            
168
/// State needed to build a stream reactor.
169
///
170
/// Used when spawning the stream reactor of a hop.
171
struct StreamReactorContext {
172
    /// An identifier for logging about this reactor's circuit.
173
    unique_id: UniqId,
174
    /// The circuit identifier on the inbound Tor channel.
175
    circ_id: CircId,
176
    /// The incoming stream handler.
177
    ///
178
    /// This is shared with every StreamReactor.
179
    #[cfg(any(feature = "hs-service", feature = "relay"))]
180
    incoming: Arc<Mutex<Option<IncomingStreamRequestHandler>>>,
181
    /// A handler for customizing the stream reactor behavior.
182
    handler: Arc<dyn StreamHandler>,
183
    /// The circuit metrics.
184
    metrics: Arc<CircuitMetrics>,
185
}
186

            
187
impl<R: Runtime> CircuitState<R> {
188
    /// Create a new [`CircuitState`] consisting of a single CircHop
189
    /// (built using the specified `settings),
190
    /// setting the incoming stream request handler to `incoming_handler`.
191
    #[cfg(feature = "relay")]
192
    #[allow(clippy::too_many_arguments)] // this is an internal function with 1 call site
193
32
    pub(crate) fn new_relay<S: StreamHandler>(
194
32
        runtime: R,
195
32
        settings: HopSettings,
196
32
        unique_id: UniqId,
197
32
        circ_id: CircId,
198
32
        handler: S,
199
32
        enc_tx: mpsc::Sender<ReadyStreamMsg>,
200
32
        incoming_handler: IncomingStreamRequestHandler,
201
32
        memquota: CircuitAccount,
202
32
        metrics: Arc<CircuitMetrics>,
203
32
    ) -> Self {
204
32
        let hops = CircHopList::new_relay(settings);
205

            
206
32
        Self::new_inner(
207
32
            runtime,
208
32
            hops,
209
32
            unique_id,
210
32
            circ_id,
211
32
            handler,
212
32
            enc_tx,
213
32
            Some(incoming_handler),
214
32
            memquota,
215
32
            metrics,
216
32
        )
217
32
    }
218

            
219
    /// Create a new [`CircuitState`] with an empty hop list.
220
    ///
221
    /// Hops are added with [`CircuitState::add_hop`].
222
    #[expect(unused)] // TODO(dedup): clients will use this
223
    pub(crate) fn new_client<S: StreamHandler>(
224
        runtime: R,
225
        unique_id: UniqId,
226
        circ_id: CircId,
227
        handler: S,
228
        enc_tx: mpsc::Sender<ReadyStreamMsg>,
229
        memquota: CircuitAccount,
230
        metrics: Arc<CircuitMetrics>,
231
    ) -> Self {
232
        let hops = CircHopList::new_client();
233
        Self::new_inner(
234
            runtime,
235
            hops,
236
            unique_id,
237
            circ_id,
238
            handler,
239
            enc_tx,
240
            #[cfg(any(feature = "hs-service", feature = "relay"))]
241
            None,
242
            memquota,
243
            metrics,
244
        )
245
    }
246

            
247
    /// Helper for the new*() functions.
248
    #[allow(clippy::too_many_arguments)] // this is an internal function with 2 call sites
249
32
    fn new_inner<S: StreamHandler>(
250
32
        runtime: R,
251
32
        hops: CircHopList,
252
32
        unique_id: UniqId,
253
32
        circ_id: CircId,
254
32
        handler: S,
255
32
        enc_tx: mpsc::Sender<ReadyStreamMsg>,
256
32
        #[cfg(any(feature = "hs-service", feature = "relay"))] incoming_handler: Option<
257
32
            IncomingStreamRequestHandler,
258
32
        >,
259
32
        memquota: CircuitAccount,
260
32
        metrics: Arc<CircuitMetrics>,
261
32
    ) -> Self {
262
32
        let hops = RwLock::new(hops);
263
32
        let ctx = StreamReactorContext {
264
32
            unique_id,
265
32
            circ_id,
266
32
            #[cfg(any(feature = "hs-service", feature = "relay"))]
267
32
            incoming: Arc::new(Mutex::new(incoming_handler)),
268
32
            handler: Arc::new(handler),
269
32
            metrics,
270
32
        };
271

            
272
32
        let shared = Arc::new(CircuitStateShared { hops });
273

            
274
32
        Self {
275
32
            runtime,
276
32
            shared,
277
32
            ctx,
278
32
            enc_tx,
279
32
            memquota,
280
32
        }
281
32
    }
282

            
283
    /// Return a reference to our shared state.
284
88
    pub(crate) fn shared(&self) -> &Arc<CircuitStateShared> {
285
88
        &self.shared
286
88
    }
287

            
288
    /// Set the incoming stream handler for this reactor.
289
    ///
290
    /// There can only be one incoming stream handler per reactor,
291
    /// and each stream handler only pertains to a single hop (see expected_hop())
292
    //
293
    // TODO: eventually, we might want a different design here,
294
    // for example we might want to allow multiple stream handlers per reactor (one per hop).
295
    // However, for now, the implementation is intentionally kept similar to that
296
    // in the client reactor (to make it easier to migrate it to the new reactor design).
297
    //
298
    /// Returns an error if a stream handler was already installed.
299
    ///
300
    /// Since the handler is shared with every hop's stream reactor,
301
    /// this function will update the handler for all of them.
302
    ///
303
    // TODO(DEDUP): almost identical to the client-side
304
    // CellHandlers::set_incoming_stream_req_handler()
305
    #[cfg(any(feature = "hs-service", feature = "relay"))]
306
    pub(crate) fn set_incoming_handler(&self, handler: IncomingStreamRequestHandler) -> Result<()> {
307
        let mut lock = self.ctx.incoming.lock().expect("poisoned lock");
308

            
309
        if lock.is_none() {
310
            *lock = Some(handler);
311
            Ok(())
312
        } else {
313
            Err(Error::from(internal!(
314
                "Tried to install a BEGIN cell handler before the old one was gone."
315
            )))
316
        }
317
    }
318

            
319
    /// Push a new hop to our hop list.
320
    ///
321
    /// Prepares a cc object for the hop, but does not spawn a stream reactor.
322
    ///
323
    /// Will return an error if the circuit already has [`u8::MAX`] hops.
324
    #[expect(unused)] // TODO(dedup): clients will use this
325
    pub(crate) fn add_hop(&mut self, settings: HopSettings) -> Result<()> {
326
        let mut hops = self.shared.hops.write().expect("poisoned lock");
327
        hops.add_hop(settings)
328
    }
329

            
330
    /// Send a message to the stream reactor of the specified `hop`,
331
    /// spawning it if necessary.
332
14
    pub(crate) async fn send(
333
14
        &mut self,
334
14
        hopnum: Option<HopNum>,
335
14
        msg: CtrlMsg,
336
14
    ) -> StdResult<(), ReactorError> {
337
14
        let mut tx = self.get_or_spawn_stream_reactor(hopnum)?;
338

            
339
14
        tx.send(msg).await.map_err(|_| {
340
            // The stream reactor has shut down
341
            ReactorError::Shutdown
342
        })
343
13
    }
344

            
345
    /// Tell the stream reactor of the specified `hop`
346
    /// to close the stream with the specified `stream_id`.
347
    #[cfg(any(feature = "hs-service", feature = "relay"))]
348
4
    pub(crate) async fn close_pending(
349
4
        &mut self,
350
4
        hopnum: Option<HopNum>,
351
4
        stream_id: StreamId,
352
4
        behav: CloseStreamBehavior,
353
4
    ) -> StdResult<(), Error> {
354
4
        let mut tx = self.get_or_spawn_stream_reactor(hopnum)?;
355

            
356
4
        let msg = CtrlMsg::ClosePendingStream { stream_id, behav };
357

            
358
4
        tx.send(msg).await.map_err(|_| {
359
            // The stream reactor has shut down
360
            Error::NotConnected
361
        })
362
4
    }
363

            
364
    /// Get a handle to the stream reactor, spawning it if necessary
365
18
    fn get_or_spawn_stream_reactor(
366
18
        &self,
367
18
        hopnum: Option<HopNum>,
368
18
    ) -> StdResult<mpsc::Sender<CtrlMsg>, Error> {
369
18
        let mut hops = self.shared.hops.write().expect("poisoned lock");
370
18
        let hop = hops.get_mut(hopnum)?;
371

            
372
18
        let tx = match &hop.tx {
373
10
            Some(tx) => tx.clone(),
374
            None => {
375
                // If we don't have a handle to the stream reactor,
376
                // it means it hasn't been spawned yet, so we have to spawn it now.
377
                let tx =
378
8
                    self.spawn_stream_reactor(hopnum, &hop.settings, Arc::clone(&hop.ccontrol))?;
379

            
380
8
                hop.tx = Some(tx.clone());
381

            
382
                // Return a copy of this sender (can't borrow because the hop
383
                // is behind a Mutex, and we can't keep it locked across the send()
384
                // await point)
385
8
                tx
386
            }
387
        };
388

            
389
18
        Ok(tx)
390
18
    }
391

            
392
    /// Spawn a [`StreamReactor`] for the specified hop.
393
8
    fn spawn_stream_reactor(
394
8
        &self,
395
8
        hopnum: Option<HopNum>,
396
8
        settings: &HopSettings,
397
8
        ccontrol: Arc<Mutex<CongestionControl>>,
398
8
    ) -> StdResult<mpsc::Sender<CtrlMsg>, Error> {
399
        use tor_rtcompat::SpawnExt as _;
400

            
401
        // NOTE: not registering this channel with the memquota subsystem is okay,
402
        // because it has no buffering (if ever decide to make the size of this buffer
403
        // non-zero for whatever reason, we must remember to register it with memquota
404
        // so that it counts towards the total memory usage for the circuit.
405
        //
406
        // NOTE: We should be careful about the effect of buffering on flow control.
407
        // See comments on `StreamReactor::cell_rx` about XON/XOFF flow control.
408
        //
409
        // TODO(tuning): having zero buffering here is very likely suboptimal.
410
        // We should do *some* buffering here, and then figure out if we should it
411
        // up to memquota or not.
412
        #[allow(clippy::disallowed_methods)]
413
8
        let (dec_stream_tx, dec_stream_rx) = mpsc::channel(0);
414

            
415
8
        let flow_ctrl_params = Arc::new(settings.flow_ctrl_params.clone());
416
8
        let relay_format = settings.relay_crypt_protocol().relay_cell_format();
417
8
        let outbound = CircHopOutbound::new(ccontrol, relay_format, flow_ctrl_params, settings);
418

            
419
8
        let stream_reactor = StreamReactor::new(
420
8
            self.runtime.clone(),
421
8
            hopnum,
422
8
            outbound,
423
8
            self.ctx.unique_id,
424
8
            self.ctx.circ_id,
425
8
            dec_stream_rx,
426
8
            self.enc_tx.clone(),
427
8
            Arc::clone(&self.ctx.handler),
428
8
            #[cfg(any(feature = "hs-service", feature = "relay"))]
429
8
            Arc::clone(&self.ctx.incoming),
430
8
            self.memquota.clone(),
431
8
            Arc::clone(&self.ctx.metrics),
432
8
        );
433

            
434
8
        self.runtime
435
8
            .spawn(async {
436
8
                let _ = stream_reactor.run().await;
437
8
            })
438
            .map_err(|e| Error::Spawn {
439
                spawning: "stream reactor",
440
                cause: e.into(),
441
            })?;
442

            
443
8
        Ok(dec_stream_tx)
444
8
    }
445
}