1
//! A circuit's view of the backward state of the circuit.
2

            
3
use crate::channel::Channel;
4
use crate::circuit::UniqId;
5
use crate::circuit::cell_sender::CircuitCellSender;
6
use crate::circuit::metrics::CircuitMetrics;
7
use crate::circuit::reactor::ControlHandler;
8
use crate::circuit::reactor::circ_state::CircuitStateShared;
9
use crate::circuit::reactor::macros::derive_deftly_template_CircuitReactor;
10
use crate::circuit::reactor::stream::ReadyStreamMsg;
11
use crate::congestion::{CongestionControl, sendme};
12
use crate::crypto::cell::RelayCellBody;
13
use crate::util::err::ReactorError;
14
use crate::util::poll_all::PollAll;
15
use crate::{Error, HopNum, Result};
16

            
17
// TODO(circpad): once padding is stabilized, the padding module will be moved out of client.
18
use crate::client::circuit::padding::{
19
    self, PaddingController, PaddingEvent, PaddingEventStream, QueuedCellPaddingInfo,
20
};
21

            
22
use tor_cell::chancell::msg::{AnyChanMsg, Relay};
23
use tor_cell::chancell::{AnyChanCell, BoxedCellBody, ChanCmd, CircId};
24
use tor_cell::relaycell::msg::{Sendme, SendmeTag};
25
use tor_cell::relaycell::{AnyRelayMsgOuter, RelayCellFormat, RelayCmd, StreamId};
26
use tor_rtcompat::{DynTimeProvider, Runtime};
27

            
28
use derive_deftly::Deftly;
29
use futures::SinkExt;
30
use futures::channel::mpsc;
31
use futures::{FutureExt as _, StreamExt, future, select_biased};
32
use tracing::{debug, trace};
33

            
34
use std::pin::Pin;
35
use std::result::Result as StdResult;
36
use std::sync::{Arc, Mutex};
37

            
38
use crate::circuit::CircuitRxReceiver;
39

            
40
#[cfg(feature = "circ-padding")]
41
use crate::circuit::padding::{CircPaddingDisposition, padding_disposition};
42

            
43
#[cfg(feature = "relay")]
44
use tor_cell::relaycell::msg::Extended2;
45

            
46
/// The "backward" circuit reactor of a relay.
47
///
48
/// See the [`reactor`](crate::circuit::reactor) module-level docs.
49
///
50
/// Shuts downs down if an error occurs, or if the [`Reactor`](super::Reactor),
51
/// [`DecryptingReactor`](super::DecryptingReactor), or if one of the
52
/// [`StreamReactor`](super::stream::StreamReactor)s of this circuit shuts down:
53
///
54
///   * if the `Reactor` shuts down, we are alerted via the ctrl/command mpsc channels
55
///     (their sending ends will close, which causes run_once() to return ReactorError::Shutdown)
56
///   * if `DecryptingReactor` shuts down, the `Reactor` will notice and will itself shut down,
57
///     which, in turn, causes the `EncryptingReactor` to shut down as described above
58
///   * if one of the `StreamReactor`s shuts down, the `DecryptingReactor` will
59
///     notice when it next tries to deliver a stream message to it, and shut down,
60
///     causing the `EncryptingReactor` and top-level `Reactor` to follow suit
61
#[derive(Deftly)]
62
#[derive_deftly(CircuitReactor)]
63
#[deftly(reactor_name = "encrypting reactor")]
64
#[deftly(run_inner_fn = "Self::run_once")]
65
#[must_use = "If you don't call run() on a reactor, the circuit won't work."]
66
pub(super) struct EncryptingReactor<E: EncryptingReactorInner> {
67
    /// The time provider.
68
    time_provider: DynTimeProvider,
69
    /// An identifier for logging about this reactor's circuit.
70
    unique_id: UniqId,
71
    /// The circuit identifier on the backward Tor channel.
72
    circ_id: CircId,
73
    /// The inbound Tor channel.
74
    channel: Arc<Channel>,
75
    /// Implementation-dependent part of the reactor.
76
    ///
77
    /// This enables us to customize the behavior of the reactor,
78
    /// depending on whether we are a client or a relay.
79
    inner: E,
80
    /// The reading end of the outbound Tor channel, if we are not the last hop.
81
    ///
82
    /// Yields cells moving from the exit towards the client, if we are a middle relay.
83
    outbound_chan_rx: Option<CircuitRxReceiver>,
84
    /// The per-hop state, shared with the decrypting reactor.
85
    ///
86
    /// The encrypting reactor acquires a read lock to this whenever it needs to
87
    ///
88
    ///   * send a circuit-level SENDME
89
    ///   * handle a circuit-level SENDME
90
    ///   * send a padding cell
91
    ///
92
    // Note: For the sending/handling of SENDMEs, we lock the hop list
93
    // to extract the relay cell format and CC state of the hop.
94
    // Technically, for the SENDME cases, we could've avoided locking
95
    // the hop list from the ENC, by having the DEC share the relay cell format
96
    // and CC state in the EncryptingReactorCmd::{Send,Handle}Sendme command.
97
    // But for the padding case, we *need* the hop list, because we need
98
    // to work out what relay cell format to use when sending the padding cell.
99
    // But for the sake of simplicity, I made the ENC consult the CircHopList in all cases.
100
    shared: Arc<CircuitStateShared>,
101
    /// The sending end of the backward Tor channel.
102
    ///
103
    /// Delivers cells towards the other endpoint: towards the client, if we are a relay,
104
    /// or towards the exit, if we are a client.
105
    inbound_chan_tx: CircuitCellSender,
106
    /// Channel for receiving control commands.
107
    command_rx: mpsc::UnboundedReceiver<CtrlCmd<E::CtrlCmd>>,
108
    /// Channel for receiving control messages.
109
    control_rx: mpsc::UnboundedReceiver<CtrlMsg<E::CtrlMsg>>,
110
    /// Receiver for [`EncryptingReactorCmd`]s coming from the decrypting reactor.
111
    ///
112
    /// The sender is in [`DecryptingReactor`](super::DecryptingReactor), which will forward all cells
113
    /// carrying Tor stream data to us.
114
    ///
115
    /// This serves a dual purpose:
116
    ///
117
    ///   * it enables the `DecryptingReactor` to deliver Tor stream data received
118
    ///     from the other endpoint
119
    ///   * it lets the `EncryptingReactor` know if the `DecryptingReactor` has shut down:
120
    ///     we select! on this MPSC channel in the main loop, so if the `DecryptingReactor`
121
    ///     shuts down, we will get EOS upon calling `.next()`)
122
    decrypting_reactor_rx: mpsc::Receiver<EncryptingReactorCmd>,
123
    /// A channel for receiving endpoint-bound stream messages from the StreamReactor(s)
124
    /// (the stream messages are client-bound if we are a relay, or exit-bound if we are a client).
125
    stream_rx: mpsc::Receiver<ReadyStreamMsg>,
126
    /// A padding controller to which padding-related events should be reported.
127
    padding_ctrl: PaddingController,
128
    /// An event stream telling us about padding-related events.
129
    padding_event_stream: PaddingEventStream,
130
    /// Current rules for blocking traffic, according to the padding controller.
131
    #[cfg(feature = "circ-padding")]
132
    padding_block: Option<padding::StartBlocking>,
133
    /// The circuit metrics.
134
    metrics: Arc<CircuitMetrics>,
135
}
136

            
137
/// A control message aimed at the generic encrypting reactor.
138
pub(crate) enum CtrlMsg<M> {
139
    /// Inform the reactor that there's a flow control update for a given stream.
140
    ///
141
    /// The reactor will decide how to handle this update depending on the type of flow control and
142
    /// the current state of the stream.
143
    FlowCtrlUpdate {
144
        /// The hop that the stream is on.
145
        /// Relay circuits use `None`.
146
        hop: Option<HopNum>,
147
        /// The stream ID that the update is for.
148
        stream_id: StreamId,
149
        /// The type of flow control update, and any associated metadata.
150
        msg: FlowCtrlMsg,
151
    },
152
    /// An implementation-dependent control message.
153
    #[allow(unused)] // TODO(relay)
154
    Custom(M),
155
}
156

            
157
/// A control command aimed at the generic encrypting reactor.
158
pub(crate) enum CtrlCmd<C> {
159
    /// An implementation-dependent control command.
160
    #[allow(unused)] // TODO(relay)
161
    Custom(C),
162
}
163

            
164
/// Trait for customizing the behavior of the encrypting reactor.
165
///
166
/// Used for plugging in the implementation-dependent (client vs relay)
167
/// parts of the implementation into the generic one.
168
pub(crate) trait EncryptingReactorInner: ControlHandler {
169
    /// The subclass of ChanMsg that can arrive on this type of circuit.
170
    type CircChanMsg: TryFrom<AnyChanMsg, Error = crate::Error> + Send;
171

            
172
    /// Encrypt a RelayCellBody that originates from us.
173
    fn originate_relay_cell(
174
        &mut self,
175
        cmd: ChanCmd,
176
        body: &mut RelayCellBody,
177
        hop: Option<HopNum>,
178
    ) -> SendmeTag;
179

            
180
    /// Encrypt a client-bound cell that did not originate from us.
181
    ///
182
    /// Returns the cell to forward towards the client,
183
    /// or an error if the reactor should shut down.
184
    ///
185
    /// Relay-only.
186
    fn encrypt_clientbound_cell(
187
        &mut self,
188
        circ_uniq_id: UniqId,
189
        circ_id: CircId,
190
        cell: Self::CircChanMsg,
191
    ) -> StdResult<AnyChanMsg, ReactorError>;
192
}
193

            
194
impl<E: EncryptingReactorInner> EncryptingReactor<E> {
195
    /// Create a new [`EncryptingReactor`].
196
    #[allow(clippy::too_many_arguments)] // TODO
197
32
    pub(super) fn new<R: Runtime>(
198
32
        runtime: R,
199
32
        channel: &Arc<Channel>,
200
32
        circ_id: CircId,
201
32
        unique_id: UniqId,
202
32
        inner: E,
203
32
        shared: Arc<CircuitStateShared>,
204
32
        decrypting_reactor_rx: mpsc::Receiver<EncryptingReactorCmd>,
205
32
        control_rx: mpsc::UnboundedReceiver<CtrlMsg<E::CtrlMsg>>,
206
32
        command_rx: mpsc::UnboundedReceiver<CtrlCmd<E::CtrlCmd>>,
207
32
        padding_ctrl: PaddingController,
208
32
        padding_event_stream: PaddingEventStream,
209
32
        stream_rx: mpsc::Receiver<ReadyStreamMsg>,
210
32
        metrics: Arc<CircuitMetrics>,
211
32
    ) -> Self {
212
32
        let channel = Arc::clone(channel);
213
32
        let inbound_chan_tx = CircuitCellSender::from_channel_sender(channel.sender());
214

            
215
32
        Self {
216
32
            time_provider: DynTimeProvider::new(runtime),
217
32
            outbound_chan_rx: None,
218
32
            channel,
219
32
            inner,
220
32
            shared,
221
32
            inbound_chan_tx,
222
32
            unique_id,
223
32
            circ_id,
224
32
            decrypting_reactor_rx,
225
32
            control_rx,
226
32
            command_rx,
227
32
            stream_rx,
228
32
            padding_ctrl,
229
32
            padding_event_stream,
230
32
            #[cfg(feature = "circ-padding")]
231
32
            padding_block: None,
232
32
            metrics,
233
32
        }
234
32
    }
235

            
236
    /// Helper for [`run`](Self::run).
237
    ///
238
    /// Handles cells arriving on the outbound Tor channel,
239
    /// and writes cells to the inbound Tor channel.
240
    ///
241
    /// Because the Tor application streams, the `decrypting_reactor_rx` MPSC streams,
242
    /// and the outbound Tor channel MPSC stream are driven concurrently using [`PollAll`],
243
    /// this function can send up to 3 cells per call over the inbound Tor channel:
244
    ///
245
    ///    * a cell carrying Tor stream data
246
    ///    * a cell received from the outbound Tor channel, if we are a relay
247
    ///      (moving from the exit towards the client)
248
    ///    * a circuit-level SENDME
249
    ///
250
    /// However, in practice, leaky pipe is not really used,
251
    /// and so relays that have application streams (i.e. the exits),
252
    /// are not going to have an outbound Tor channel,
253
    /// and so this will only really drive Tor stream data,
254
    /// delivering at most 2 cells per call.
255
44
    async fn run_once(&mut self) -> StdResult<(), ReactorError> {
256
        /// The maximum number of events we expect to handle per reactor loop.
257
        ///
258
        /// This is bounded by the number of futures we push into the PollAll.
259
        const PER_LOOP_EVENT_COUNT: usize = 3;
260

            
261
        // A collection of futures we plan to drive concurrently.
262
        let mut poll_all =
263
44
            PollAll::<PER_LOOP_EVENT_COUNT, Option<CircuitEvent<E::CircChanMsg>>>::new();
264

            
265
        // Flush the backward Tor channel sink, and check it for readiness
266
        //
267
        // TODO(flushing): here and everywhere else we need to flush:
268
        //
269
        // Currently, we try to flush every time we want to write to the sink,
270
        // but may be suboptimal.
271
        //
272
        // However, we don't actually *wait* for the flush to complete
273
        // (we just make a bit of progress by calling poll_flush),
274
        // so it's possible that this is actually tolerable.
275
        // We should run some tests, and if this turns out to be a performance bottleneck,
276
        // we'll have to rethink our flushing approach.
277
44
        let backward_chan_ready = future::poll_fn(|cx| {
278
            // The flush outcome doesn't matter,
279
            // so we simply move on to the readiness check.
280
            // The reason we don't wait on the flush is because we don't
281
            // want to flush on *every* reactor loop, but we do want to make
282
            // a bit of progress each time.
283
            //
284
            // (TODO: do we want to handle errors here?)
285
44
            let _ = self.inbound_chan_tx.poll_flush_unpin(cx);
286

            
287
44
            self.inbound_chan_tx.poll_ready_unpin(cx)
288
44
        });
289

            
290
        // Concurrently, drive :
291
        //  1. a future that reads from the StreamReactor, to see if there are
292
        //  any application streams that have a message to send
293
        //  (this resolves to a message that needs to be delivered to the peer)
294
44
        poll_all.push(async {
295
            // Internally, each stream reactor checks if we're allowed to send anything
296
            // that counts towards SENDME windows (and ceases to send us stream data if not)
297
            //
298
            // The reason we don't check that here is because stream_rx multiplexes stream data
299
            // from all hops, and we have no way of knowing which hop will want to send us stream
300
            // data next, and therefore we can't know which hop's CC object to use
301
44
            self.stream_rx.next().await.map(CircuitEvent::Send)
302
6
        });
303

            
304
        //  2. the stream of commands coming from the DecryptingReactor
305
        //  (this resolves to a EncryptingReactorCmd)
306
44
        poll_all.push(async {
307
44
            let event = match self.decrypting_reactor_rx.next().await {
308
6
                Some(cmd) => CircuitEvent::Forwarded(cmd),
309
                None => {
310
                    // The decrypting reactor has crashed, so we have to shut down.
311
                    CircuitEvent::ReactorShutdown
312
                }
313
            };
314

            
315
6
            Some(event)
316
6
        });
317

            
318
        // 3. Messages moving from the outbound channel towards the inbound Tor channel,
319
        // if we have an outbound Tor channel.
320
        //
321
        // NOTE: in practice, clients and exits won't have an outbound Tor channel,
322
        // so for them this will be a no-op.
323
44
        poll_all.push(async {
324
44
            let event = if let Some(outbound_chan_rx) = self.outbound_chan_rx.as_mut() {
325
                // Forward channel unexpectedly closed, we should close too
326
6
                match outbound_chan_rx.next().await {
327
                    Some(msg) => {
328
                        // TODO(relay): This assumes cells travel in the backward direction.
329
2
                        self.metrics.backward_cell_read();
330
2
                        match msg.try_into() {
331
                            Err(e) => CircuitEvent::ProtoViolation(e),
332
2
                            Ok(cell) => CircuitEvent::Cell(cell),
333
                        }
334
                    }
335
                    None => {
336
                        // The decrypting reactor has crashed, so we have to shut down.
337
                        CircuitEvent::ReactorShutdown
338
                    }
339
                }
340
            } else {
341
38
                future::pending().await
342
            };
343

            
344
2
            Some(event)
345
2
        });
346

            
347
44
        let poll_all = async move {
348
            // Avoid polling **any** of the futures if the outgoing sink is blocked.
349
            //
350
            // This implements backpressure: we avoid reading from our input sources
351
            // if we know we're unable to write to the inbound Tor channel sink.
352
            //
353
            // More specifically, if our inbound Tor channel sink is full and can no longer
354
            // accept cells, we stop reading:
355
            //
356
            //   1. From the application streams (received from StreamReactor), if there are any.
357
            //
358
            //   2. From the decrypting_reactor_rx channel, used by the decrypting reactor to send us
359
            //
360
            //     - a circuit-level SENDME that we have received, or
361
            //     - a circuit-level SENDME that we need to deliver to the client
362
            //
363
            //     Not reading from the decrypting_reactor_rx channel, in turn, causes the decrypting reactor
364
            //     to block and therefore stop reading from **its** input sources,
365
            //     propagating backpressure all the way to the other endpoint of the circuit.
366
            //
367
            //   3. From the outbound Tor channel, if there is one.
368
            //
369
            // This will delay any SENDMEs the client or exit might have sent along
370
            // the way, and therefore count as a congestion signal.
371
            //
372
            // TODO: memquota setup to make sure this doesn't turn into a memory DOS vector
373
44
            let _ = backward_chan_ready.await;
374

            
375
            // TODO: it's important to not block reading from the decrypting_reactor_rx channel on the chan
376
            // sender readiness (for instance, we should not block the sending of SENDMEs
377
            // if the channel is blocked on a padding-induced block).
378
            //
379
            // This means we will need to move the decrypting_reactor_rx handling out of the PollAll
380
            // to the select_biased! below.
381
44
            poll_all.await
382
14
        };
383

            
384
44
        let events = select_biased! {
385
44
            res = self.command_rx.next().fuse() => {
386
                let cmd = res.ok_or_else(|| ReactorError::Shutdown)?;
387
                self.handle_cmd(cmd)?;
388
                return Ok(());
389
            }
390
44
            res = self.control_rx.next().fuse() => {
391
                let msg = res.ok_or_else(|| ReactorError::Shutdown)?;
392
                if let Some(new_msg) = self.handle_msg(msg)? {
393
                    let mut events = <PollAll::<_, _> as Future>::Output::new();
394
                    events.push(Some(CircuitEvent::Send(new_msg)));
395
                    events
396
                } else {
397
                    return Ok(());
398
                }
399
            }
400
44
            res = self.padding_event_stream.next().fuse() => {
401
                // If there's a padding event, we need to handle it immediately,
402
                // because it might tell us to start blocking the inbound_chan_tx sink,
403
                // which, in turn, means we need to stop trying to read from
404
                // the application streams.
405
                let event = res.ok_or_else(|| ReactorError::Shutdown)?;
406

            
407
                cfg_if::cfg_if! {
408
                    if #[cfg(feature = "circ-padding")] {
409
                        self.run_padding_event(event).await?;
410
                    } else {
411
                        // If padding isn't enabled, we never generate a padding event,
412
                        // so we can be sure this case will never be called.
413
                        void::unreachable(event.0);
414
                    }
415
                }
416
                return Ok(())
417
            }
418
44
            res = poll_all.fuse() => res,
419
        };
420

            
421
        // Note: there shouldn't be more than N < PER_LOOP_EVENT_COUNT events to handle
422
        // per reactor loop. We need to be careful here, because we must avoid blocking
423
        // the reactor.
424
        //
425
        // If handling more than one event per loop turns out to be a problem, we may
426
        // need to dispatch this to a background task instead.
427
        //
428
        // TODO(relay): this loop is actually a problem.
429
        // As mentioned in the run_once() docs, this will attempt to send up
430
        // to 3 cells on the inbound tor Channel (or 2 cells, assuming no leaky pipe).
431
        //
432
        // The problem is that the readiness check above (see backward_chan_ready)
433
        // only checks that the queue has enough room for 1 cell, not *2 cells*.
434
        // Trying to send more than 2 cell when there is only room for one
435
        // will cause the reactor to block (and because there is nothing
436
        // driving the flushing of this channel, this will be a hard block).
437
        //
438
        // We need to rethink the strategy here (e.g. by flushing in parallel
439
        // with handle_event())
440
14
        for event in events.into_iter().flatten() {
441
14
            self.handle_event(event).await?;
442
        }
443

            
444
12
        Ok(())
445
14
    }
