1
//! Incoming data stream cell handlers, shared by the relay and onion service implementations.
2

            
3
use bitvec::prelude::*;
4
use derive_deftly::Deftly;
5
use oneshot_fused_workaround as oneshot;
6

            
7
use tor_cell::relaycell::{RelayCellFormat, RelayCmd, StreamId, UnparsedRelayMsg, msg};
8
use tor_cell::restricted_msg;
9
use tor_error::internal;
10
use tor_memquota::derive_deftly_template_HasMemoryCost;
11
use tor_memquota::mq_queue::{self, MpscSpec};
12
use tor_rtcompat::DynTimeProvider;
13

            
14
use crate::circuit::CircHopSyncView;
15
use crate::circuit::circhop::ReactorStreamComponents;
16
use crate::stream::cmdcheck::{AnyCmdChecker, CmdChecker, StreamStatus};
17
use crate::stream::{CloseStreamBehavior, StreamComponents};
18
use crate::{Error, Result};
19

            
20
// TODO(relay): move these to a shared module
21
use crate::client::stream::DataStream;
22

            
23
use crate::memquota::StreamAccount;
24
use crate::{HopLocation, HopNum};
25

            
26
/// A `CmdChecker` that enforces invariants for inbound data streams.
27
#[derive(Debug, Default)]
28
pub(crate) struct InboundDataCmdChecker;
29

            
30
restricted_msg! {
31
    /// An allowable incoming message on an incoming data stream.
32
    enum IncomingDataStreamMsg:RelayMsg {
33
        // SENDME is handled by the reactor.
34
        Data, End,
35
    }
36
}
37

            
38
impl CmdChecker for InboundDataCmdChecker {
39
14
    fn check_msg(&mut self, msg: &tor_cell::relaycell::UnparsedRelayMsg) -> Result<StreamStatus> {
40
        use StreamStatus::*;
41
14
        match msg.cmd() {
42
14
            RelayCmd::DATA => Ok(Open),
43
            RelayCmd::END => Ok(Closed),
44
            _ => Err(Error::StreamProto(format!(
45
                "Unexpected {} on an incoming data stream!",
46
                msg.cmd()
47
            ))),
48
        }
49
14
    }
50

            
51
    fn consume_checked_msg(&mut self, msg: tor_cell::relaycell::UnparsedRelayMsg) -> Result<()> {
52
        let _ = msg
53
            .decode::<IncomingDataStreamMsg>()
54
            .map_err(|err| Error::from_bytes_err(err, "cell on half-closed stream"))?;
55
        Ok(())
56
    }
57
}
58

            
59
impl InboundDataCmdChecker {
60
    /// Return a new boxed `DataCmdChecker` in a state suitable for a
61
    /// connection where an initial CONNECTED cell is not expected.
62
    ///
63
    /// This is used by hidden services, exit relays, and directory servers
64
    /// to accept streams.
65
26
    pub(crate) fn new_connected() -> AnyCmdChecker {
66
26
        Box::new(Self)
67
26
    }
68
}
69

            
70
/// A pending request from the other end of the circuit for us to open a new
71
/// stream.
72
///
73
/// Exits, directory caches, and onion services expect to receive these; others
74
/// do not.
75
///
76
/// On receiving one of these objects, the party handling it should accept it or
77
/// reject it.  If it is dropped without being explicitly handled, a reject
78
/// message will be sent anyway.
79
#[derive(Debug)]
80
pub struct IncomingStream {
81
    /// The runtime's time provider.
82
    time_provider: DynTimeProvider,
83
    /// The message that the client sent us to begin the stream.
84
    request: IncomingStreamRequest,
85
    /// Stream components used to assemble the [`DataStream`].
86
    components: StreamComponents,
87
}
88

            
89
impl IncomingStream {
90
    /// Create a new `IncomingStream`.
91
26
    pub(crate) fn new(
92
26
        time_provider: DynTimeProvider,
93
26
        request: IncomingStreamRequest,
94
26
        components: StreamComponents,
95
26
    ) -> Self {
96
26
        Self {
97
26
            time_provider,
98
26
            request,
99
26
            components,
100
26
        }
101
26
    }
102

            
103
    /// Return the underlying message that was used to try to begin this stream.
104
2
    pub fn request(&self) -> &IncomingStreamRequest {
105
2
        &self.request
106
2
    }
107

            
108
    /// Return the stream ID of this stream.
109
    pub fn stream_id(&self) -> StreamId {
110
        self.components.target.stream_id
111
    }
112

            
113
    /// Accept this stream as a new [`DataStream`], and send the client a
114
    /// message letting them know the stream was accepted.
115
    ///
116
    /// Returns an error if this is not a data or directory stream.
117
14
    pub async fn accept_data(self, message: msg::Connected) -> Result<DataStream> {
118
        let Self {
119
            time_provider,
120
            request,
121
            components:
122
                StreamComponents {
123
                    mut target,
124
                    stream_receiver,
125
                    xon_xoff_reader_ctrl,
126
                    memquota,
127
                },
128
14
        } = self;
129

            
130
14
        match request {
131
            IncomingStreamRequest::Begin(_) | IncomingStreamRequest::BeginDir(_) => {
132
14
                target.send(message.into()).await?;
133
14
                Ok(DataStream::new_connected(
134
14
                    time_provider,
135
14
                    stream_receiver,
136
14
                    xon_xoff_reader_ctrl,
137
14
                    target,
138
14
                    memquota,
139
14
                ))
140
            }
141
            IncomingStreamRequest::Resolve(_) => {
142
                Err(internal!("Cannot accept data on a RESOLVE stream").into())
143
            }
144
        }
145
14
    }
146

            
147
    /// Respond to a DNS stream by sending the specified `message` to the client.
148
    ///
149
    /// This closes the stream.
150
    ///
151
    /// Returns an error this is not a DNS stream.
152
    #[cfg(feature = "relay")]
153
2
    pub async fn resolve(mut self, message: msg::Resolved) -> Result<()> {
154
2
        match self.request {
155
            IncomingStreamRequest::Begin(_) | IncomingStreamRequest::BeginDir(_) => {
156
                Err(internal!("Cannot send RESOLVED on a data or directory stream").into())
157
            }
158
            IncomingStreamRequest::Resolve(_) => {
159
2
                let rx = self.close(CloseStreamBehavior::SendResolved(message))?;
160

            
161
2
                rx.await.map_err(|_| Error::CircuitClosed)?
162
            }
163
        }
164
2
    }
165

            
166
    /// Reject this request and send an error message to the client.
167
8
    pub async fn reject(mut self, message: msg::End) -> Result<()> {
168
8
        let rx = self.close(CloseStreamBehavior::SendEnd(message))?;
169

            
170
8
        rx.await.map_err(|_| Error::CircuitClosed)?
171
8
    }
172

            
173
    /// Close this stream, and possibly send a message (END or RESOLVED) to the client.
174
    ///
175
    /// Returns a [`oneshot::Receiver`] that can be used to await the reactor's response.
176
10
    fn close(&mut self, message: CloseStreamBehavior) -> Result<oneshot::Receiver<Result<()>>> {
177
10
        self.components.target.close_pending(message)
178
10
    }
179

            
180
    /// Ignore this request without replying to the client.
181
    ///
182
    /// (If you drop an [`IncomingStream`] without calling `accept_data`,
183
    /// `reject`, or this method, the drop handler will cause it to be
184
    /// rejected.)
185
    pub async fn discard(mut self) -> Result<()> {
186
        let rx = self.close(CloseStreamBehavior::SendNothing)?;
187

            
188
        rx.await.map_err(|_| Error::CircuitClosed)?.map(|_| ())
189
    }
190
}
191

            
192
// NOTE: We do not need to `impl Drop for IncomingStream { .. }`: when its
193
// StreamTarget is dropped, this will drop its internal mpsc::Sender, and the
194
// circuit reactor will see a close on its mpsc::Receiver, and the circuit
195
// reactor will itself send an End.
196

            
197
restricted_msg! {
198
    /// The allowed incoming messages on an `IncomingStream`.
199
    #[derive(Clone, Debug, Deftly)]
200
    #[derive_deftly(HasMemoryCost)]
201
    #[non_exhaustive]
202
    pub enum IncomingStreamRequest: RelayMsg {
203
        /// A BEGIN message.
204
        Begin,
205
        /// A BEGIN_DIR message.
206
        BeginDir,
207
        /// A RESOLVE message.
208
        Resolve,
209
    }
210
}
211

            
212
/// Bit-vector used to represent a list of permitted commands.
213
///
214
/// This is cheaper and faster than using a vec, and avoids side-channel
215
/// attacks.
216
type RelayCmdSet = bitvec::BitArr!(for 256);
217

            
218
/// A `CmdChecker` that enforces correctness for incoming commands on unrecognized streams that
219
/// have a non-zero stream ID.
220
#[derive(Debug)]
221
pub(crate) struct IncomingCmdChecker {
222
    /// The "begin" commands that can be received on this type of circuit:
223
    ///
224
    ///   * onion service circuits only accept `BEGIN`
225
    ///   * all relay circuits accept `BEGIN_DIR`
226
    ///   * exit relays additionally accept `BEGIN` or `RESOLVE` on relay circuits
227
    ///   * once CONNECT_UDP is implemented, relays and later onion services may accept CONNECT_UDP
228
    ///     as well
229
    allow_commands: RelayCmdSet,
230
}
231

            
232
impl IncomingCmdChecker {
233
    /// Create a new boxed `IncomingCmdChecker`.
234
65
    pub(crate) fn new_any(allow_commands: &[RelayCmd]) -> AnyCmdChecker {
235
65
        let mut array = BitArray::ZERO;
236
65
        for c in allow_commands {
237
58
            array.set(u8::from(*c) as usize, true);
238
        }
239
65
        Box::new(Self {
240
65
            allow_commands: array,
241
65
        })
242
65
    }
243
}
244

            
245
impl CmdChecker for IncomingCmdChecker {
246
40
    fn check_msg(&mut self, msg: &UnparsedRelayMsg) -> Result<StreamStatus> {
247
40
        if self.allow_commands[u8::from(msg.cmd()) as usize] {
248
30
            Ok(StreamStatus::Open)
249
        } else {
250
10
            Err(Error::StreamProto(format!(
251
10
                "Unexpected {} on incoming stream",
252
10
                msg.cmd()
253
10
            )))
254
        }
255
40
    }
256

            
257
    fn consume_checked_msg(&mut self, msg: UnparsedRelayMsg) -> Result<()> {
258
        let _ = msg
259
            .decode::<IncomingStreamRequest>()
260
            .map_err(|err| Error::from_bytes_err(err, "invalid message on incoming stream"))?;
261

            
262
        Ok(())
263
    }
264
}
265

            
266
/// A callback that can check whether a given stream request is acceptable
267
/// immediately on its receipt.
268
///
269
/// This should only be used for checks that need to be done immediately, with a
270
/// view of the state of the circuit hop the stream request arrived on.
271
/// Any other checks should, if possible,
272
/// be done on the [`IncomingStream`] objects as they are received.
273
pub trait IncomingStreamRequestFilter: Send + 'static {
274
    /// Check an incoming stream request, and decide what to do with it.
