net-wire 0.1.0

Allocation-free no_std wire views and codecs for network protocols.
Documentation
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! Protected QUIC v1 and v2 length-delimited long-packet builders.

use super::super::packet::header::{
    QuicConnectionId, QuicConnectionIdField, QuicLongHeader, QuicLongPacketType, QuicVersion,
};
use super::super::packet::long::QuicProtectedLongPacket;
use super::super::varint::{QuicVarInt, QuicVarIntBuildError, QuicVarIntLen};
use super::{QuicPacketBuildError, QuicPacketBuildField};

/// Builds a protected QUIC v1 or v2 Initial packet in caller-owned storage.
pub struct QuicInitialPacketBuilder<'buffer, 'input> {
    destination: &'buffer mut [u8],
    version: QuicVersion,
    protected_low_bits: u8,
    destination_connection_id: QuicConnectionId<'input>,
    source_connection_id: QuicConnectionId<'input>,
    token: &'input [u8],
    protected_remainder: &'input [u8],
    token_length_len: Option<QuicVarIntLen>,
    length_len: Option<QuicVarIntLen>,
}

impl<'buffer, 'input> QuicInitialPacketBuilder<'buffer, 'input> {
    /// Creates a builder with exact opaque Initial token and protected-remainder bytes.
    pub fn new(
        destination: &'buffer mut [u8],
        version: QuicVersion,
        protected_low_bits: u8,
        destination_connection_id: QuicConnectionId<'input>,
        source_connection_id: QuicConnectionId<'input>,
        token: &'input [u8],
        protected_remainder: &'input [u8],
    ) -> Self {
        Self {
            destination,
            version,
            protected_low_bits,
            destination_connection_id,
            source_connection_id,
            token,
            protected_remainder,
            token_length_len: None,
            length_len: None,
        }
    }

    /// Requests an explicit legal encoded width for the Initial token-length field.
    pub fn with_token_length_len(mut self, length: QuicVarIntLen) -> Self {
        self.token_length_len = Some(length);
        self
    }

    /// Requests an explicit legal encoded width for the protected packet-length field.
    pub fn with_length_len(mut self, length: QuicVarIntLen) -> Self {
        self.length_len = Some(length);
        self
    }

    /// Validates all inputs and capacity before writing a complete protected Initial packet.
    pub fn build(self) -> Result<QuicProtectedLongPacket<'buffer>, QuicPacketBuildError> {
        build_long(BuildInput {
            destination: self.destination,
            version: self.version,
            protected_low_bits: self.protected_low_bits,
            destination_connection_id: self.destination_connection_id,
            source_connection_id: self.source_connection_id,
            packet_type: QuicLongPacketType::Initial,
            token: Some(self.token),
            token_length_len: self.token_length_len,
            length_len: self.length_len,
            protected_remainder: self.protected_remainder,
        })
    }
}

/// Builds a protected QUIC v1 or v2 0-RTT packet in caller-owned storage.
pub struct QuicZeroRttPacketBuilder<'buffer, 'input> {
    destination: &'buffer mut [u8],
    version: QuicVersion,
    protected_low_bits: u8,
    destination_connection_id: QuicConnectionId<'input>,
    source_connection_id: QuicConnectionId<'input>,
    protected_remainder: &'input [u8],
    length_len: Option<QuicVarIntLen>,
}

impl<'buffer, 'input> QuicZeroRttPacketBuilder<'buffer, 'input> {
    /// Creates a builder with exact opaque protected-remainder bytes.
    pub fn new(
        destination: &'buffer mut [u8],
        version: QuicVersion,
        protected_low_bits: u8,
        destination_connection_id: QuicConnectionId<'input>,
        source_connection_id: QuicConnectionId<'input>,
        protected_remainder: &'input [u8],
    ) -> Self {
        Self {
            destination,
            version,
            protected_low_bits,
            destination_connection_id,
            source_connection_id,
            protected_remainder,
            length_len: None,
        }
    }

    /// Requests an explicit legal encoded width for the protected packet-length field.
    pub fn with_length_len(mut self, length: QuicVarIntLen) -> Self {
        self.length_len = Some(length);
        self
    }

    /// Validates all inputs and capacity before writing a complete protected 0-RTT packet.
    pub fn build(self) -> Result<QuicProtectedLongPacket<'buffer>, QuicPacketBuildError> {
        build_long(BuildInput {
            destination: self.destination,
            version: self.version,
            protected_low_bits: self.protected_low_bits,
            destination_connection_id: self.destination_connection_id,
            source_connection_id: self.source_connection_id,
            packet_type: QuicLongPacketType::ZeroRtt,
            token: None,
            token_length_len: None,
            length_len: self.length_len,
            protected_remainder: self.protected_remainder,
        })
    }
}

