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
use super::super::*;

use std::net::Ipv6Addr;

extern crate byteorder;
use self::byteorder::{ByteOrder, BigEndian, ReadBytesExt, WriteBytesExt};

///IPv6 header according to rfc8200.
#[derive(Clone, Debug, Eq, PartialEq, Default)]
pub struct Ipv6Header {
    pub traffic_class: u8,
    ///If non 0 serves as a hint to router and switches with multiple outbound paths that these packets should stay on the same path, so that they will not be reordered.
    pub flow_label: u32,
    ///The length of the payload and extension headers in bytes (0 in case of jumbo payloads).
    pub payload_length: u16,
    ///Specifies what the next header or transport layer protocol is (see IpTrafficClass for a definitions of ids).
    pub next_header: u8,
    ///The number of hops the packet can take before it is discarded.
    pub hop_limit: u8,
    ///IPv6 source address
    pub source: [u8;16],
    ///IPv6 destination address
    pub destination: [u8;16]
}

impl SerializedSize for Ipv6Header {
    ///Size of the header itself in bytes.
    const SERIALIZED_SIZE:usize = 40;
}

impl Ipv6Header {

    ///Read an Ipv6Header from a slice and return the header & unused parts of the slice.
    pub fn read_from_slice(slice: &[u8]) -> Result<(Ipv6Header, &[u8]), ReadError> {
        Ok((
            Ipv6HeaderSlice::from_slice(slice)?.to_header(), 
            &slice[Ipv6Header::SERIALIZED_SIZE..]
        ))
    }

    ///Reads an IPv6 header from the current position.
    pub fn read<T: io::Read + io::Seek + Sized>(reader: &mut T) -> Result<Ipv6Header, ReadError> {
        let value = reader.read_u8()?;
        let version = value >> 4;
        if 6 != version {
            return Err(ReadError::Ipv6UnexpectedVersion(version));
        }
        match Ipv6Header::read_without_version(reader, value & 0xf) {
            Ok(value) => Ok(value),
            Err(err) => Err(ReadError::IoError(err))
        }
    }

    ///Reads an IPv6 header assuming the version & flow_label field have already been read.
    pub fn read_without_version<T: io::Read + io::Seek + Sized>(reader: &mut T, version_rest: u8) -> Result<Ipv6Header, io::Error> {
        let (traffic_class, flow_label) = {
            //read 4 bytes
            let mut buffer: [u8; 4] = [0;4];
            reader.read_exact(&mut buffer[1..])?;

            //extract class
            let traffic_class = (version_rest << 4) | (buffer[1] >> 4);

            //remove traffic class from buffer & read flow_label
            buffer[1] &= 0xf;
            (traffic_class, byteorder::BigEndian::read_u32(&buffer))
        };
        
        Ok(Ipv6Header{
            traffic_class,
            flow_label,
            payload_length: reader.read_u16::<BigEndian>()?,
            next_header: reader.read_u8()?,
            hop_limit: reader.read_u8()?,
            source: {
                let mut buffer: [u8; 16] = [0;16];
                reader.read_exact(&mut buffer)?;
                buffer
            },
            destination: {
                let mut buffer: [u8; 16] = [0;16];
                reader.read_exact(&mut buffer)?;
                buffer
            }
        })
    }

    ///Takes a slice and skips an ipv6 header extensions and returns the next_header id & the slice past the header.
    ///NOTE: There must be a ipv6 header extension id given as a traffic_class.
    pub fn skip_header_extension_in_slice(slice: &[u8], traffic_class: u8) -> Result<(u8, &[u8]), ReadError> {
        if slice.len() < 8 {
            Err(ReadError::UnexpectedEndOfSlice(8))
        } else {
            let next_header = slice[0];
            const FRAG: u8 = IpTrafficClass::IPv6FragmentationHeader as u8;
            //determine the length (fragmentation header has a fixed length & the rest a length field)
            let len = if traffic_class == FRAG {
                8
            } else {
                (usize::from(slice[1]) + 1)*8
            };
            if slice.len() < len {
                Err(ReadError::UnexpectedEndOfSlice(len))
            } else {
                Ok((next_header, &slice[len..]))
            }
        }
    }

    ///Takes a slice & traffic class (identifying the first header type) and returns next_header id & the slice past after all ipv6 header extensions.
    pub fn skip_all_header_extensions_in_slice(slice: &[u8], traffic_class: u8) -> Result<(u8, &[u8]), ReadError> {
        
        let mut next_traffic_class = traffic_class;
        let mut rest = slice;
        
        for _i in 0..IPV6_MAX_NUM_HEADER_EXTENSIONS {

            if IpTrafficClass::is_ipv6_ext_header_value(next_traffic_class)
            {
                let (n_id, n_rest) = Ipv6Header::skip_header_extension_in_slice(rest, next_traffic_class)?;
                next_traffic_class = n_id;
                rest = n_rest;
            } else {
                return Ok((next_traffic_class, rest))
            }
        }

        //final check
        if IpTrafficClass::is_ipv6_ext_header_value(next_traffic_class) {
            Err(ReadError::Ipv6TooManyHeaderExtensions)
        } else {
            Ok((next_traffic_class, rest))
        }
    }

