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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
use super::super::*;
use std::slice::from_raw_parts;

/// IPv6 extension headers present after the ip header.
///
/// Currently supported:
///
/// * Authentication Header
/// * Hop by Hop Options Header
/// * Destination Options Header (before and after routing headers)
/// * Routing Header
/// * Fragment
/// * Authentication Header
///
/// Currently not supported:
////
/// * Encapsulating Security Payload Header (ESP)
/// * Host Identity Protocol (HIP)
/// * IP Mobility
/// * Site Multihoming by IPv6 Intermediation (SHIM6)
#[derive(Clone, Debug, Eq, PartialEq, Default)]
pub struct Ipv6Extensions {
    pub hop_by_hop_options: Option<Ipv6RawExtensionHeader>,
    pub destination_options: Option<Ipv6RawExtensionHeader>,
    pub routing: Option<Ipv6RoutingExtensions>,
    pub fragment: Option<Ipv6FragmentHeader>,
    pub auth: Option<IpAuthenticationHeader>,
}

impl Ipv6Extensions {

    /// Reads as many extension headers as possible from the slice.
    ///
    /// Returns the found ipv6 extension headers, the next header ip number after the read
    /// headers and a slice containing the rest of the packet after the read headers.
    ///
    /// Note that this function can only handle ipv6 extensions if each extension header does 
    /// occur at most once, except for destination options headers which are allowed to 
    /// exist once in front of a routing header and once after a routing header.
    ///
    /// In case that more extension headers then can fit into a `Ipv6Extensions` struct are
    /// encountered, the parsing is stoped at the point where the data would no longer fit into
    /// the struct. In such a scenario a struct with the data that could be parsed is returned
    /// together with the next header ip number and slice containing the unparsed data.
    ///
    /// It is in the responsibility of the caller to handle a scenario like this.
    ///
    /// The reason that no error is generated, is that even though according to RFC 8200 packets 
    /// "should" not contain more then one occurence of an extension header the RFC also specifies
    /// that "IPv6 nodes must accept and attempt to process extension headers in any order and 
    /// occurring any number of times in the same packet". So packets with multiple headers "should"
    /// not exist, but are still valid IPv6 packets. As such this function does not generate a
    /// parsing error, as it is not an invalid packet, but if packets like these are encountered
    /// the user of this function has to themself decide how to handle packets like these.
    ///
    /// The only exception is if an hop by hop header is located somewhere else then directly at 
    /// the start. In this case an `ReadError::Ipv6HopByHopHeaderNotAtStart` error is generated as
    /// the hop by hop header is required to be located directly after the IPv6 header according 
    /// to RFC 8200.
    pub fn from_slice(start_ip_number: u8, slice: &[u8]) -> Result<(Ipv6Extensions, u8, &[u8]), ReadError> {
        let mut result: Ipv6Extensions = Default::default();
        let mut rest = slice;
        let mut next_header = start_ip_number;

        use ip_number::*;
        use ReadError::*;

        // the hop by hop header is required to occur directly after the ipv6 header
        if IPV6_HOP_BY_HOP == next_header {
            let slice = Ipv6RawExtensionHeaderSlice::from_slice(rest)?;
            rest = &rest[slice.slice().len()..];
            next_header = slice.next_header();
            result.hop_by_hop_options = Some(slice.to_header());   
        }

        loop {
            match next_header {
                IPV6_HOP_BY_HOP => {
                    return Err(Ipv6HopByHopHeaderNotAtStart);
                },
                IPV6_DEST_OPTIONS => {
                    if let Some(ref mut routing) = result.routing {
                        // if the routing header is already present
                        // this this a "final destination options" header
                        if routing.final_destination_options.is_some() {
                            // more then one header of this type found -> abort parsing
                            return Ok((result, next_header, rest))
                        } else {
                            let slice = Ipv6RawExtensionHeaderSlice::from_slice(rest)?;
                            rest = &rest[slice.slice().len()..];
                            next_header = slice.next_header();
                            routing.final_destination_options = Some(slice.to_header());
                        }
                    } else if result.destination_options.is_some() {
                        // more then one header of this type found -> abort parsing
                        return Ok((result, next_header, rest));
                    } else {
                        let slice = Ipv6RawExtensionHeaderSlice::from_slice(rest)?;
                        rest = &rest[slice.slice().len()..];
                        next_header = slice.next_header();
                        result.destination_options = Some(slice.to_header());
                    }
                },
                IPV6_ROUTE => {
                    if result.routing.is_some() {
                        // more then one header of this type found -> abort parsing
                        return Ok((result, next_header, rest))
                    } else {
                        let slice = Ipv6RawExtensionHeaderSlice::from_slice(rest)?;
                        rest = &rest[slice.slice().len()..];
                        next_header = slice.next_header();
                        result.routing = Some(
                            Ipv6RoutingExtensions {
                                routing: slice.to_header(),
                                final_destination_options: None,
                            }
                        );
                    }
                },
                IPV6_FRAG => {
                    if result.fragment.is_some() {
                        // more then one header of this type found -> abort parsing
                        return Ok((result, next_header, rest))
                    } else {
                        let slice = Ipv6FragmentHeaderSlice::from_slice(rest)?;
                        rest = &rest[slice.slice().len()..];
                        next_header = slice.next_header();
                        result.fragment = Some(slice.to_header());
                    }
                },
                AUTH => {
                    if result.auth.is_some() {
                        // more then one header of this type found -> abort parsing
                        return Ok((result, next_header, rest))
                    } else {
                        let slice = IpAuthenticationHeaderSlice::from_slice(rest)?;
                        rest = &rest[slice.slice().len()..];
                        next_header = slice.next_header();
                        result.auth = Some(slice.to_header());
                    }
                },
                _ => {
                    // done parsing, the next header is not a known header extension
                    return Ok((result, next_header, rest))
                }
            }
        }
        //should not be hit
    }

