Skip to main content

smb_server/proto/messages/
change_notify.rs

1//! CHANGE_NOTIFY Request/Response (MS-SMB2 2.2.35 / 2.2.36) and the
2//! FILE_NOTIFY_INFORMATION entries a response carries (MS-FSCC 2.7.1).
3
4use binrw::{BinRead, BinWrite, binrw};
5use std::io::Cursor;
6
7use super::create::FileId;
8use crate::proto::error::ProtoResult;
9
10// CompletionFilter bits (MS-SMB2 2.2.35).
11pub const FILE_NOTIFY_CHANGE_FILE_NAME: u32 = 0x0000_0001;
12pub const FILE_NOTIFY_CHANGE_DIR_NAME: u32 = 0x0000_0002;
13pub const FILE_NOTIFY_CHANGE_ATTRIBUTES: u32 = 0x0000_0004;
14pub const FILE_NOTIFY_CHANGE_SIZE: u32 = 0x0000_0008;
15pub const FILE_NOTIFY_CHANGE_LAST_WRITE: u32 = 0x0000_0010;
16pub const FILE_NOTIFY_CHANGE_LAST_ACCESS: u32 = 0x0000_0020;
17pub const FILE_NOTIFY_CHANGE_CREATION: u32 = 0x0000_0040;
18pub const FILE_NOTIFY_CHANGE_EA: u32 = 0x0000_0080;
19pub const FILE_NOTIFY_CHANGE_SECURITY: u32 = 0x0000_0100;
20pub const FILE_NOTIFY_CHANGE_STREAM_NAME: u32 = 0x0000_0200;
21pub const FILE_NOTIFY_CHANGE_STREAM_SIZE: u32 = 0x0000_0400;
22pub const FILE_NOTIFY_CHANGE_STREAM_WRITE: u32 = 0x0000_0800;
23/// Every CompletionFilter bit; a server ignores the others.
24pub const FILE_NOTIFY_VALID_MASK: u32 = 0x0000_0FFF;
25
26// Action of a FILE_NOTIFY_INFORMATION entry (MS-FSCC 2.7.1).
27pub const FILE_ACTION_ADDED: u32 = 1;
28pub const FILE_ACTION_REMOVED: u32 = 2;
29pub const FILE_ACTION_MODIFIED: u32 = 3;
30pub const FILE_ACTION_RENAMED_OLD_NAME: u32 = 4;
31pub const FILE_ACTION_RENAMED_NEW_NAME: u32 = 5;
32pub const FILE_ACTION_ADDED_STREAM: u32 = 6;
33pub const FILE_ACTION_REMOVED_STREAM: u32 = 7;
34pub const FILE_ACTION_MODIFIED_STREAM: u32 = 8;
35
36/// Bytes of a FILE_NOTIFY_INFORMATION entry before its name.
37const ENTRY_HEADER_LEN: usize = 12;
38
39#[binrw]
40#[brw(little)]
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct ChangeNotifyRequest {
43    pub structure_size: u16,
44    pub flags: u16,
45    pub output_buffer_length: u32,
46    pub file_id: FileId,
47    pub completion_filter: u32,
48    pub reserved: u32,
49}
50
51impl ChangeNotifyRequest {
52    /// Flag: SMB2_WATCH_TREE.
53    pub const FLAG_WATCH_TREE: u16 = 0x0001;
54
55    pub fn parse(buf: &[u8]) -> ProtoResult<Self> {
56        Ok(Self::read(&mut Cursor::new(buf))?)
57    }
58    pub fn write_to(&self, out: &mut Vec<u8>) -> ProtoResult<()> {
59        let mut c = Cursor::new(Vec::new());
60        BinWrite::write(self, &mut c)?;
61        out.extend_from_slice(&c.into_inner());
62        Ok(())
63    }
64}
65
66#[binrw]
67#[brw(little)]
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct ChangeNotifyResponse {
70    pub structure_size: u16,
71    pub output_buffer_offset: u16,
72    pub output_buffer_length: u32,
73    #[br(parse_with = super::read_buf, args(output_buffer_length as usize))]
74    pub buffer: Vec<u8>,
75}
76
77impl ChangeNotifyResponse {
78    /// OutputBufferOffset: the buffer follows the fixed part of the body.
79    pub const BUFFER_OFFSET: u16 = 0x48;
80
81    /// The response body carrying the entries `buffer`. Without entries
82    /// the body is the 8 fixed bytes, as Windows sends it.
83    pub(crate) fn encode(buffer: &[u8]) -> Vec<u8> {
84        let mut out = Vec::with_capacity(8 + buffer.len());
85        out.extend_from_slice(&9u16.to_le_bytes());
86        out.extend_from_slice(&Self::BUFFER_OFFSET.to_le_bytes());
87        out.extend_from_slice(&(buffer.len() as u32).to_le_bytes());
88        out.extend_from_slice(buffer);
89        out
90    }
91
92    pub fn parse(buf: &[u8]) -> ProtoResult<Self> {
93        Ok(Self::read(&mut Cursor::new(buf))?)
94    }
95    pub fn write_to(&self, out: &mut Vec<u8>) -> ProtoResult<()> {
96        let mut c = Cursor::new(Vec::new());
97        BinWrite::write(self, &mut c)?;
98        out.extend_from_slice(&c.into_inner());
99        Ok(())
100    }
101}
102
103/// Appends a FILE_NOTIFY_INFORMATION entry for `action` on `name` to
104/// `buf`, padded to 4 bytes, and points the NextEntryOffset of the entry
105/// at `last` to it; `last` then names the new entry. An entry equal to the
106/// one at `last` is not added again.
107pub(crate) fn push_entry(buf: &mut Vec<u8>, last: &mut Option<usize>, action: u32, name: &[u16]) {
108    let name_len = name.len() * 2;
109    if let Some(at) = *last {
110        let same_name = buf[at + 8..at + 12] == (name_len as u32).to_le_bytes()
111            && buf[at + ENTRY_HEADER_LEN..]
112                .chunks_exact(2)
113                .zip(name)
114                .all(|(unit, &c)| unit == c.to_le_bytes());
115        if same_name && buf[at + 4..at + 8] == action.to_le_bytes() {
116            return;
117        }
118        let next = (buf.len() - at) as u32;
119        buf[at..at + 4].copy_from_slice(&next.to_le_bytes());
120    }
121    let start = buf.len();
122    buf.extend_from_slice(&0u32.to_le_bytes());
123    buf.extend_from_slice(&action.to_le_bytes());
124    buf.extend_from_slice(&(name_len as u32).to_le_bytes());
125    buf.extend(name.iter().flat_map(|c| c.to_le_bytes()));
126    buf.resize(start + (ENTRY_HEADER_LEN + name_len).next_multiple_of(4), 0);
127    *last = Some(start);
128}
129
130/// Length of the entries in `buf` without the padding after the last one,
131/// which starts at `last`: what a response carries.
132pub(crate) fn entries_len(buf: &[u8], last: Option<usize>) -> usize {
133    match last {
134        Some(at) => {
135            let name_len = u32::from_le_bytes(buf[at + 8..at + 12].try_into().expect("4 bytes"));
136            at + ENTRY_HEADER_LEN + name_len as usize
137        }
138        None => 0,
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    #[test]
147    fn request_round_trips() {
148        let r = ChangeNotifyRequest {
149            structure_size: 32,
150            flags: ChangeNotifyRequest::FLAG_WATCH_TREE,
151            output_buffer_length: 0x1000,
152            file_id: FileId::new(1, 2),
153            completion_filter: 0xFF,
154            reserved: 0,
155        };
156        let mut buf = Vec::new();
157        r.write_to(&mut buf).unwrap();
158        assert_eq!(ChangeNotifyRequest::parse(&buf).unwrap(), r);
159    }
160
161    #[test]
162    fn response_round_trips() {
163        let r = ChangeNotifyResponse {
164            structure_size: 9,
165            output_buffer_offset: 0x48,
166            output_buffer_length: 0,
167            buffer: vec![],
168        };
169        let mut buf = Vec::new();
170        r.write_to(&mut buf).unwrap();
171        assert_eq!(ChangeNotifyResponse::parse(&buf).unwrap(), r);
172    }
173
174    fn units(s: &str) -> Vec<u16> {
175        s.encode_utf16().collect()
176    }
177
178    /// (NextEntryOffset, Action, name) of each entry, checking the layout
179    /// rules of MS-FSCC 2.7.1 on the way.
180    fn entries(buf: &[u8]) -> Vec<(u32, u32, String)> {
181        let mut out = Vec::new();
182        let mut at = 0;
183        loop {
184            let field = |o: usize| u32::from_le_bytes(buf[at + o..at + o + 4].try_into().unwrap());
185            let (next, action, len) = (field(0), field(4), field(8) as usize);
186            assert_eq!(len % 2, 0);
187            let name: Vec<u16> = buf[at + 12..at + 12 + len]
188                .chunks_exact(2)
189                .map(|c| u16::from_le_bytes([c[0], c[1]]))
190                .collect();
191            out.push((next, action, String::from_utf16(&name).unwrap()));
192            if next == 0 {
193                assert_eq!(at + 12 + len, buf.len(), "the last entry is not padded");
194                return out;
195            }
196            assert_eq!(next % 4, 0);
197            assert_eq!(next as usize, (12 + len).next_multiple_of(4));
198            at += next as usize;
199        }
200    }
201
202    #[test]
203    fn entries_chain_and_pad_to_four_bytes() {
204        let mut buf = Vec::new();
205        let mut last = None;
206        assert_eq!(entries_len(&buf, last), 0);
207        push_entry(&mut buf, &mut last, FILE_ACTION_ADDED, &units("ab"));
208        assert_eq!(buf.len(), 16);
209        assert_eq!(entries_len(&buf, last), 16);
210        push_entry(&mut buf, &mut last, FILE_ACTION_REMOVED, &units("odd"));
211        push_entry(&mut buf, &mut last, FILE_ACTION_ADDED, &units("d\\été"));
212        assert_eq!(buf.len() % 4, 0);
213        let len = entries_len(&buf, last);
214        assert_eq!(len, 16 + 20 + 12 + 10);
215        assert_eq!(
216            entries(&buf[..len]),
217            [
218                (16, FILE_ACTION_ADDED, "ab".to_string()),
219                (20, FILE_ACTION_REMOVED, "odd".to_string()),
220                (0, FILE_ACTION_ADDED, "d\\été".to_string()),
221            ]
222        );
223    }
224
225    #[test]
226    fn only_adjacent_duplicates_collapse() {
227        let mut buf = Vec::new();
228        let mut last = None;
229        push_entry(&mut buf, &mut last, FILE_ACTION_ADDED, &units("x"));
230        push_entry(&mut buf, &mut last, FILE_ACTION_ADDED, &units("x"));
231        push_entry(&mut buf, &mut last, FILE_ACTION_REMOVED, &units("x"));
232        push_entry(&mut buf, &mut last, FILE_ACTION_ADDED, &units("x"));
233        push_entry(&mut buf, &mut last, FILE_ACTION_ADDED, &units("xy"));
234        let len = entries_len(&buf, last);
235        let found: Vec<_> = entries(&buf[..len])
236            .into_iter()
237            .map(|(_, action, name)| (action, name))
238            .collect();
239        assert_eq!(
240            found,
241            [
242                (FILE_ACTION_ADDED, "x".to_string()),
243                (FILE_ACTION_REMOVED, "x".to_string()),
244                (FILE_ACTION_ADDED, "x".to_string()),
245                (FILE_ACTION_ADDED, "xy".to_string()),
246            ]
247        );
248    }
249
250    #[test]
251    fn responses_without_entries_are_8_bytes() {
252        let empty = ChangeNotifyResponse::encode(&[]);
253        assert_eq!(empty, [9, 0, 0x48, 0, 0, 0, 0, 0]);
254        assert_eq!(ChangeNotifyResponse::parse(&empty).unwrap().buffer, []);
255        let full = ChangeNotifyResponse::encode(&[1, 2, 3]);
256        let parsed = ChangeNotifyResponse::parse(&full).unwrap();
257        assert_eq!(parsed.output_buffer_length, 3);
258        assert_eq!(parsed.buffer, [1, 2, 3]);
259    }
260}