275
    fn disposition(
276
        &mut self,
277
        ctx: &IncomingStreamRequestContext<'_>,
278
        circ: &CircHopSyncView<'_>,
279
    ) -> Result<IncomingStreamRequestDisposition>;
280
}
281

            
282
/// What action to take with an incoming stream request.
283
#[derive(Clone, Debug)]
284
#[non_exhaustive]
285
pub enum IncomingStreamRequestDisposition {
286
    /// Accept the request (for now) and pass it to the mpsc::Receiver
287
    /// that is yielding them as [`IncomingStream``
288
    Accept,
289
    /// Rejected the request, and close the circuit on which it was received.
290
    CloseCircuit,
291
    /// Reject the request and send an END message.
292
    RejectRequest(msg::End),
293
}
294

            
295
/// Information about a stream request, as passed to an [`IncomingStreamRequestFilter`].
296
pub struct IncomingStreamRequestContext<'a> {
297
    /// The request message itself
298
    pub(crate) request: &'a IncomingStreamRequest,
299
}
300
impl<'a> IncomingStreamRequestContext<'a> {
301
    /// Return a reference to the message used to request this stream.
302
    pub fn request(&self) -> &'a IncomingStreamRequest {
303
        self.request
304
    }
305
}
306

            
307
/// A no-op request filter to be used in testing.
308
#[cfg(test)]
309
#[derive(Copy, Clone, Debug, Default)]
310
pub(crate) struct NoOpRequestFilter;
311

            
312
#[cfg(test)]
313
impl IncomingStreamRequestFilter for NoOpRequestFilter {
314
    fn disposition(
315
        &mut self,
316
        _ctx: &IncomingStreamRequestContext<'_>,
317
        _circ: &CircHopSyncView<'_>,
318
    ) -> crate::Result<IncomingStreamRequestDisposition> {
319
        Ok(IncomingStreamRequestDisposition::Accept)
320
    }
321
}
322

            
323
/// Information about an incoming stream request.
324
#[derive(Debug, Deftly)]
325
#[derive_deftly(HasMemoryCost)]
326
pub(crate) struct StreamReqInfo {
327
    /// The [`IncomingStreamRequest`].
328
    pub(crate) req: IncomingStreamRequest,
329
    /// The ID of the stream being requested.
330
    pub(crate) stream_id: StreamId,
331
    /// The [`HopNum`].
332
    ///
333
    /// Set to `None` if we are an exit relay.
334
    //
335
    // TODO: For onion services, we might be able to enforce the HopNum earlier: we would never accept an
336
    // incoming stream request from two separate hops.  (There is only one that's valid.)
337
    pub(crate) hop: Option<HopLocation>,
338
    /// The format which must be used with this stream to encode messages.
339
    #[deftly(has_memory_cost(indirect_size = "0"))]
340
    pub(crate) relay_cell_format: RelayCellFormat,
341
    /// A collection of queues/channels that can be used to interact with this stream.
342
    pub(crate) stream_components: ReactorStreamComponents,
343
    /// The memory quota account to be used for this stream
344
    #[deftly(has_memory_cost(indirect_size = "0"))] // estimate (it contains an Arc)
345
    pub(crate) memquota: StreamAccount,
346
}
347

            
348
/// MPSC queue containing stream requests
349
#[cfg(any(feature = "hs-service", feature = "relay"))]
350
pub(crate) type StreamReqSender = mq_queue::Sender<StreamReqInfo, MpscSpec>;
351

            
352
/// Data required for handling an incoming stream request.
353
#[derive(educe::Educe)]
354
#[educe(Debug)]
355
#[cfg(any(feature = "hs-service", feature = "relay"))]
356
pub(crate) struct IncomingStreamRequestHandler {
357
    /// A sender for sharing information about an incoming stream request.
358
    pub(crate) incoming_sender: StreamReqSender,
359
    /// The hop to expect incoming stream requests from.
360
    ///
361
    /// Set to `None` if we are a relay.
362
    pub(crate) hop_num: Option<HopNum>,
363
    /// A [`CmdChecker`] for validating incoming streams.
364
    pub(crate) cmd_checker: AnyCmdChecker,
365
    /// An [`IncomingStreamRequestFilter`] for checking whether the user wants
366
    /// this request, or wants to reject it immediately.
367
    #[educe(Debug(ignore))]
368
    pub(crate) filter: Box<dyn IncomingStreamRequestFilter>,
369
}
370

            
371
#[cfg(test)]
372
mod test {
373
    // @@ begin test lint list maintained by maint/add_warning @@
374
    #![allow(clippy::bool_assert_comparison)]
375
    #![allow(clippy::clone_on_copy)]
376
    #![allow(clippy::dbg_macro)]
377
    #![allow(clippy::mixed_attributes_style)]
378
    #![allow(clippy::print_stderr)]
379
    #![allow(clippy::print_stdout)]
380
    #![allow(clippy::single_char_pattern)]
381
    #![allow(clippy::unwrap_used)]
382
    #![allow(clippy::unchecked_time_subtraction)]
383
    #![allow(clippy::useless_vec)]
384
    #![allow(clippy::needless_pass_by_value)]
385
    #![allow(clippy::string_slice)] // See arti#2571
386
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
387

            
388
    use std::num::NonZero;
389
    use tor_cell::relaycell::{
390
        AnyRelayMsgOuter, RelayCellFormat,
391
        msg::{Begin, BeginAddr, BeginDir, BeginHostname, Data, Resolve},
392
    };
393

            
394
    use super::*;
395

            
396
    #[test]
397
    fn incoming_cmd_checker() {
398
        // Convert an AnyRelayMsg to an UnparsedRelayCell.
399
        let u = |msg| {
400
            let body = AnyRelayMsgOuter::new(None, msg)
401
                .encode(RelayCellFormat::V0, &mut rand::rng())
402
                .unwrap();
403
            UnparsedRelayMsg::from_singleton_body(RelayCellFormat::V0, body).unwrap()
404
        };
405
        let addr = BeginAddr::Hostname(BeginHostname::new("allium.example.com").unwrap());
406
        let port = NonZero::new(443).unwrap();
407
        let begin = u(Begin::new(addr.encode(), port, 0).into());
408
        let begin_dir = u(BeginDir::default().into());
409
        let resolve = u(Resolve::new("allium.example.com").into());
410
        let data = u(Data::new(&[1, 2, 3]).unwrap().into());
411

            
412
        {
413
            let mut cc_none = IncomingCmdChecker::new_any(&[]);
414
            for m in [&begin, &begin_dir, &resolve, &data] {
415
                assert!(cc_none.check_msg(m).is_err());
416
            }
417
        }
418

            
419
        {
420
            let mut cc_begin = IncomingCmdChecker::new_any(&[RelayCmd::BEGIN]);
421
            assert_eq!(cc_begin.check_msg(&begin).unwrap(), StreamStatus::Open);
422
            for m in [&begin_dir, &resolve, &data] {
423
                assert!(cc_begin.check_msg(m).is_err());
424
            }
425
        }
426

            
427
        {
428
            let mut cc_any = IncomingCmdChecker::new_any(&[
429
                RelayCmd::BEGIN,
430
                RelayCmd::BEGIN_DIR,
431
                RelayCmd::RESOLVE,
432
            ]);
433
            for m in [&begin, &begin_dir, &resolve] {
434
                assert_eq!(cc_any.check_msg(m).unwrap(), StreamStatus::Open);
435
            }
436
            assert!(cc_any.check_msg(&data).is_err());
437
        }
438
    }
439
}