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
use super::{Chunker, ChunkerError};
use fastcdc;
use std::io::Read;

/// Settings for a fastcdc `Chunker`
///
/// These are limited to `usize`, and not `u64`, because this implementation makes
/// extensive use of in memory buffers of size `max_size`
///
/// This chunker, unlike `BuzHash` does not support any attempted mitigation of
/// chunk based fingerprinting attacks. Those who are concerned about such an
/// attack may wish to use the `BuzHash` chunker until such a time that a better
/// repository format that does not leak information about chunk sizes can be
/// developed.
#[derive(Clone, Copy)]
pub struct FastCDC {
    pub min_size: usize,
    pub max_size: usize,
    pub avg_size: usize,
}

impl Chunker for FastCDC {
    type Chunks = FastCDCChunker;
    fn chunk_boxed(&self, read: Box<dyn Read + Send + 'static>) -> Self::Chunks {
        FastCDCChunker {
            settings: *self,
            buffer: vec![0_u8; self.max_size],
            length: 0,
            read,
            eof: false,
        }
    }
}

impl Default for FastCDC {
    fn default() -> Self {
        FastCDC {
            min_size: 32_768,
            avg_size: 65_536,
            max_size: 131_072,
        }
    }
}

pub struct FastCDCChunker {
    /// The settings used for this `Chunker`
    settings: FastCDC,
    /// The in memory buffer used to hack the chosen FastCDC implementation into working
    ///
    /// This must always be kept at a size of `max_size`
    buffer: Vec<u8>,
    /// The length of the data in the buffer
    length: usize,
    /// The reader this `Chunker` is slicing
    read: Box<dyn Read + Send + 'static>,
    /// Has the reader hit EoF?
    eof: bool,
}

impl FastCDCChunker {
    /// Drains a specified number of bytes from the reader, and refills it back up to `max_size` with
    /// zeros.
    ///
    /// Additionally updates the pointer to the new end of the vec
    ///
    /// # Errors
    ///
    /// Returns `ChunkerError::InternalError` if the given count of bytes to drain is greater than the
    /// current size of the used region of the buffer.
    ///
    /// # Panics
    ///
    /// Panics if the internal buffer's length is not `max_size`. This is an invariant, and the end
    /// consumer of the struct should never be exposed to this error.
    fn drain_bytes(&mut self, count: usize) -> Result<Vec<u8>, ChunkerError> {
        assert!(self.buffer.len() == self.settings.max_size);
        if count > self.length {
            Err(ChunkerError::InternalError(format!(
                "Invalid count given to FastCDCChunker::drain_bytes. Count: {}, Length: {}",
                count, self.length
            )))
        } else {
            // Drain the bytes from the vec
            let output = self.buffer.drain(..count).collect::<Vec<_>>();
            // Update the length
            self.length -= count;
            // Resize the buffer back to max_size
            self.buffer.resize(self.settings.max_size, 0_u8);
            // Return the drained bytes
            Ok(output)
        }
    }

    /// Returns true if the internal buffer is empty
    fn is_empty(&self) -> bool {
        self.length == 0
    }

    /// Attempts fill the buffer back up with bytes from the read
    ///
    /// Returns the number of bytes read. Will not attempt to read bytes if `EoF` has already been
    /// encountered.
    ///
    /// # Errors
    ///
    /// Returns `ChunkerError::IOError` if the reader provides any error value during reading
    ///
    /// # Panics
    ///
    /// Panics if the internal buffer's length is not `max_size`. This is an invariant, and the end
    /// consumer of the struct shuold never be exposed to this error.
    fn read_bytes(&mut self) -> Result<usize, ChunkerError> {
        assert!(self.buffer.len() == self.settings.max_size);
        if self.eof {
            Ok(0)
        } else {
            let mut total_bytes = 0;
            // While we have not hit eof, and there is still room in the buffer, keep reading
            while !self.eof && self.length < self.settings.max_size {
                // read some bytes
                let bytes_read = self.read.read(&mut self.buffer[self.length..])?;
                // Update the length
                self.length += bytes_read;
                // If the number of bytes read was zero, set the eof flag
                if bytes_read == 0 {
                    self.eof = true;
                }
                // Update the total
                total_bytes += bytes_read;
            }
            Ok(total_bytes)
        }
    }

