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
//             DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
//                    Version 2, December 2004
//
// Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
//
// Everyone is permitted to copy and distribute verbatim or modified
// copies of this license document, and changing it is allowed as long
// as the name is changed.
//
//            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
//   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
//
//  0. You just DO WHAT THE FUCK YOU WANT TO.
//
// Author: zadig <thomas chr(0x40) bailleux.me>

use std;

#[derive(Debug)]
pub(crate) enum NodeColour {
  Red,
  Black
}

impl NodeColour {
  fn from(t: u8) -> Result<NodeColour, super::error::OLEError> {
    match t {
      0 => Ok(NodeColour::Red),
      1 => Ok(NodeColour::Black),
      _ => Err(super::error::OLEError::NodeTypeUnknown)
    }
  }
}

impl std::fmt::Display for NodeColour {
  fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
    match *self {
      NodeColour::Red => write!(f, "RED"),
      NodeColour::Black => write!(f, "BLACK")
    }
  }
}

#[derive(Debug, Clone, Copy)]
pub enum EntryType {
  /// Empty entry.
  Empty,

  /// Storage, i.e. a directory.
  UserStorage,

  /// Stream, i.e. a file.
  UserStream,

  /// LockBytes (unknown usage).
  LockBytes,

  /// Property (unknown usage).
  Property,

  /// Root storage.
  RootStorage
}

impl EntryType {
  fn from(t: u8) -> Result<EntryType, super::error::OLEError> {
    match t {
      0 => Ok(EntryType::Empty),
      1 => Ok(EntryType::UserStorage),
      2 => Ok(EntryType::UserStream),
      3 => Ok(EntryType::LockBytes),
      4 => Ok(EntryType::Property),
      5 => Ok(EntryType::RootStorage),
      _ => Err(super::error::OLEError::NodeTypeUnknown)
    }
  }
}

impl std::fmt::Display for EntryType {
  fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
    match *self {
      EntryType::Empty => write!(f, "Empty"),
      EntryType::UserStorage => write!(f, "User storage"),
      EntryType::UserStream => write!(f, "User stream"),
      EntryType::LockBytes => write!(f, "?? Lock bytes ??"),
      EntryType::Property => write!(f, "?? Property ??"),
      EntryType::RootStorage => write!(f, "Root storage")
    }
  }
}

#[derive(Debug)]
pub struct Timestamp {}

/// An entry in an OLE file.
///
/// An entry means a stream or a storage.
/// A stream is a file, and a storage is a folder.
///
/// # Basic Example
///
/// ```
/// use ole::OLEReader;
///
/// let mut parser =
///       OLEReader::<std::fs::File>::from_path("assets/Thumbs.db").unwrap();
///
/// let entry = parser.iterate().next().unwrap();
/// println!("Name of the entry: {}", entry.name());
/// println!("Type of the entry: {}", entry._type());
/// println!("Size of the entry: {}", entry.len());
/// ```
#[derive(Debug)]
pub struct OLEEntry {

  /// ID of the entry.
  id: u32,

  /// Name of the stream or the storage.
  name: std::string::String,

  /// Type of the entry.
  entry_type: EntryType,

  /// Color of the entry (see <https://en.wikipedia.org/wiki/Red%E2%80%93black_tree>)
  color: NodeColour,

  /// ID of the left child entry.
  left_child_node: u32,

  /// ID of the right child entry.
  right_child_node: u32,

  /// ID of the root entry.
  root_node: u32,

  /// UID of the entry.
  identifier: std::vec::Vec<u8>, // 16 bytes

  /// Flags of the entry.
  flags: std::vec::Vec<u8>, // 4 bytes

  /// Creation time.
  creation_time: Option<Timestamp>,

  /// Last modification time.
  last_modification_time: Option<Timestamp>,

  /// Chain of secID which hold the stream or the storage
  sec_id_chain: std::vec::Vec<u32>,

  /// Size of the entry.
  size: usize
}

impl OLEEntry {