    ///Skips the ipv6 header extension and returns the traffic_class
    pub fn skip_header_extension<T: io::Read + io::Seek + Sized>(reader: &mut T, traffic_class: u8) -> Result<u8, io::Error> {
        let next_header = reader.read_u8()?;
        //determine the length (fragmentation header has a fixed length & the rest a length field)
        const FRAG: u8 = IpTrafficClass::IPv6FragmentationHeader as u8;
        let rest_length = if traffic_class == FRAG {
            //fragmentation header has the fixed length of 64bits (one already read)
            7
        } else {
            //Length of the Hop-by-Hop Options header in 8-octet units, not including the first 8 octets.
            ((i64::from(reader.read_u8()?) + 1)*8) - 2
        };
        //Sadly seek does not return an error if the seek could not be fullfilled.
        //Some implementations do not even truncate the returned position to the
        //last valid one. std::io::Cursor for example just moves the position
        //over the border of the given slice (e.g. returns position 15 even when
        //the given slice contains only 1 element).
        //The only option, to detect that we are in an invalid state, is to move the
        //seek offset to one byte before the end and then execute a normal read to
        //trigger an error.
        reader.seek(io::SeekFrom::Current(rest_length - 1))?;
        reader.read_u8()?;
        Ok(next_header)
    }

    ///Skips all ipv6 header extensions and returns the last traffic_class
    pub fn skip_all_header_extensions<T: io::Read + io::Seek + Sized>(reader: &mut T, traffic_class: u8) -> Result<u8, ReadError> {

        let mut next_traffic_class = traffic_class;

        for _i in 0..IPV6_MAX_NUM_HEADER_EXTENSIONS {
            if IpTrafficClass::is_ipv6_ext_header_value(next_traffic_class)
            {
                next_traffic_class = Ipv6Header::skip_header_extension(reader, next_traffic_class)?;
            } else {
                return Ok(next_traffic_class);
            }
        }

        //final check
        if IpTrafficClass::is_ipv6_ext_header_value(next_traffic_class) {
            Err(ReadError::Ipv6TooManyHeaderExtensions)
        } else {
            Ok(next_traffic_class)
        }
    }

    ///Writes a given IPv6 header to the current position.
    pub fn write<T: io::Write + Sized>(&self, writer: &mut T) -> Result<(), WriteError> {
        use crate::ErrorField::*;
        fn max_check_u32(value: u32, max: u32, field: ErrorField) -> Result<(), WriteError> {
            if value <= max {
                Ok(())
            } else {
                Err(
                    WriteError::ValueError(
                        ValueError::U32TooLarge{
                            value, 
                            max, 
                            field }))
            }
        };

        //version & traffic class p0
        writer.write_u8((6 << 4) | (self.traffic_class >> 4))?;

        //flow label
        max_check_u32(self.flow_label, 0xfffff, Ipv6FlowLabel)?;
        {
            //write as a u32 to a buffer and write only the "lower bytes"
            let mut buffer: [u8; 4] = [0;4];
            byteorder::BigEndian::write_u32(&mut buffer, self.flow_label);
            //add the traffic_class
            buffer[1] |= self.traffic_class << 4;
            //skip "highest" byte of big endian
            writer.write_all(&buffer[1..])?;
        }

        //rest
        writer.write_u16::<BigEndian>(self.payload_length)?;
        writer.write_u8(self.next_header)?;
        writer.write_u8(self.hop_limit)?;
        writer.write_all(&self.source)?;
        writer.write_all(&self.destination)?;

        Ok(())
    }

    ///Sets the field total_length based on the size of the payload and the options. Returns an error if the payload is too big to fit.
    pub fn set_payload_length(&mut self, size: usize) -> Result<(), ValueError> {
        //check that the total length fits into the field
        const MAX_PAYLOAD_LENGTH: usize = std::u16::MAX as usize;
        if MAX_PAYLOAD_LENGTH < size {
            return Err(ValueError::Ipv6PayloadLengthTooLarge(size));
        }

        self.payload_length = size as u16;
        Ok(())
    }
}

///A slice containing an ipv6 header of a network package.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Ipv6HeaderSlice<'a> {
    slice: &'a [u8]
}

impl<'a> Ipv6HeaderSlice<'a, > {

