summaryrefslogtreecommitdiff
path: root/crates/tor-proto/src/stream/incoming.rs
blob: 537e81ec13afd4f34e5f37a9138e41eab53269d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//! Incoming data stream cell handlers, shared by the relay and onion service implementations.

use tor_cell::relaycell::RelayCmd;
use tor_cell::restricted_msg;

use crate::stream::cmdcheck::{AnyCmdChecker, CmdChecker, StreamStatus};
use crate::{Error, Result};

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

restricted_msg! {
    /// An allowable incoming message on an incoming data stream.
    enum IncomingDataStreamMsg:RelayMsg {
        // SENDME is handled by the reactor.
        Data, End,
    }
}

impl CmdChecker for InboundDataCmdChecker {
    fn check_msg(&mut self, msg: &tor_cell::relaycell::UnparsedRelayMsg) -> Result<StreamStatus> {
        use StreamStatus::*;
        match msg.cmd() {
            RelayCmd::DATA => Ok(Open),
            RelayCmd::END => Ok(Closed),
            _ => Err(Error::StreamProto(format!(
                "Unexpected {} on an incoming data stream!",
                msg.cmd()
            ))),
        }
    }

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

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