calamine/
cfb.rs

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
//! Compound File Binary format MS-CFB

use std::borrow::Cow;
use std::cmp::min;
use std::io::Read;

use log::debug;

use encoding_rs::{Encoding, UTF_16LE, UTF_8};

use crate::utils::*;

const RESERVED_SECTORS: u32 = 0xFFFF_FFFA;
const DIFSECT: u32 = 0xFFFF_FFFC;
// const FATSECT: u32 = 0xFFFF_FFFD;
const ENDOFCHAIN: u32 = 0xFFFF_FFFE;
//const FREESECT: u32 = 0xFFFF_FFFF;

/// A Cfb specific error enum
#[derive(Debug)]
pub enum CfbError {
    Io(std::io::Error),
    Ole,
    EmptyRootDir,
    StreamNotFound(String),
    Invalid {
        name: &'static str,
        expected: &'static str,
        found: u16,
    },
    CodePageNotFound(u16),
}

impl std::fmt::Display for CfbError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CfbError::Io(e) => write!(f, "I/O error: {}", e),
            CfbError::Ole => write!(f, "Invalid OLE signature (not an office document?)"),
            CfbError::EmptyRootDir => write!(f, "Empty Root directory"),
            CfbError::StreamNotFound(e) => write!(f, "Cannot find {} stream", e),
            CfbError::Invalid {
                name,
                expected,
                found,
            } => write!(
                f,
                "Invalid {}, expecting {} found {:X}",
                name, expected, found
            ),
            CfbError::CodePageNotFound(e) => write!(f, "Codepage {:X} not found", e),
        }
    }
}

impl std::error::Error for CfbError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            CfbError::Io(e) => Some(e),
            _ => None,
        }
    }
}

/// A struct for managing Compound File Binary format
#[derive(Debug, Clone)]
pub struct Cfb {
    directories: Vec<Directory>,
    sectors: Sectors,
    fats: Vec<u32>,
    mini_sectors: Sectors,
    mini_fats: Vec<u32>,
}

impl Cfb {
    /// Create a new `Cfb`
    ///
    /// Starts reading project metadata (header, directories, sectors and minisectors).
    pub fn new<R: Read>(mut reader: &mut R, len: usize) -> Result<Cfb, CfbError> {
        // load header
        let (h, mut difat) = Header::from_reader(&mut reader)?;
        let mut sectors = Sectors::new(h.sector_size, Vec::with_capacity(len));

        // load fat and dif sectors
        debug!("load difat {h:?}");
        let mut sector_id = h.difat_start;
        while sector_id < RESERVED_SECTORS {
            difat.extend(to_u32(sectors.get(sector_id, reader)?));
            sector_id = difat.pop().unwrap(); //TODO: check if in infinite loop
        }

        // load the FATs
        debug!("load fat (len {})", h.fat_len);
        let mut fats = Vec::with_capacity(h.fat_len);
        for id in difat.into_iter().filter(|id| *id < DIFSECT) {
            fats.extend(to_u32(sectors.get(id, reader)?));
        }

        // get the list of directory sectors
        debug!("load directories");
        let dirs = sectors.get_chain(h.dir_start, &fats, reader, h.dir_len * h.sector_size)?;
        let dirs = dirs
            .chunks(128)
            .map(|c| Directory::from_slice(c, h.sector_size))
            .collect::<Vec<_>>();

        if dirs.is_empty() || (h.version != 3 && dirs[0].start == ENDOFCHAIN) {
            return Err(CfbError::EmptyRootDir);
        }

        // load the mini streams
        debug!("load minis {dirs:?}");
        let (mini_fats, ministream) = if h.mini_fat_len > 0 {
            let ministream = sectors.get_chain(dirs[0].start, &fats, reader, dirs[0].len)?;
            let minifat = sectors.get_chain(
                h.mini_fat_start,
                &fats,
                reader,
                h.mini_fat_len * h.sector_size,
            )?;
            let minifat = to_u32(&minifat).collect();
            (minifat, ministream)
        } else {
            (Vec::new(), Vec::new())
        };
        Ok(Cfb {
            directories: dirs,
            sectors,
            fats,
            mini_sectors: Sectors::new(64, ministream),
            mini_fats,
        })
    }

    /// Checks if directory exists
    pub fn has_directory(&self, name: &str) -> bool {
        self.directories.iter().any(|d| &*d.name == name)
    }

    /// Gets a stream by name out of directories
    pub fn get_stream<R: Read>(&mut self, name: &str, r: &mut R) -> Result<Vec<u8>, CfbError> {
        match self.directories.iter().find(|d| &*d.name == name) {
            None => Err(CfbError::StreamNotFound(name.to_string())),
            Some(d) => {
                if d.len < 4096 {
                    // TODO: Study the possibility to return a `VecArray` (stack allocated)
                    self.mini_sectors
                        .get_chain(d.start, &self.mini_fats, r, d.len)
                } else {
                    self.sectors.get_chain(d.start, &self.fats, r, d.len)
                }
            }
        }
    }
}