    /// Reads as many extension headers as possible from the reader and returns the found ipv6
    /// extension headers and the next header ip number.
    ///
    /// If no extension headers are present an unfilled struct and the original `first_header`
    /// ip number is returned.
    ///
    /// Note that this function can only handle ipv6 extensions if each extension header does 
    /// occur at most once, except for destination options headers which are allowed to 
    /// exist once in front of a routing header and once after a routing header.
    ///
    /// In case that more extension headers then can fit into a `Ipv6Extensions` struct are
    /// encountered, the parsing is stoped at the point where the data would no longer fit into
    /// the struct. In such a scenario a struct with the data that could be parsed is returned
    /// together with the next header ip number that identfies which header could be read next.
    ///
    /// It is in the responsibility of the caller to handle a scenario like this.
    ///
    /// The reason that no error is generated, is that even though according to RFC 8200, packets 
    /// "should" not contain more then one occurence of an extension header, the RFC also specifies
    /// that "IPv6 nodes must accept and attempt to process extension headers in any order and 
    /// occurring any number of times in the same packet". So packets with multiple headers "should"
    /// not exist, but are still valid IPv6 packets. As such this function does not generate a
    /// parsing error, as it is not an invalid packet, but if packets like these are encountered
    /// the user of this function has to themself decide how to handle packets like these.
    ///
    /// The only exception is if an hop by hop header is located somewhere else then directly at 
    /// the start. In this case an `ReadError::Ipv6HopByHopHeaderNotAtStart` error is generated as
    /// the hop by hop header is required to be located directly after the IPv6 header according 
    /// to RFC 8200.
    pub fn read<T: io::Read + io::Seek + Sized>(reader: &mut T, start_ip_number: u8) -> Result<(Ipv6Extensions, u8), ReadError> {
        let mut result: Ipv6Extensions = Default::default();
        let mut next_protocol = start_ip_number;

        use ip_number::*;
        use ReadError::*;

        // the hop by hop header is required to occur directly after the ipv6 header
        if IPV6_HOP_BY_HOP == next_protocol {
            let header = Ipv6RawExtensionHeader::read(reader)?;
            next_protocol = header.next_header;
            result.hop_by_hop_options = Some(header);   
        }

        loop {
            match next_protocol {
                IPV6_HOP_BY_HOP => {
                    return Err(Ipv6HopByHopHeaderNotAtStart);
                },
                IPV6_DEST_OPTIONS => {
                    if let Some(ref mut routing) = result.routing {
                        // if the routing header is already present
                        // asume this is a "final destination options" header
                        if routing.final_destination_options.is_some() {
                            // more then one header of this type found -> abort parsing
                            return Ok((result, next_protocol));
                        } else {
                            let header = Ipv6RawExtensionHeader::read(reader)?;
                            next_protocol = header.next_header;
                            routing.final_destination_options = Some(header);
                        }
                    } else if result.destination_options.is_some() {
                        // more then one header of this type found -> abort parsing
                        return Ok((result, next_protocol));
                    } else {
                        let header = Ipv6RawExtensionHeader::read(reader)?;
                        next_protocol = header.next_header;
                        result.destination_options = Some(header);
                    }
                },
                IPV6_ROUTE => {
                    if result.routing.is_some() {
                        // more then one header of this type found -> abort parsing
                        return Ok((result, next_protocol));
                    } else {
                        let header = Ipv6RawExtensionHeader::read(reader)?;
                        next_protocol = header.next_header;
                        result.routing = Some(
                            Ipv6RoutingExtensions{
                                routing: header,
                                final_destination_options: None,
                            }
                        );
                    }
                },
                IPV6_FRAG => {
                    if result.fragment.is_some() {
                        // more then one header of this type found -> abort parsing
                        return Ok((result, next_protocol));
                    } else {
                        let header = Ipv6FragmentHeader::read(reader)?;
                        next_protocol = header.next_header;
                        result.fragment = Some(header);
                    }
                },
                AUTH => {
                    if result.auth.is_some() {
                        // more then one header of this type found -> abort parsing
                        return Ok((result, next_protocol));
                    } else {
                        let header = IpAuthenticationHeader::read(reader)?;
                        next_protocol = header.next_header;
                        result.auth = Some(header);
                    }
                },
                _ => {
                    // done parsing, the next header is not a known header extension
                    return Ok((result, next_protocol))
                }
            }
        }

        //should not be hit
    }