    /// Uses the `FastCDC` algorithm to produce the next chunk of data.
    ///
    /// # Errors
    ///
    /// Returns `ChunkerError::Empty` if `EoF` has been hit
    ///
    /// # Panics
    ///
    /// Panics if the internal buffer's length is not `max_size`. This is an invariant, and the end
    /// consumer of the struct should never be exposed to this error.
    fn next_chunk(&mut self) -> Result<Vec<u8>, ChunkerError> {
        assert_eq!(self.buffer.len(), self.settings.max_size);
        // First, perform a read, to make sure the buffer is as full as it can be
        self.read_bytes()?;
        // Check to see if we are empty, if so, return early
        if self.is_empty() {
            Err(ChunkerError::Empty)
        } else {
            // Attempt to produce our slice
            let mut slicer = fastcdc::FastCDC::new(
                &self.buffer[..self.length],
                self.settings.min_size,
                self.settings.avg_size,
                self.settings.max_size,
            );
            if let Some(chunk) = slicer.next() {
                let result = self.drain_bytes(chunk.length)?;
                Ok(result)
            } else {
                // We really shouldn't be here, since we ruled out the empty case, earlier but we
                // will error anyway
                Err(ChunkerError::Empty)
            }
        }
    }
}

impl Iterator for FastCDCChunker {
    type Item = Result<Vec<u8>, ChunkerError>;

    fn next(&mut self) -> Option<Result<Vec<u8>, ChunkerError>> {
        let slice = self.next_chunk();
        if let Err(ChunkerError::Empty) = slice {
            None
        } else {
            Some(slice)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rand::prelude::*;
    use std::io::Cursor;

    // Provides a test slice 10 times the default max size in length
    fn get_test_data() -> Vec<u8> {
        let size = FastCDC::default().max_size * 10;
        let mut vec = vec![0_u8; size];
        rand::thread_rng().fill_bytes(&mut vec);
        vec
    }

    // Data should be split into one or more chunks.
    //
    // In this case, the data is larger than `max_size`, so it should be more than one chunk
    #[test]
    fn one_or_more_chunks() {
        let data = get_test_data();
        let cursor = Cursor::new(data);
        let chunker = FastCDC::default();
        let chunks = chunker
            .chunk(cursor)
            .map(|x| x.unwrap())
            .collect::<Vec<_>>();
        assert!(chunks.len() > 1);
    }

    // Data should be identical after reassembaly by simple concatenation
    #[test]
    fn reassemble_data() {
        let data = get_test_data();
        let cursor = Cursor::new(data.clone());
        let chunks = FastCDC::default()
            .chunk(cursor)
            .map(|x| x.unwrap())
            .collect::<Vec<_>>();
        let rebuilt: Vec<u8> = chunks.concat();
        assert_eq!(data, rebuilt);
    }

    // Running the chunker over the same data twice should result in identical chunks
    #[test]
    fn identical_chunks() {
        let data = get_test_data();
        let cursor1 = Cursor::new(data.clone());
        let chunks1 = FastCDC::default()
            .chunk(cursor1)
            .map(|x| x.unwrap())
            .collect::<Vec<_>>();
        let cursor2 = Cursor::new(data);
        let chunks2 = FastCDC::default()
            .chunk(cursor2)
            .map(|x| x.unwrap())
            .collect::<Vec<_>>();
        assert_eq!(chunks1, chunks2);
    }

    // Verifies that this `Chunker` does not produce chunks larger than its max size
    #[test]
    fn max_size() {
        let data = get_test_data();
        let max_size = FastCDC::default().max_size;

        let chunks = FastCDC::default()
            .chunk(Cursor::new(data))
            .map(|x| x.unwrap())
            .collect::<Vec<_>>();

        for chunk in chunks {
            assert!(chunk.len() <= max_size);
        }
    }

    // Verifies that this `Chunker`, at most, produces 1 under-sized chunk
    #[test]
    fn min_size() {
        let data = get_test_data();
        let min_size = FastCDC::default().min_size;

        let chunks = FastCDC::default()
            .chunk(Cursor::new(data))
            .map(|x| x.unwrap())
            .collect::<Vec<_>>();

        let mut undersized_count = 0;
        for chunk in chunks {
            if chunk.len() < min_size {
                undersized_count += 1;
            }
        }

        assert!(undersized_count <= 1);
    }
}