446

            
447
    /// Handle a control command.
448
    fn handle_cmd(&mut self, cmd: CtrlCmd<E::CtrlCmd>) -> StdResult<(), ReactorError> {
449
        match cmd {
450
            CtrlCmd::Custom(c) => self.inner.handle_cmd(c),
451
        }
452
    }
453

            
454
    /// Handle a control message.
455
    ///
456
    /// This may result in a new stream message that needs to be sent backward.
457
    fn handle_msg(
458
        &mut self,
459
        msg: CtrlMsg<E::CtrlMsg>,
460
    ) -> StdResult<Option<ReadyStreamMsg>, ReactorError> {
461
        match msg {
462
            CtrlMsg::Custom(c) => {
463
                // In the future we may also want `inner.handle_msg(c)` to return an
464
                // `Option<ReadyStreamMsg>`, and we can pass it through.
465
                let () = self.inner.handle_msg(c)?;
466
                Ok(None)
467
            }
468
            CtrlMsg::FlowCtrlUpdate {
469
                hop,
470
                stream_id,
471
                msg,
472
            } => match msg {
473
                FlowCtrlMsg::Sendme => {
474
                    // Congestion control decides if we can send stream level SENDMEs or not.
475
                    let (cell_fmt, cc) = self.shared.hop_info(hop)?;
476
                    let uses_stream_sendme = cc.lock().expect("poisoned").uses_stream_sendme();
477

            
478
                    if !uses_stream_sendme {
479
                        // Nothing to do, so discard the SENDME.
480
                        //
481
                        // TODO(arti#2068): We should do something better here,
482
                        // like ensure that nothing sends `FlowCtrlMsg::Sendme` when it shouldn't,
483
                        // and making this an error instead.
484
                        return Ok(None);
485
                    }
486

            
487
                    let sendme = Sendme::new_empty();
488
                    let msg = AnyRelayMsgOuter::new(Some(stream_id), sendme.into());
489

            
490
                    Ok(Some(ReadyStreamMsg {
491
                        hop,
492
                        msg,
493
                        relay_cell_format: cell_fmt,
494
                        ccontrol: Arc::clone(&cc),
495
                    }))
496
                }
497
            },
498
        }
499
    }
