1
//! This module contains a WIP relay tunnel reactor.
2
//!
3
//! The initial version will duplicate some of the logic from
4
//! the client tunnel reactor.
5
//!
6
//! TODO(relay): refactor the relay tunnel
7
//! to share the same base tunnel implementation
8
//! as the client tunnel (to reduce code duplication).
9
//!
10
//! See the design notes at doc/dev/notes/relay-reactor.md
11

            
12
pub(crate) mod channel;
13
#[allow(unreachable_pub)] // TODO(relay): use in tor-chanmgr(?)
14
pub mod channel_provider;
15
pub(crate) mod reactor;
16

            
17
pub use channel::MaybeVerifiableRelayResponderChannel;
18

            
19
use derive_deftly::Deftly;
20
use futures::StreamExt as _;
21
use oneshot_fused_workaround as oneshot;
22

            
23
use tor_cell::chancell::msg::{self as chanmsg};
24
use tor_cell::relaycell::StreamId;
25
use tor_cell::relaycell::flow_ctrl::XonKbpsEwma;
26
use tor_memquota::derive_deftly_template_HasMemoryCost;
27
use tor_memquota::mq_queue::{ChannelSpec as _, MpscSpec};
28

            
29
use crate::Error;
30
use crate::circuit::celltypes::derive_deftly_template_RestrictedChanMsgSet;
31
use crate::circuit::reactor::CircReactorHandle;
32
use crate::circuit::reactor::{CtrlCmd, forward};
33
use crate::congestion::sendme::StreamRecvWindow;
34
use crate::memquota::SpecificAccount;
35
use crate::relay::reactor::backward::Backward;
36
use crate::relay::reactor::forward::Forward;
37
use crate::stream::flow_ctrl::xon_xoff::reader::XonXoffReaderCtrl;
38
use crate::stream::incoming::{
39
    IncomingCmdChecker, IncomingStream, IncomingStreamRequestFilter, StreamReqInfo,
40
};
41
use crate::stream::raw::StreamReceiver;
42
use crate::stream::{RECV_WINDOW_INIT, StreamComponents, StreamTarget, Tunnel};
43

            
44
use std::sync::Arc;
45

            
46
/// A subclass of ChanMsg that can correctly arrive on a live relay
47
/// circuit (one where a CREATE* has been received).
48
#[derive(Debug, Deftly)]
49
#[derive_deftly(HasMemoryCost)]
50
#[derive_deftly(RestrictedChanMsgSet)]
51
#[deftly(usage = "on an open relay circuit")]
52
#[cfg(feature = "relay")]
53
#[cfg_attr(not(test), allow(unused))] // TODO(relay)
54
pub(crate) enum RelayCircChanMsg {
55
    /// A relay cell telling us some kind of remote command from some
56
    /// party on the circuit.
57
    Relay(chanmsg::Relay),
58
    /// A relay early cell that is allowed to contain a CREATE message.
59
    RelayEarly(chanmsg::RelayEarly),
60
    /// A cell telling us to destroy the circuit.
61
    Destroy(chanmsg::Destroy),
62
    /// A cell telling us to enable/disable channel padding.
63
    PaddingNegotiate(chanmsg::PaddingNegotiate),
64
}
65

            
66
/// A handle for interacting with a relay circuit.
67
#[allow(unused)] // TODO(relay)
68
#[derive(Debug)]
69
pub struct RelayCirc(pub(crate) CircReactorHandle<Forward, Backward>);
70

            
71
impl RelayCirc {
72
    /// Shut down this circuit, along with all streams that are using it.
73
    /// Happens asynchronously (i.e. the tunnel won't necessarily be done shutting down
74
    /// immediately after this function returns!).
75
    ///
76
    /// Note that other references to this tunnel may exist.
77
    /// If they do, they will stop working after you call this function.
78
    ///
79
    /// It's not necessary to call this method if you're just done with a circuit:
80
    /// the circuit should close on its own once nothing is using it any more.
81
    pub fn terminate(&self) {
82
        let _ = self.0.command.unbounded_send(CtrlCmd::Shutdown);
83
    }
84

            
85
    /// Return true if this circuit is closed and therefore unusable.
86
    pub fn is_closing(&self) -> bool {
87
        self.0.control.is_closed()
88
    }
89

            
90
    /// Inform the circuit reactor that there has been a change in the drain rate for this stream.
91
    ///
92
    /// Typically the circuit reactor would send this new rate in an XON message to the other end of
93
    /// the stream.
94
    /// But it may decide not to, and may discard this update.
95
    /// For example the stream may have a large amount of buffered data, and the reactor may not
96
    /// want to send an XON while the buffer is large.
97
    ///
98
    /// This sends a message to inform the circuit reactor of the new drain rate,
99
    /// but it does not block or wait for a response from the reactor.
100
    /// An error is only returned if we are unable to send the update.
101
    //
102
    // TODO(relay): this duplicates the ClientTunnel API and docs. Do we care?
103
    pub(crate) fn drain_rate_update(
104
        &self,
105
        _stream_id: StreamId,
106
        _rate: XonKbpsEwma,
107
    ) -> crate::Result<()> {
108
        todo!()
109
    }
110

            
111
    /// Request to send a SENDME cell for this stream.
112
    ///
113
    /// This sends a request to the circuit reactor to send a stream-level SENDME, but it does not
114
    /// block or wait for a response from the circuit reactor.
115
    /// An error is only returned if we are unable to send the request.
116
    /// This means that if the circuit reactor is unable to send the SENDME, we are not notified of
117
    /// this here and an error will not be returned.
118
    //
119
    // TODO(relay): this duplicates the ClientTunnel API and docs. Do we care?
120
    pub(crate) fn send_sendme(&self, _stream_id: StreamId) -> crate::Result<()> {
121
        todo!()
122
    }
123

            
124
    /// Close the pending stream that owns this StreamTarget, delivering the specified
125
    /// END message (if any)
126
    ///
127
    /// The stream is closed by sending a control message (`ClosePendingStream`)
128
    /// to the reactor.
129
    ///
130
    /// Returns a [`oneshot::Receiver`] that can be used to await the reactor's response.
131
    ///
132
    /// The StreamTarget will set the correct stream ID and pick the
133
    /// right hop, but will not validate that the message is well-formed
134
    /// or meaningful in context.
135
    ///
136
    /// Note that in many cases, the actual contents of an END message can leak unwanted
137
    /// information. Please consider carefully before sending anything but an
138
    /// [`End::new_misc()`](tor_cell::relaycell::msg::End::new_misc) message over a `ClientTunnel`.
139
    /// (For onion services, we send [`DONE`](tor_cell::relaycell::msg::EndReason::DONE) )
140
    ///
141
    /// In addition to sending the END message, this function also ensures
142
    /// the state of the stream map entry of this stream is updated
143
    /// accordingly.
144
    ///
145
    /// Normally, you shouldn't need to call this function, as streams are implicitly closed by the
146
    /// reactor when their corresponding `StreamTarget` is dropped. The only valid use of this
147
    /// function is for closing pending incoming streams (a stream is said to be pending if we have
148
    /// received the message initiating the stream but have not responded to it yet).
149
    ///
150
    /// **NOTE**: This function should be called at most once per request.
151
    /// Calling it twice is an error.
152
    //
153
    // TODO(relay): this duplicates the ClientTunnel API and docs. Do we care?
154
    pub(crate) fn close_pending(
155
        &self,
156
        _stream_id: StreamId,
157
        _message: crate::stream::CloseStreamBehavior,
158
    ) -> crate::Result<oneshot::Receiver<crate::Result<()>>> {
159
        todo!()
160
    }
161

            
162
    /// Tell this reactor to begin allowing incoming stream requests,
163
    /// and to return those pending requests in an asynchronous stream.
164
    ///
165
    /// Ordinarily, these requests are rejected.
166
    ///
167
    /// Needed for exits. Middle relays should reject every incoming stream,
168
    /// either through the `filter` provided in `filter`,
169
    /// or by explicitly calling .reject() on each received stream.
170
    ///
171
    // TODO(relay): I think we will prefer using the .reject() approach
172
    // for this, because the filter is only meant for inexpensive quick
173
    // checks that are done immediately in the reactor (any blocking
174
    // in the filter will block the relay reactor main loop!).
175
    ///
176
    /// The user of the reactor **must** handle this stream
177
    /// (either by .accept()ing and opening and proxying the corresponding
178
    /// streams as appropriate, or by .reject()ing).
179
    ///
180
    // TODO: declare a type-alias for the return type when support for
181
    // impl in type aliases gets stabilized.
182
    //
183
    // See issue #63063 <https://github.com/rust-lang/rust/issues/63063>
184
    //
185
    /// There can only be one [`Stream`](futures::Stream) of this type created on a given reactor.
186
    /// If a such a [`Stream`](futures::Stream) already exists, this method will return
187
    /// an error.
188
    ///
189
    /// After this method has been called on a reactor, the reactor is expected
190
    /// to receive requests of this type indefinitely, until it is finally closed.
191
    /// If the `Stream` is dropped, the next request on this reactor will cause it to close.
192
    ///
193
    // TODO: Someday, we might want to allow a stream request handler to be
194
    // un-registered.  However, nothing in the Tor protocol requires it.
195
    //
196
    // TODO(DEDUP): *very* similar to ServiceOnionServiceDataTunnel::allow_stream_requests
197
    #[allow(unused)] // TODO(relay): call this from the task that creates the circ
198
    pub(crate) async fn allow_stream_requests<'a, FILT>(
199
        self: Arc<Self>,
200
        allow_commands: &'a [tor_cell::relaycell::RelayCmd],
201
        filter: FILT,
202
    ) -> crate::Result<impl futures::Stream<Item = IncomingStream> + use<'a, FILT>>