/// A hidden struct which defines cfb files structure
#[derive(Debug)]
struct Header {
    version: u16,
    sector_size: usize,
    dir_len: usize,
    dir_start: u32,
    fat_len: usize,
    mini_fat_len: usize,
    mini_fat_start: u32,
    difat_start: u32,
}

impl Header {
    fn from_reader<R: Read>(f: &mut R) -> Result<(Header, Vec<u32>), CfbError> {
        let mut buf = [0u8; 512];
        f.read_exact(&mut buf).map_err(CfbError::Io)?;

        // check ole signature
        let signature = buf
            .get(0..8)
            .map(|slice| u64::from_le_bytes(slice.try_into().unwrap()));
        if signature != Some(0xE11A_B1A1_E011_CFD0) {
            return Err(CfbError::Ole);
        }

        let version = read_u16(&buf[26..28]);

        let sector_size = match read_u16(&buf[30..32]) {
            0x0009 => 512,
            0x000C => {
                // sector size is 4096 bytes, but header is 512 bytes,
                // so the remaining sector bytes have to be read
                let mut buf_end = [0u8; 4096 - 512];
                f.read_exact(&mut buf_end).map_err(CfbError::Io)?;
                4096
            }
            s => {
                return Err(CfbError::Invalid {
                    name: "sector shift",
                    expected: "0x09 or 0x0C",
                    found: s,
                });
            }
        };

        if read_u16(&buf[32..34]) != 0x0006 {
            return Err(CfbError::Invalid {
                name: "minisector shift",
                expected: "0x06",
                found: read_u16(&buf[32..34]),
            });
        }

        let dir_len = read_usize(&buf[40..44]);
        let fat_len = read_usize(&buf[44..48]);
        let dir_start = read_u32(&buf[48..52]);
        let mini_fat_start = read_u32(&buf[60..64]);
        let mini_fat_len = read_usize(&buf[64..68]);
        let difat_start = read_u32(&buf[68..72]);
        let difat_len = read_usize(&buf[62..76]);

        let mut difat = Vec::with_capacity(difat_len);
        difat.extend(to_u32(&buf[76..512]));

        Ok((
            Header {
                version,
                sector_size,
                dir_len,
                dir_start,
                fat_len,
                mini_fat_len,
                mini_fat_start,
                difat_start,
            },
            difat,
        ))
    }
}

/// A struct corresponding to the elementary block of memory
///
/// `data` will persist in memory to ensure the file is read once
#[derive(Debug, Clone)]
struct Sectors {
    data: Vec<u8>,
    size: usize,
}

impl Sectors {
    fn new(size: usize, data: Vec<u8>) -> Sectors {
        Sectors { data, size }
    }

    fn get<R: Read>(&mut self, id: u32, r: &mut R) -> Result<&[u8], CfbError> {
        let start = id as usize * self.size;
        let end = start + self.size;
        if end > self.data.len() {
            let mut len = self.data.len();
            self.data.resize(end, 0);
            // read_exact or stop if EOF
            while len < end {
                let read = r.read(&mut self.data[len..end]).map_err(CfbError::Io)?;
                if read == 0 {
                    return Ok(&self.data[start..len]);
                }
                len += read;
            }
        }
        Ok(&self.data[start..end])
    }

    fn get_chain<R: Read>(
        &mut self,
        mut sector_id: u32,
        fats: &[u32],
        r: &mut R,
        len: usize,
    ) -> Result<Vec<u8>, CfbError> {
        let mut chain = if len > 0 {
            Vec::with_capacity(len)
        } else {
            Vec::new()
        };
        while sector_id != ENDOFCHAIN {
            chain.extend_from_slice(self.get(sector_id, r)?);
            sector_id = fats[sector_id as usize];
        }
        if len > 0 {
            chain.truncate(len);
        }
        Ok(chain)
    }
}

/// A struct representing sector organizations, behaves similarly to a tree
#[derive(Debug, Clone)]
struct Directory {
    name: String,
    start: u32,
    len: usize,
}

impl Directory {
    fn from_slice(buf: &[u8], sector_size: usize) -> Directory {
        let mut name = UTF_16LE.decode(&buf[..64]).0.into_owned();
        if let Some(l) = name.as_bytes().iter().position(|b| *b == 0) {
            name.truncate(l);
        }
        let start = read_u32(&buf[116..120]);
        let len: usize = if sector_size == 512 {
            read_u32(&buf[120..124]).try_into().unwrap()
        } else {
            read_u64(&buf[120..128]).try_into().unwrap()
        };

        Directory { start, len, name }
    }
}

