1use std::str::FromStr;
6
7use async_trait::async_trait;
8
9use crate::backend::{DirEntry, DirWatch, FileInfo, FileTimes, Handle};
10use crate::error::{SmbError, SmbResult};
11use crate::path::SmbPath;
12
13#[derive(Debug, Clone, PartialEq, Eq, Hash)]
20pub struct StreamName(String);
21
22impl StreamName {
23 pub fn as_str(&self) -> &str {
25 &self.0
26 }
27
28 pub fn matches(&self, other: &StreamName) -> bool {
31 self.0 == other.0 || self.0.to_lowercase() == other.0.to_lowercase()
32 }
33}
34
35pub(crate) fn same_stream(a: Option<&StreamName>, b: Option<&StreamName>) -> bool {
38 match (a, b) {
39 (None, None) => true,
40 (Some(a), Some(b)) => a.matches(b),
41 _ => false,
42 }
43}
44
45#[derive(Debug, Clone)]
48#[non_exhaustive]
49pub struct StreamInfo {
50 pub name: StreamName,
52 pub size: u64,
54 pub allocation_size: u64,
56}
57
58impl StreamInfo {
59 pub fn new(name: StreamName, size: u64, allocation_size: u64) -> Self {
61 Self {
62 name,
63 size,
64 allocation_size,
65 }
66 }
67}
68
69impl FromStr for StreamName {
70 type Err = SmbError;
71
72 fn from_str(s: &str) -> Result<Self, Self::Err> {
73 let units = s.encode_utf16().count();
74 if !(1..=MAX_STREAM_NAME_UNITS).contains(&units) || s.contains(['\\', '/', ':', '\0']) {
75 return Err(SmbError::NameInvalid);
76 }
77 Ok(Self(s.to_string()))
78 }
79}
80
81const MAX_STREAM_NAME_UNITS: usize = 255;
83
84#[derive(Debug, Clone, PartialEq, Eq)]
86pub(crate) enum StreamPart {
87 None,
89 Data,
91 Directory,
94 Named(StreamName),
96 NamedDirectory(StreamName),
98}
99
100pub(crate) fn parse_create_name(units: &[u16]) -> SmbResult<(SmbPath, StreamPart)> {
106 let name = String::from_utf16(units).map_err(|_| SmbError::NameInvalid)?;
107 let Some((file, suffix)) = name.split_once(':') else {
108 return Ok((name.parse()?, StreamPart::None));
109 };
110 if name.ends_with(':') {
111 return Err(SmbError::NameInvalid);
112 }
113 let (stream, kind) = suffix.split_once(':').unwrap_or((suffix, "$DATA"));
116 let directory = if kind.eq_ignore_ascii_case("$DATA") {
117 false
118 } else if kind.eq_ignore_ascii_case("$INDEX_ALLOCATION") {
119 true
120 } else {
121 return Err(SmbError::NameInvalid);
122 };
123 let path = file.parse()?;
124 let part = match (stream, directory) {
126 ("", false) => StreamPart::Data,
127 ("", true) => StreamPart::Directory,
128 (index, true) if index.eq_ignore_ascii_case("$I30") => StreamPart::Directory,
129 (stream, false) => StreamPart::Named(stream.parse()?),
130 (stream, true) => StreamPart::NamedDirectory(stream.parse()?),
131 };
132 Ok((path, part))
133}
134
135#[derive(Debug, Clone, PartialEq, Eq)]
138pub(crate) struct StreamTarget {
139 pub stream: Option<StreamName>,
141 pub kind: Option<StreamType>,
143}
144
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub(crate) enum StreamType {
148 Data,
150 Directory,
152 Other,
154}
155
156pub(crate) fn parse_stream_target(units: &[u16]) -> Result<StreamTarget, u32> {
161 let invalid = crate::ntstatus::STATUS_INVALID_PARAMETER;
162 let name = String::from_utf16(units).map_err(|_| invalid)?;
163 let rest = name.strip_prefix(':').ok_or(invalid)?;
164 if name.ends_with(':') {
165 return Err(invalid);
166 }
167 let (stream, kind) = match rest.split_once(':') {
168 Some((stream, kind)) => (stream, Some(kind)),
169 None => (rest, None),
170 };
171 if kind.is_some_and(|k| k.contains(['\\', '/', ':', '\0'])) {
172 return Err(invalid);
173 }
174 let stream = match stream {
175 "" => None,
176 stream => Some(stream.parse().map_err(|_| invalid)?),
177 };
178 let kind = kind.map(|kind| {
179 if kind.eq_ignore_ascii_case("$DATA") {
180 StreamType::Data
181 } else if kind.eq_ignore_ascii_case("$INDEX_ALLOCATION") {
182 StreamType::Directory
183 } else {
184 StreamType::Other
185 }
186 });
187 Ok(StreamTarget { stream, kind })
188}
189
190#[cfg(any(all(feature = "localfs", target_os = "macos"), test))]
194const SFM_CHARS: [char; 8] = ['"', '*', ':', '<', '>', '?', '\\', '|'];
195
196#[cfg(any(all(feature = "localfs", target_os = "macos"), test))]
202pub(crate) fn from_sfm(name: &str) -> String {
203 let last = name.chars().count().saturating_sub(1);
204 name.chars()
205 .enumerate()
206 .map(|(i, c)| match u32::from(c) {
207 n @ 0xF001..=0xF01F => char::from_u32(n - 0xF000).unwrap_or(c),
208 n @ 0xF020..=0xF027 => SFM_CHARS[(n - 0xF020) as usize],
209 0xF028 if i == last => ' ',
210 0xF029 if i == last => '.',
211 _ => c,
212 })
213 .collect()
214}
215
216#[cfg(any(all(feature = "localfs", target_os = "macos"), test))]
221pub(crate) fn to_sfm(name: &str) -> String {
222 let last = name.chars().count().saturating_sub(1);
223 name.chars()
224 .enumerate()
225 .map(|(i, c)| match c {
226 '\u{1}'..='\u{1F}' => char::from_u32(0xF000 + u32::from(c)).unwrap_or(c),
227 ' ' if i == last => '\u{F028}',
228 '.' if i == last => '\u{F029}',
229 c => SFM_CHARS
230 .iter()
231 .position(|&m| m == c)
232 .and_then(|at| char::from_u32(0xF020 + at as u32))
233 .unwrap_or(c),
234 })
235 .collect()
236}
237
238pub(crate) fn data_stream_info(info: FileInfo) -> FileInfo {
243 FileInfo {
244 is_directory: false,
245 ..info
246 }
247}
248
249pub(crate) fn stream_error(e: SmbError) -> SmbError {
255 match e {
256 SmbError::NotSupported => SmbError::AccessDenied,
257 e => e,
258 }
259}
260
261pub(crate) fn unsupported(on_stream: bool) -> u32 {
265 if on_stream {
266 crate::ntstatus::STATUS_INVALID_PARAMETER
267 } else {
268 crate::ntstatus::STATUS_NOT_SUPPORTED
269 }
270}
271
272pub(crate) struct StreamHandle(pub(crate) Box<dyn Handle>);
275
276#[async_trait]
277impl Handle for StreamHandle {
278 async fn read(&self, offset: u64, len: u32) -> SmbResult<bytes::Bytes> {
279 self.0.read(offset, len).await.map_err(stream_error)
280 }
281
282 async fn write(&self, offset: u64, data: &[u8]) -> SmbResult<u32> {
283 self.0.write(offset, data).await.map_err(stream_error)
284 }
285
286 async fn write_owned(&self, offset: u64, data: Vec<u8>) -> SmbResult<u32> {
287 self.0.write_owned(offset, data).await.map_err(stream_error)
288 }
289
290 async fn flush(&self) -> SmbResult<()> {
291 self.0.flush().await.map_err(stream_error)
292 }
293
294 async fn stat(&self) -> SmbResult<FileInfo> {
295 self.0.stat().await.map_err(stream_error)
296 }
297
298 async fn set_times(&self, times: FileTimes) -> SmbResult<()> {
299 self.0.set_times(times).await.map_err(stream_error)
300 }
301
302 async fn set_attributes(&self, attributes: u32) -> SmbResult<()> {
303 self.0
304 .set_attributes(attributes)
305 .await
306 .map_err(stream_error)
307 }
308
309 async fn truncate(&self, len: u64) -> SmbResult<()> {
310 self.0.truncate(len).await.map_err(stream_error)
311 }
312
313 async fn list_dir(&self, pattern: Option<&str>) -> SmbResult<Vec<DirEntry>> {
314 self.0.list_dir(pattern).await.map_err(stream_error)
315 }
316
317 async fn close(self: Box<Self>) -> SmbResult<()> {
318 self.0.close().await.map_err(stream_error)
319 }
320
321 async fn link_count(&self) -> SmbResult<u32> {
322 self.0.link_count().await.map_err(stream_error)
323 }
324
325 async fn dir_is_empty(&self) -> SmbResult<bool> {
326 self.0.dir_is_empty().await.map_err(stream_error)
327 }
328
329 async fn watch(&self) -> SmbResult<Option<Box<dyn DirWatch>>> {
330 self.0.watch().await.map_err(stream_error)
331 }
332
333 async fn streams(&self) -> SmbResult<Vec<StreamInfo>> {
334 self.0.streams().await.map_err(stream_error)
335 }
336}
337
338#[cfg(test)]
339mod tests {
340 use super::*;
341
342 fn parse(s: &str) -> SmbResult<(SmbPath, StreamPart)> {
343 parse_create_name(&s.encode_utf16().collect::<Vec<_>>())
344 }
345
346 fn named(s: &str) -> StreamPart {
347 StreamPart::Named(s.parse().unwrap())
348 }
349
350 fn path(s: &str) -> SmbPath {
351 s.parse().unwrap()
352 }
353
354 #[test]
355 fn names_without_a_suffix_are_paths() {
356 assert_eq!(
357 parse("dir\\f.txt").unwrap(),
358 (path("dir\\f.txt"), StreamPart::None)
359 );
360 assert_eq!(parse("").unwrap(), (SmbPath::root(), StreamPart::None));
361 }
362
363 #[test]
364 fn suffixes_select_a_stream() {
365 let cases = [
366 ("f:s", named("s")),
367 ("f:s:$DATA", named("s")),
368 ("f:s:$DaTa", named("s")),
369 ("f:$DATA", named("$DATA")),
370 ("f:$DATA:$DATA", named("$DATA")),
371 ("f::$DATA", StreamPart::Data),
372 ("f::$data", StreamPart::Data),
373 ("f::$INDEX_ALLOCATION", StreamPart::Directory),
374 ("f::$Index_Allocation", StreamPart::Directory),
375 ("f:$I30:$INDEX_ALLOCATION", StreamPart::Directory),
376 ("f:$i30:$index_allocation", StreamPart::Directory),
377 ("f:$I30", named("$I30")),
378 ("f:$I30:$DATA", named("$I30")),
379 (
380 "f:s:$INDEX_ALLOCATION",
381 StreamPart::NamedDirectory("s".parse().unwrap()),
382 ),
383 ];
384 for (name, part) in cases {
385 assert_eq!(parse(name).unwrap(), (path("f"), part), "{name}");
386 }
387 assert_eq!(
388 parse("\\dir\\f.txt:s").unwrap(),
389 (path("dir\\f.txt"), named("s"))
390 );
391 assert_eq!(parse(":s").unwrap(), (SmbPath::root(), named("s")));
392 for root in ["::$DATA", ".::$DATA", "\\::$DATA"] {
393 assert_eq!(
394 parse(root).unwrap(),
395 (SmbPath::root(), StreamPart::Data),
396 "{root}"
397 );
398 }
399 assert_eq!(
400 parse("::$INDEX_ALLOCATION").unwrap(),
401 (SmbPath::root(), StreamPart::Directory)
402 );
403 }
404
405 #[test]
406 fn stream_names_take_characters_file_names_refuse() {
407 for stream in ["\u{5}?*", "a\"b<c>|", " lead and trail. ", "\n"] {
408 assert_eq!(
409 parse(&format!("f:{stream}")).unwrap(),
410 (path("f"), named(stream)),
411 "{stream:?}"
412 );
413 }
414 let tags = "com.apple.metadata\u{F022}_kMDItemUserTags";
415 assert_eq!(parse(&format!("f:{tags}")).unwrap().1, named(tags));
416 }
417
418 #[test]
419 fn malformed_suffixes_are_refused() {
420 for name in [
421 "f:",
422 "f::",
423 "f:s:",
424 "f::$DATA:",
425 "f:a:b:c",
426 "f:s:$DATA:$DATA",
427 "f:s:$FOO",
428 "f::$BITMAP",
429 "f:s:DATA",
430 "a:s\\b",
431 "a:s/b",
432 "a::$DATA\\b",
433 "dir:s\\f.txt",
434 "dir\\:s",
435 "f:\0",
436 "*:s",
437 "a\\..\\b:s",
438 ] {
439 assert!(parse(name).is_err(), "{name:?}");
440 }
441 }
442
443 #[test]
444 fn stream_names_count_utf16_units() {
445 let longest = "x".repeat(255);
446 assert_eq!(parse(&format!("f:{longest}")).unwrap().1, named(&longest));
447 assert!(parse(&format!("f:{longest}x")).is_err());
448 let pairs = format!("{}x", "\u{1F600}".repeat(127));
450 assert_eq!(parse(&format!("f:{pairs}")).unwrap().1, named(&pairs));
451 assert!(parse(&format!("f:{}", "\u{1F600}".repeat(128))).is_err());
452 }
453
454 #[test]
455 fn unpaired_surrogates_are_refused() {
456 let mut units: Vec<u16> = "f:s".encode_utf16().collect();
457 units.push(0xD800);
458 assert!(parse_create_name(&units).is_err());
459 }
460
461 fn target(s: &str) -> Result<StreamTarget, u32> {
462 parse_stream_target(&s.encode_utf16().collect::<Vec<_>>())
463 }
464
465 #[test]
466 fn rename_targets_name_a_stream_and_maybe_its_type() {
467 let cases = [
468 (":t", Some("t"), None),
469 (":t:$DATA", Some("t"), Some(StreamType::Data)),
470 (":t:$data", Some("t"), Some(StreamType::Data)),
471 (
472 ":t:$INDEX_ALLOCATION",
473 Some("t"),
474 Some(StreamType::Directory),
475 ),
476 (":t:$FOO", Some("t"), Some(StreamType::Other)),
477 ("::$DATA", None, Some(StreamType::Data)),
478 ("::$INDEX_ALLOCATION", None, Some(StreamType::Directory)),
479 (":a\"b*?", Some("a\"b*?"), None),
480 ];
481 for (name, stream, kind) in cases {
482 let expected = StreamTarget {
483 stream: stream.map(|s| s.parse().unwrap()),
484 kind,
485 };
486 assert_eq!(target(name), Ok(expected), "{name}");
487 }
488 let longest = format!(":{}", "x".repeat(255));
489 assert!(target(&longest).is_ok());
490 }
491
492 #[test]
493 fn malformed_rename_targets_are_invalid_parameters() {
494 let long = format!(":{}", "x".repeat(256));
495 for name in [
496 ":",
497 "::",
498 ":t:",
499 "::$DATA:",
500 ":a:b:c",
501 ":t:$DATA:$DATA",
502 ":a\\b",
503 ":a/b",
504 ":t:$DA\\TA",
505 ":a\0",
506 "t",
507 long.as_str(),
508 ] {
509 assert_eq!(
510 target(name),
511 Err(crate::ntstatus::STATUS_INVALID_PARAMETER),
512 "{name:?}"
513 );
514 }
515 }
516
517 #[test]
518 fn stream_names_match_without_case() {
519 let name = |s: &str| s.parse::<StreamName>().unwrap();
520 assert!(name("Zone.Identifier").matches(&name("zone.IDENTIFIER")));
521 assert!(name("\u{C9}t\u{E9}").matches(&name("\u{E9}T\u{C9}")));
522 assert!(!name("a").matches(&name("b")));
523 assert_ne!(name("A"), name("a"));
524 }
525
526 #[test]
527 fn stream_errors_never_say_not_supported() {
528 assert!(matches!(
529 stream_error(SmbError::NotSupported),
530 SmbError::AccessDenied
531 ));
532 assert!(matches!(
533 stream_error(SmbError::DiskFull),
534 SmbError::DiskFull
535 ));
536 }
537
538 #[test]
539 fn private_use_characters_from_macos_map_back() {
540 assert_eq!(
541 from_sfm("com.apple.metadata\u{F022}_kMDItemUserTags"),
542 "com.apple.metadata:_kMDItemUserTags"
543 );
544 let sent: String = (0xF001..=0xF027)
545 .map(|n| char::from_u32(n).unwrap())
546 .collect();
547 let meant: String = (1..=0x1F)
548 .map(|n| char::from_u32(n).unwrap())
549 .chain("\"*:<>?\\|".chars())
550 .collect();
551 assert_eq!(from_sfm(&sent), meant);
552 assert_eq!(from_sfm("tag\u{F028}"), "tag ");
553 assert_eq!(from_sfm("tag\u{F029}"), "tag.");
554 for kept in [
555 "\u{F000}",
556 "\u{F02A}",
557 "a\u{F028}b",
558 "a\u{F029}b",
559 "a*b",
560 "\u{1F600}",
561 ] {
562 assert_eq!(from_sfm(kept), kept);
563 }
564 }
565
566 #[test]
567 fn names_map_to_stream_names_and_back() {
568 let name = to_sfm("com.apple.metadata:kMDItemFinderComment");
569 assert_eq!(name, "com.apple.metadata\u{F022}kMDItemFinderComment");
570 assert!(name.parse::<StreamName>().is_ok());
571 assert_eq!(to_sfm("a*?\\b"), "a\u{F021}\u{F025}\u{F026}b");
572 assert_eq!(to_sfm("a. b "), "a. b\u{F028}");
573 assert_eq!(to_sfm("x\u{1}."), "x\u{F001}\u{F029}");
574 for name in ["a:b\\c", "trailing. ", "a*?<>|\"\u{1}.", "plain", ""] {
575 assert_eq!(from_sfm(&to_sfm(name)), name);
576 assert!(!to_sfm(name).contains(['*', ':', '\\']));
577 }
578 for name in ["a\u{F021}b", "tag\u{F028}"] {
581 assert_ne!(from_sfm(&to_sfm(name)), name);
582 }
583 for literal in ["a*b", "tag ", "x\u{1}"] {
585 assert_ne!(to_sfm(&from_sfm(literal)), literal);
586 }
587 }
588
589 #[test]
590 fn stream_names_validate_on_their_own() {
591 assert_eq!("s".parse::<StreamName>().unwrap().as_str(), "s");
592 for bad in ["", "a:b", "a\\b", "a/b", "a\0b"] {
593 assert!(bad.parse::<StreamName>().is_err(), "{bad:?}");
594 }
595 }
596}