203
    where
204
        FILT: IncomingStreamRequestFilter,
205
    {
206
        let tunnel = Arc::clone(&self);
207
        /// The size of the channel receiving IncomingStreamRequestContexts.
208
        ///
209
        // TODO(relay-tuning): buffer size
210
        const INCOMING_BUFFER: usize = crate::stream::STREAM_READER_BUFFER;
211

            
212
        let (incoming_sender, incoming_receiver) = MpscSpec::new(INCOMING_BUFFER).new_mq(
213
            self.0.time_provider.clone(),
214
            tunnel.0.memquota.as_raw_account(),
215
        )?;
216

            
217
        let cmd_checker = IncomingCmdChecker::new_any(allow_commands);
218
        let (tx, rx) = oneshot::channel();
219
        let cmd = forward::CtrlCmd::AwaitStreamRequests {
220
            incoming_sender,
221
            cmd_checker,
222
            hop: None,
223
            filter: Box::new(filter),
224
            done: tx,
225
        };
226

            
227
        tunnel
228
            .0
229
            .command
230
            .unbounded_send(CtrlCmd::Forward(cmd))
231
            .map_err(|_| Error::CircuitClosed)?;
232

            
233
        // Check whether the AwaitStreamRequest was processed successfully.
234
        rx.await.map_err(|_| Error::CircuitClosed)??;
235

            
236
        // TODO(relay): this is more or less copy-pasta from client code
237
        let stream = incoming_receiver.map(move |req_ctx| {
238
            let StreamReqInfo {
239
                req,
240
                stream_id,
241
                hop,
242
                receiver,
243
                msg_tx,
244
                rate_limit_stream,
245
                drain_rate_request_stream,
246
                memquota,
247
                relay_cell_format,
248
            } = req_ctx;
249

            
250
            // There is no originating hop if we're a relay
251
            debug_assert!(hop.is_none());
252

            
253
            let target = StreamTarget {
254
                tunnel: Tunnel::Relay(Arc::clone(&tunnel)),
255
                tx: msg_tx,
256
                hop: None,
257
                stream_id,
258
                relay_cell_format,
259
                rate_limit_stream,
260
            };
261

            
262
            // can be used to build a reader that supports XON/XOFF flow control
263
            let xon_xoff_reader_ctrl =
264
                XonXoffReaderCtrl::new(drain_rate_request_stream, target.clone());
265

            
266
            let reader = StreamReceiver {
267
                target: target.clone(),
268
                receiver,
269
                recv_window: StreamRecvWindow::new(RECV_WINDOW_INIT),
270
                ended: false,
271
            };
272

            
273
            let components = StreamComponents {
274
                stream_receiver: reader,
275
                target,
276
                memquota,
277
                xon_xoff_reader_ctrl,
278
            };
279

            
280
            IncomingStream::new(self.0.time_provider.clone(), req, components)
281
        });
282

            
283
        Ok(stream)
284
    }
