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
//! Sparse image reading and raw image encoding.

use std::cell::RefCell;
use std::fs::File as StdFile;
use std::io::{ErrorKind, Read, Seek, SeekFrom};
use std::rc::Rc;

use byteorder::{LittleEndian, ReadBytesExt};
use crc::crc32;
use crc::crc32::Hasher32;

use constants::BLOCK_SIZE;
use file::{Chunk, File};
use headers::{ChunkHeader, ChunkType, FileHeader};
use result::Result;

/// Reads sparse files from sparse images.
pub struct Reader {
    src: Rc<RefCell<StdFile>>,
    crc: Option<crc32::Digest>,
}

impl Reader {
    /// Creates a new sparse file reader that reads from `src`.
    pub fn new(src: StdFile) -> Self {
        Self {
            src: Rc::new(RefCell::new(src)),
            crc: None,
        }
    }

    /// Enables CRC32 checksum validation.
    pub fn with_crc(mut self) -> Self {
        self.crc = Some(crc32::Digest::new(crc32::IEEE));
        self
    }

    /// Reads `sparse_file` from this reader's source.
    pub fn read(mut self, mut sparse_file: &mut File) -> Result<()> {
        let header = FileHeader::deserialize(&*self.src.borrow_mut())?;
        for _ in 0..header.total_chunks {
            self.read_chunk(&mut sparse_file)?;
        }

        Ok(())
    }

    fn read_chunk(&mut self, mut spf: &mut File) -> Result<()> {
        let header = ChunkHeader::deserialize(&*self.src.borrow_mut())?;
        let num_blocks = header.chunk_size;

        match header.chunk_type {
            ChunkType::Raw => self.read_raw_chunk(&mut spf, num_blocks),
            ChunkType::Fill => self.read_fill_chunk(&mut spf, num_blocks),
            ChunkType::DontCare => self.read_dont_care_chunk(&mut spf, num_blocks),
            ChunkType::Crc32 => self.read_crc32_chunk(&mut spf),
        }
    }

    fn read_raw_chunk(&mut self, spf: &mut File, num_blocks: u32) -> Result<()> {
        let offset = self.src.borrow_mut().seek(SeekFrom::Current(0))?;

        if let Some(ref mut digest) = self.crc {
            let mut block = [0; BLOCK_SIZE as usize];
            for _ in 0..num_blocks {
                self.src.borrow_mut().read_exact(&mut block)?;
                digest.write(&block);
            }
        } else {
            let size = i64::from(num_blocks * BLOCK_SIZE);
            self.src.borrow_mut().seek(SeekFrom::Current(size))?;
        }

        let chunk = Chunk::Raw {
            file: self.src.clone(),
            offset,
            num_blocks,
        };
        spf.add_chunk(chunk);

        Ok(())
    }

    fn read_fill_chunk(&mut self, spf: &mut File, num_blocks: u32) -> Result<()> {
        let fill = read4(&*self.src.borrow_mut())?;

        if let Some(ref mut digest) = self.crc {
            for _ in 0..(num_blocks * BLOCK_SIZE / 4) {
                digest.write(&fill);
            }
        }

        let chunk = Chunk::Fill { fill, num_blocks };
        spf.add_chunk(chunk);

        Ok(())
    }

    fn read_dont_care_chunk(&mut self, spf: &mut File, num_blocks: u32) -> Result<()> {
        if let Some(ref mut digest) = self.crc {
            let block = [0; BLOCK_SIZE as usize];
            for _ in 0..num_blocks {
                digest.write(&block);
            }
        }

        let chunk = Chunk::DontCare { num_blocks };
        spf.add_chunk(chunk);

        Ok(())
    }

    fn read_crc32_chunk(&mut self, spf: &mut File) -> Result<()> {
        let crc = self.src.borrow_mut().read_u32::<LittleEndian>()?;
        self.check_crc(crc)?;

        let chunk = Chunk::Crc32 { crc };
        spf.add_chunk(chunk);

        Ok(())
    }

    fn check_crc(&self, crc: u32) -> Result<()> {
        if let Some(ref digest) = self.crc {
            if digest.sum32() != crc {
                return Err("Checksum does not match".into());
            }
        }
        Ok(())
    }
}

/// Reads raw images and encodes them as sparse files.
pub struct Encoder {
    src: Rc<RefCell<StdFile>>,
    chunk: Option<Chunk>,
}

impl Encoder {
    /// Creates a new sparse file encoder that reads from `src`.
    pub fn new(src: StdFile) -> Self {
        Self {
            src: Rc::new(RefCell::new(src)),
            chunk: None,
        }
    }