  fn from_slice(sector: &[u8], dir_id: u32)
      -> Result<OLEEntry, super::error::OLEError> {
    use util::FromSlice;
    let entry = OLEEntry {
      id: dir_id,
      name: OLEEntry::build_name(&sector[0 .. 64]),
      entry_type: EntryType::from(sector[66])?,
      color: NodeColour::from(sector[67])?,
      left_child_node: u32::from_slice(&sector[68 .. 72]),
      right_child_node: u32::from_slice(&sector[72 .. 76]),
      root_node: u32::from_slice(&sector[76 .. 80]),
      identifier: sector[80 .. 96].to_vec(),
      flags: sector[96 .. 100].to_vec(),
      creation_time: None,
      last_modification_time: None,
      sec_id_chain: vec![u32::from_slice(&sector[116 .. 120])],
      size: usize::from_slice(&sector[120 .. 124])
    };


    Ok(entry)

  }

  fn build_name(array: &[u8]) -> std::string::String {
    let mut name = std::string::String::new();

    let mut i = 0usize;
    while i < 64 && array[i] != 0 {
      name.push(array[i] as char);
      i = i + 2;
    }

    name
  }

  /// Returns the ID of the entry.
  pub fn id(&self) -> u32 {
    self.id
  }

  /// Returns the creation time of the entry, if defined (i.e. not zero).
  pub fn creation_time(&self) -> Option<&Timestamp> {
    self.creation_time.as_ref()
  }


  /// Returns the last modification time of the entry, if defined (i.e. not zero).
  pub fn last_modification_time(&self) -> Option<&Timestamp> {
    self.last_modification_time.as_ref()
  }

  /// Returns the name of the entry.
  pub fn name(&self) -> &str {
    &self.name
  }

  /// Return the type of the entry.
  pub fn _type(&self) -> EntryType {
    self.entry_type
  }

  /// Return the size of the entry
  pub fn len(&self) -> usize {
    self.size
  }

}

impl std::fmt::Display for OLEEntry {
  fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
    write!(f, "Entry #{}. Type: {}, Color: {}, Name: {},
      Size: {}. SecID chain: {:?}",
      self.id, self.entry_type, self.color, &self.name,
      self.size, self.sec_id_chain)
  }
}


/// Slice of the content of the entry.
///
/// This is not an ordinary slice, because OLE files are like FAT system:
/// they are based on sector and SAT. Therefore, a stream can be fragmented
/// through the file.
///
/// # Basic example
///
/// ```
/// use ole::OLEReader;
/// use std::io::Read;
/// let mut parser =
///       OLEReader::<std::fs::File>::from_path("assets/Thumbs.db").unwrap();
///
/// let entry = parser.iterate().next().unwrap();
/// let mut slice = parser.get_entry_slice(entry).unwrap();
/// // Read the first 42 bytes of the entry;
/// let mut buf = [0u8; 42];
/// let nread = slice.read(&mut buf).unwrap();
///
/// ```
pub struct OLEEntrySlice<'s> {

  /// Chunk size, i.e. size of the sector.
  max_chunk_size: usize,

  /// List of slices.
  chunks: std::vec::Vec<&'s [u8]>,

  /// How many bytes which have been already read.
  read: usize,

  /// Total size of slice.
  total_size: usize
}

impl<'s> OLEEntrySlice<'s> {
  fn new(max_chunk_size: usize, size: usize) -> OLEEntrySlice<'s> {
    OLEEntrySlice {
      max_chunk_size: max_chunk_size,
      chunks: std::vec::Vec::new(),
      read: 0usize,
      total_size: size
    }
  }

  fn add_chunk(&mut self, chunk: &'s [u8]) {
    self.chunks.push(chunk);
  }

  /// Returns the length of the slice, therefore the length of the entry.
  pub fn len(&self) -> usize {
    self.total_size
  }
}

impl<'s> std::io::Read for OLEEntrySlice<'s> {

  fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
    println!("READ: {}, MAX_CHUNK_SIZE: {}, TOTAL_SIZE: {}", self.read,
      self.max_chunk_size, self.total_size);
    let to_read = std::cmp::min(buf.len(), self.total_size - self.read);
    let result: Result<usize, std::io::Error>;
    if to_read == 0 {
      result = Ok(0usize);
    } else {
      let mut offset = self.read;
      let mut read = 0;
      while read != to_read {
        let chunk_index = offset / self.max_chunk_size;
        if chunk_index >= self.chunks.len() {
          break;
        }
        let chunk = &self.chunks[chunk_index];
        let local_offset = offset % self.max_chunk_size;
        let end = std::cmp::min(local_offset + to_read - read,
        self.max_chunk_size);
        let slice = &chunk[local_offset .. end];
        for u in slice {
          buf[read] = *u;
          read += 1;
          self.read += 1;
        }
        offset = self.read;
      }
      result = Ok(read);
    }

