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
//! Directory entry parser of FAT32.

use crate::from_bytes;
use core::{
    cmp,
    convert::{TryFrom, TryInto},
    num, str,
};

use alloc::vec::Vec;
use kalloc::wrapper::vec_push;
use kcore::error::{Error, Result};

const SPACE: u8 = 0x20;

pub const ATTR_READ_ONLY: u8 = 0x01;
pub const ATTR_HIDDEN: u8 = 0x02;
pub const ATTR_SYSTEM: u8 = 0x04;
pub const ATTR_VOLUME_ID: u8 = 0x08;
pub const ATTR_LONG_NAME: u8 = ATTR_READ_ONLY | ATTR_HIDDEN | ATTR_SYSTEM | ATTR_VOLUME_ID;

pub const ATTR_DIRECTORY: u8 = 0x10;
/// Normal file. See https://en.wikipedia.org/wiki/Archive_bit
pub const ATTR_ARCHIVE: u8 = 0x20;
pub const ATTR_LONG_NAME_MASK: u8 = ATTR_LONG_NAME | ATTR_DIRECTORY | ATTR_ARCHIVE;

pub const LAST_LONG_ENTRY: u8 = 0x40;
pub const MAX_LONG_ENTRY: u8 = LAST_LONG_ENTRY - 1;

/// Maximum number x of the numeric tail ~x.
pub const MAX_NUMERIC_TAIL: usize = 999999;
/// Each directory entry in FAT32 is of 32 bytes.
pub const DIRENTSZ: usize = 32;

/// Get the 8.3-style file name, convert to lowercase.
pub fn sfn_name(buf: &[u8; DIRENTSZ]) -> Result<Vec<u16>> {
    let mut name = Vec::new();
    let mut has_dot = false;
    for i in (0..8).take_while(|i| buf[i.clone()] != SPACE) {
        vec_push(&mut name, buf[i].to_ascii_lowercase() as u16)?;
    }
    for i in (8..11).take_while(|i| buf[i.clone()] != SPACE) {
        if !has_dot {
            vec_push(&mut name, b'.' as u16)?;
            has_dot = true;
        }
        vec_push(&mut name, buf[i].to_ascii_lowercase() as u16)?;
    }
    Ok(name)
}

pub fn sfn_set_name(buf: &mut [u8; DIRENTSZ], name: &[u8; 11]) {
    buf[0..11].copy_from_slice(name);
}

/// Get the file size in bytes.
pub fn sfn_size(buf: &[u8; DIRENTSZ]) -> u32 {
    from_bytes!(u32, buf[28..32])
}
/// Alter the file size field of a sfn entry.
pub fn sfn_set_size(buf: &mut [u8; DIRENTSZ], sz: u32) {
    buf[28..32].copy_from_slice(&sz.to_le_bytes());
}

/// Get the cluster number of the file.
pub fn sfn_cno(buf: &[u8; DIRENTSZ]) -> u32 {
    let hi = from_bytes!(u16, buf[20..22]) as u32;
    let lo = from_bytes!(u16, buf[26..28]) as u32;
    (hi << 16) | lo
}

/// Set the cluster number of the file.
pub fn sfn_set_cno(buf: &mut [u8; DIRENTSZ], cno: u32) {
    let hi = (cno >> 16) as u16;
    let lo = (cno & 0xFFFF) as u16;
    buf[20..22].copy_from_slice(&hi.to_le_bytes());
    buf[26..28].copy_from_slice(&lo.to_le_bytes());
}

/// Get File attribute.
pub fn sfn_attr(buf: &[u8; DIRENTSZ]) -> u8 {
    buf[11]
}

/// Set File attribute.
pub fn sfn_set_attr(buf: &mut [u8; DIRENTSZ], attr: u8) {
    buf[11] = attr
}

/// Get name from a LFN entry.
pub fn lfn_name(buf: &[u8; DIRENTSZ]) -> Result<Vec<u16>> {
    let mut name = Vec::new();
    let range = [(1..11), (14..26), (28..32)];
    for rg in range.iter() {
        for i in rg.clone().step_by(2) {
            if buf[i] == 0 && buf[i + 1] == 0 {
                return Ok(name);
            }
            vec_push(&mut name, from_bytes!(u16, buf[i..i + 2]))?;
        }
    }
    Ok(name)
}

/// Initialize the LFN entry by setting some default values.
pub fn lfn_init(buf: &mut [u8; DIRENTSZ], chksum: u8) {
    buf[11] = ATTR_LONG_NAME;
    buf[13] = chksum;

    // If zero, indicates a directory entry that is a sub-component of along name.
    // NOTE: Other values reserved for future extensions. Non-zero implies other dirent types.
    buf[12] = 0;

    // Must be ZERO. This is an artifact of the FAT "first cluster" and must be zero for
    // compatibility with existing disk utilities.
    // It's meaningless in the context of a long dir entry.
    buf[26] = 0;
    buf[27] = 0;
}