    /// Reads a raw image from this encoder's source and encodes it into
    /// `sparse_file`.
    pub fn read(mut self, mut sparse_file: &mut File) -> Result<()> {
        let block_size = BLOCK_SIZE as usize;
        let mut block = vec![0; block_size];
        loop {
            let bytes_read = read_all(&*self.src.borrow_mut(), &mut block)?;
            self.read_block(&mut sparse_file, &block[..bytes_read])?;
            if bytes_read != block_size {
                break;
            }
        }

        if let Some(last_chunk) = self.chunk.take() {
            sparse_file.add_chunk(last_chunk);
        }

        Ok(())
    }

    fn read_block(&mut self, spf: &mut File, block: &[u8]) -> Result<()> {
        if block.is_empty() {
            return Ok(());
        }

        if let Some(chunk) = self.merge_block(block)? {
            spf.add_chunk(chunk);
        }

        Ok(())
    }

    /// Tries to merge `block` into the current chunk. If this is not
    /// possible, returns the current chunk and makes `block` the new current
    /// chunk.
    fn merge_block(&mut self, block: &[u8]) -> Result<Option<Chunk>> {
        if is_sparse_block(block) {
            let fill = read4(block)?;
            if fill == [0; 4] {
                Ok(self.merge_don_care_block())
            } else {
                Ok(self.merge_fill_block(fill))
            }
        } else {
            self.merge_raw_block()
        }
    }

    /// Tries to merge the current chunk with the following raw block.
    fn merge_raw_block(&mut self) -> Result<Option<Chunk>> {
        let (old, new) = match self.chunk.take() {
            Some(Chunk::Raw {
                file,
                offset,
                num_blocks,
            }) => {
                let merged = Chunk::Raw {
                    file,
                    offset,
                    num_blocks: num_blocks + 1,
                };
                (None, merged)
            }
            old_chunk => {
                let mut file = self.src.clone();
                let curr_off = file.borrow_mut().seek(SeekFrom::Current(0))?;
                let new_chunk = Chunk::Raw {
                    file,
                    offset: curr_off - u64::from(BLOCK_SIZE),
                    num_blocks: 1,
                };
                (old_chunk, new_chunk)
            }
        };
        self.chunk = Some(new);
        Ok(old)
    }

    /// Tries to merge the current chunk with the following block, filled with
    /// `fill`.
    fn merge_fill_block(&mut self, fill: [u8; 4]) -> Option<Chunk> {
        let new_fill = fill;
        let (old, new) = match self.chunk.take() {
            Some(Chunk::Fill { fill, num_blocks }) if fill == new_fill => (
                None,
                Chunk::Fill {
                    fill,
                    num_blocks: num_blocks + 1,
                },
            ),
            old_chunk => (
                old_chunk,
                Chunk::Fill {
                    fill: new_fill,
                    num_blocks: 1,
                },
            ),
        };
        self.chunk = Some(new);
        old
    }

    // Tries to merge the current chunk with the following don't-care block.
    fn merge_don_care_block(&mut self) -> Option<Chunk> {
        let (old, new) = match self.chunk.take() {
            Some(Chunk::DontCare { num_blocks }) => (
                None,
                Chunk::DontCare {
                    num_blocks: num_blocks + 1,
                },
            ),
            old_chunk => (old_chunk, Chunk::DontCare { num_blocks: 1 }),
        };
        self.chunk = Some(new);
        old
    }
}

/// Is `block` filled with the same 4-byte value?
fn is_sparse_block(block: &[u8]) -> bool {
    if block.len() != BLOCK_SIZE as usize {
        return false;
    }

    let mut words = block.chunks(4);
    let first = words.next().unwrap();
    for word in words {
        if word != first {
            return false;
        }
    }

    true
}

/// Reads 4 bytes from `r`.
fn read4<R: Read>(mut r: R) -> Result<[u8; 4]> {
    let mut buf = [0; 4];
    r.read_exact(&mut buf)?;
    Ok(buf)
}

/// Fills `buf` from `r`, returns an error if not possible.
fn read_all<R: Read>(mut r: R, mut buf: &mut [u8]) -> Result<usize> {
    let buf_size = buf.len();

    while !buf.is_empty() {
        match r.read(buf) {
            Ok(0) => break,
            Ok(n) => {
                let tmp = buf;
                buf = &mut tmp[n..]
            }
            Err(ref e) if e.kind() == ErrorKind::Interrupted => (),
            Err(e) => return Err(e.into()),
        };
    }

    Ok(buf_size - buf.len())
}