500

            
501
    /// Perform some circuit-padding-based event on the specified circuit.
502
    //
503
    // TODO(DEDUP): this is almost identical to the client-side Conflux::run_padding_event()
504
    #[cfg(feature = "circ-padding")]
505
    async fn run_padding_event(
506
        &mut self,
507
        padding_event: PaddingEvent,
508
    ) -> StdResult<(), ReactorError> {
509
        use PaddingEvent as E;
510

            
511
        match padding_event {
512
            E::SendPadding(send_padding) => {
513
                self.send_padding(send_padding).await?;
514
            }
515
            E::StartBlocking(start_blocking) => {
516
                self.start_blocking_for_padding(start_blocking);
517
            }
518
            E::StopBlocking => {
519
                self.stop_blocking_for_padding();
520
            }
521
        }
522
        Ok(())
523
    }
524

            
525
    /// Handle a request from our padding subsystem to send a padding packet.
526
    //
527
    // TODO(DEDUP): this is almost identical to the client-side Client::send_padding()
528
    #[cfg(feature = "circ-padding")]
529
    async fn send_padding(&mut self, send_padding: padding::SendPadding) -> Result<()> {
530
        use CircPaddingDisposition::*;
531

            
532
        let target_hop = send_padding.hop;
533

            
534
        match padding_disposition(
535
            &send_padding,
536
            &self.inbound_chan_tx,
537
            self.padding_block.as_ref(),
538
        ) {
539
            QueuePaddingNormally => {
540
                let queue_info = self.padding_ctrl.queued_padding(target_hop, send_padding);
541
                self.queue_padding_cell_for_hop(target_hop, queue_info)
542
                    .await?;
543
            }
544
            QueuePaddingAndBypass => {
545
                let queue_info = self.padding_ctrl.queued_padding(target_hop, send_padding);
546
                self.queue_padding_cell_for_hop(target_hop, queue_info)
547
                    .await?;
548
            }
549
            TreatQueuedCellAsPadding => {
550
                self.padding_ctrl
551
                    .replaceable_padding_already_queued(target_hop, send_padding);
552
            }
553
        }
554
        Ok(())
555
    }
