Skip to content

Add LFN support #155

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/fat/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,11 +252,12 @@ mod test {
let on_disk_entry = OnDiskDirEntry::new(part);
match expected {
Expected::Lfn(start, index, contents) if on_disk_entry.is_lfn() => {
let (calc_start, calc_index, calc_contents) =
let (calc_start, calc_index, calc_contents, _) =
on_disk_entry.lfn_contents().unwrap();
assert_eq!(*start, calc_start);
assert_eq!(*index, calc_index);
assert_eq!(*contents, calc_contents);
// TODO: Check checksum
}
Expected::Short(expected_entry) if !on_disk_entry.is_lfn() => {
let parsed_entry = on_disk_entry.get_entry(FatType::Fat32, BlockIdx(0), 0);
Expand Down
33 changes: 30 additions & 3 deletions src/fat/ondiskdirentry.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
//! Directory Entry as stored on-disk

use crate::{fat::FatType, Attributes, BlockIdx, ClusterId, DirEntry, ShortFileName, Timestamp};
use crate::{
fat::FatType, sdcard::proto::dos_name_checksum, Attributes, BlockIdx, ClusterId, DirEntry,
ShortFileName, Timestamp,
};
use byteorder::{ByteOrder, LittleEndian};
use heapless::String;

/// A 32-byte directory entry as stored on-disk in a directory file.
///
Expand Down Expand Up @@ -78,11 +82,12 @@ impl<'a> OnDiskDirEntry<'a> {
}

/// If this is an LFN, get the contents so we can re-assemble the filename.
pub fn lfn_contents(&self) -> Option<(bool, u8, [char; 13])> {
pub fn lfn_contents(&self) -> Option<(bool, u8, [char; 13], u8)> {
if self.is_lfn() {
let mut buffer = [' '; 13];
let is_start = (self.data[0] & 0x40) != 0;
let sequence = self.data[0] & 0x1F;
let checksum = self.data[13];
// LFNs store UCS-2, so we can map from 16-bit char to 32-bit char without problem.
buffer[0] =
core::char::from_u32(u32::from(LittleEndian::read_u16(&self.data[1..=2]))).unwrap();
Expand Down Expand Up @@ -118,7 +123,7 @@ impl<'a> OnDiskDirEntry<'a> {
buffer[12] =
core::char::from_u32(u32::from(LittleEndian::read_u16(&self.data[30..=31])))
.unwrap();
Some((is_start, sequence, buffer))
Some((is_start, sequence, buffer, checksum))
} else {
None
}
Expand Down Expand Up @@ -177,6 +182,28 @@ impl<'a> OnDiskDirEntry<'a> {
result.name.contents.copy_from_slice(&self.data[0..11]);
result
}

/// Get the CRC hash of this entry
pub fn get_name_hash(&self) -> u8 {
return dos_name_checksum(&self.data[0..11]);
}

/// Get short name in form of string
pub fn get_name(&self) -> String<255> {
let mut name: String<255> = String::new();
let mut seen_dot = false;
for it in &self.data[0..11] {
if *it == b' ' {
if !seen_dot {
name.push('.');
seen_dot = true;
}
} else {
name.push(*it as char);
}
}
name
}
}

// ****************************************************************************
Expand Down
100 changes: 95 additions & 5 deletions src/fat/volume.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,80 @@ use crate::{
};
use byteorder::{ByteOrder, LittleEndian};
use core::convert::TryFrom;
use heapless::{String, Vec};

/// Helper struct to construct a Long File Name (LFN)
struct LFNStack {
stack: Vec<String<32>, 8>,
current_checksum: Option<u8>,
current_sequence: Option<u8>,
}

impl LFNStack {
pub fn new() -> Self {
Self {
stack: Vec::new(),
current_checksum: None,
current_sequence: None,
}
}

fn clear(&mut self) {
self.stack.clear();
self.current_checksum = None;
self.current_sequence = None;

}

pub fn maybe_push(&mut self, is_start: bool, sequence: u8, data: [char; 13], checksum: u8) {
if is_start {
self.clear();
}
// Case for malformed LFN entries, if they ale placed before
// actual entries
let checksum_ok = match self.current_checksum {
Some(c) => c == checksum,
None => true,
};
let sequence_ok = match self.current_sequence {
Some(s) => sequence == s - 1 && sequence < 8,
None => true,
};
if checksum_ok && sequence_ok {
self.current_checksum = Some(checksum);
self.current_sequence = Some(sequence);

let mut name_chunk: String<32> = String::new();
for i in 0..13 {
if data[i] == '\0' {
break;
}
name_chunk.push(data[i]).unwrap();
}
self.stack.push(name_chunk).unwrap();
} else {
self.clear();
}
}

pub fn create_name(&mut self, hash: u8) -> Result<String<255>, ()> {
let hash_correct = match self.current_checksum {
Some(c) => c == hash,
None => false,
};
if self.stack.is_empty() || !hash_correct {
return Err(());
}
let mut filename: String<255> = String::new();
self.stack.reverse();
for name_chunk in self.stack.iter() {
filename.push_str(name_chunk).unwrap();
}
self.clear();

Ok(filename)
}
}

/// An MS-DOS 11 character volume label.
///
Expand Down Expand Up @@ -613,6 +687,9 @@ impl FatVolume {
ClusterId::ROOT_DIR => Some(fat32_info.first_root_dir_cluster),
_ => Some(dir_info.cluster),
};

let mut lfn_stack = LFNStack::new();

while let Some(cluster) = current_cluster {
let start_block_idx = self.cluster_to_block(cluster);
for block_idx in start_block_idx.range(BlockCount(u32::from(self.blocks_per_cluster))) {
Expand All @@ -623,11 +700,24 @@ impl FatVolume {
if dir_entry.is_end() {
// Can quit early
return Ok(());
} else if dir_entry.is_valid() && !dir_entry.is_lfn() {
// Safe, since Block::LEN always fits on a u32
let start = (i * OnDiskDirEntry::LEN) as u32;
let entry = dir_entry.get_entry(FatType::Fat32, block_idx, start);
func(&entry);
} else if dir_entry.is_valid() {
if dir_entry.is_lfn() {
if let Some((is_start, sequence, data, checksum)) =
dir_entry.lfn_contents()
{
lfn_stack.maybe_push(is_start, sequence, data, checksum);
}
} else {
let lfn_filename = match lfn_stack.create_name(dir_entry.get_name_hash()) {
Ok(n) => n,
Err(_) => dir_entry.get_name(),
};

// Safe, since Block::LEN always fits on a u32
let start = (i * OnDiskDirEntry::LEN) as u32;
let entry = dir_entry.get_entry(FatType::Fat32, block_idx, start);
func(&entry);
}
}
}
}
Expand Down
15 changes: 15 additions & 0 deletions src/sdcard/proto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,15 @@ pub fn crc16(data: &[u8]) -> u16 {
crc
}

/// DOS name checksum
pub fn dos_name_checksum(data: &[u8]) -> u8 {
let mut sum: u8 = 0;
for item in data.iter() {
sum = sum.rotate_right(1).overflowing_add(*item).0;
}
sum
}

// ****************************************************************************
//
// Unit Tests
Expand All @@ -264,6 +273,12 @@ mod test {
assert_eq!(crc16(&DATA), 0x9fc5);
}

#[test]
fn test_name_checksum() {
const DATA: [u8; 15] = hex!("00 26 00 32 5F 59 83 C8 AD DB CF FF D2 40 40");
assert_eq!(dos_name_checksum(&DATA), 0xFA);
}

#[test]
fn test_csdv1b() {
const EXAMPLE: CsdV1 = CsdV1 {
Expand Down
Loading