    /// Writes the given headers to a writer based on the order defined in the next_header fields of 
    /// the headers and the first header_id passed to this function.
    ///
    /// It is required that all next header are correctly set in the headers and no other ipv6 header 
    /// extensions follow this header. If this is not the case a `ValueError::Ipv6ExtensionNotReferenced`
    pub fn write<T: io::Write + Sized>(&self, writer: &mut T, first_header: u8) -> Result<(), WriteError> {
        use ip_number::*;
        use IpNumber::*;
        use ValueError::*;

        /// Struct flagging if a header needs to be written.
        struct NeedsWrite {
            pub hop_by_hop_options: bool,
            pub destination_options: bool,
            pub routing: bool,
            pub fragment: bool,
            pub auth: bool,
            pub final_destination_options: bool
        }

        let mut needs_write = NeedsWrite {
            hop_by_hop_options: self.hop_by_hop_options.is_some(),
            destination_options: self.destination_options.is_some(),
            routing: self.routing.is_some(),
            fragment: self.fragment.is_some(),
            auth: self.auth.is_some(),
            final_destination_options: if let Some(ref routing) = self.routing {
                routing.final_destination_options.is_some()
            } else {
                false
            }
        };

        let mut next_header = first_header;
        let mut route_written = false;

        // check if hop by hop header should be written first
        if IPV6_HOP_BY_HOP == next_header {
            let header = &self.hop_by_hop_options.as_ref().unwrap();
            header.write(writer)?;
            next_header = header.next_header;
            needs_write.hop_by_hop_options = false;
        }

        loop {
            match next_header {
                IPV6_HOP_BY_HOP => {
                    // Only trigger a "hop by hop not at start" error
                    // if we actually still have to write a hop by hop header.
                    //
                    // The ip number for hop by hop is 0, which could be used
                    // as a placeholder by user and later replaced. So let's
                    // not be overzealous and allow a next header with hop
                    // by hop if it is not part of this extensions struct.
                    if needs_write.hop_by_hop_options {
                        // the hop by hop header is only allowed at the start
                        return Err(Ipv6ExtensionHopByHopNotAtStart.into());
                    } else {
                        break;
                    }
                },
                IPV6_DEST_OPTIONS => {
                    // the destination options are allowed to be written twice
                    // once before a routing header and once after.
                    if route_written {
                        if needs_write.final_destination_options {
                            let header = &self.routing.as_ref().unwrap().final_destination_options.as_ref().unwrap();
                            header.write(writer)?;
                            next_header = header.next_header;
                            needs_write.final_destination_options = false;
                        } else {
                            break;
                        }
                    } else if needs_write.destination_options {
                        let header = &self.destination_options.as_ref().unwrap();
                        header.write(writer)?;
                        next_header = header.next_header;
                        needs_write.destination_options = false;
                    } else {
                        break;
                    }
                },
                IPV6_ROUTE => {
                    if needs_write.routing {
                        let header = &self.routing.as_ref().unwrap().routing;
                        header.write(writer)?;
                        next_header = header.next_header;
                        needs_write.routing = false;
                        // for destination options
                        route_written = true;
                    } else {
                        break;
                    }
                },
                IPV6_FRAG => {
                    if needs_write.fragment {
                        let header = &self.fragment.as_ref().unwrap();
                        header.write(writer)?;
                        next_header = header.next_header;
                        needs_write.fragment = false;
                    } else {
                        break;
                    }
                },
                AUTH => {
                    if needs_write.auth {
                        let header = &self.auth.as_ref().unwrap();
                        header.write(writer)?;
                        next_header = header.next_header;
                        needs_write.auth = false;
                    } else {
                        break;
                    }
                },
                _ => {
                    // reached an unknown next_header id, proceed to check if everything was written
                    break;
                }
            }
        }

        // check that all header have been written
        if needs_write.hop_by_hop_options {
            Err(Ipv6ExtensionNotReferenced(IPv6HeaderHopByHop).into())
        } else if needs_write.destination_options {
            Err(Ipv6ExtensionNotReferenced(IPv6DestinationOptions).into())
        } else if needs_write.routing {
            Err(Ipv6ExtensionNotReferenced(IPv6RouteHeader).into())
        } else if needs_write.fragment {
            Err(Ipv6ExtensionNotReferenced(IPv6FragmentationHeader).into())
        } else if needs_write.auth {
            Err(Ipv6ExtensionNotReferenced(AuthenticationHeader).into())
        } else if needs_write.final_destination_options {
            Err(Ipv6ExtensionNotReferenced(IPv6DestinationOptions).into())
        } else {
            Ok(())
        }
    }