556

            
557
    /// Enable padding-based blocking,
558
    /// or change the rule for padding-based blocking to the one in `block`.
559
    //
560
    // TODO(DEDUP): copy of Client::start_blocking_for_padding()
561
    #[cfg(feature = "circ-padding")]
562
    pub(super) fn start_blocking_for_padding(&mut self, block: padding::StartBlocking) {
563
        self.inbound_chan_tx.start_blocking();
564
        self.padding_block = Some(block);
565
    }
566

            
567
    /// Disable padding-based blocking.
568
    ///
569
    // TODO(DEDUP): copy of Client::stop_blocking_for_padding()
570
    #[cfg(feature = "circ-padding")]
571
    pub(super) fn stop_blocking_for_padding(&mut self) {
572
        self.inbound_chan_tx.stop_blocking();
573
        self.padding_block = None;
574
    }
575

            
576
    /// Generate and encrypt a padding cell, and send it to a targeted hop.
577
    ///
578
    /// Ignores any padding-based blocking.
579
    ///
580
    // TODO(DEDUP): copy of Client::queue_padding_cell_for_hop()
581
    #[cfg(feature = "circ-padding")]
582
    async fn queue_padding_cell_for_hop(
583
        &mut self,
584
        target_hop: HopNum,
585
        queue_info: Option<QueuedCellPaddingInfo>,
586
    ) -> Result<()> {
587
        use tor_cell::relaycell::msg::Drop as DropMsg;
588

            
589
        let msg = AnyRelayMsgOuter::new(None, DropMsg::default().into());
590
        let hopnum = Some(target_hop);
591

            
592
        // TODO: the ccontrol state isn't actually needed here, because
593
        // DROP cells don't count towards SENDME windows.
594
        // Technically, we could avoid unnecessarily Arc::clone()ing the CC state
595
        // here, and just extract the relay cell format.
596
        // But for that we would need a specialized send_relay_cell_inner()-like function
597
        // that doesn't take a CC object, or to make the CC object optional in
598
        // send_relay_cell_inner().
599
        let (relay_cell_format, ccontrol) = self.shared.hop_info(hopnum)?;
600

            
601
        self.send_relay_cell_inner(hopnum, relay_cell_format, msg, false, &ccontrol, queue_info)
602
            .await
603
    }