    result
  }
}




impl<T> super::ole::OLEReader<T>
  where T: std::io::Read {


  /// Returns the slice for the entry.
  pub fn get_entry_slice(&self, entry: &OLEEntry) ->
    Result<OLEEntrySlice, super::error::OLEError> {

    let entry_slice: OLEEntrySlice;
    let size = entry.size;
    if &size < self.minimum_standard_stream_size.as_ref().unwrap() {
      // sometimes, this rule is not followed. So you're gi
      entry_slice = self.get_short_stream_slices(&entry.sec_id_chain, size)?;
    } else {
      entry_slice = self.get_stream_slices(&entry.sec_id_chain, size)?;
    }

    Ok(entry_slice)
  }

  pub(crate) fn build_directory_entries(&mut self)
      -> Result<(), super::error::OLEError> {
    let n_entry_by_sector = self.sec_size.as_ref().unwrap()
      / super::constants::DIRECTORY_ENTRY_SIZE;
    let mut entries = std::vec::Vec::<OLEEntry>::with_capacity(
      self.dsat.as_ref().unwrap().len() * n_entry_by_sector);

    let mut k = 0usize;
    for i in 0 .. self.dsat.as_ref().unwrap().len() {
      let sector_index = self.dsat.as_ref().unwrap()[i];
      let sector = self.read_sector(sector_index as usize)?;
      for l in 0 .. n_entry_by_sector - 1 {
        let entry = OLEEntry::from_slice(&sector[l
          * super::constants::DIRECTORY_ENTRY_SIZE .. (l + 1)
          * super::constants::DIRECTORY_ENTRY_SIZE], k as u32)?;
        entries.push(entry);
        k = k + 1;
      }
    }
    let stream_size = *self.minimum_standard_stream_size.as_ref().unwrap();
    for i in 0 .. entries.len() {
      let entry = &mut entries[i];
      match entry.entry_type {
        EntryType::UserStream => {
          let start_index = entry.sec_id_chain.pop().unwrap();
          if entry.size < stream_size {
            entry.sec_id_chain = self.build_chain_from_ssat(start_index);
          } else {
            entry.sec_id_chain = self.build_chain_from_sat(start_index);
          }
        },
        EntryType::RootStorage => {
          self.root_entry = Some(i as u32);
          let start_index = entry.sec_id_chain.pop().unwrap();
          entry.sec_id_chain = self.build_chain_from_sat(start_index);
        },
        _ => {}
      }
    }
    self.entries = Some(entries);
    Ok(())
  }

  fn get_short_stream_slices(&self, chain: &std::vec::Vec<u32>, size: usize)
  -> Result<OLEEntrySlice, super::error::OLEError> {
    let ssector_size = *self.short_sec_size.as_ref().unwrap();
    let mut entry_slice = OLEEntrySlice::new(ssector_size, size);
    let short_stream_chain =
    &self.entries.as_ref().unwrap()[0].sec_id_chain.clone();
    let n_per_sector = *self.sec_size.as_ref().unwrap() /
      ssector_size;
    let mut total_read = 0;
    for ssector_id in chain {
      let sector_index = short_stream_chain[*ssector_id as usize / n_per_sector];
      let sector = self.read_sector(sector_index as usize)?;
      let ssector_index = *ssector_id as usize % n_per_sector;
      let start = ssector_index as usize * ssector_size;
      let end = start + std::cmp::min(ssector_size, size - total_read);
      entry_slice.add_chunk(&sector[start .. end]);
      total_read += end - start;
    }
    //assert_eq!(total_read, size);
    Ok(entry_slice)
  }

  fn get_stream_slices(&self, chain: &std::vec::Vec<u32>, size: usize)
  -> Result<OLEEntrySlice, super::error::OLEError> {
    let sector_size = *self.sec_size.as_ref().unwrap();
    let mut entry_slice = OLEEntrySlice::new(sector_size, size);
    let mut total_read = 0;
    for sector_id in chain {
      let sector = self.read_sector(*sector_id as usize)?;
      let start = 0usize;
      let end = std::cmp::min(sector_size, size - total_read);
      entry_slice.add_chunk(&sector[start .. end]);
      total_read += end - start;
    }
    assert_eq!(total_read, size);
    Ok(entry_slice)
  }
}