    /// Length of the all present headers in bytes.
    pub fn header_len(&self) -> usize {
        let mut result = 0;

        if let Some(ref header) = self.hop_by_hop_options {
            result += header.header_len();
        }
        if let Some(ref header) = self.destination_options {
            result += header.header_len();
        }
        if let Some(ref header) = self.routing {
            result += header.routing.header_len();
            if let Some(ref header) = header.final_destination_options {
                result += header.header_len();
            }
        }
        if let Some(ref header) = self.fragment {
            result += header.header_len();
        }
        if let Some(ref header) = self.auth {
            result += header.header_len();
        }

        result
    }

    /// Sets all the next_header fields of the headers based on the adviced default order
    /// with the given protocol number as last "next header" value. The return value is the protocol
    /// number of the first existing extension header that should be entered in the ipv6 header as
    /// next_header.
    ///
    /// If no extension headers are present the value of the argument is returned.
    pub fn set_next_headers(&mut self, last_protocol_number: u8) -> u8 {
        use ip_number::*;

        let mut next = last_protocol_number;

        // go through the proposed order of extension headers from
        // RFC 8200 backwards. The header order defined in RFC8200 is:
        //
        // * IPv6 header
        // * Hop-by-Hop Options header
        // * Destination Options header
        // * Routing header
        // * Fragment header
        // * Authentication header
        // * Encapsulating Security Payload header
        // * Destination Options header
        // * Upper-Layer header
        //
        if let Some(ref mut routing) = self.routing {
            if let Some(ref mut header) = routing.final_destination_options {
                header.next_header = next;
                next = IPV6_DEST_OPTIONS;
            }
        }
        if let Some(ref mut header) = self.auth {
            header.next_header = next;
            next = AUTH;
        }
        if let Some(ref mut header) = self.fragment {
            header.next_header = next;
            next = IPV6_FRAG;
        }
        if let Some(ref mut routing) = self.routing {
            routing.routing.next_header = next;
            next = IPV6_ROUTE;
        }
        if let Some(ref mut header) = self.destination_options {
            header.next_header = next;
            next = IPV6_DEST_OPTIONS;
        }
        if let Some(ref mut header) = self.hop_by_hop_options {
            header.next_header = next;
            next = IPV6_HOP_BY_HOP;
        }

        next
    }