604

            
605
    /// Determine how exactly to handle a request to handle padding.
606
    #[cfg(feature = "circ-padding")]
607
    #[allow(unused)] // TODO(relay)
608
    fn padding_disposition(&self, send_padding: &padding::SendPadding) -> CircPaddingDisposition {
609
        crate::circuit::padding::padding_disposition(
610
            send_padding,
611
            &self.inbound_chan_tx,
612
            self.padding_block.as_ref(),
613
        )
614
    }
615

            
616
    /// Handle a circuit event.
617
14
    async fn handle_event(
618
14
        &mut self,
619
14
        event: CircuitEvent<E::CircChanMsg>,
620
14
    ) -> StdResult<(), ReactorError> {
621
        use CircuitEvent::*;
622

            
623
14
        match event {
624
2
            Cell(cell) => self.handle_clientbound_cell(cell).await,
625
            Send(msg) => {
626
                let ReadyStreamMsg {
627
                    hop,
628
                    relay_cell_format,
629
                    msg,
630
                    ccontrol,
631
6
                } = msg;
632

            
633
6
                self.send_relay_cell(hop, relay_cell_format, msg, false, &ccontrol)
634
6
                    .await?;
635

            
636
6
                Ok(())
637
            }
638
6
            Forwarded(cmd) => self.handle_reactor_cmd(cmd).await,
639
            ReactorShutdown => {
640
                // The decrypting reactor has crashed, so we have to shut down.
641
                trace!(
642
                    circ_uniq_id = %self.unique_id,
643
                    backward_circ_id = %self.circ_id,
644
                    "Encrypting relay reactor shutdown (decrypting reactor has closed)",
645
                );
646

            
647
                Err(ReactorError::Shutdown)
648
            }
649
            ProtoViolation(err) => Err(err.into()),
650
        }
651
14
    }
