Skip to main content

smb_server/
ea.rs

1//! Extended attributes: the FILE_FULL_EA_INFORMATION and
2//! FILE_GET_EA_INFORMATION lists of MS-FSCC 2.4.16, the names a file's
3//! attributes may have, and their sizes and limits.
4
5use std::collections::{HashMap, HashSet};
6
7use crate::ntstatus;
8
9/// One extended attribute of a file or directory (MS-FSCC 2.4.16). Built
10/// with [`Ea::new`]; every field is public.
11///
12/// The protocol layer passes backends only names of 1 to 254 bytes of
13/// UTF-8 without control characters or any of `\ / : * ? " < > | , + = [
14/// ] ;`. Names compare without regard to ASCII case.
15#[derive(Debug, Clone, PartialEq, Eq)]
16#[non_exhaustive]
17pub struct Ea {
18    pub name: String,
19    /// The value. Setting an empty value removes the attribute; a listed
20    /// attribute has a value.
21    pub value: Vec<u8>,
22    /// FILE_NEED_EA: the file cannot be read by applications that do not
23    /// understand extended attributes, and a CREATE with
24    /// FILE_NO_EA_KNOWLEDGE fails on it.
25    pub needed: bool,
26}
27
28impl Ea {
29    /// The attribute `name` holding `value`, without FILE_NEED_EA.
30    pub fn new(name: impl Into<String>, value: impl Into<Vec<u8>>) -> Self {
31        Self {
32            name: name.into(),
33            value: value.into(),
34            needed: false,
35        }
36    }
37}
38
39/// `name` as names compare: in ASCII lowercase.
40pub(crate) fn name_key(name: &str) -> String {
41    name.to_ascii_lowercase()
42}
43
44/// Flags value of an attribute with FILE_NEED_EA.
45pub(crate) const FILE_NEED_EA: u8 = 0x80;
46
47/// Longest name: under 255 bytes (MS-FSCC 2.4.16).
48pub(crate) const MAX_NAME: usize = 254;
49
50/// Longest value.
51pub(crate) const MAX_VALUE: usize = 0xFFFF;
52
53/// Most bytes the attributes of one file take as [`stored_length`] counts
54/// them: 64 KiB - 5 (MS-FSA 2.1.5.15.6).
55pub(crate) const MAX_STORED_LENGTH: usize = 65531;
56
57/// Bytes of a FILE_FULL_EA_INFORMATION entry before its name.
58const FULL_HEADER: usize = 8;
59
60/// Bytes of a FILE_GET_EA_INFORMATION entry before its name.
61const GET_HEADER: usize = 5;
62
63/// Fewest bytes a FILE_GET_EA_INFORMATION entry takes in its list: the
64/// size of the structure.
65const MIN_GET_ENTRY: usize = 8;
66
67/// True if `name` is a name an attribute may have: 1 to 254 bytes, none
68/// of them a control character or one of `\ / : * ? " < > | , + = [ ] ;`.
69/// [`Ea`] names are also UTF-8.
70pub(crate) fn valid_name(name: &[u8]) -> bool {
71    (1..=MAX_NAME).contains(&name.len())
72        && name
73            .iter()
74            .all(|&b| b >= 0x20 && !b"\\/:*?\"<>|,+=[];".contains(&b))
75}
76
77/// The name `bytes` spell, if [`valid_name`] takes it and it is UTF-8.
78fn name_of(bytes: &[u8]) -> Result<String, u32> {
79    if !valid_name(bytes) {
80        return Err(ntstatus::STATUS_INVALID_EA_NAME);
81    }
82    String::from_utf8(bytes.to_vec()).map_err(|_| ntstatus::STATUS_INVALID_EA_NAME)
83}
84
85/// [`FileInfo::ea_size`](crate::FileInfo::ea_size) of attributes with the
86/// name and value lengths `eas`: their FILE_FULL_EA_INFORMATION entries,
87/// each padded to 4 bytes. 0 for none.
88#[cfg(any(test, all(feature = "localfs", target_os = "linux")))]
89pub(crate) fn list_length(eas: impl IntoIterator<Item = (usize, usize)>) -> u32 {
90    let total: usize = eas
91        .into_iter()
92        .map(|(name, value)| (FULL_HEADER + name + 1 + value).next_multiple_of(4))
93        .sum();
94    u32::try_from(total).unwrap_or(u32::MAX)
95}
96
97/// What the attributes `eas` take against [`MAX_STORED_LENGTH`]: 5 bytes,
98/// the name and the value of each.
99pub(crate) fn stored_length(eas: &[Ea]) -> usize {
100    eas.iter().map(stored_size).sum()
101}
102
103fn stored_size(ea: &Ea) -> usize {
104    5 + ea.name.len() + ea.value.len()
105}
106
107/// [`stored_length`] of the attributes a file with `current` has once
108/// `changes`, each name once, replace, add or with empty values remove
109/// theirs.
110pub(crate) fn stored_length_after(current: &[Ea], changes: &[Ea]) -> usize {
111    let mut sizes: HashMap<String, usize> = current
112        .iter()
113        .map(|ea| (name_key(&ea.name), stored_size(ea)))
114        .collect();
115    for change in changes {
116        let key = name_key(&change.name);
117        if change.value.is_empty() {
118            sizes.remove(&key);
119        } else {
120            sizes.insert(key, stored_size(change));
121        }
122    }
123    sizes.values().sum()
124}
125
126/// An entry of a list as found in its buffer.
127struct Raw<'a> {
128    flags: u8,
129    name: &'a [u8],
130    /// The byte after the name, where its NUL goes.
131    nul: u8,
132    value: &'a [u8],
133}
134
135/// The entries of a list whose entries have `header` bytes before their
136/// names and need at least `min` bytes left in the buffer; `lengths` gives
137/// the lengths of an entry's name and value from its header. `None` when
138/// an entry runs past the buffer, or names a next entry that is not 4-byte
139/// aligned past its end.
140fn entries<'a>(
141    buf: &'a [u8],
142    header: usize,
143    min: usize,
144    lengths: impl Fn(&[u8]) -> (usize, usize),
145) -> Option<Vec<Raw<'a>>> {
146    let mut out = Vec::new();
147    let mut at = 0usize;
148    loop {
149        let entry = buf.get(at..)?;
150        let head = entry.get(..header.max(min))?;
151        let next = u32::from_le_bytes(head[0..4].try_into().expect("four bytes")) as usize;
152        let (name_len, value_len) = lengths(head);
153        let len = header + name_len + 1 + value_len;
154        let body = entry.get(..len)?;
155        if next != 0 && (!next.is_multiple_of(4) || next < len) {
156            return None;
157        }
158        out.push(Raw {
159            flags: if header == FULL_HEADER { head[4] } else { 0 },
160            name: &body[header..header + name_len],
161            nul: body[header + name_len],
162            value: &body[header + name_len + 1..],
163        });
164        if next == 0 {
165            return Some(out);
166        }
167        at = at.checked_add(next)?;
168    }
169}
170
171/// Reads a FILE_FULL_EA_INFORMATION list, as SET_INFO and the `ExtA`
172/// create context carry it: STATUS_EA_LIST_INCONSISTENT
173/// when an entry runs past the buffer, has no NUL after its name or names
174/// a next entry that is not 4-byte aligned past its end, then
175/// STATUS_INVALID_EA_NAME for a name [`valid_name`] refuses or that is not
176/// UTF-8, or flags other than FILE_NEED_EA. Bytes after the last entry and
177/// in padding are ignored.
178pub(crate) fn parse_full_list(buf: &[u8]) -> Result<Vec<Ea>, u32> {
179    full_entries(buf)?
180        .into_iter()
181        .map(|e| {
182            if e.flags & !FILE_NEED_EA != 0 {
183                return Err(ntstatus::STATUS_INVALID_EA_NAME);
184            }
185            Ok(Ea {
186                name: name_of(e.name)?,
187                value: e.value.to_vec(),
188                needed: e.flags & FILE_NEED_EA != 0,
189            })
190        })
191        .collect()
192}
193
194/// Checks a FILE_FULL_EA_INFORMATION list as [`parse_full_list`] does,
195/// but for its names and flags.
196pub(crate) fn check_full_list(buf: &[u8]) -> Result<(), u32> {
197    full_entries(buf).map(|_| ())
198}
199
200fn full_entries(buf: &[u8]) -> Result<Vec<Raw<'_>>, u32> {
201    let lengths = |head: &[u8]| {
202        let value = u16::from_le_bytes([head[6], head[7]]);
203        (usize::from(head[5]), usize::from(value))
204    };
205    entries(buf, FULL_HEADER, FULL_HEADER, lengths)
206        .filter(|raw| raw.iter().all(|e| e.nul == 0))
207        .ok_or(ntstatus::STATUS_EA_LIST_INCONSISTENT)
208}
209
210/// Reads a FILE_GET_EA_INFORMATION list, the names a FileFullEaInformation
211/// query asks for: STATUS_EA_LIST_INCONSISTENT for an
212/// empty name, an entry with fewer than 8 bytes left in the buffer or one
213/// that runs past it, or a next entry that is not 4-byte aligned past it,
214/// then STATUS_INVALID_EA_NAME for a name [`valid_name`] refuses or that
215/// is not UTF-8. The byte after a name is taken for its NUL, whatever it
216/// holds. A name listed again is left out.
217pub(crate) fn parse_get_list(buf: &[u8]) -> Result<Vec<String>, u32> {
218    let raw = entries(buf, GET_HEADER, MIN_GET_ENTRY, |head| {
219        (usize::from(head[4]), 0)
220    })
221    .filter(|raw| raw.iter().all(|e| !e.name.is_empty()))
222    .ok_or(ntstatus::STATUS_EA_LIST_INCONSISTENT)?;
223    let mut seen = HashSet::with_capacity(raw.len());
224    let mut out: Vec<String> = Vec::with_capacity(raw.len());
225    for e in raw {
226        let name = name_of(e.name)?;
227        if seen.insert(name_key(&name)) {
228            out.push(name);
229        }
230    }
231    Ok(out)
232}
233
234/// The attributes of `eas` that `names` name, in their order, with an
235/// empty value for a name none of them has.
236pub(crate) fn select(eas: &[Ea], names: &[String]) -> Vec<Ea> {
237    let by_name: HashMap<String, &Ea> = eas.iter().map(|ea| (name_key(&ea.name), ea)).collect();
238    names
239        .iter()
240        .map(|name| match by_name.get(&name_key(name)) {
241            Some(&ea) => ea.clone(),
242            None => Ea::new(name.as_str(), Vec::new()),
243        })
244        .collect()
245}
246
247/// Keeps the last of the attributes in `eas` that share a name, in the
248/// place of the first.
249pub(crate) fn dedup(eas: &mut Vec<Ea>) {
250    let mut at: HashMap<String, usize> = HashMap::with_capacity(eas.len());
251    let mut kept: Vec<Ea> = Vec::with_capacity(eas.len());
252    for ea in eas.drain(..) {
253        match at.get(&name_key(&ea.name)) {
254            Some(&i) => kept[i] = ea,
255            None => {
256                at.insert(name_key(&ea.name), kept.len());
257                kept.push(ea);
258            }
259        }
260    }
261    *eas = kept;
262}
263
264/// Bytes the FILE_FULL_EA_INFORMATION entry of `ea` takes, unpadded.
265pub(crate) fn entry_len(ea: &Ea) -> usize {
266    FULL_HEADER + ea.name.len() + 1 + ea.value.len()
267}
268
269/// Encodes `eas` as a FILE_FULL_EA_INFORMATION list: each entry but the
270/// last padded with zeros to 4 bytes, the last with NextEntryOffset 0.
271pub(crate) fn encode_full_list<'a>(eas: impl IntoIterator<Item = &'a Ea>) -> Vec<u8> {
272    let mut out = Vec::new();
273    let mut last: Option<usize> = None;
274    for ea in eas {
275        if let Some(prev) = last {
276            out.resize(out.len().next_multiple_of(4), 0);
277            let next = (out.len() - prev) as u32;
278            out[prev..prev + 4].copy_from_slice(&next.to_le_bytes());
279        }
280        last = Some(out.len());
281        out.extend_from_slice(&0u32.to_le_bytes());
282        out.push(if ea.needed { FILE_NEED_EA } else { 0 });
283        out.push(ea.name.len() as u8);
284        out.extend_from_slice(&(ea.value.len() as u16).to_le_bytes());
285        out.extend_from_slice(ea.name.as_bytes());
286        out.push(0);
287        out.extend_from_slice(&ea.value);
288    }
289    out
290}
291
292/// True if `ea` is one FILE_FULL_EA_INFORMATION can carry and a client
293/// can name: a valid name and a value of 1 to 65535 bytes.
294pub(crate) fn listable(ea: &Ea) -> bool {
295    valid_name(ea.name.as_bytes()) && (1..=MAX_VALUE).contains(&ea.value.len())
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301
302    fn entry(next: u32, flags: u8, name: &[u8], value: &[u8]) -> Vec<u8> {
303        let mut out = next.to_le_bytes().to_vec();
304        out.push(flags);
305        out.push(name.len() as u8);
306        out.extend_from_slice(&(value.len() as u16).to_le_bytes());
307        out.extend_from_slice(name);
308        out.push(0);
309        out.extend_from_slice(value);
310        out
311    }
312
313    fn get(next: u32, name: &[u8]) -> Vec<u8> {
314        let mut out = next.to_le_bytes().to_vec();
315        out.push(name.len() as u8);
316        out.extend_from_slice(name);
317        out.push(0);
318        out
319    }
320
321    #[test]
322    fn a_list_reads_back_as_encoded() {
323        let mut needed = Ea::new("Big", vec![7; 300]);
324        needed.needed = true;
325        let eas = vec![
326            Ea::new("a", b"x".to_vec()),
327            needed,
328            Ea::new("c.d", b"yz".to_vec()),
329        ];
330        let buf = encode_full_list(&eas);
331        // "a": 8 + 1 + 1 + 1 = 11, padded to 12; "Big": 8 + 3 + 1 + 300 =
332        // 312; "c.d" unpadded.
333        assert_eq!(buf.len(), 12 + 312 + 14);
334        assert_eq!(buf[0..4], 12u32.to_le_bytes());
335        assert_eq!(buf[11], 0, "padding");
336        assert_eq!(buf[12..16], 312u32.to_le_bytes());
337        assert_eq!(buf[16], FILE_NEED_EA);
338        assert_eq!(buf[324..328], 0u32.to_le_bytes(), "the last entry");
339        assert_eq!(parse_full_list(&buf).unwrap(), eas);
340        // The last entry counts padded.
341        let lengths = eas.iter().map(|ea| (ea.name.len(), ea.value.len()));
342        assert_eq!(list_length(lengths), 12 + 312 + 16);
343        assert_eq!(list_length([]), 0);
344        assert_eq!(stored_length(&eas), 7 + 308 + 10);
345    }
346
347    #[test]
348    fn a_list_that_runs_past_its_buffer_is_inconsistent() {
349        let inconsistent = Err(ntstatus::STATUS_EA_LIST_INCONSISTENT);
350        let one = entry(0, 0, b"n", b"v");
351        assert_eq!(parse_full_list(&one[..one.len() - 1]), inconsistent);
352        assert_eq!(parse_full_list(&one[..7]), inconsistent);
353        assert_eq!(parse_full_list(&[]), inconsistent);
354        // A header alone, with an empty name and no NUL.
355        assert_eq!(parse_full_list(&entry(0, 0, b"", b"")[..8]), inconsistent);
356        // Next entry past the end, misaligned, or inside this one.
357        let mut two = entry(12, 0, b"n", b"v");
358        two.push(0xEE);
359        two.extend_from_slice(&entry(0, 0, b"m", b"w"));
360        assert_eq!(parse_full_list(&two).unwrap().len(), 2, "any padding");
361        for next in [24, 14, 8] {
362            two[0] = next;
363            assert_eq!(parse_full_list(&two), inconsistent, "next {next}");
364        }
365        // No NUL after the name.
366        let mut unterminated = entry(0, 0, b"n", b"v");
367        unterminated[9] = b'x';
368        assert_eq!(parse_full_list(&unterminated), inconsistent);
369        // A malformed entry wins over a bad name before it.
370        let mut bad_then_short = entry(12, 0, b"a*", b"");
371        bad_then_short.resize(12, 0);
372        bad_then_short.extend_from_slice(&entry(0, 0, b"m", b"w")[..9]);
373        assert_eq!(parse_full_list(&bad_then_short), inconsistent);
374        // Bytes after the last entry are ignored.
375        let mut trailing = entry(0, 0, b"n", b"v");
376        trailing.extend_from_slice(&[1, 2, 3]);
377        assert_eq!(parse_full_list(&trailing).unwrap().len(), 1);
378    }
379
380    #[test]
381    fn names_and_flags_are_checked() {
382        let invalid = Err(ntstatus::STATUS_INVALID_EA_NAME);
383        for name in [
384            &b""[..],
385            b"a*b",
386            b"a:b",
387            b"a\x01",
388            b"caf\xe9",
389            b"[x]",
390            b"a;b",
391        ] {
392            assert_eq!(
393                parse_full_list(&entry(0, 0, name, b"v")),
394                invalid,
395                "{name:?}"
396            );
397        }
398        assert_eq!(parse_full_list(&entry(0, 0, &[b'a'; 255], b"v")), invalid);
399        assert_eq!(parse_full_list(&entry(0, 0x01, b"n", b"v")), invalid);
400        for name in [&[b'a'; 254][..], b"a b.c#$\x7f", "caf\u{e9}".as_bytes()] {
401            assert!(
402                parse_full_list(&entry(0, 0, name, b"v")).is_ok(),
403                "{name:?}"
404            );
405        }
406    }
407
408    #[test]
409    fn long_lists_avoid_pairwise_name_checks() {
410        let count = 100_000;
411        let names: Vec<String> = (0..count).map(|i| format!("n{i:06}")).collect();
412        let mut get = Vec::new();
413        for (at, name) in names.iter().chain(names.iter()).enumerate() {
414            let next: u32 = if at + 1 == 2 * count { 0 } else { 16 };
415            let start = get.len();
416            get.extend_from_slice(&next.to_le_bytes());
417            get.push(name.len() as u8);
418            get.extend_from_slice(name.as_bytes());
419            get.push(0);
420            get.resize(start + 16, 0);
421        }
422        let eas: Vec<Ea> = names
423            .iter()
424            .map(|n| Ea::new(n.as_str(), b"v".to_vec()))
425            .collect();
426        let started = std::time::Instant::now();
427        let parsed = parse_get_list(&get).unwrap();
428        assert_eq!(parsed.len(), count);
429        assert_eq!(select(&eas, &parsed).len(), count);
430        let mut twice: Vec<Ea> = eas.iter().chain(eas.iter()).cloned().collect();
431        dedup(&mut twice);
432        assert_eq!(twice.len(), count);
433        assert_eq!(stored_length_after(&eas, &eas), stored_length(&eas));
434        // Pairwise name checks would take minutes here.
435        assert!(
436            started.elapsed() < std::time::Duration::from_secs(60),
437            "{:?}",
438            started.elapsed()
439        );
440    }
441
442    #[test]
443    fn a_name_list_reads_each_name_once() {
444        let mut buf = get(8, b"ab");
445        buf.extend_from_slice(&get(0, b"CDE"));
446        assert_eq!(parse_get_list(&buf).unwrap(), ["ab", "CDE"]);
447        let mut twice = get(12, b"beta");
448        twice.resize(12, 0);
449        twice.extend_from_slice(&get(0, b"BETA"));
450        assert_eq!(parse_get_list(&twice).unwrap(), ["beta"]);
451        buf[0] = 6;
452        assert_eq!(
453            parse_get_list(&buf),
454            Err(ntstatus::STATUS_EA_LIST_INCONSISTENT)
455        );
456        assert_eq!(
457            parse_get_list(&get(0, b"a?b")),
458            Err(ntstatus::STATUS_INVALID_EA_NAME)
459        );
460        // A one-character name takes 7 bytes, one short of an entry.
461        let short = get(0, b"x");
462        assert_eq!(
463            parse_get_list(&short),
464            Err(ntstatus::STATUS_EA_LIST_INCONSISTENT)
465        );
466        let mut padded = short.clone();
467        padded.push(0);
468        assert_eq!(parse_get_list(&padded).unwrap(), ["x"]);
469        // The byte after the name need not be a NUL.
470        let mut unterminated = get(0, b"alpha");
471        *unterminated.last_mut().unwrap() = b'X';
472        assert_eq!(parse_get_list(&unterminated).unwrap(), ["alpha"]);
473        for bad in [&get(0, b"")[..], &[0, 0, 0, 0], &get(0, b"alpha")[..9]] {
474            assert_eq!(
475                parse_get_list(bad),
476                Err(ntstatus::STATUS_EA_LIST_INCONSISTENT),
477                "{bad:?}"
478            );
479        }
480    }
481}