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
use crate::wire::packet::{Metadata, Packet, PacketEncryption, PacketType};
use over_there_auth::Signer;
use over_there_derive::Error;
use std::collections::HashMap;

pub(crate) struct DisassembleInfo<'d, 's, S: Signer> {
    /// ID used to group created packets together
    pub id: u32,

    /// Used to specify the level of encryption to use
    pub encryption: PacketEncryption,

    /// Desired maximum size of each packet (including metadata)
    pub desired_chunk_size: usize,

    /// Key used to generate signatures
    pub signer: &'s S,

    /// The data to build packets around; encryption should have already happened
    /// by this point
    pub data: &'d [u8],
}

#[derive(Debug, Error)]
pub enum DisassemblerError {
    DesiredChunkSizeTooSmall,
    FailedToEstimatePacketSize,
    FailedToSignPacket,
}

#[derive(Debug, Clone)]
pub(crate) struct Disassembler {
    packet_overhead_size_cache: HashMap<String, usize>,
}

impl Disassembler {
    pub fn make_packets_from_data<S: Signer>(
        &mut self,
        info: DisassembleInfo<S>,
    ) -> Result<Vec<Packet>, DisassemblerError> {
        let DisassembleInfo {
            id,
            encryption,
            desired_chunk_size,
            signer,
            data,
        } = info;

        // Determine overhead needed to produce packet with desired data size
        let non_final_overhead_size = self
            .cached_estimate_packet_overhead_size(
                desired_chunk_size,
                PacketType::NotFinal,
                signer,
            )
            .map_err(|_| DisassemblerError::FailedToEstimatePacketSize)?;

        let final_overhead_size = self
            .cached_estimate_packet_overhead_size(
                desired_chunk_size,
                PacketType::Final { encryption },
                signer,
            )
            .map_err(|_| DisassemblerError::FailedToEstimatePacketSize)?;

        // If the packet size would be so big that the overhead is at least
        // as large as our desired total byte stream (chunk) size, we will
        // exit because we cannot send packets without violating the requirement
        if non_final_overhead_size >= desired_chunk_size
            || final_overhead_size >= desired_chunk_size
        {
            return Err(DisassemblerError::DesiredChunkSizeTooSmall);
        }

        // Compute the data size for a non-final and final packet
        let non_final_chunk_size = desired_chunk_size - non_final_overhead_size;
        let final_chunk_size = desired_chunk_size - final_overhead_size;

        // Construct the packets, using the single id to associate all of
        // them together and linking each to an individual position in the
        // collective using the chunks
        let mut packets = Vec::new();
        let mut i = 0;
        while i < data.len() {
            // Chunk length is determined by this logic:
            // 1. If we have room in the final packet for the remaining data,
            //    store it in the final packet
            // 2. If we have so much data left that it won't fit in the final
            //    packet and it won't fit in a non-final packet, we store N
            //    bytes into a non-final packet where N is the capable size
            //    of a non-final packet data section
            // 3. If we have so much data left that it won't fit in the final
            //    packet but it will fit entirely in a non-final packet, we
            //    store N bytes into a non-final packet where N is the capable
            //    size of the final packet data section
            let can_fit_all_in_final_packet =
                i + final_chunk_size >= data.len();
            let can_fit_all_in_non_final_packet =
                i + non_final_chunk_size >= data.len();
            let chunk_size = if can_fit_all_in_final_packet
                || can_fit_all_in_non_final_packet
            {
                final_chunk_size
            } else {
                non_final_chunk_size
            };

            // Ensure chunk size does not exceed our remaining data
            let chunk_size = std::cmp::min(chunk_size, data.len() - i);

            // Grab our chunk of data to store into a packet
            let chunk = &data[i..i + chunk_size];

            // Construct the packet based on whether or not is final
            let packet = Self::make_new_packet(
                id,
                packets.len() as u32,
                if can_fit_all_in_final_packet {
                    PacketType::Final { encryption }
                } else {
                    PacketType::NotFinal
                },
                chunk,
                signer,
            )
            .map_err(|_| DisassemblerError::FailedToSignPacket)?;

            // Store packet in our collection
            packets.push(packet);

            // Move our pointer by N bytes
            i += chunk_size;
        }

        Ok(packets)
    }