652

            
653
    /// Handle a command sent to us by the decrypting reactor.
654
6
    async fn handle_reactor_cmd(
655
6
        &mut self,
656
6
        msg: EncryptingReactorCmd,
657
6
    ) -> StdResult<(), ReactorError> {
658
        use EncryptingReactorCmd::*;
659

            
660
6
        match msg {
661
            SendRelayMsg { hop, msg } => {
662
                self.send_relay_msg(hop, msg).await?;
663
            }
664
            HandleSendme { hop, sendme } => {
665
                self.handle_sendme(hop, sendme).await?;
666
                return Ok(());
667
            }
668
            #[cfg(feature = "relay")]
669
            HandleCircuitExtended {
670
                hop,
671
                extended2,
672
                outbound_chan_rx,
673
            } => {
674
6
                self.outbound_chan_rx = Some(outbound_chan_rx);
675
6
                let msg = AnyRelayMsgOuter::new(None, extended2.into());
676
6
                self.send_relay_msg(hop, msg).await?;
677

            
678
6
                debug!(
679
                    circ_uniq_id = %self.unique_id,
680
                    backward_circ_id = %self.circ_id,
681
                    "Extended circuit to the next hop"
682
                );
683
            }
684
        }
685

            
686
6
        Ok(())
687
6
    }
688

            
689
    /// Send a relay message to the specified hop.
690
6
    async fn send_relay_msg(
691
6
        &mut self,
692
6
        hopnum: Option<HopNum>,
693
6
        msg: AnyRelayMsgOuter,
694
6
    ) -> StdResult<(), ReactorError> {
695
6
        let (relay_cell_format, ccontrol) = self.shared.hop_info(hopnum)?;
696
6
        let cmd = msg.cmd();
697

            
698
        // TODO(relay): remove this log once we add some tests
699
        // and confirm relaying cells works as expected
700
        // (in practice it will be too noisy to be useful, even at trace level).
701
6
        trace!(
702
            circ_uniq_id = %self.unique_id,
703
            backward_circ_id = %self.circ_id,
704
            hopnum=?hopnum,
705
            cmd = %cmd,
706
            "Sending backward cell"
707
        );
708

            
709
6
        self.send_relay_cell(hopnum, relay_cell_format, msg, false, &ccontrol)
710
6
            .await?;
711

            
712
6
        if cmd == RelayCmd::SENDME {
713
            // TODO: does note_sendme_sent() need to be fallible?
714
            // Neither Vegas nor the fixed-window impl ever return Err
715
            ccontrol.lock().expect("poisoned lock").note_sendme_sent()?;
716
6
        }
717

            
718
6
        Ok(())
719
6
    }