    /// Return next header based on the extension headers and
    /// the first ip protocol number.
    pub fn next_header(&self, first_next_header: u8) -> Result<u8, ValueError> {
        use ValueError::*;
        use ip_number::*;

        /// Struct flagging if a header needs to be referenced.
        struct OutstandingRef {
            pub hop_by_hop_options: bool,
            pub destination_options: bool,
            pub routing: bool,
            pub fragment: bool,
            pub auth: bool,
            pub final_destination_options: bool
        }

        let mut outstanding_refs = OutstandingRef {
            hop_by_hop_options: self.hop_by_hop_options.is_some(),
            destination_options: self.destination_options.is_some(),
            routing: self.routing.is_some(),
            fragment: self.fragment.is_some(),
            auth: self.auth.is_some(),
            final_destination_options: if let Some(ref routing) = self.routing {
                routing.final_destination_options.is_some()
            } else {
                false
            }
        };

        let mut next = first_next_header;
        let mut route_refed = false;

        // check if hop by hop header should be written first
        if IPV6_HOP_BY_HOP == next {
            if let Some(ref header) = self.hop_by_hop_options {
                next = header.next_header;
                outstanding_refs.hop_by_hop_options = false;
            }
        }

        loop {
            match next {
                IPV6_HOP_BY_HOP => {
                    // Only trigger a "hop by hop not at start" error
                    // if we actually still have to write a hop by hop header.
                    //
                    // The ip number for hop by hop is 0, which could be used
                    // as a placeholder by user and later replaced. So let's
                    // not be overzealous and allow a next header with hop
                    // by hop if it is not part of this extensions struct.
                    if outstanding_refs.hop_by_hop_options {
                        // the hop by hop header is only allowed at the start
                        return Err(Ipv6ExtensionHopByHopNotAtStart);
                    } else {
                        break;
                    }
                },
                IPV6_DEST_OPTIONS => {
                    // the destination options are allowed to be written twice
                    // once before a routing header and once after.
                    if route_refed {
                        if outstanding_refs.final_destination_options {
                            let header = &self.routing.as_ref().unwrap().final_destination_options.as_ref().unwrap();
                            next = header.next_header;
                            outstanding_refs.final_destination_options = false;
                        } else {
                            break;
                        }
                    } else if outstanding_refs.destination_options {
                        let header = &self.destination_options.as_ref().unwrap();
                        next = header.next_header;
                        outstanding_refs.destination_options = false;
                    } else {
                        break;
                    }
                },
                IPV6_ROUTE => {
                    if outstanding_refs.routing {
                        let header = &self.routing.as_ref().unwrap().routing;
                        next = header.next_header;
                        outstanding_refs.routing = false;
                        // for destination options
                        route_refed = true;
                    } else {
                        break;
                    }
                },
                IPV6_FRAG => {
                    if outstanding_refs.fragment {
                        let header = &self.fragment.as_ref().unwrap();
                        next = header.next_header;
                        outstanding_refs.fragment = false;
                    } else {
                        break;
                    }
                },
                AUTH => {
                    if outstanding_refs.auth {
                        let header = &self.auth.as_ref().unwrap();
                        next = header.next_header;
                        outstanding_refs.auth = false;
                    } else {
                        break;
                    }
                },
                _ => break,
            }
        }

        // assume all done
        if outstanding_refs.hop_by_hop_options {
            return Err(
                Ipv6ExtensionNotReferenced(IpNumber::IPv6HeaderHopByHop)
            );
        }
        if outstanding_refs.destination_options {
            return Err(
                Ipv6ExtensionNotReferenced(IpNumber::IPv6DestinationOptions)
            );
        }
        if outstanding_refs.routing {
            return Err(
                Ipv6ExtensionNotReferenced(IpNumber::IPv6RouteHeader)
            );
        }
        if outstanding_refs.fragment {
            return Err(
                Ipv6ExtensionNotReferenced(IpNumber::IPv6FragmentationHeader)
            );
        }
        if outstanding_refs.auth {
            return Err(
                Ipv6ExtensionNotReferenced(IpNumber::AuthenticationHeader)
            );
        }
        if outstanding_refs.final_destination_options {
            return Err(
                Ipv6ExtensionNotReferenced(IpNumber::IPv6DestinationOptions)
            );
        }

        Ok(next)
    }