    /// Creates a new packet and signs it using the given authenticator
    fn make_new_packet<S: Signer>(
        id: u32,
        index: u32,
        r#type: PacketType,
        data: &[u8],
        signer: &S,
    ) -> Result<Packet, rmp_serde::encode::Error> {
        let metadata = Metadata { id, index, r#type };
        metadata.to_vec().map(|md| {
            let sig = signer.sign(&[md, data.to_vec()].concat());
            Packet::new(metadata, sig, data.to_vec())
        })
    }

    fn cached_estimate_packet_overhead_size<S: Signer>(
        &mut self,
        desired_data_size: usize,
        r#type: PacketType,
        signer: &S,
    ) -> Result<usize, rmp_serde::encode::Error> {
        // Calculate key to use for cache
        // TODO: Convert authenticator into part of the key? Is this necessary?
        let key = format!("{}{:?}", desired_data_size, r#type);

        // Check if we have a cached value and, if so, use it
        if let Some(value) = self.packet_overhead_size_cache.get(&key) {
            return Ok(*value);
        }

        // Otherwise, estimate the packet size, cache it, and return it
        let overhead_size = Self::estimate_packet_overhead_size(
            desired_data_size,
            r#type,
            signer,
        )?;
        self.packet_overhead_size_cache.insert(key, overhead_size);
        Ok(overhead_size)
    }

    pub(crate) fn estimate_packet_overhead_size<S: Signer>(
        desired_data_size: usize,
        r#type: PacketType,
        signer: &S,
    ) -> Result<usize, rmp_serde::encode::Error> {
        let packet_size =
            Self::estimate_packet_size(desired_data_size, r#type, signer)?;

        // Figure out how much overhead is needed to fit the data into the packet
        // NOTE: If for some reason the packet -> msgpack has optimized the
        //       byte stream so well that it is smaller than the provided
        //       data, we will assume no overhead
        Ok(if packet_size > desired_data_size {
            packet_size - desired_data_size
        } else {
            0
        })
    }

    fn estimate_packet_size<S: Signer>(
        desired_data_size: usize,
        r#type: PacketType,
        signer: &S,
    ) -> Result<usize, rmp_serde::encode::Error> {
        // Produce random fake data to avoid any byte sequencing
        let fake_data: Vec<u8> = (0..desired_data_size)
            .map(|_| rand::random::<u8>())
            .collect();

        // Produce a fake packet whose data fills the entire size, and then
        // see how much larger it is and use that as the overhead cost
        //
        // NOTE: This is a rough estimate and requires an entire serialization,
        //       but is the most straightforward way I can think of unless
        //       serde offers some form of size hinting for msgpack specifically
        Disassembler::make_new_packet(
            u32::max_value(),
            u32::max_value(),
            r#type,
            &fake_data,
            signer,
        )?
        .to_vec()
        .map(|v| v.len())
    }
}

impl Default for Disassembler {
    fn default() -> Self {
        Self {
            packet_overhead_size_cache: HashMap::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use over_there_auth::NoopAuthenticator;
    use over_there_crypto::{nonce, Nonce};

    #[test]
    fn fails_if_desired_chunk_size_is_too_low() {
        // Needs to accommodate metadata & data, which this does not
        let chunk_size = 1;
        let err = Disassembler::default()
            .make_packets_from_data(DisassembleInfo {
                id: 0,
                encryption: PacketEncryption::None,
                data: &vec![1, 2, 3],
                desired_chunk_size: chunk_size,
                signer: &NoopAuthenticator,
            })
            .unwrap_err();

        match err {
            DisassemblerError::DesiredChunkSizeTooSmall => (),
            x => panic!("Unexpected error: {:?}", x),
        }
    }

    #[test]
    fn produces_single_packet_with_data() {
        let id = 12345;
        let data: Vec<u8> = vec![1, 2];
        let encryption =
            PacketEncryption::from(Nonce::from(nonce::new_128bit_nonce()));

        // Make it so all the data fits in one packet
        let chunk_size = 1000;

        let packets = Disassembler::default()
            .make_packets_from_data(DisassembleInfo {
                id,
                encryption,
                data: &data,
                desired_chunk_size: chunk_size,
                signer: &NoopAuthenticator,
            })
            .unwrap();
        assert_eq!(packets.len(), 1, "More than one packet produced");

        let p = &packets[0];
        assert_eq!(p.id(), id, "ID not properly set on packet");
        assert_eq!(p.index(), 0, "Unexpected index for single packet");
        assert_eq!(
            p.is_final(),
            true,
            "Single packet not marked as last packet"
        );
        assert_eq!(p.data(), &data);
    }

    #[test]
    fn produces_multiple_packets_with_data() {
        let id = 67890;
        let data: Vec<u8> = vec![1, 2, 3];
        let nonce = Nonce::from(nonce::new_128bit_nonce());

        // Calculate the bigger of the two overhead sizes (final packet)
        // and ensure that we can only fit the last element in it
        let overhead_size = Disassembler::estimate_packet_overhead_size(
            /* data size */ 1,
            PacketType::Final {
                encryption: PacketEncryption::from(nonce),
            },
            &NoopAuthenticator,
        )
        .unwrap();
        let chunk_size = overhead_size + 2;

        let packets = Disassembler::default()
            .make_packets_from_data(DisassembleInfo {
                id,
                encryption: PacketEncryption::from(nonce),
                data: &data,
                desired_chunk_size: chunk_size,
                signer: &NoopAuthenticator,
            })
            .unwrap();
        assert_eq!(packets.len(), 2, "Unexpected number of packets");

        // Check data quality of first packet
        let p1 = packets.get(0).unwrap();
        assert_eq!(p1.id(), id, "ID not properly set on first packet");
        assert_eq!(p1.index(), 0, "First packet not marked with index 0");
        assert_eq!(
            p1.is_final(),
            false,
            "Non-final packet unexpectedly marked as last"
        );
        assert_eq!(&p1.data()[..], &data[0..2]);

        // Check data quality of second packet
        let p2 = packets.get(1).unwrap();
        assert_eq!(p2.id(), id, "ID not properly set on second packet");
        assert_eq!(p2.index(), 1, "Last packet not marked with correct index");
        assert_eq!(p2.is_final(), true, "Last packet not marked as final");
        assert_eq!(&p2.data()[..], &data[2..]);
    }

    #[test]
    fn produces_multiple_packets_respecting_size_constraints() {
        let id = 67890;
        let encryption =
            PacketEncryption::from(Nonce::from(nonce::new_128bit_nonce()));

        // Make it so not all of the data fits in one packet
        //
        // NOTE: Make sure we make large enough chunks so msgpack
        //       serialization needs more bytes; use 100k of memory to
        //       spread out packets
        //
        let data: Vec<u8> = [0; 100000].to_vec();
        let chunk_size = 512;

        let packets = Disassembler::default()
            .make_packets_from_data(DisassembleInfo {
                id,
                encryption,
                data: &data,
                desired_chunk_size: chunk_size,
                signer: &NoopAuthenticator,
            })
            .unwrap();

        // All packets should be no larger than chunk size
        for (i, p) in packets.iter().enumerate() {
            let actual_size = p.to_vec().unwrap().len();
            assert!(
                actual_size <= chunk_size,
                "Serialized packet {}/{} was {} bytes instead of max size of {}",
                i + 1,
                packets.len(),
                actual_size,
                chunk_size
            );
        }
    }
}