720

            
721
    /// Handle a circuit-level SENDME (stream ID = 0).
722
    ///
723
    /// Returns an error if the SENDME does not have an authentication tag
724
    /// (versions of Tor <=0.3.5 omit the SENDME tag, but we don't support
725
    /// those any longer).
726
    ///
727
    /// Any error returned from this function will shut down the reactor.
728
    ///
729
    // TODO(DEDUP): duplicates the logic from the client-side Circuit::handle_sendme()
730
    async fn handle_sendme(
731
        &mut self,
732
        hopnum: Option<HopNum>,
733
        sendme: Sendme,
734
    ) -> StdResult<(), ReactorError> {
735
        let tag = sendme
736
            .into_sendme_tag()
737
            .ok_or_else(|| Error::CircProto("missing tag on circuit sendme".into()))?;
738

            
739
        // NOTE: it's okay to await. We are only awaiting on the congestion_signals
740
        // future which *should* resolve immediately
741
        let signals = self.inbound_chan_tx.congestion_signals().await;
742

            
743
        // Update the CC object that we received a SENDME along
744
        // with possible congestion signals.
745
        self.shared
746
            .note_sendme_received(hopnum, &self.time_provider, tag, signals)?;
747

            
748
        Ok(())
749
    }
750

            
751
    /// Encode `msg` and encrypt it, returning the resulting cell
752
    /// and tag that should be expected for an authenticated SENDME sent
753
    /// in response to that cell.
754
    ///
755
    // TODO(DEDUP): duplicates the logic from the client-side Circuit::encode_relay_cell()
756
12
    fn encode_relay_cell(
757
12
        &mut self,
758
12
        relay_format: RelayCellFormat,
759
12
        hop: Option<HopNum>,
760
12
        early: bool,
761
12
        msg: AnyRelayMsgOuter,
762
12
    ) -> Result<(AnyChanMsg, SendmeTag)> {
763
12
        let mut body: RelayCellBody = msg
764
12
            .encode(relay_format, &mut rand::rng())
765
            .map_err(|e| Error::from_cell_enc(e, "relay cell body"))?
766
            .into();
767
12
        let cmd = if early {
768
            ChanCmd::RELAY_EARLY
769
        } else {
770
12
            ChanCmd::RELAY
771
        };
772

            
773
        // Use the implementation-dependent encryption logic
774
12
        let tag = self.inner.originate_relay_cell(cmd, &mut body, hop);
775
12
        let msg = Relay::from(BoxedCellBody::from(body));
776
12
        let msg = if early {
777
            AnyChanMsg::RelayEarly(msg.into())
778
        } else {
779
12
            AnyChanMsg::Relay(msg)
780
        };
781

            
782
12
        Ok((msg, tag))
783
12
    }
784

            
785
    /// Encode `msg`, encrypt it, and send it to the 'hop'th hop.
786
    ///
787
    /// If there is insufficient outgoing *circuit-level* or *stream-level*
788
    /// SENDME window, an error is returned instead.
789
    ///
790
    /// Does not check whether the cell is well-formed or reasonable.
791
12
    async fn send_relay_cell(
792
12
        &mut self,
793
12
        hop: Option<HopNum>,
794
12
        relay_cell_format: RelayCellFormat,
795
12
        msg: AnyRelayMsgOuter,
796
12
        early: bool,
797
12
        ccontrol: &Arc<Mutex<CongestionControl>>,
798
12
    ) -> Result<()> {
799
12
        self.send_relay_cell_inner(hop, relay_cell_format, msg, early, ccontrol, None)
800
12
            .await
801
12
    }
802

            
803
    /// As [`send_relay_cell`](Self::send_relay_cell), but takes an optional
804
    /// [`QueuedCellPaddingInfo`] in `padding_info`.
805
    ///
806
    /// If `padding_info` is None, `msg` must be non-padding: we report it as such to the
807
    /// padding controller.
808
    ///
809
    // TODO(DEDUP): this contains parts of Circuit::send_relay_cell_inner()