    /// Returns true if no IPv6 extension header is present (all fields `None`).
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.hop_by_hop_options.is_none() &&
        self.destination_options.is_none() &&
        self.routing.is_none() &&
        self.fragment.is_none() &&
        self.auth.is_none()
    }
}

/// In case a route header is present it is also possible
/// to attach a "final destination" header.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Ipv6RoutingExtensions {
    pub routing: Ipv6RawExtensionHeader,
    pub final_destination_options: Option<Ipv6RawExtensionHeader>
}

/// Slice containing the IPv6 extension headers present after the ip header.
///
/// Currently supported:
/// * Authentication Header
/// * Hop by Hop Options Header
/// * Destination Options Header (before and after routing headers)
/// * Routing Header
/// * Fragment
/// * Authentication Header
///
/// Currently not supported:
/// * Encapsulating Security Payload Header (ESP)
/// * Host Identity Protocol (HIP)
/// * IP Mobility
/// * Site Multihoming by IPv6 Intermediation (SHIM6)
#[derive(Clone, Debug, Eq, PartialEq, Default)]
pub struct Ipv6ExtensionsSlice<'a> {
    /// IP protocol number of the first header present in the slice.
    first_header: Option<u8>,
    /// True if a fragment header is present in the ipv6 header extensions that causes the payload to be fragmented.
    fragmented: bool,
    /// Slice containing ipv6 extension headers.
    slice: &'a [u8]
}

impl<'a> Ipv6ExtensionsSlice<'a> {

    /// Collects all ipv6 extension headers in a slice & checks if
    /// a fragmentation header that fragments the packet is present.
    pub fn from_slice(start_ip_number: u8, start_slice: &'a [u8]) -> Result<(Ipv6ExtensionsSlice, u8, &'a[u8]), ReadError> {
        let mut rest = start_slice;
        let mut next_header = start_ip_number;
        let mut fragmented = false;

        use ip_number::*;
        use ReadError::*;

        // the hop by hop header is required to occur directly after the ipv6 header
        if IPV6_HOP_BY_HOP == next_header {
            let slice = Ipv6RawExtensionHeaderSlice::from_slice(rest)?;
            rest = &rest[slice.slice().len()..];
            next_header = slice.next_header();
        }
 
        loop {
            match next_header {
                IPV6_HOP_BY_HOP => {
                    return Err(Ipv6HopByHopHeaderNotAtStart);
                },
                IPV6_DEST_OPTIONS | IPV6_ROUTE => {
                    let slice = Ipv6RawExtensionHeaderSlice::from_slice(rest)?;
                    // SAFETY:
                    // Ipv6RawExtensionHeaderSlice::from_slice always generates
                    // a subslice from the given slice rest. Therefor it is guranteed
                    // that len is always greater or equal the len of rest.
                    rest = unsafe {
                        let len = slice.slice().len();
                        from_raw_parts(
                            rest.as_ptr().add(len),
                            rest.len() - len
                        )
                    };
                    next_header = slice.next_header();
                },
                IPV6_FRAG => {
                    let slice = Ipv6FragmentHeaderSlice::from_slice(rest)?;
                    // SAFETY:
                    // Ipv6FragmentHeaderSlice::from_slice always generates
                    // a subslice from the given slice rest. Therefor it is guranteed
                    // that len is always greater or equal the len of rest.
                    rest = unsafe {
                        let len = slice.slice().len();
                        from_raw_parts(
                            rest.as_ptr().add(len),
                            rest.len() - len
                        )
                    };
                    next_header = slice.next_header();

                    // check if the fragment header actually causes fragmentation
                    fragmented = fragmented || slice.is_fragmenting_payload();
                },
                AUTH => {
                    let slice = IpAuthenticationHeaderSlice::from_slice(rest)?;
                    // SAFETY:
                    // IpAuthenticationHeaderSlice::from_slice always generates
                    // a subslice from the given slice rest. Therefor it is guranteed
                    // that len is always greater or equal the len of rest.
                    rest = unsafe {
                        let len = slice.slice().len();
                        from_raw_parts(
                            rest.as_ptr().add(len),
                            rest.len() - len
                        )
                    };
                    next_header = slice.next_header();
                },
                // done parsing, the next header is not a known/supported header extension
                _ => break,
            }
        }

        Ok((Ipv6ExtensionsSlice{
            first_header: if rest.len() != start_slice.len() {
                Some(start_ip_number)
            } else {
                None
            },
            fragmented,
            slice: &start_slice[..start_slice.len() - rest.len()],
        }, next_header, rest))
    }