pub fn lfn_set_name(buf: &mut [u8; DIRENTSZ], name: &[u16]) {
    let len = name.len();
    let rng = [(1..11), (14..26), (28..32)];
    let mut end = false;
    let mut i = 0;
    for rg in rng.iter() {
        for bi in rg.clone().step_by(2) {
            if end {
                buf[bi..(bi + 2)].copy_from_slice(&(0xFFFF as u16).to_le_bytes());
            } else {
                let x = if let Some(x) = name.get(i) {
                    *x
                } else {
                    end = true;
                    0
                };
                buf[bi..(bi + 2)].copy_from_slice(&x.to_le_bytes());
                i += 1;
            }
        }
    }
}

/// Compute the checksum of SFN.
pub fn checksum(buf: &[u8]) -> u8 {
    let mut chksum = num::Wrapping(0_u8);
    for x in buf.iter() {
        chksum = (chksum << 7) + (chksum >> 1) + num::Wrapping(*x);
    }
    chksum.0
}

/// Convert utf-8 bytes to utf-16.
pub fn utf8_to_utf16(bytes: &[u8]) -> Result<Vec<u16>> {
    let mut ret = Vec::new();
    let str = str::from_utf8(bytes).map_err(|_| Error::BadRequest("utf8 to utf16 failed"))?;
    for c in str.chars() {
        let mut buf = [0u16; 2];
        let buf = c.encode_utf16(&mut buf);
        for x in buf {
            vec_push(&mut ret, *x)?;
        }
    }
    Ok(ret)
}

fn valid_sfn_char(c: &char) -> bool {
    match c {
        '\u{80}'..='\u{FF}' => true,
        'a'..='z' | 'A'..='Z' | '0'..='9' => true,
        '$' | '%' | '\'' | '-' | '_' | '@' | '~' | '`' | '!' | '(' | ')' | '{' | '}' | '^'
        | '#' | '&' => true,
        '.' => true,
        _ => false,
    }
}

/// Valid file name.
#[derive(Debug)]
pub struct Filename {
    pub base_len: usize,
    pub ext_len: usize,
    pub has_period: bool,
    /// Is it a SFN or LFN?
    pub is_sfn: bool,
    pub data: Vec<u16>,
}

impl Filename {
    /// Number of required entries to store this file name.
    pub fn nent(&self) -> usize {
        if self.is_sfn {
            1
        } else {
            1 + (self.data.len() + 12) / 13
        }
    }
    /// Generate SFN from LFN.
    pub fn gen_sfn(&self, mut i: usize) -> Result<Self> {
        assert_eq!(self.is_sfn, false);
        debug_assert!(1 <= i && i <= MAX_NUMERIC_TAIL);

        let mut data = Vec::new();
        data.try_reserve(8)?;
        for c in self.data[0..cmp::min(8, self.data.len())].iter() {
            let mut c = if *c > 0xFF { '_' } else { *c as u8 as char };
            if !valid_sfn_char(&c) || c == '.' {
                c = '_';
            }
            let c = c.to_ascii_uppercase();
            data.push(c as u16);
        }
        // Padded with '_'.
        while data.len() < 8 {
            data.push(b'_' as u16);
        }

        // Overwrite with "~xxx".
        let mut di = 7;
        while i != 0 {
            data[di] = b'0' as u16 + (i % 10) as u16;
            i /= 10;
            di -= 1;
        }
        data[di] = b'~' as u16;

        Ok(Self {
            base_len: 8,
            ext_len: 0,
            has_period: false,
            is_sfn: true,
            data,
        })
    }

    /// Dump SFN to buffer.
    pub fn dump_sfn(&self, buf: &mut [u8; 11]) {
        debug_assert_eq!(self.is_sfn, true);
        debug_assert!(self.base_len <= 8 && self.ext_len <= 3);
        for b in buf.iter_mut() {
            *b = b' ';
        }
        for (mut i, b) in self.data.iter().enumerate() {
            if i >= self.base_len {
                i = if self.has_period {
                    if i == self.base_len {
                        continue;
                    } else {
                        8 + i - self.base_len - 1
                    }
                } else {
                    8 + i - self.base_len
                };
            }
            buf[i] = (*b as u8).to_ascii_uppercase();
        }
    }
}