285
}
286

            
287
#[cfg(test)]
288
mod test {
289
    // @@ begin test lint list maintained by maint/add_warning @@
290
    #![allow(clippy::bool_assert_comparison)]
291
    #![allow(clippy::clone_on_copy)]
292
    #![allow(clippy::dbg_macro)]
293
    #![allow(clippy::mixed_attributes_style)]
294
    #![allow(clippy::print_stderr)]
295
    #![allow(clippy::print_stdout)]
296
    #![allow(clippy::single_char_pattern)]
297
    #![allow(clippy::unwrap_used)]
298
    #![allow(clippy::unchecked_time_subtraction)]
299
    #![allow(clippy::useless_vec)]
300
    #![allow(clippy::needless_pass_by_value)]
301
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
302

            
303
    #[test]
304
    fn relay_circ_chan_msg() {
305
        use tor_cell::chancell::msg::{self, AnyChanMsg};
306
        fn good(m: AnyChanMsg) {
307
            use crate::relay::RelayCircChanMsg;
308
            assert!(RelayCircChanMsg::try_from(m).is_ok());
309
        }
310
        fn bad(m: AnyChanMsg) {
311
            use crate::relay::RelayCircChanMsg;
312
            assert!(RelayCircChanMsg::try_from(m).is_err());
313
        }
314

            
315
        good(msg::Destroy::new(2.into()).into());
316
        bad(msg::CreatedFast::new(&b"The great globular mass"[..]).into());
317
        bad(msg::Created2::new(&b"of protoplasmic slush"[..]).into());
318
        good(msg::Relay::new(&b"undulated slightly,"[..]).into());
319
        good(msg::AnyChanMsg::RelayEarly(
320
            msg::Relay::new(&b"as if aware of him"[..]).into(),
321
        ));
322
        bad(msg::Versions::new([1, 2, 3]).unwrap().into());
323
        good(msg::PaddingNegotiate::start_default().into());
324
        good(msg::RelayEarly::from(msg::Relay::new(b"snail-like unipedular organism")).into());
325
    }
326
}