    /// Returns true if a fragmentation header is present in
    /// the extensions that fragments the payload.
    ///
    /// Note: A fragmentation header can still be present
    /// even if the return value is false in case the fragmentation
    /// headers don't fragment the payload. This is the case if
    /// the offset of all fragmentation header is 0 and the
    /// more fragment bit is not set.
    #[inline]
    pub fn is_fragmenting_payload(&self) -> bool {
        self.fragmented
    }

    /// Returns the ip protocol number of the first header in the slice
    /// if the slice contains an ipv6 extension header. If no ipv6 header
    /// is present None is returned.
    ///
    /// None is only returned if the slice length of this struct is 0.
    #[inline]
    pub fn first_header(&self) -> Option<u8> {
        self.first_header
    }

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

    /// Returns true if no IPv6 extension header is present (slice is empty).
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.slice.is_empty()
    }
}

/// Enum containing a slice of a supported ipv6 extension header.
///
/// This enum is used as item type when iterating over a list of extension headers
/// with an [Ipv6ExtensionSliceIter].
///
/// Note the following extension headers are missing from
/// this enum and currently not supported (list taken on 2021-07-17
/// from <https://www.iana.org/assignments/ipv6-parameters/ipv6-parameters.xhtml>):
///
/// * Encapsulating Security Payload \[[RFC4303](https://datatracker.ietf.org/doc/html/rfc4303)\]
/// * Mobility Header \[[RFC6275](https://datatracker.ietf.org/doc/html/rfc6275)\]
/// * Host Identity Protocol \[[RFC7401](https://datatracker.ietf.org/doc/html/rfc7401)\]
/// * Shim6 Protocol \[[RFC5533](https://datatracker.ietf.org/doc/html/rfc5533)\]
/// * 253 Use for experimentation and testing \[[RFC3692](https://datatracker.ietf.org/doc/html/rfc3692)\]\[[RFC4727](https://datatracker.ietf.org/doc/html/rfc4727)\]
/// * 254 Use for experimentation and testing \[[RFC3692](https://datatracker.ietf.org/doc/html/rfc3692)\]\[[RFC4727](https://datatracker.ietf.org/doc/html/rfc4727)\]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Ipv6ExtensionSlice<'a> {
    /// IPv6 Hop-by-Hop Option \[[RFC8200](https://datatracker.ietf.org/doc/html/rfc8200)\]
    HopByHop(Ipv6RawExtensionHeaderSlice<'a>),
    /// Routing Header for IPv6 \[[RFC8200](https://datatracker.ietf.org/doc/html/rfc8200)\] \[[RFC5095](https://datatracker.ietf.org/doc/html/rfc5095)\]
    Routing(Ipv6RawExtensionHeaderSlice<'a>),
    /// Fragment Header for IPv6 \[[RFC8200](https://datatracker.ietf.org/doc/html/rfc8200)\]
    Fragment(Ipv6FragmentHeaderSlice<'a>),
    /// Destination Options for IPv6 \[[RFC8200](https://datatracker.ietf.org/doc/html/rfc8200)\]
    DestinationOptions(Ipv6RawExtensionHeaderSlice<'a>),
    /// Authentication Header \[[RFC4302](https://datatracker.ietf.org/doc/html/rfc4302)\]
    Authentication(IpAuthenticationHeaderSlice<'a>),
}

impl<'a> IntoIterator for Ipv6ExtensionsSlice<'a> {
    type Item = Ipv6ExtensionSlice<'a>;
    type IntoIter = Ipv6ExtensionSliceIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        Ipv6ExtensionSliceIter {
            // map the next header None value to some non ipv6 ext header
            // value.
            next_header: self.first_header.unwrap_or(ip_number::UDP),
            rest: self.slice,
        }
    }
}

/// Allows iterating over the IPv6 extension headers present in an [Ipv6ExtensionsSlice].
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Ipv6ExtensionSliceIter<'a> {
    next_header: u8,
    rest: &'a [u8],
}

impl<'a> Default for Ipv6ExtensionSliceIter<'a> {
    fn default() -> Self {
        Ipv6ExtensionSliceIter {
            // don't use 0 as this is the reserved value
            // for the hop by hop header
            next_header: IpNumber::IPv6NoNextHeader as u8,
            rest: &[],
        }
    }
}

impl<'a> Iterator for Ipv6ExtensionSliceIter<'a> {
    type Item = Ipv6ExtensionSlice<'a>;

    fn next(&mut self) -> Option<Ipv6ExtensionSlice<'a>> {
        use ip_number::*;
        use Ipv6ExtensionSlice::*;

        match self.next_header {
            // Note on the unsafe calls:
            //
            // As the slice contents & length were previously checked by
            // Ipv6ExtensionsSlice::from_slice the content does not have to be
            // rechecked.
            IPV6_HOP_BY_HOP => unsafe {
                let slice = Ipv6RawExtensionHeaderSlice::from_slice_unchecked(self.rest);
                let len = slice.slice().len();
                self.rest = from_raw_parts(
                    self.rest.as_ptr().add(len),
                    self.rest.len() - len
                );
                self.next_header = slice.next_header();
                Some(HopByHop(slice))
            },
            IPV6_ROUTE => unsafe {
                let slice = Ipv6RawExtensionHeaderSlice::from_slice_unchecked(self.rest);
                let len = slice.slice().len();
                self.rest = from_raw_parts(
                    self.rest.as_ptr().add(len),
                    self.rest.len() - len
                );
                self.next_header = slice.next_header();
                Some(Routing(slice))
            },
            IPV6_DEST_OPTIONS => unsafe {
                let slice = Ipv6RawExtensionHeaderSlice::from_slice_unchecked(self.rest);
                let len = slice.slice().len();
                self.rest = from_raw_parts(
                    self.rest.as_ptr().add(len),
                    self.rest.len() - len
                );
                self.next_header = slice.next_header();
                Some(DestinationOptions(slice))
            },
            IPV6_FRAG => unsafe {
                let slice = Ipv6FragmentHeaderSlice::from_slice_unchecked(self.rest);
                let len = slice.slice().len();
                self.rest = from_raw_parts(
                    self.rest.as_ptr().add(len),
                    self.rest.len() - len
                );
                self.next_header = slice.next_header();

                Some(Fragment(slice))
            },
            AUTH => unsafe {
                let slice = IpAuthenticationHeaderSlice::from_slice_unchecked(self.rest);
                let len = slice.slice().len();
                self.rest = from_raw_parts(
                    self.rest.as_ptr().add(len),
                    self.rest.len() - len
                );
                self.next_header = slice.next_header();
                Some(Authentication(slice))
            },
            // done parsing, the next header is not a known/supported header extension
            _ => None,
        }
    }
}