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
//! Sparse image writing and decoding to raw images.

use std::fs::File as StdFile;
use std::io::{Read, Seek, SeekFrom, Write};

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

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

/// Writes sparse files to sparse images.
pub struct Writer<W> {
    dst: W,
    crc: Option<crc32::Digest>,
}

impl<W: Write> Writer<W> {
    /// Creates a new sparse file writer that writes to `dst`.
    pub fn new(dst: W) -> Self {
        Self { dst, crc: None }
    }

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

    /// Writes `sparse_file` to this writer's destination.
    pub fn write(mut self, sparse_file: &File) -> Result<()> {
        self.write_file_header(sparse_file)?;

        for chunk in sparse_file.chunk_iter() {
            self.write_chunk(chunk)?;
        }

        self.write_end_chunk()
    }

    fn write_file_header(&mut self, spf: &File) -> Result<()> {
        let mut total_chunks = spf.num_chunks();
        if self.crc.is_some() {
            total_chunks += 1; // count extra Crc32 chunk
        }

        // Like libsparse, we always set the checksum value in the file header
        // to 0. If checksum writing is enabled, we append a Crc32 chunk at
        // the end of the file instead.
        let image_checksum = 0;

        let header = FileHeader {
            total_blocks: spf.num_blocks(),
            total_chunks,
            image_checksum,
        };
        header.serialize(&mut self.dst)
    }

    fn write_chunk(&mut self, chunk: &Chunk) -> Result<()> {
        self.write_chunk_header(chunk)?;

        match *chunk {
            Chunk::Raw {
                ref file,
                offset,
                num_blocks,
            } => self.write_raw_chunk(&*file.borrow_mut(), offset, num_blocks),
            Chunk::Fill { fill, num_blocks } => self.write_fill_chunk(fill, num_blocks),
            Chunk::DontCare { num_blocks } => self.write_dont_care_chunk(num_blocks),
            Chunk::Crc32 { crc } => self.write_crc32_chunk(crc),
        }
    }

    fn write_chunk_header(&mut self, chunk: &Chunk) -> Result<()> {
        let chunk_type = match chunk {
            Chunk::Raw { .. } => ChunkType::Raw,
            Chunk::Fill { .. } => ChunkType::Fill,
            Chunk::DontCare { .. } => ChunkType::DontCare,
            Chunk::Crc32 { .. } => ChunkType::Crc32,
        };
        let header = ChunkHeader {
            chunk_type,
            chunk_size: chunk.num_blocks(),
            total_size: chunk.sparse_size(),
        };
        header.serialize(&mut self.dst)
    }

    fn write_raw_chunk(&mut self, file: &StdFile, offset: u64, num_blocks: u32) -> Result<()> {
        let mut file = file.try_clone()?;
        file.seek(SeekFrom::Start(offset))?;

        if let Some(ref mut digest) = self.crc {
            let mut block = [0; BLOCK_SIZE as usize];
            for _ in 0..num_blocks {
                file.read_exact(&mut block)?;
                digest.write(&block);
                self.dst.write_all(&block)?;
            }
        } else {
            copy_blocks(&mut file, &mut self.dst, num_blocks)?;
        }

        Ok(())
    }

    fn write_fill_chunk(&mut self, fill: [u8; 4], num_blocks: u32) -> Result<()> {
        if let Some(ref mut digest) = self.crc {
            for _ in 0..(num_blocks * BLOCK_SIZE / 4) {
                digest.write(&fill);
            }
        }

        self.dst.write_all(&fill).map_err(|e| e.into())
    }

    fn write_dont_care_chunk(&mut self, 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);
            }
        }

        Ok(())
    }

    fn write_crc32_chunk(&mut self, crc: u32) -> Result<()> {
        self.dst
            .write_u32::<LittleEndian>(crc)
            .map_err(|e| e.into())
    }

    fn write_end_chunk(&mut self) -> Result<()> {
        let crc = self.crc.take();
        if let Some(digest) = crc {
            let chunk = Chunk::Crc32 {
                crc: digest.sum32(),
            };
            self.write_chunk(&chunk)
        } else {
            Ok(())
        }
    }
}

/// Decodes sparse files and writes them as raw images.
pub struct Decoder<W> {
    dst: W,
}

impl<W: Write> Decoder<W> {
    /// Creates a new sparse file decoder that writes to `dst`.
    pub fn new(dst: W) -> Self {
        Self { dst }
    }

    /// Decodes `sparse_file` and write the raw image to this decoder's
    /// destination.
    pub fn write(mut self, sparse_file: &File) -> Result<()> {
        for chunk in sparse_file.chunk_iter() {
            self.write_chunk(chunk)?;
        }

        Ok(())
    }

    fn write_chunk(&mut self, chunk: &Chunk) -> Result<()> {
        match *chunk {
            Chunk::Raw {
                ref file,
                offset,
                num_blocks,
            } => copy_from_file(&*file.borrow(), &mut self.dst, offset, num_blocks)?,

            Chunk::Fill { fill, num_blocks } => {
                let block = fill
                    .iter()
                    .cycle()
                    .cloned()
                    .take(BLOCK_SIZE as usize)
                    .collect::<Vec<_>>();
                for _ in 0..num_blocks {
                    self.dst.write_all(&block)?;
                }
            }

            Chunk::DontCare { num_blocks } => {
                let block = [0; BLOCK_SIZE as usize];
                for _ in 0..num_blocks {
                    self.dst.write_all(&block)?;
                }
            }

            Chunk::Crc32 { .. } => (),
        };

        Ok(())
    }
}

/// Starting from `offset`, reads `num_blocks` blocks from `file` and copies
/// them to `writer`.
fn copy_from_file<W: Write>(file: &StdFile, writer: W, offset: u64, num_blocks: u32) -> Result<()> {
    let mut file = file.try_clone()?;
    file.seek(SeekFrom::Start(offset))?;
    copy_blocks(&mut file, writer, num_blocks)
}

/// Copies `num_blocks` blocks from `r` to `w`.
fn copy_blocks<R: Read, W: Write>(mut r: R, mut w: W, num_blocks: u32) -> Result<()> {
    let mut block = [0; BLOCK_SIZE as usize];
    for _ in 0..num_blocks {
        r.read_exact(&mut block)?;
        w.write_all(&block)?;
    }

    Ok(())
}