impl TryFrom<&[u8]> for Filename {
    type Error = Error;
    /// The rule for LFN is slightly different from FAT32 specification.
    /// We allow any bytes in LFN.
    fn try_from(bytes: &[u8]) -> core::result::Result<Self, Self::Error> {
        if bytes.len() > 0 && (bytes[0] == 0 || bytes[0] == 0xE5) {
            return Err(Error::BadRequest("empty file name"));
        }

        let mut data = Vec::new();
        let str: &str =
            str::from_utf8(bytes).map_err(|_| Error::BadRequest("filename invalid utf-8"))?;
        let mut is_sfn = true;
        let mut nperiod = 0;
        for c in str.chars() {
            if c == 0 as char {
                break;
            }
            // Valid character set of SFN.
            if valid_sfn_char(&c) {
                if c == '.' {
                    nperiod += 1;
                    if nperiod > 1 {
                        is_sfn = false;
                    }
                }
            } else {
                is_sfn = false;
            }
            let mut buf = [0u16; 2];
            let buf = c.encode_utf16(&mut buf);
            for x in buf {
                vec_push(&mut data, *x)?;
            }
        }

        if data.is_empty() || data.len() > 255 {
            return Err(Error::BadRequest("file name is empty or too long"));
        }

        let last_period = data.iter().enumerate().rfind(|(i, c)| **c == '.' as u16);
        let (base_len, ext_len, has_period) = if let Some((i, c)) = last_period {
            (i, data.len() - i - 1, true)
        } else {
            (data.len(), 0, false)
        };

        if base_len == 0 || base_len > 8 || ext_len > 3 {
            is_sfn = false;
        }
        Ok(Self {
            base_len,
            ext_len,
            has_period,
            is_sfn,
            data,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_sfn() {
        let ent: [u8; DIRENTSZ] = [
            b'a', b'b', b'c', b' ', b' ', b' ', b' ', b' ', b't', b'x', b't', 0x20, 0x18, 0x7D,
            0x11, 0xB8, 0x2C, 0x3B, 0x2C, 0x3B, 0, 0, 0x29, 0xB8, 0x2C, 0x3B, 0x03, 0, 0xC8, 0x07,
            0, 0,
        ];
        assert_eq!(sfn_size(&ent), 1992);
        assert_eq!(sfn_cno(&ent), 3);
    }

    #[test]
    fn test_invalid_filename() {
        assert_eq!(Filename::try_from(b"" as &[u8]).is_err(), true);
        assert_eq!(Filename::try_from(b"\0" as &[u8]).is_err(), true);
        assert_eq!(Filename::try_from(b"\xE5" as &[u8]).is_err(), true);
        assert_eq!(Filename::try_from(b"\xFF\xFF\xFF" as &[u8]).is_err(), true);
    }

    #[test]
    fn test_to_sfn() {
        let mut buf = [0u8; 11];

        let fname = Filename::try_from(b"foo.bar" as &[u8]).unwrap();
        fname.dump_sfn(&mut buf);
        assert_eq!(&buf, b"FOO     BAR");
        assert_eq!(fname.is_sfn, true);
        assert_eq!(fname.has_period, true);
        assert_eq!(fname.base_len, 3);
        assert_eq!(fname.ext_len, 3);

        let fname = Filename::try_from(b"foo\0.bar" as &[u8]).unwrap();
        fname.dump_sfn(&mut buf);
        assert_eq!(&buf, b"FOO        ");
        assert_eq!(fname.is_sfn, true);
        assert_eq!(fname.has_period, false);
        assert_eq!(fname.base_len, 3);
        assert_eq!(fname.ext_len, 0);

        let fname = Filename::try_from(b"Foo.Bar" as &[u8]).unwrap();
        fname.dump_sfn(&mut buf);
        assert_eq!(&buf, b"FOO     BAR");
        assert_eq!(fname.is_sfn, true);
        assert_eq!(fname.has_period, true);
        assert_eq!(fname.base_len, 3);
        assert_eq!(fname.ext_len, 3);

        let fname = Filename::try_from(b"foo" as &[u8]).unwrap();
        fname.dump_sfn(&mut buf);
        assert_eq!(&buf, b"FOO        ");
        assert_eq!(fname.is_sfn, true);
        assert_eq!(fname.has_period, false);
        assert_eq!(fname.base_len, 3);
        assert_eq!(fname.ext_len, 0);

        let fname = Filename::try_from(b"foo." as &[u8]).unwrap();
        fname.dump_sfn(&mut buf);
        assert_eq!(&buf, b"FOO        ");
        assert_eq!(fname.is_sfn, true);
        assert_eq!(fname.has_period, true);
        assert_eq!(fname.base_len, 3);
        assert_eq!(fname.ext_len, 0);

        let fname = Filename::try_from(b"PICKLE.A" as &[u8]).unwrap();
        fname.dump_sfn(&mut buf);
        assert_eq!(&buf, b"PICKLE  A  ");
        assert_eq!(fname.is_sfn, true);
        assert_eq!(fname.has_period, true);
        assert_eq!(fname.base_len, 6);
        assert_eq!(fname.ext_len, 1);

        let fname = Filename::try_from(b"prettybg.big" as &[u8]).unwrap();
        fname.dump_sfn(&mut buf);
        assert_eq!(&buf, b"PRETTYBGBIG");
        assert_eq!(fname.is_sfn, true);
        assert_eq!(fname.has_period, true);
        assert_eq!(fname.base_len, 8);
        assert_eq!(fname.ext_len, 3);
    }

    #[test]
    fn test_to_lfn() {
        let fname = Filename::try_from(b".big" as &[u8]).unwrap();
        assert_eq!(fname.is_sfn, false);
        assert_eq!(fname.base_len, 0);
        assert_eq!(fname.ext_len, 3);
        assert_eq!(fname.has_period, true);
        assert_eq!(
            fname.gen_sfn(1).unwrap().data,
            Filename::try_from(b"_BIG__~1" as &[u8]).unwrap().data
        );

        let fname = Filename::try_from(b"foo.bar1" as &[u8]).unwrap();
        assert_eq!(fname.is_sfn, false);
        assert_eq!(fname.base_len, 3);
        assert_eq!(fname.ext_len, 4);
        assert_eq!(fname.has_period, true);
        assert_eq!(
            fname.gen_sfn(1).unwrap().data,
            Filename::try_from(b"FOO_BA~1" as &[u8]).unwrap().data
        );

        let fname = Filename::try_from(b"foo.bar." as &[u8]).unwrap();
        assert_eq!(fname.is_sfn, false);
        assert_eq!(fname.base_len, 7);
        assert_eq!(fname.ext_len, 0);
        assert_eq!(fname.has_period, true);
        assert_eq!(
            fname.gen_sfn(2).unwrap().data,
            Filename::try_from(b"FOO_BA~2" as &[u8]).unwrap().data
        );

        let fname = Filename::try_from(b"F.BAR.X" as &[u8]).unwrap();
        assert_eq!(fname.is_sfn, false);
        assert_eq!(fname.base_len, 5);
        assert_eq!(fname.ext_len, 1);
        assert_eq!(fname.has_period, true);
        assert_eq!(
            fname.gen_sfn(2).unwrap().data,
            Filename::try_from(b"F_BAR_~2" as &[u8]).unwrap().data
        );

        let fname = Filename::try_from(b"foo bar" as &[u8]).unwrap();
        assert_eq!(fname.is_sfn, false);
        assert_eq!(fname.base_len, 7);
        assert_eq!(fname.ext_len, 0);
        assert_eq!(fname.has_period, false);
        assert_eq!(
            fname.gen_sfn(2).unwrap().data,
            Filename::try_from(b"FOO_BA~2" as &[u8]).unwrap().data
        );

        let fname = Filename::try_from(b" " as &[u8]).unwrap();
        assert_eq!(fname.is_sfn, false);
        assert_eq!(fname.base_len, 1);
        assert_eq!(fname.ext_len, 0);
        assert_eq!(fname.has_period, false);
        assert_eq!(
            fname.gen_sfn(100).unwrap().data,
            Filename::try_from(b"____~100" as &[u8]).unwrap().data
        );

        let fname = Filename::try_from(b"\x10" as &[u8]).unwrap();
        assert_eq!(fname.is_sfn, false);
        assert_eq!(fname.base_len, 1);
        assert_eq!(fname.ext_len, 0);
        assert_eq!(fname.has_period, false);
        assert_eq!(
            fname.gen_sfn(999999).unwrap().data,
            Filename::try_from(b"_~999999" as &[u8]).unwrap().data
        );
    }

    #[test]
    fn test_lfn_set_name() {
        let mut buf = [0u8; DIRENTSZ];
        let name = "foo-bar-123";
        let name2 = utf8_to_utf16(name.as_bytes()).unwrap();

        lfn_set_name(&mut buf, &name2);
        let lname = lfn_name(&buf).unwrap();
        assert_eq!(name2, lname);
        assert_eq!(&buf[1..11], &[b'f', 0, b'o', 0, b'o', 0, b'-', 0, b'b', 0]);
        assert_eq!(
            &buf[14..26],
            &[b'a', 0, b'r', 0, b'-', 0, b'1', 0, b'2', 0, b'3', 0]
        );
        assert_eq!(&buf[28..32], &[0, 0, 0xFF, 0xFF]);
    }
}