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

use std::fs::File;
use std::io::{prelude::*, BufWriter, SeekFrom};

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

use block::Block;
use ext::{Tell, WriteBlock};
use headers::{ChunkHeader, ChunkType, FileHeader};
use result::Result;

/// Writes sparse blocks to a sparse image.
pub struct Writer {
    dst: BufWriter<File>,
    current_chunk: Option<ChunkHeader>,
    current_fill: Option<[u8; 4]>,
    num_blocks: u32,
    num_chunks: u32,
    crc: Option<crc32::Digest>,
    finished: bool,
}

impl Writer {
    /// Creates a new writer that writes to `file`.
    ///
    /// The created writer skips checksum calculation in favor of
    /// speed. To get a writer that does checksum calculation, use
    /// `Writer::with_crc` instead.
    pub fn new(file: File) -> Result<Self> {
        let mut dst = BufWriter::new(file);
        // We cannot write the file header until we know the total number of
        // blocks and chunks. So we skip it here and write it at the end in
        // `finish`.
        dst.seek(SeekFrom::Current(i64::from(FileHeader::SIZE)))?;

        Ok(Self {
            dst,
            current_chunk: None,
            current_fill: None,
            num_blocks: 0,
            num_chunks: 0,
            crc: None,
            finished: false,
        })
    }

    /// Creates a new writer that writes to `file` and adds a checksum
    /// at the end.
    pub fn with_crc(file: File) -> Result<Self> {
        let mut writer = Self::new(file)?;
        writer.crc = Some(crc32::Digest::new(crc32::IEEE));
        Ok(writer)
    }

    /// Writes a sparse block to this writer.
    ///
    /// The sparse block is converted into the sparse file format and
    /// written to this decoder's destination.
    pub fn write_block(&mut self, block: &Block) -> Result<()> {
        if !self.can_merge(block) {
            self.finish_chunk()?;
            self.start_chunk(block)?;
        }

        let chunk = self.current_chunk.as_mut().unwrap();

        match block {
            Block::Raw(buf) => {
                self.dst.write_all(&**buf)?;
                chunk.total_size += Block::SIZE;
            }
            Block::Fill(value) => if self.current_fill.is_none() {
                self.dst.write_all(value)?;
                self.current_fill = Some(*value);
            },
            Block::Skip => (),
            Block::Crc32(checksum) => {
                self.dst.write_u32::<LittleEndian>(*checksum)?;
                // CRC chunk size must remain 0, so drop out here already.
                return Ok(());
            }
        }

        if let Some(digest) = self.crc.as_mut() {
            digest.write_block(&block);
        }

        chunk.chunk_size += 1;
        Ok(())
    }

    /// Finishes writing the sparse image and flushes any buffered data.
    ///
    /// Consumes the reader as using it afterward would be invalid.
    pub fn close(mut self) -> Result<()> {
        self.finish()
    }

    fn finish(&mut self) -> Result<()> {
        assert!(!self.finished);
        self.finished = true;

        self.write_checksum()?;
        self.finish_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: self.num_blocks,
            total_chunks: self.num_chunks,
            image_checksum,
        };

        self.dst.seek(SeekFrom::Start(0))?;
        header.write_to(&mut self.dst)?;

        self.dst.flush()?;
        Ok(())
    }

    fn can_merge(&self, block: &Block) -> bool {
        let chunk = match self.current_chunk.as_ref() {
            Some(c) => c,
            None => return false,
        };

        match (chunk.chunk_type, block) {
            (ChunkType::Raw, Block::Raw(_)) | (ChunkType::DontCare, Block::Skip) => true,
            (ChunkType::Fill, Block::Fill(value)) => self.current_fill.unwrap() == *value,
            _ => false,
        }
    }

    fn start_chunk(&mut self, block: &Block) -> Result<()> {
        assert!(self.current_chunk.is_none());

        let (chunk_type, init_size) = match block {
            Block::Raw(_) => (ChunkType::Raw, 0),
            Block::Fill(_) => (ChunkType::Fill, 4),
            Block::Skip => (ChunkType::DontCare, 0),
            Block::Crc32(_) => (ChunkType::Crc32, 4),
        };

        let chunk = ChunkHeader {
            chunk_type,
            chunk_size: 0,
            total_size: init_size + u32::from(ChunkHeader::SIZE),
        };

        // We cannot write the chunk header until we know the total number of
        // blocks in the chunk. So we skip it here and write it later in
        // `finish_chunk`.
        let header_size = i64::from(ChunkHeader::SIZE);
        self.dst.seek(SeekFrom::Current(header_size))?;

        self.current_chunk = Some(chunk);

        Ok(())
    }

    fn finish_chunk(&mut self) -> Result<()> {
        let chunk = match self.current_chunk.take() {
            Some(c) => c,
            None => return Ok(()),
        };

        let pos = self.dst.tell()?;
        let header_off = i64::from(chunk.total_size);
        self.dst.seek(SeekFrom::Current(-header_off))?;
        chunk.write_to(&mut self.dst)?;
        self.dst.seek(SeekFrom::Start(pos))?;

        self.current_fill = None;
        self.num_chunks += 1;
        self.num_blocks += chunk.chunk_size;

        Ok(())
    }

    fn write_checksum(&mut self) -> Result<()> {
        let checksum = match self.crc.as_ref() {
            Some(digest) => digest.sum32(),
            None => return Ok(()),
        };

        let block = Block::Crc32(checksum);
        self.write_block(&block)
    }
}

impl Drop for Writer {
    fn drop(&mut self) {
        if !self.finished {
            let _ = self.finish();
        }
    }
}

/// Decodes sparse blocks and writes them to a raw image.
pub struct Decoder {
    dst: BufWriter<File>,
    finished: bool,
}

impl Decoder {
    /// Creates a new decoder that writes to `file`.
    pub fn new(file: File) -> Result<Self> {
        let dst = BufWriter::new(file);
        Ok(Self {
            dst,
            finished: false,
        })
    }

    /// Writes a sparse block to this decoder.
    ///
    /// The sparse block is decoded into its raw form and written to
    /// this decoder's destination.
    pub fn write_block(&mut self, block: &Block) -> Result<()> {
        match block {
            Block::Raw(buf) => self.dst.write_all(&**buf)?,
            Block::Fill(value) => {
                let count = Block::SIZE as usize / 4;
                for _ in 0..count {
                    self.dst.write_all(value)?;
                }
            }
            Block::Skip => {
                let offset = i64::from(Block::SIZE);
                self.dst.seek(SeekFrom::Current(offset))?;
            }
            Block::Crc32(_) => (),
        }
        Ok(())
    }

    /// Finishes writing the raw image and flushes any buffered data.
    ///
    /// Consumes the reader as using it afterward would be invalid.
    pub fn close(mut self) -> Result<()> {
        self.finish()
    }

    fn finish(&mut self) -> Result<()> {
        assert!(!self.finished);
        self.finished = true;

        // Ensure the file has the correct size if the last block was a
        // skip block.
        let file = self.dst.get_mut();
        let offset = file.tell()?;
        file.set_len(offset)?;

        file.flush()?;
        Ok(())
    }
}

impl Drop for Decoder {
    fn drop(&mut self) {
        if !self.finished {
            let _ = self.finish();
        }
    }
}