Skip to main content

smb_server/proto/messages/
tree_connect.rs

1//! TREE_CONNECT Request/Response (MS-SMB2 §2.2.9 / §2.2.10).
2
3use binrw::{BinRead, BinWrite, binrw};
4use std::io::Cursor;
5
6use crate::proto::error::ProtoResult;
7use crate::proto::header::SMB2_HEADER_LEN;
8use crate::utils::utf16le_to_units;
9
10/// SMB2_TREE_CONNECT_REQUEST (MS-SMB2 §2.2.9).
11///
12/// `path` is UTF-16LE. The wire format gives `PathOffset` (from the start of
13/// the SMB2 header) and `PathLength`; `path` is encoded and decoded
14/// immediately following the fixed prefix, and [`TreeConnectRequest::path_in`]
15/// finds it by `PathOffset`. 3.1.1 tree-connect extensions are not decoded.
16#[binrw]
17#[brw(little)]
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct TreeConnectRequest {
20    pub structure_size: u16,
21    /// 3.1.1: flags. 2.x/3.0/3.0.2: reserved.
22    pub flags: u16,
23    pub path_offset: u16,
24    pub path_length: u16,
25    /// UTF-16LE share path bytes (e.g. `\\server\share`).
26    #[br(parse_with = super::read_buf, args(path_length as usize))]
27    pub path: Vec<u8>,
28}
29
30impl TreeConnectRequest {
31    /// Flag: SMB2_TREE_CONNECT_FLAG_CLUSTER_RECONNECT (3.1.1).
32    pub const FLAG_CLUSTER_RECONNECT: u16 = 0x0001;
33    /// Flag: SMB2_TREE_CONNECT_FLAG_REDIRECT_TO_OWNER (3.1.1).
34    pub const FLAG_REDIRECT_TO_OWNER: u16 = 0x0002;
35    /// Flag: SMB2_TREE_CONNECT_FLAG_EXTENSION_PRESENT (3.1.1).
36    pub const FLAG_EXTENSION_PRESENT: u16 = 0x0004;
37
38    /// Decode the UTF-16LE share path into a `String`. Returns `None` if the
39    /// stored bytes are not an even length (malformed UTF-16LE).
40    pub fn path_str(&self) -> Option<String> {
41        utf16le_to_units(&self.path).map(|units| String::from_utf16_lossy(&units))
42    }
43
44    /// The share path bytes in `body`, the request after the SMB2 header,
45    /// located by `PathOffset` and `PathLength`. With
46    /// SMB2_TREE_CONNECT_FLAG_EXTENSION_PRESENT the path follows the
47    /// extension and `PathOffset` points at it. `None` when the path lies
48    /// outside the request's buffer.
49    pub fn path_in<'a>(&self, body: &'a [u8]) -> Option<&'a [u8]> {
50        let start = usize::from(self.path_offset).checked_sub(SMB2_HEADER_LEN)?;
51        if start < FIXED_LEN {
52            return None;
53        }
54        body.get(start..start + usize::from(self.path_length))
55    }
56
57    pub fn parse(buf: &[u8]) -> ProtoResult<Self> {
58        Ok(Self::read(&mut Cursor::new(buf))?)
59    }
60    pub fn write_to(&self, out: &mut Vec<u8>) -> ProtoResult<()> {
61        let mut c = Cursor::new(Vec::new());
62        BinWrite::write(self, &mut c)?;
63        out.extend_from_slice(&c.into_inner());
64        Ok(())
65    }
66}
67
68/// Size of the fixed part of a TREE_CONNECT request, before Buffer.
69const FIXED_LEN: usize = 8;
70
71/// SMB2_TREE_CONNECT_RESPONSE (MS-SMB2 §2.2.10).
72#[binrw]
73#[brw(little)]
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct TreeConnectResponse {
76    pub structure_size: u16,
77    pub share_type: u8,
78    pub reserved: u8,
79    pub share_flags: u32,
80    pub capabilities: u32,
81    pub maximal_access: u32,
82}
83
84impl TreeConnectResponse {
85    /// Share type: SMB2_SHARE_TYPE_DISK.
86    pub const SHARE_TYPE_DISK: u8 = 0x01;
87    pub const SHARE_TYPE_PIPE: u8 = 0x02;
88    pub const SHARE_TYPE_PRINT: u8 = 0x03;
89
90    pub fn parse(buf: &[u8]) -> ProtoResult<Self> {
91        Ok(Self::read(&mut Cursor::new(buf))?)
92    }
93    pub fn write_to(&self, out: &mut Vec<u8>) -> ProtoResult<()> {
94        let mut c = Cursor::new(Vec::new());
95        BinWrite::write(self, &mut c)?;
96        out.extend_from_slice(&c.into_inner());
97        Ok(())
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104
105    fn utf16le(s: &str) -> Vec<u8> {
106        s.encode_utf16().flat_map(u16::to_le_bytes).collect()
107    }
108
109    #[test]
110    fn request_round_trips() {
111        let path = utf16le(r"\\server\share");
112        let r = TreeConnectRequest {
113            structure_size: 9,
114            flags: 0,
115            path_offset: 0x48,
116            path_length: path.len() as u16,
117            path,
118        };
119        let mut buf = Vec::new();
120        r.write_to(&mut buf).unwrap();
121        let decoded = TreeConnectRequest::parse(&buf).unwrap();
122        assert_eq!(decoded, r);
123        assert_eq!(decoded.path_str().unwrap(), r"\\server\share");
124    }
125
126    #[test]
127    fn path_is_found_by_path_offset() {
128        let path = utf16le(r"\\srv\data");
129        // A 16-byte extension header comes before the path.
130        let mut body = vec![9, 0, 4, 0];
131        body.extend_from_slice(&(64u16 + 8 + 16).to_le_bytes());
132        body.extend_from_slice(&(path.len() as u16).to_le_bytes());
133        body.extend_from_slice(&[0u8; 16]);
134        body.extend_from_slice(&path);
135        let req = TreeConnectRequest::parse(&body).unwrap();
136        assert_eq!(req.path_in(&body), Some(&path[..]));
137
138        let mut short = req.clone();
139        short.path_offset = 64 + 4;
140        assert_eq!(short.path_in(&body), None);
141        short.path_offset = 64 + 30;
142        assert_eq!(short.path_in(&body), None);
143        short.path_offset = 10;
144        assert_eq!(short.path_in(&body), None);
145    }
146
147    #[test]
148    fn response_round_trips() {
149        let r = TreeConnectResponse {
150            structure_size: 16,
151            share_type: TreeConnectResponse::SHARE_TYPE_DISK,
152            reserved: 0,
153            share_flags: 0,
154            capabilities: 0,
155            maximal_access: 0x001F_01FF,
156        };
157        let mut buf = Vec::new();
158        r.write_to(&mut buf).unwrap();
159        assert_eq!(TreeConnectResponse::parse(&buf).unwrap(), r);
160    }
161}