-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdir.rs
More file actions
1425 lines (1323 loc) · 49.7 KB
/
dir.rs
File metadata and controls
1425 lines (1323 loc) · 49.7 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use alloc::sync::Arc;
#[cfg(feature = "lfn")]
use alloc::vec::Vec;
use core::fmt::Debug;
use core::num;
use core::str;
#[cfg(feature = "lfn")]
use core::{iter, slice};
use super::super::error::IoError;
use super::super::io::{IoBase, Read, Seek, SeekFrom, Write};
use super::dir_entry::{
DirEntry, DirEntryData, DirFileEntryData, DirLfnEntryData, FileAttributes, ShortName,
DIR_ENTRY_SIZE,
};
#[cfg(feature = "lfn")]
use super::dir_entry::{LFN_ENTRY_LAST_FLAG, LFN_PART_LEN};
use super::dir_entry::{SFN_PADDING, SFN_SIZE};
use super::error::Error;
use super::file::File;
use super::fs::{DiskSlice, FileSystem, FsIoAdapter, OemCpConverter, ReadWriteSeek};
use super::time::TimeProvider;
#[cfg(feature = "lfn")]
const LFN_PADDING: u16 = 0xFFFF;
pub(crate) enum DirRawStream<IO: ReadWriteSeek + Send + Debug, TP, OCC> {
File(File<IO, TP, OCC>),
Root(DiskSlice<FsIoAdapter<IO, TP, OCC>, FsIoAdapter<IO, TP, OCC>>),
}
impl<IO: ReadWriteSeek + Send + Debug, TP, OCC> DirRawStream<IO, TP, OCC> {
fn abs_pos(&self) -> Option<u64> {
match self {
DirRawStream::File(file) => file.abs_pos(),
DirRawStream::Root(slice) => Some(slice.abs_pos()),
}
}
fn first_cluster(&self) -> Option<u32> {
match self {
DirRawStream::File(file) => file.first_cluster(),
DirRawStream::Root(_) => None,
}
}
pub(crate) fn is_root_dir(&self) -> bool {
match self {
DirRawStream::File(file) => file.is_root_dir(),
DirRawStream::Root(_) => true,
}
}
}
// Note: derive cannot be used because of invalid bounds. See: https://github.com/rust-lang/rust/issues/26925
impl<IO: ReadWriteSeek + Send + Debug, TP, OCC> Clone for DirRawStream<IO, TP, OCC> {
fn clone(&self) -> Self {
match self {
DirRawStream::File(file) => DirRawStream::File(file.clone()),
DirRawStream::Root(raw) => DirRawStream::Root(raw.clone()),
}
}
}
impl<IO: ReadWriteSeek + Send + Debug, TP, OCC> IoBase for DirRawStream<IO, TP, OCC> {
type Error = Error<IO::Error>;
}
impl<IO: ReadWriteSeek + Send + Debug, TP: TimeProvider, OCC> Read for DirRawStream<IO, TP, OCC> {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
match self {
DirRawStream::File(file) => file.read(buf),
DirRawStream::Root(raw) => raw.read(buf),
}
}
}
impl<IO: ReadWriteSeek + Send + Debug, TP: TimeProvider, OCC> Write for DirRawStream<IO, TP, OCC> {
fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
match self {
DirRawStream::File(file) => file.write(buf),
DirRawStream::Root(raw) => raw.write(buf),
}
}
fn flush(&mut self) -> Result<(), Self::Error> {
match self {
DirRawStream::File(file) => file.flush(),
DirRawStream::Root(raw) => raw.flush(),
}
}
}
impl<IO: ReadWriteSeek + Send + Debug, TP, OCC> Seek for DirRawStream<IO, TP, OCC> {
fn seek(&mut self, pos: SeekFrom) -> Result<u64, Self::Error> {
match self {
DirRawStream::File(file) => file.seek(pos),
DirRawStream::Root(raw) => raw.seek(pos),
}
}
}
fn split_path(path: &str) -> (&str, Option<&str>) {
let trimmed_path = path.trim_matches('/');
trimmed_path.find('/').map_or((trimmed_path, None), |n| {
(&trimmed_path[..n], Some(&trimmed_path[n + 1..]))
})
}
enum DirEntryOrShortName<IO: ReadWriteSeek + Send + Debug, TP, OCC> {
DirEntry(DirEntry<IO, TP, OCC>),
ShortName([u8; SFN_SIZE]),
}
/// A FAT filesystem directory.
///
/// This struct is created by the `open_dir` or `create_dir` methods on `Dir`.
/// The root directory is returned by the `root_dir` method on `FileSystem`.
pub struct Dir<IO: ReadWriteSeek + Send + Debug, TP, OCC> {
stream: DirRawStream<IO, TP, OCC>,
fs: Arc<FileSystem<IO, TP, OCC>>,
}
impl<IO: ReadWriteSeek + Send + Debug, TP, OCC> Dir<IO, TP, OCC> {
pub(crate) fn new(stream: DirRawStream<IO, TP, OCC>, fs: Arc<FileSystem<IO, TP, OCC>>) -> Self {
Dir { stream, fs }
}
/// Creates directory entries iterator.
#[must_use]
#[allow(clippy::iter_not_returning_iterator)]
pub fn iter(&self) -> DirIter<IO, TP, OCC> {
DirIter::new(self.stream.clone(), self.fs.clone(), true)
}
}
impl<IO: ReadWriteSeek + Send + Debug, TP: TimeProvider, OCC: OemCpConverter> Dir<IO, TP, OCC> {
pub fn find_entry(
&self,
name: &str,
is_dir: Option<bool>,
mut short_name_gen: Option<&mut ShortNameGenerator>,
) -> Result<DirEntry<IO, TP, OCC>, Error<IO::Error>> {
for r in self.iter() {
let e = r?;
// compare name ignoring case
if e.eq_name(name) {
// check if file or directory is expected
if is_dir.is_some() && Some(e.is_dir()) != is_dir {
if e.is_dir() {
log::error!("Is a directory");
} else {
log::error!("Not a directory");
}
return Err(Error::InvalidInput);
}
return Ok(e);
}
// update short name generator state
if let Some(ref mut gen) = short_name_gen {
gen.add_existing(e.raw_short_name());
}
}
Err(Error::NotFound) //("No such file or directory"))
}
#[allow(clippy::type_complexity)]
pub(crate) fn find_volume_entry(
&self,
) -> Result<Option<DirEntry<IO, TP, OCC>>, Error<IO::Error>> {
for r in DirIter::new(self.stream.clone(), self.fs.clone(), false) {
let e = r?;
if e.data.is_volume() {
return Ok(Some(e));
}
}
Ok(None)
}
fn check_for_existence(
&self,
name: &str,
is_dir: Option<bool>,
) -> Result<DirEntryOrShortName<IO, TP, OCC>, Error<IO::Error>> {
let mut short_name_gen = ShortNameGenerator::new(name);
loop {
// find matching entry
let r = self.find_entry(name, is_dir, Some(&mut short_name_gen));
match r {
// file not found - continue with short name generation
Err(Error::NotFound) => {}
// unexpected error - return it
Err(err) => return Err(err),
// directory already exists - return it
Ok(e) => return Ok(DirEntryOrShortName::DirEntry(e)),
}
// try to generate short name
if let Ok(name) = short_name_gen.generate() {
return Ok(DirEntryOrShortName::ShortName(name));
}
// there were too many collisions in short name generation
// try different checksum in the next iteration
short_name_gen.next_iteration();
}
}
/// Opens existing subdirectory.
///
/// `path` is a '/' separated directory path relative to self directory.
///
/// # Errors
///
/// Errors that can be returned:
///
/// * `Error::NotFound` will be returned if `path` does not point to any existing directory entry.
/// * `Error::InvalidInput` will be returned if `path` points to a file that is not a directory.
/// * `Error::Io` will be returned if the underlying storage object returned an I/O error.
pub fn open_dir(&self, path: &str) -> Result<Self, Error<IO::Error>> {
log::trace!("Dir::open_dir {path}");
let (name, rest_opt) = split_path(path);
let e = self.find_entry(name, Some(true), None)?;
match rest_opt {
Some(rest) => e.to_dir().open_dir(rest),
None => Ok(e.to_dir()),
}
}
/// Opens existing file.
///
/// `path` is a '/' separated file path relative to self directory.
///
/// # Errors
///
/// Errors that can be returned:
///
/// * `Error::NotFound` will be returned if `path` points to a non-existing directory entry.
/// * `Error::InvalidInput` will be returned if `path` points to a file that is a directory.
/// * `Error::Io` will be returned if the underlying storage object returned an I/O error.
pub fn open_file(&self, path: &str) -> Result<File<IO, TP, OCC>, Error<IO::Error>> {
log::trace!("Dir::open_file {path}");
// traverse path
let (name, rest_opt) = split_path(path);
if let Some(rest) = rest_opt {
let e = self.find_entry(name, Some(true), None)?;
return e.to_dir().open_file(rest);
}
// convert entry to a file
let e = self.find_entry(name, Some(false), None)?;
Ok(e.to_file())
}
/// Creates new or opens existing file=.
///
/// `path` is a '/' separated file path relative to `self` directory.
/// File is never truncated when opening. It can be achieved by calling `File::truncate` method after opening.
///
/// # Errors
///
/// Errors that can be returned:
///
/// * `Error::InvalidInput` will be returned if `path` points to an existing file that is a directory.
/// * `Error::InvalidFileNameLength` will be returned if the file name is empty or if it is too long.
/// * `Error::UnsupportedFileNameCharacter` will be returned if the file name contains an invalid character.
/// * `Error::NotEnoughSpace` will be returned if there is not enough free space to create a new file.
/// * `Error::Io` will be returned if the underlying storage object returned an I/O error.
pub fn create_file(&self, path: &str) -> Result<File<IO, TP, OCC>, Error<IO::Error>> {
log::trace!("Dir::create_file {path}");
// traverse path
let (name, rest_opt) = split_path(path);
if let Some(rest) = rest_opt {
return self
.find_entry(name, Some(true), None)?
.to_dir()
.create_file(rest);
}
// this is final filename in the path
let r = self.check_for_existence(name, Some(false))?;
match r {
// file does not exist - create it
DirEntryOrShortName::ShortName(short_name) => {
let sfn_entry =
self.create_sfn_entry(short_name, FileAttributes::from_bits_truncate(0), None);
Ok(self.write_entry(name, sfn_entry)?.to_file())
}
// file already exists - return it
DirEntryOrShortName::DirEntry(e) => Ok(e.to_file()),
}
}
/// Creates new directory or opens existing.
///
/// `path` is a '/' separated path relative to self directory.
///
/// # Errors
///
/// Errors that can be returned:
///
/// * `Error::InvalidInput` will be returned if `path` points to an existing file that is not a directory.
/// * `Error::InvalidFileNameLength` will be returned if the file name is empty or if it is too long.
/// * `Error::UnsupportedFileNameCharacter` will be returned if the file name contains an invalid character.
/// * `Error::NotEnoughSpace` will be returned if there is not enough free space to create a new directory.
/// * `Error::Io` will be returned if the underlying storage object returned an I/O error.
pub fn create_dir(&self, path: &str) -> Result<Self, Error<IO::Error>> {
log::trace!("Dir::create_dir {path}");
// traverse path
let (name, rest_opt) = split_path(path);
if let Some(rest) = rest_opt {
return self
.find_entry(name, Some(true), None)?
.to_dir()
.create_dir(rest);
}
// this is final filename in the path
let r = self.check_for_existence(name, Some(true))?;
match r {
// directory does not exist - create it
DirEntryOrShortName::ShortName(short_name) => {
// alloc cluster for directory data
let cluster = FileSystem::alloc_cluster(&self.fs, None, true)?;
// create entry in parent directory
let sfn_entry =
self.create_sfn_entry(short_name, FileAttributes::DIRECTORY, Some(cluster));
let entry = self.write_entry(name, sfn_entry)?;
let dir = entry.to_dir();
// create special entries "." and ".."
let dot_sfn = ShortNameGenerator::generate_dot();
let sfn_entry = self.create_sfn_entry(
dot_sfn,
FileAttributes::DIRECTORY,
entry.first_cluster(),
);
dir.write_entry(".", sfn_entry)?;
let dotdot_sfn = ShortNameGenerator::generate_dotdot();
// cluster of the root dir shall be set to 0 in directory entries.
let dotdot_cluster = if self.stream.is_root_dir() {
None
} else {
self.stream.first_cluster()
};
let sfn_entry =
self.create_sfn_entry(dotdot_sfn, FileAttributes::DIRECTORY, dotdot_cluster);
dir.write_entry("..", sfn_entry)?;
Ok(dir)
}
// directory already exists - return it
DirEntryOrShortName::DirEntry(e) => Ok(e.to_dir()),
}
}
fn is_empty(&self) -> Result<bool, Error<IO::Error>> {
log::trace!("Dir::is_empty");
// check if directory contains no files
for r in self.iter() {
let e = r?;
let name = e.short_file_name_as_bytes();
// ignore special entries "." and ".."
if name != b"." && name != b".." {
return Ok(false);
}
}
Ok(true)
}
/// Removes existing file or directory.
///
/// `path` is a '/' separated file path relative to self directory.
/// Make sure there is no reference to this file (no File instance) or filesystem corruption
/// can happen.
///
/// # Errors
///
/// Errors that can be returned:
///
/// * `Error::NotFound` will be returned if `path` points to a non-existing directory entry.
/// * `Error::InvalidInput` will be returned if `path` points to a file that is not a directory.
/// * `Error::DirectoryIsNotEmpty` will be returned if the specified directory is not empty.
/// * `Error::Io` will be returned if the underlying storage object returned an I/O error.
pub fn remove(&self, path: &str) -> Result<(), Error<IO::Error>> {
log::trace!("Dir::remove {path}");
// traverse path
let (name, rest_opt) = split_path(path);
if let Some(rest) = rest_opt {
let e = self.find_entry(name, Some(true), None)?;
return e.to_dir().remove(rest);
}
// in case of directory check if it is empty
let e = self.find_entry(name, None, None)?;
if e.is_dir() && !e.to_dir().is_empty()? {
return Err(Error::DirectoryIsNotEmpty);
}
// free data
if let Some(n) = e.first_cluster() {
FileSystem::free_cluster_chain(&self.fs, n)?;
}
// free long and short name entries
let mut stream = self.stream.clone();
stream.seek(SeekFrom::Start(e.offset_range.0))?;
let num = ((e.offset_range.1 - e.offset_range.0) / u64::from(DIR_ENTRY_SIZE)) as usize;
for _ in 0..num {
let mut data = DirEntryData::deserialize(&mut stream)?;
log::trace!("removing dir entry {data:?}");
data.set_deleted();
stream.seek(SeekFrom::Current(-i64::from(DIR_ENTRY_SIZE)))?;
data.serialize(&mut stream)?;
}
Ok(())
}
/// Renames or moves existing file or directory.
///
/// `src_path` is a '/' separated source file path relative to self directory.
/// `dst_path` is a '/' separated destination file path relative to `dst_dir`.
/// `dst_dir` can be set to self directory if rename operation without moving is needed.
/// Make sure there is no reference to this file (no File instance) or filesystem corruption
/// can happen.
///
/// # Errors
///
/// Errors that can be returned:
///
/// * `Error::NotFound` will be returned if `src_path` points to a non-existing directory entry or if `dst_path`
/// stripped from the last component does not point to an existing directory.
/// * `Error::AlreadyExists` will be returned if `dst_path` points to an existing directory entry.
/// * `Error::Io` will be returned if the underlying storage object returned an I/O error.
pub fn rename(
&self,
src_path: &str,
dst_dir: &Dir<IO, TP, OCC>,
dst_path: &str,
) -> Result<(), Error<IO::Error>> {
log::trace!("Dir::rename {src_path} {dst_path}");
// traverse source path
let (src_name, src_rest_opt) = split_path(src_path);
if let Some(rest) = src_rest_opt {
let e = self.find_entry(src_name, Some(true), None)?;
return e.to_dir().rename(rest, dst_dir, dst_path);
}
// traverse destination path
let (dst_name, dst_rest_opt) = split_path(dst_path);
if let Some(rest) = dst_rest_opt {
let e = dst_dir.find_entry(dst_name, Some(true), None)?;
return self.rename(src_path, &e.to_dir(), rest);
}
// move/rename file
self.rename_internal(src_path, dst_dir, dst_path)
}
fn rename_internal(
&self,
src_name: &str,
dst_dir: &Dir<IO, TP, OCC>,
dst_name: &str,
) -> Result<(), Error<IO::Error>> {
log::trace!("Dir::rename_internal {src_name} {dst_name}");
// find existing file
let e = self.find_entry(src_name, None, None)?;
// check if destionation filename is unused
let r = dst_dir.check_for_existence(dst_name, None)?;
let short_name = match r {
// destination file already exist
DirEntryOrShortName::DirEntry(ref dst_e) => {
// check if source and destination entry is the same
if e.is_same_entry(dst_e) {
// nothing to do
return Ok(());
}
// destination file exists and it is not the same as source file - fail
return Err(Error::AlreadyExists);
}
// destionation file does not exist, short name has been generated
DirEntryOrShortName::ShortName(short_name) => short_name,
};
// free long and short name entries
let mut stream = self.stream.clone();
stream.seek(SeekFrom::Start(e.offset_range.0))?;
let num = ((e.offset_range.1 - e.offset_range.0) / u64::from(DIR_ENTRY_SIZE)) as usize;
for _ in 0..num {
let mut data = DirEntryData::deserialize(&mut stream)?;
log::trace!("removing LFN entry {data:?}");
data.set_deleted();
stream.seek(SeekFrom::Current(-i64::from(DIR_ENTRY_SIZE)))?;
data.serialize(&mut stream)?;
}
// save new directory entry
let sfn_entry = e.data.renamed(short_name);
dst_dir.write_entry(dst_name, sfn_entry)?;
Ok(())
}
fn find_free_entries(
&self,
num_entries: u32,
) -> Result<DirRawStream<IO, TP, OCC>, Error<IO::Error>> {
let mut stream = self.stream.clone();
let mut first_free: u32 = 0;
let mut num_free: u32 = 0;
let mut i: u32 = 0;
loop {
let raw_entry = DirEntryData::deserialize(&mut stream)?;
if raw_entry.is_end() {
// first unused entry - all remaining space can be used
if num_free == 0 {
first_free = i;
}
let pos = u64::from(first_free * DIR_ENTRY_SIZE);
stream.seek(super::super::io::SeekFrom::Start(pos))?;
return Ok(stream);
} else if raw_entry.is_deleted() {
// free entry - calculate number of free entries in a row
if num_free == 0 {
first_free = i;
}
num_free += 1;
if num_free == num_entries {
// enough space for new file
let pos = u64::from(first_free * DIR_ENTRY_SIZE);
stream.seek(super::super::io::SeekFrom::Start(pos))?;
return Ok(stream);
}
} else {
// used entry - start counting from 0
num_free = 0;
}
i += 1;
}
}
fn create_sfn_entry(
&self,
short_name: [u8; SFN_SIZE],
attrs: FileAttributes,
first_cluster: Option<u32>,
) -> DirFileEntryData {
let mut raw_entry = DirFileEntryData::new(short_name, attrs);
raw_entry.set_first_cluster(first_cluster, self.fs.fat_type());
let now = self.fs.options.time_provider.get_current_date_time();
raw_entry.set_created(now);
raw_entry.set_accessed(now.date);
raw_entry.set_modified(now);
raw_entry
}
#[cfg(feature = "lfn")]
fn encode_lfn_utf16(name: &str) -> LfnBuffer {
LfnBuffer::from_ucs2_units(name.encode_utf16())
}
#[cfg(not(feature = "lfn"))]
fn encode_lfn_utf16(_name: &str) -> LfnBuffer {
LfnBuffer {}
}
#[allow(clippy::type_complexity)]
fn alloc_and_write_lfn_entries(
&self,
lfn_utf16: &LfnBuffer,
short_name: &[u8; SFN_SIZE],
) -> Result<(DirRawStream<IO, TP, OCC>, u64), Error<IO::Error>> {
// get short name checksum
let lfn_chsum = lfn_checksum(short_name);
// create LFN entries generator
let lfn_iter = LfnEntriesGenerator::new(lfn_utf16.as_ucs2_units(), lfn_chsum);
// find space for new entries (multiple LFN entries and 1 SFN entry)
let num_entries = lfn_iter.len() as u32 + 1;
let mut stream = self.find_free_entries(num_entries)?;
let start_pos = stream.seek(super::super::io::SeekFrom::Current(0))?;
// write LFN entries before SFN entry
for lfn_entry in lfn_iter {
lfn_entry.serialize(&mut stream)?;
}
Ok((stream, start_pos))
}
#[allow(clippy::type_complexity)]
fn alloc_sfn_entry(&self) -> Result<(DirRawStream<IO, TP, OCC>, u64), Error<IO::Error>> {
let mut stream = self.find_free_entries(1)?;
let start_pos = stream.seek(super::super::io::SeekFrom::Current(0))?;
Ok((stream, start_pos))
}
fn write_entry(
&self,
name: &str,
raw_entry: DirFileEntryData,
) -> Result<DirEntry<IO, TP, OCC>, Error<IO::Error>> {
log::trace!("Dir::write_entry {name}");
// check if name doesn't contain unsupported characters
validate_long_name(name)?;
// convert long name to UTF-16
let lfn_utf16 = Self::encode_lfn_utf16(name);
// write LFN entries, except for . and .., which need to be at
// the first two slots and don't need LFNs anyway
let (mut stream, start_pos) = if name == "." || name == ".." {
self.alloc_sfn_entry()?
} else {
self.alloc_and_write_lfn_entries(&lfn_utf16, raw_entry.name())?
};
// write short name entry
raw_entry.serialize(&mut stream)?;
// Get position directory stream after entries were written
let end_pos = stream.seek(super::super::io::SeekFrom::Current(0))?;
// Get current absolute position on the storage
// Unwrapping is safe because abs_pos() returns None only if stream is at position 0. This is not
// the case because an entry was just written
// Note: if current position is on the cluster boundary then a position in the cluster containing the entry is
// returned
let end_abs_pos = stream.abs_pos().unwrap();
// Calculate SFN entry start position on the storage
let start_abs_pos = end_abs_pos - u64::from(DIR_ENTRY_SIZE);
// return new logical entry descriptor
let short_name = ShortName::new(raw_entry.name());
Ok(DirEntry {
data: raw_entry,
short_name,
#[cfg(feature = "lfn")]
lfn_utf16,
fs: self.fs.clone(),
entry_pos: start_abs_pos,
offset_range: (start_pos, end_pos),
})
}
}
// Note: derive cannot be used because of invalid bounds. See: https://github.com/rust-lang/rust/issues/26925
impl<IO: ReadWriteSeek + Send + Debug, TP: TimeProvider, OCC: OemCpConverter> Clone
for Dir<IO, TP, OCC>
{
fn clone(&self) -> Self {
Self {
stream: self.stream.clone(),
fs: self.fs.clone(),
}
}
}
/// An iterator over the directory entries.
///
/// This struct is created by the `iter` method on `Dir`.
pub struct DirIter<IO: ReadWriteSeek + Send + Debug, TP, OCC> {
stream: DirRawStream<IO, TP, OCC>,
fs: Arc<FileSystem<IO, TP, OCC>>,
skip_volume: bool,
err: bool,
}
impl<IO: ReadWriteSeek + Send + Debug, TP, OCC> DirIter<IO, TP, OCC> {
fn new(
stream: DirRawStream<IO, TP, OCC>,
fs: Arc<FileSystem<IO, TP, OCC>>,
skip_volume: bool,
) -> Self {
DirIter {
stream,
fs,
skip_volume,
err: false,
}
}
}
impl<IO: ReadWriteSeek + Send + Debug, TP: TimeProvider, OCC> DirIter<IO, TP, OCC> {
fn should_skip_entry(&self, raw_entry: &DirEntryData) -> bool {
if raw_entry.is_deleted() {
return true;
}
match raw_entry {
DirEntryData::File(sfn_entry) => self.skip_volume && sfn_entry.is_volume(),
DirEntryData::Lfn(_) => false,
}
}
#[allow(clippy::type_complexity)]
fn read_dir_entry(&mut self) -> Result<Option<DirEntry<IO, TP, OCC>>, Error<IO::Error>> {
log::trace!("DirIter::read_dir_entry");
let mut lfn_builder = LongNameBuilder::new();
let mut offset = self.stream.seek(SeekFrom::Current(0))?;
let mut begin_offset = offset;
loop {
let raw_entry = DirEntryData::deserialize(&mut self.stream)?;
offset += u64::from(DIR_ENTRY_SIZE);
// Check if this is end of dir
if raw_entry.is_end() {
return Ok(None);
}
// Check if this is deleted or volume ID entry
if self.should_skip_entry(&raw_entry) {
log::trace!("skip entry");
lfn_builder.clear();
begin_offset = offset;
continue;
}
match raw_entry {
DirEntryData::File(data) => {
// Get current absolute position on the storage
// Unwrapping is safe because abs_pos() returns None only if stream is at position 0. This is not
// the case because an entry was just read
// Note: if current position is on the cluster boundary then a position in the cluster containing the entry is
// returned
let end_abs_pos = self.stream.abs_pos().unwrap();
// Calculate SFN entry start position on the storage
let abs_pos = end_abs_pos - u64::from(DIR_ENTRY_SIZE);
// Check if LFN checksum is valid
lfn_builder.validate_chksum(data.name());
// Return directory entry
let short_name = ShortName::new(data.name());
log::trace!("file entry {:?}", data.name());
return Ok(Some(DirEntry {
data,
short_name,
#[cfg(feature = "lfn")]
lfn_utf16: lfn_builder.into_buf(),
fs: self.fs.clone(),
entry_pos: abs_pos,
offset_range: (begin_offset, offset),
}));
}
DirEntryData::Lfn(data) => {
// Append to LFN buffer
log::trace!("lfn entry");
lfn_builder.process(&data);
}
}
}
}
}
// Note: derive cannot be used because of invalid bounds. See: https://github.com/rust-lang/rust/issues/26925
impl<IO: ReadWriteSeek + Send + Debug, TP, OCC> Clone for DirIter<IO, TP, OCC> {
fn clone(&self) -> Self {
Self {
stream: self.stream.clone(),
fs: self.fs.clone(),
err: self.err,
skip_volume: self.skip_volume,
}
}
}
impl<IO: ReadWriteSeek + Send + Debug, TP: TimeProvider, OCC> Iterator for DirIter<IO, TP, OCC> {
type Item = Result<DirEntry<IO, TP, OCC>, Error<IO::Error>>;
fn next(&mut self) -> Option<Self::Item> {
if self.err {
return None;
}
let r = self.read_dir_entry();
match r {
Ok(Some(e)) => Some(Ok(e)),
Ok(None) => None,
Err(err) => {
self.err = true;
Some(Err(err))
}
}
}
}
#[rustfmt::skip]
fn validate_long_name<E: IoError>(name: &str) -> Result<(), Error<E>> {
// check if length is valid
if name.is_empty() {
return Err(Error::InvalidFileNameLength);
}
if name.len() > MAX_LONG_NAME_LEN {
return Err(Error::InvalidFileNameLength);
}
// check if there are only valid characters
for c in name.chars() {
match c {
'a'..='z' | 'A'..='Z' | '0'..='9'
| '\u{80}'..='\u{FFFF}'
| '$' | '%' | '\'' | '-' | '_' | '@' | '~' | '`' | '!' | '(' | ')' | '{' | '}' | '.' | ' ' | '+' | ','
| ';' | '=' | '[' | ']' | '^' | '#' | '&' => {},
_ => return Err(Error::UnsupportedFileNameCharacter),
}
}
Ok(())
}
fn lfn_checksum(short_name: &[u8; SFN_SIZE]) -> u8 {
let mut chksum = num::Wrapping(0_u8);
for b in short_name {
chksum = (chksum << 7) + (chksum >> 1) + num::Wrapping(*b);
}
chksum.0
}
#[cfg(feature = "lfn")]
#[derive(Clone)]
pub(crate) struct LfnBuffer {
ucs2_units: Vec<u16>,
}
const MAX_LONG_NAME_LEN: usize = 255;
#[cfg(feature = "lfn")]
const MAX_LONG_DIR_ENTRIES: usize = (MAX_LONG_NAME_LEN + LFN_PART_LEN - 1) / LFN_PART_LEN;
#[cfg(feature = "lfn")]
const LONG_NAME_BUFFER_LEN: usize = MAX_LONG_DIR_ENTRIES * LFN_PART_LEN;
#[cfg(feature = "lfn")]
#[derive(Clone)]
pub(crate) struct LfnBuffer {
ucs2_units: [u16; LONG_NAME_BUFFER_LEN],
len: usize,
}
#[cfg(feature = "lfn")]
impl LfnBuffer {
fn new() -> Self {
Self {
ucs2_units: Vec::<u16>::new(),
}
}
fn from_ucs2_units<I: Iterator<Item = u16>>(usc2_units: I) -> Self {
Self {
ucs2_units: usc2_units.collect(),
}
}
fn clear(&mut self) {
self.ucs2_units.clear();
}
pub(crate) fn len(&self) -> usize {
self.ucs2_units.len()
}
fn set_len(&mut self, len: usize) {
self.ucs2_units.resize(len, 0_u16);
}
pub(crate) fn as_ucs2_units(&self) -> &[u16] {
&self.ucs2_units
}
}
#[cfg(feature = "lfn")]
impl LfnBuffer {
fn new() -> Self {
Self {
ucs2_units: [0_u16; LONG_NAME_BUFFER_LEN],
len: 0,
}
}
fn from_ucs2_units<I: Iterator<Item = u16>>(usc2_units: I) -> Self {
let mut lfn = Self {
ucs2_units: [0_u16; LONG_NAME_BUFFER_LEN],
len: 0,
};
for (i, usc2_unit) in usc2_units.enumerate() {
lfn.ucs2_units[i] = usc2_unit;
lfn.len += 1;
}
lfn
}
fn clear(&mut self) {
self.ucs2_units = [0_u16; LONG_NAME_BUFFER_LEN];
self.len = 0;
}
pub(crate) fn len(&self) -> usize {
self.len
}
fn set_len(&mut self, len: usize) {
self.len = len;
}
pub(crate) fn as_ucs2_units(&self) -> &[u16] {
&self.ucs2_units[..self.len]
}
}
#[cfg(not(feature = "lfn"))]
#[derive(Clone)]
pub(crate) struct LfnBuffer {}
#[cfg(not(feature = "lfn"))]
impl LfnBuffer {
#[allow(clippy::unused_self)]
pub(crate) fn as_ucs2_units(&self) -> &[u16] {
&[]
}
}
#[cfg(feature = "lfn")]
struct LongNameBuilder {
buf: LfnBuffer,
chksum: u8,
index: u8,
}
#[cfg(feature = "lfn")]
impl LongNameBuilder {
fn new() -> Self {
Self {
buf: LfnBuffer::new(),
chksum: 0,
index: 0,
}
}
fn clear(&mut self) {
self.buf.clear();
self.index = 0;
}
fn into_buf(mut self) -> LfnBuffer {
// Check if last processed entry had index 1
if self.index == 1 {
self.truncate();
} else if !self.is_empty() {
warn!("unfinished LFN sequence {}", self.index);
self.clear();
}
self.buf
}
fn truncate(&mut self) {
// Truncate 0 and 0xFFFF characters from LFN buffer
let ucs2_units = &self.buf.ucs2_units;
let new_len = ucs2_units
.iter()
.rposition(|c| *c != 0xFFFF && *c != 0)
.map_or(0, |n| n + 1);
self.buf.set_len(new_len);
}
fn is_empty(&self) -> bool {
// Check if any LFN entry has been processed
// Note: index 0 is not a valid index in LFN and can be seen only after struct initialization
self.index == 0
}
fn process(&mut self, data: &DirLfnEntryData) {
let is_last = (data.order() & LFN_ENTRY_LAST_FLAG) != 0;
let index = data.order() & 0x1F;
if index == 0 || usize::from(index) > MAX_LONG_DIR_ENTRIES {
// Corrupted entry
warn!("currupted lfn entry! {:x}", data.order());
self.clear();
return;
}
if is_last {
// last entry is actually first entry in stream
self.index = index;
self.chksum = data.checksum();
self.buf.set_len(usize::from(index) * LFN_PART_LEN);
} else if self.index == 0 || index != self.index - 1 || data.checksum() != self.chksum {
// Corrupted entry
warn!(
"currupted lfn entry! {:x} {:x} {:x} {:x}",
data.order(),
self.index,
data.checksum(),
self.chksum
);
self.clear();
return;
} else {
// Decrement LFN index only for non-last entries
self.index -= 1;
}
let pos = LFN_PART_LEN * usize::from(index - 1);
// copy name parts into LFN buffer
data.copy_name_to_slice(&mut self.buf.ucs2_units[pos..pos + 13]);
}
fn validate_chksum(&mut self, short_name: &[u8; SFN_SIZE]) {
if self.is_empty() {
// Nothing to validate - no LFN entries has been processed
return;
}
let chksum = lfn_checksum(short_name);
if chksum != self.chksum {
warn!(
"checksum mismatch {:x} {:x} {:?}",
chksum, self.chksum, short_name
);
self.clear();
}
}
}
// Dummy implementation for non-alloc build
struct LongNameBuilder {}
impl LongNameBuilder {
fn new() -> Self {
LongNameBuilder {}
}
#[allow(clippy::unused_self)]
fn clear(&mut self) {}
#[allow(clippy::unused_self)]
#[cfg(feature = "lfn")]
fn into_vec(self) {}
#[allow(clippy::unused_self)]
#[cfg(feature = "lfn")]