/// Decompresses stream
pub fn decompress_stream(s: &[u8]) -> Result<Vec<u8>, CfbError> {
    const POWER_2: [usize; 16] = [
        1,
        1 << 1,
        1 << 2,
        1 << 3,
        1 << 4,
        1 << 5,
        1 << 6,
        1 << 7,
        1 << 8,
        1 << 9,
        1 << 10,
        1 << 11,
        1 << 12,
        1 << 13,
        1 << 14,
        1 << 15,
    ];

    debug!("decompress stream");
    let mut res = Vec::new();

    if s[0] != 0x01 {
        return Err(CfbError::Invalid {
            name: "signature",
            expected: "0x01",
            found: s[0] as u16,
        });
    }

    let mut i = 1;
    while i < s.len() {
        let chunk_header = read_u16(&s[i..]);
        i += 2;

        // each 'chunk' is 4096 wide, let's reserve that space
        let start = res.len();
        res.reserve(4096);

        let chunk_size = chunk_header & 0x0FFF;
        let chunk_signature = (chunk_header & 0x7000) >> 12;
        let chunk_flag = (chunk_header & 0x8000) >> 15;

        assert_eq!(chunk_signature, 0b011, "i={}, len={}", i, s.len());

        if chunk_flag == 0 {
            // uncompressed
            res.extend_from_slice(&s[i..i + 4096]);
            i += 4096;
        } else {
            let mut chunk_len = 0;
            let mut buf = [0u8; 4096];
            'chunk: loop {
                if i >= s.len() {
                    break;
                }

                let bit_flags = s[i];
                i += 1;
                chunk_len += 1;

                for bit_index in 0..8 {
                    if chunk_len > chunk_size {
                        break 'chunk;
                    }

                    if (bit_flags & (1 << bit_index)) == 0 {
                        // literal token
                        res.push(s[i]);
                        i += 1;
                        chunk_len += 1;
                    } else {
                        // copy token
                        let token = read_u16(&s[i..]);
                        i += 2;
                        chunk_len += 2;

                        let decomp_len = res.len() - start;
                        let bit_count = (4..16).find(|i| POWER_2[*i] >= decomp_len).unwrap();
                        let len_mask = 0xFFFF >> bit_count;
                        let mut len = (token & len_mask) as usize + 3;
                        let offset = ((token & !len_mask) >> (16 - bit_count)) as usize + 1;

                        while len > offset {
                            buf[..offset].copy_from_slice(&res[res.len() - offset..]);
                            res.extend_from_slice(&buf[..offset]);
                            len -= offset;
                        }
                        buf[..len]
                            .copy_from_slice(&res[res.len() - offset..res.len() - offset + len]);
                        res.extend_from_slice(&buf[..len]);
                    }
                }
            }
        }
    }
    Ok(res)
}

#[derive(Clone)]
pub struct XlsEncoding {
    encoding: &'static Encoding,
}

impl XlsEncoding {
    pub fn from_codepage(codepage: u16) -> Result<XlsEncoding, CfbError> {
        let e = codepage::to_encoding(codepage).ok_or(CfbError::CodePageNotFound(codepage))?;
        Ok(XlsEncoding { encoding: e })
    }

    fn high_byte(&self, high_byte: Option<bool>) -> Option<bool> {
        high_byte.or_else(|| {
            if self.encoding == UTF_8 || self.encoding.is_single_byte() {
                None
            } else {
                Some(false)
            }
        })
    }

    pub fn decode_to(
        &self,
        stream: &[u8],
        len: usize,
        s: &mut String,
        high_byte: Option<bool>,
    ) -> (usize, usize) {
        let (l, ub, bytes) = match self.high_byte(high_byte) {
            None => {
                let l = min(stream.len(), len);
                (l, l, Cow::Borrowed(&stream[..l]))
            }
            Some(false) => {
                let l = min(stream.len(), len);

                // add 0x00 high bytes to unicodes
                let mut bytes = vec![0; l * 2];
                for (i, sce) in stream.iter().take(l).enumerate() {
                    bytes[2 * i] = *sce;
                }
                (l, l, Cow::Owned(bytes))
            }
            Some(true) => {
                let l = min(stream.len() / 2, len);
                (l, 2 * l, Cow::Borrowed(&stream[..2 * l]))
            }
        };

        s.push_str(&self.encoding.decode(&bytes).0);
        (l, ub)
    }

    pub fn decode_all(&self, stream: &[u8]) -> String {
        self.encoding.decode(stream).0.into_owned()
    }
}