/// Builds a protected QUIC v1 or v2 Handshake packet in caller-owned storage.
pub struct QuicHandshakePacketBuilder<'buffer, 'input> {
    destination: &'buffer mut [u8],
    version: QuicVersion,
    protected_low_bits: u8,
    destination_connection_id: QuicConnectionId<'input>,
    source_connection_id: QuicConnectionId<'input>,
    protected_remainder: &'input [u8],
    length_len: Option<QuicVarIntLen>,
}

impl<'buffer, 'input> QuicHandshakePacketBuilder<'buffer, 'input> {
    /// Creates a builder with exact opaque protected-remainder bytes.
    pub fn new(
        destination: &'buffer mut [u8],
        version: QuicVersion,
        protected_low_bits: u8,
        destination_connection_id: QuicConnectionId<'input>,
        source_connection_id: QuicConnectionId<'input>,
        protected_remainder: &'input [u8],
    ) -> Self {
        Self {
            destination,
            version,
            protected_low_bits,
            destination_connection_id,
            source_connection_id,
            protected_remainder,
            length_len: None,
        }
    }

    /// Requests an explicit legal encoded width for the protected packet-length field.
    pub fn with_length_len(mut self, length: QuicVarIntLen) -> Self {
        self.length_len = Some(length);
        self
    }

    /// Validates all inputs and capacity before writing a complete protected Handshake packet.
    pub fn build(self) -> Result<QuicProtectedLongPacket<'buffer>, QuicPacketBuildError> {
        build_long(BuildInput {
            destination: self.destination,
            version: self.version,
            protected_low_bits: self.protected_low_bits,
            destination_connection_id: self.destination_connection_id,
            source_connection_id: self.source_connection_id,
            packet_type: QuicLongPacketType::Handshake,
            token: None,
            token_length_len: None,
            length_len: self.length_len,
            protected_remainder: self.protected_remainder,
        })
    }
}

struct BuildInput<'buffer, 'input> {
    destination: &'buffer mut [u8],
    version: QuicVersion,
    protected_low_bits: u8,
    destination_connection_id: QuicConnectionId<'input>,
    source_connection_id: QuicConnectionId<'input>,
    packet_type: QuicLongPacketType,
    token: Option<&'input [u8]>,
    token_length_len: Option<QuicVarIntLen>,
    length_len: Option<QuicVarIntLen>,
    protected_remainder: &'input [u8],
}