    ///Creates a slice containing an ipv6 header (without header extensions).
    pub fn from_slice(slice: &'a[u8]) -> Result<Ipv6HeaderSlice<'a>, ReadError> {

        //check length
        use crate::ReadError::*;
        if slice.len() < Ipv6Header::SERIALIZED_SIZE {
            return Err(UnexpectedEndOfSlice(Ipv6Header::SERIALIZED_SIZE));
        }

        //read version & ihl
        let version = slice[0] >> 4;

        //check version
        if 6 != version {
            return Err(Ipv6UnexpectedVersion(version));
        }

        //all good
        Ok(Ipv6HeaderSlice {
            slice: &slice[..Ipv6Header::SERIALIZED_SIZE]
        })
    }

    ///Returns the slice containing the ipv6 header
    #[inline]
    pub fn slice(&self) -> &'a [u8] {
        self.slice
    }

    ///Read the "version" field from the slice (should be 6).
    pub fn version(&self) -> u8 {
        self.slice[0] >> 4
    }

    ///Read the "traffic class" field from the slice.
    pub fn traffic_class(&self) -> u8 {
        (self.slice[0] << 4) | (self.slice[1] >> 4)
    }

    ///Read the "flow label" field from the slice.
    pub fn flow_label(&self) -> u32 {
        byteorder::BigEndian::read_u32(&[0, self.slice[1] & 0xf, self.slice[2], self.slice[3]])
    }

    ///Read the "payload length" field from  the slice. The length should contain the length of all extension headers and payload.
    pub fn payload_length(&self) -> u16 {
        byteorder::BigEndian::read_u16(&self.slice[4..6])
    }

    ///Read the "next header" field from the slice. The next header value specifies what the next header or transport layer protocol is (see IpTrafficClass for a definitions of ids).
    pub fn next_header(&self) -> u8 {
        self.slice[6]
    }

    ///Read the "hop limit" field from the slice. The hop limit specifies the number of hops the packet can take before it is discarded.
    pub fn hop_limit(&self) -> u8 {
        self.slice[7]
    }

    ///Returns a slice containing the IPv6 source address.
    pub fn source(&self) -> &'a[u8] {
        &self.slice[8..8+16]
    }

    ///Return the ipv6 source address as an std::net::Ipv6Addr
    pub fn source_addr(&self) -> Ipv6Addr {
        let mut result: [u8; 16] = Default::default();
        result.copy_from_slice(self.source());
        Ipv6Addr::from(result)
    }

    ///Returns a slice containing the IPv6 destination address.
    pub fn destination(&self) -> &'a[u8] {
        &self.slice[24..24+16]
    }

    ///Return the ipv6 destination address as an std::net::Ipv6Addr
    pub fn destination_addr(&self) -> Ipv6Addr {
        let mut result: [u8; 16] = Default::default();
        result.copy_from_slice(self.destination());
        Ipv6Addr::from(result)
    }

    ///Decode all the fields and copy the results to a Ipv6Header struct
    pub fn to_header(&self) -> Ipv6Header {
        Ipv6Header {
            traffic_class: self.traffic_class(),
            flow_label: self.flow_label(),
            payload_length: self.payload_length(),
            next_header: self.next_header(),
            hop_limit: self.hop_limit(),
            source: {
                let mut result: [u8; 16] = Default::default();
                result.copy_from_slice(self.source());
                result
            },
            destination: {
                let mut result: [u8; 16] = Default::default();
                result.copy_from_slice(self.destination());
                result
            }
        }
    }
}

///Maximum number of header extensions allowed (according to the ipv6 rfc8200, & iana protocol numbers).
pub const IPV6_MAX_NUM_HEADER_EXTENSIONS: usize = 12;

///Dummy struct for ipv6 header extensions.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Ipv6ExtensionHeader {
    next_header: u8,
    length: u8
}

///A slice containing an ipv6 extension header of a network package.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Ipv6ExtensionHeaderSlice<'a> {
    slice: &'a [u8]
}

impl<'a> Ipv6ExtensionHeaderSlice<'a> {
    ///Creates a slice containing an ipv6 header extension.
    pub fn from_slice(header_type: u8, slice: &'a[u8]) -> Result<Ipv6ExtensionHeaderSlice<'a>, ReadError> {

        //check length
        use crate::ReadError::*;
        if slice.len() < 8 {
            return Err(UnexpectedEndOfSlice(8));
        }

        //check length
        const FRAG: u8 = IpTrafficClass::IPv6FragmentationHeader as u8;
        let len = if FRAG == header_type {
            8
        } else {
            ((slice[1] as usize) + 1)*8
        };

        //check the length again now that the expected length is known
        if slice.len() < len {
            return Err(UnexpectedEndOfSlice(len));
        }

        //all good
        Ok(Ipv6ExtensionHeaderSlice {
            slice: &slice[..len]
        })
    }

    ///Returns the slice containing the ipv6 extension header
    #[inline]
    pub fn slice(&self) -> &'a [u8] {
        self.slice
    }

    ///Returns the id of the next header (see IpTrafficClass for a definition of all ids).
    pub fn next_header(&self) -> u8 {
        self.slice[0]
    }
}