810
12
    async fn send_relay_cell_inner(
811
12
        &mut self,
812
12
        hop: Option<HopNum>,
813
12
        relay_cell_format: RelayCellFormat,
814
12
        msg: AnyRelayMsgOuter,
815
12
        early: bool,
816
12
        ccontrol: &Arc<Mutex<CongestionControl>>,
817
12
        padding_info: Option<QueuedCellPaddingInfo>,
818
12
    ) -> Result<()> {
819
12
        let c_t_w = sendme::cmd_counts_towards_windows(msg.cmd());
820
12
        let (msg, tag) = self.encode_relay_cell(relay_cell_format, hop, early, msg)?;
821
12
        let cell = AnyChanCell::new(Some(self.circ_id), msg);
822

            
823
        // NOTE: we use HopNum(0) if we're a relay (i.e. if the hop is None).
824
12
        let hop = hop.unwrap_or_else(|| HopNum::from(0));
825
        // Remember that we've enqueued this cell.
826
12
        let padding_info = padding_info.or_else(|| self.padding_ctrl.queued_data(hop));
827

            
828
        // Note: this future is always `Ready`, because we checked the sink for readiness
829
        // before polling the async streams, so await won't block.
830
12
        Pin::new(&mut self.inbound_chan_tx)
831
12
            .send_unbounded((cell, padding_info))
832
12
            .await?;
833
        // TODO(relay): This assumes cells travel in the backward direction.
834
12
        self.metrics.backward_cell_written();
835

            
836
12
        if c_t_w {
837
            ccontrol
838
                .lock()
839
                .expect("poisoned lock")
840
                .note_data_sent(&self.time_provider, &tag)?;
841
12
        }
842

            
843
12
        Ok(())
844
12
    }
845

            
846
    /// Handle a client-bound cell (moving from the exit towards the client).
847
    ///
848
    /// Relay-only.
849
2
    async fn handle_clientbound_cell(
850
2
        &mut self,
851
2
        cell: E::CircChanMsg,
852
2
    ) -> StdResult<(), ReactorError> {
853
2
        let cell = self
854
2
            .inner
855
2
            .encrypt_clientbound_cell(self.unique_id, self.circ_id, cell)?;
856
        let cell = AnyChanCell::new(Some(self.circ_id), cell);
857
        self.inbound_chan_tx
858
            .send((cell, None))
859
            .await
860
            .map_err(ReactorError::Err)?;
861
        // TODO(relay): This assumes cells travel in the backward direction.
862
        self.metrics.backward_cell_written();
863
        Ok(())
864
2
    }
865
}
866

            
867
impl<E: EncryptingReactorInner> Drop for EncryptingReactor<E> {
868
32
    fn drop(&mut self) {
869
        // This will send a DESTROY down the inbound Tor channel
870
32
        let _ = self.channel.close_circuit(self.circ_id);
871
32
    }
872
}
873

            
874
/// A circuit event that must be handled by the [`EncryptingReactor`].
875
enum CircuitEvent<M> {
876
    /// We received a cell that needs to be handled.
877
    ///
878
    /// (The cell is client-bound if we are a relay, or exit-bound if we are a client).
879
    Cell(M),
880
    /// A stream has a RELAY cell that needs
881
    /// to be packaged and written to our Tor channel.
882
    ///
883
    /// (The message is client-bound if we are a relay, or exit-bound if we are a client).
884
    Send(ReadyStreamMsg),
885
    /// We received a cell from the DecryptingReactor that we need to handle.
886
    ///
887
    /// This might be
888
    ///
889
    ///   * a circuit-level SENDME that we have received, or
890
    ///   * a circuit-level SENDME that we need to deliver to the client
891
    Forwarded(EncryptingReactorCmd),
892
    /// The decrypting reactor has shut down.
893
    ///
894
    /// We need to shut down too.
895
    ReactorShutdown,
896
    /// Protocol violation.
897
    ///
898
    /// This can happen if we receive a channel message that is not supported on the channel.
899
    ProtoViolation(Error),
900
}
901

            
902
/// Instructions from the decrypting reactor.
903
pub(crate) enum EncryptingReactorCmd {
904
    /// A circuit SENDME we received from the other endpoint.
905
    HandleSendme {
906
        /// The hop the SENDME came on.
907
        hop: Option<HopNum>,
908
        /// The SENDME.
909
        sendme: Sendme,
910
    },
911
    /// A message we need to send back to the other endpoint.
912
    SendRelayMsg {
913
        /// The hop to encode the message for.
914
        hop: Option<HopNum>,
915
        /// The message to send.
916
        msg: AnyRelayMsgOuter,
917
    },
918
    /// This relay circuit was extended by another hop.
919
    ///
920
    /// This causes the reactor send the `extended2` message on its inbound channel,
921
    /// and start reading from `outbound_chan_rx` in the main loop.
922
    //
923
    ///
924
    // TODO: I wish we didn't need to expose this relay-specific variant
925
    // in the generic reactor but we have no choice: abstracting it away
926
    // means either introducing a mutex between the relay-side decrypting/encrypting
927
    // handlers, or yet another mpsc between them.
928
    #[cfg(feature = "relay")]
929
    HandleCircuitExtended {
930
        /// The hop to encode the message for.
931
        ///
932
        /// In practice, this is always None, because only relays use this.
933
        hop: Option<HopNum>,
934
        /// The cell to send to the specified hop,
935
        extended2: Extended2,
936
        /// The reading end of the outbound Tor channel, if we are not the last hop.
937
        ///
938
        /// Yields cells moving from the exit towards the client, if we are a middle relay.
939
        outbound_chan_rx: CircuitRxReceiver,
940
    },
941
}
942

            
943
/// A flow control update message.
944
///
945
/// TODO(DEDUP): This is a duplicate of the client's
946
/// `crate::client::reactor::control::FlowCtrlMsg`.
947
#[derive(Debug)]
948
pub(crate) enum FlowCtrlMsg {
949
    /// Send a SENDME message on this stream.
950
    Sendme,
951
}