fn build_long<'buffer>(
    input: BuildInput<'buffer, '_>,
) -> Result<QuicProtectedLongPacket<'buffer>, QuicPacketBuildError> {
    let raw_type = input.packet_type.raw_type(input.version).ok_or(
        QuicPacketBuildError::UnsupportedVersion {
            version: input.version,
        },
    )?;
    if input.protected_low_bits > 0x0f {
        return Err(QuicPacketBuildError::ProtectedLowBitsOutOfRange {
            maximum: 0x0f,
            actual: input.protected_low_bits,
        });
    }
    validate_connection_id(
        QuicConnectionIdField::Destination,
        input.destination_connection_id.len(),
    )?;
    validate_connection_id(
        QuicConnectionIdField::Source,
        input.source_connection_id.len(),
    )?;
    if input.protected_remainder.len() < 2 {
        return Err(QuicPacketBuildError::ProtectedRemainderTooShort {
            minimum: 2,
            actual: input.protected_remainder.len(),
        });
    }

    let protected_length = u64::try_from(input.protected_remainder.len()).map_err(|_| {
        QuicPacketBuildError::VarInt {
            field: QuicPacketBuildField::ProtectedLength,
            error: QuicVarIntBuildError::ValueTooLarge { value: u64::MAX },
        }
    })?;
    let length_len = validate_varint(
        QuicPacketBuildField::ProtectedLength,
        protected_length,
        input.length_len,
    )?;
    let token_length = input.token.map(|token| token.len());
    let token_length_value = match token_length {
        Some(length) => u64::try_from(length).map_err(|_| QuicPacketBuildError::VarInt {
            field: QuicPacketBuildField::TokenLength,
            error: QuicVarIntBuildError::ValueTooLarge { value: u64::MAX },
        })?,
        None => 0,
    };
    let token_length_len = match token_length {
        Some(_) => Some(validate_varint(
            QuicPacketBuildField::TokenLength,
            token_length_value,
            input.token_length_len,
        )?),
        None => None,
    };

    let destination_start = 6;
    let destination_end = checked_add(
        destination_start,
        input.destination_connection_id.len(),
        "destination connection ID",
    )?;
    let source_length_offset = destination_end;
    let source_start = checked_add(source_length_offset, 1, "source connection ID length")?;
    let source_end = checked_add(
        source_start,
        input.source_connection_id.len(),
        "source connection ID",
    )?;
    let token_length_offset = source_end;
    let token_start = match (input.token, token_length_len) {
        (Some(_), Some(length)) => {
            checked_add(token_length_offset, length.byte_len(), "token length")?
        }
        (None, None) => source_end,
        _ => {
            return Err(QuicPacketBuildError::LengthOverflow {
                component: "token fields",
                offset: source_end,
                length: 0,
            });
        }
    };
    let token_end = match input.token {
        Some(token) => checked_add(token_start, token.len(), "Initial token")?,
        None => token_start,
    };
    let length_offset = token_end;
    let packet_number_offset =
        checked_add(length_offset, length_len.byte_len(), "protected length")?;
    let required = checked_add(
        packet_number_offset,
        input.protected_remainder.len(),
        "protected remainder",
    )?;
    if input.destination.len() < required {
        return Err(QuicPacketBuildError::BufferTooShort {
            required,
            available: input.destination.len(),
        });
    }

    let destination = input.destination;
    destination[0] = 0xc0 | (raw_type << 4) | input.protected_low_bits;
    destination[1..5].copy_from_slice(&input.version.raw().to_be_bytes());
    destination[5] = input.destination_connection_id.len() as u8;
    destination[destination_start..destination_end]
        .copy_from_slice(input.destination_connection_id.as_bytes());
    destination[source_length_offset] = input.source_connection_id.len() as u8;
    destination[source_start..source_end].copy_from_slice(input.source_connection_id.as_bytes());
    if let (Some(token), Some(token_length_len)) = (input.token, token_length_len) {
        write_varint(
            &mut destination[token_length_offset..token_start],
            token_length_value,
            token_length_len,
        );
        destination[token_start..token_end].copy_from_slice(token);
    }
    write_varint(
        &mut destination[length_offset..packet_number_offset],
        protected_length,
        length_len,
    );
    destination[packet_number_offset..required].copy_from_slice(input.protected_remainder);

    let bytes = &destination[..required];
    let header = QuicLongHeader::from_validated(
        &bytes[..source_end],
        bytes[0],
        input.version,
        QuicConnectionId::new(&bytes[destination_start..destination_end]),
        QuicConnectionId::new(&bytes[source_start..source_end]),
        &bytes[source_end..],
    );
    let token_length = token_length_len.map(|length| {
        QuicVarInt::from_validated(
            &bytes[token_length_offset..token_start],
            token_length_value,
            length,
        )
    });
    let token_fields =
        token_length.map(|token_length| (token_length, &bytes[token_start..token_end]));
    let length = QuicVarInt::from_validated(
        &bytes[length_offset..packet_number_offset],
        protected_length,
        length_len,
    );
    Ok(QuicProtectedLongPacket::from_validated(
        bytes,
        header,
        input.packet_type,
        token_fields,
        length,
        packet_number_offset,
        &bytes[packet_number_offset..required],
    ))
}

fn validate_connection_id(
    field: QuicConnectionIdField,
    actual: usize,
) -> Result<(), QuicPacketBuildError> {
    if actual > 20 {
        return Err(QuicPacketBuildError::ConnectionIdTooLong {
            field,
            maximum: 20,
            actual,
        });
    }
    Ok(())
}

fn validate_varint(
    field: QuicPacketBuildField,
    value: u64,
    requested: Option<QuicVarIntLen>,
) -> Result<QuicVarIntLen, QuicPacketBuildError> {
    if value > QuicVarIntLen::Eight.max_value() {
        return Err(QuicPacketBuildError::VarInt {
            field,
            error: QuicVarIntBuildError::ValueTooLarge { value },
        });
    }
    let length = requested.unwrap_or_else(|| canonical_len(value));
    if value > length.max_value() {
        return Err(QuicPacketBuildError::VarInt {
            field,
            error: QuicVarIntBuildError::WidthTooSmall { length, value },
        });
    }
    Ok(length)
}

const fn canonical_len(value: u64) -> QuicVarIntLen {
    if value <= QuicVarIntLen::One.max_value() {
        QuicVarIntLen::One
    } else if value <= QuicVarIntLen::Two.max_value() {
        QuicVarIntLen::Two
    } else if value <= QuicVarIntLen::Four.max_value() {
        QuicVarIntLen::Four
    } else {
        QuicVarIntLen::Eight
    }
}

fn checked_add(
    offset: usize,
    length: usize,
    component: &'static str,
) -> Result<usize, QuicPacketBuildError> {
    offset
        .checked_add(length)
        .ok_or(QuicPacketBuildError::LengthOverflow {
            component,
            offset,
            length,
        })
}

fn write_varint(destination: &mut [u8], value: u64, length: QuicVarIntLen) {
    let value_bytes = value.to_be_bytes();
    let length_bytes = length.byte_len();
    destination.copy_from_slice(&value_bytes[value_bytes.len() - length_bytes..]);
    destination[0] |= match length {
        QuicVarIntLen::One => 0,
        QuicVarIntLen::Two => 0x40,
        QuicVarIntLen::Four => 0x80,
        QuicVarIntLen::Eight => 0xc0,
    };
}