Skip to main content

fips_core/node/
endpoint_traffic.rs

1use super::*;
2
3#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
4pub(in crate::node) struct FmpPlaintextTrafficClass {
5    pub(in crate::node) bulk_endpoint_data: bool,
6    pub(in crate::node) drop_on_backpressure: bool,
7}
8
9/// Priority/bulk lane selected for an app-owned endpoint payload.
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
11pub enum EndpointPayloadLane {
12    #[default]
13    Priority,
14    Bulk,
15}
16
17impl EndpointPayloadLane {
18    fn command_lane(self) -> EndpointCommandLane {
19        match self {
20            Self::Priority => EndpointCommandLane::Priority,
21            Self::Bulk => EndpointCommandLane::Bulk,
22        }
23    }
24}
25
26/// Traffic policy selected for an app-owned endpoint payload.
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
28pub struct EndpointPayloadClass {
29    lane: EndpointPayloadLane,
30    drop_on_backpressure: bool,
31}
32
33#[derive(Clone, Copy, Debug, Eq, PartialEq)]
34pub(in crate::node) struct EndpointFlowDispatchKey(u64);
35
36impl EndpointFlowDispatchKey {
37    pub(in crate::node) fn get(self) -> u64 {
38        self.0
39    }
40}
41
42impl EndpointPayloadClass {
43    pub fn lane(self) -> EndpointPayloadLane {
44        self.lane
45    }
46
47    pub fn is_latency_sensitive(self) -> bool {
48        self.lane == EndpointPayloadLane::Priority
49    }
50
51    pub fn drop_on_backpressure(self) -> bool {
52        self.drop_on_backpressure
53    }
54}
55
56#[cfg(unix)]
57pub(in crate::node) struct FmpWorkerSendReservation {
58    pub(in crate::node) counter: u64,
59    pub(in crate::node) header: [u8; ESTABLISHED_HEADER_SIZE],
60    pub(in crate::node) cipher: ring::aead::LessSafeKey,
61}
62
63#[cfg(unix)]
64pub(in crate::node) fn reserve_fmp_worker_send(
65    session: &mut crate::noise::NoiseSession,
66    their_index: crate::utils::index::SessionIndex,
67    flags: u8,
68    payload_len: u16,
69) -> Result<Option<FmpWorkerSendReservation>, crate::noise::NoiseError> {
70    let Some(cipher) = session.send_cipher_clone() else {
71        return Ok(None);
72    };
73    let counter = session.take_send_counter()?;
74    let header = build_established_header(their_index, counter, flags, payload_len);
75    Ok(Some(FmpWorkerSendReservation {
76        counter,
77        header,
78        cipher,
79    }))
80}
81
82#[derive(Clone, Copy, Debug, PartialEq, Eq)]
83pub(crate) enum EndpointCommandLane {
84    Priority,
85    Bulk,
86}
87
88pub(in crate::node) fn classify_fmp_plaintext_traffic(
89    plaintext: &[u8],
90) -> FmpPlaintextTrafficClass {
91    let bulk_endpoint_data = fmp_plaintext_is_bulk_session_datagram(plaintext);
92    // At this layer established FSP payloads are already end-to-end encrypted,
93    // so a bulk SessionDatagram may still be TCP endpoint traffic. Keep it out
94    // of the control lane, but only the pre-FSP endpoint path may mark known
95    // non-TCP packets as discardable under sender backpressure.
96    FmpPlaintextTrafficClass {
97        bulk_endpoint_data,
98        drop_on_backpressure: false,
99    }
100}
101
102pub(in crate::node) fn fmp_plaintext_is_bulk_session_datagram(plaintext: &[u8]) -> bool {
103    if plaintext
104        .first()
105        .is_none_or(|ty| *ty != LinkMessageType::SessionDatagram.to_byte())
106    {
107        return false;
108    }
109    let Some(fsp_payload) = plaintext.get(crate::protocol::SESSION_DATAGRAM_HEADER_SIZE..) else {
110        return false;
111    };
112    FspCommonPrefix::parse(fsp_payload).is_some_and(|prefix| {
113        prefix.phase == FSP_PHASE_ESTABLISHED && !prefix.is_unencrypted() && !prefix.has_coords()
114    })
115}
116
117pub(in crate::node) fn endpoint_flow_dispatch_key(
118    payload: &[u8],
119) -> Option<EndpointFlowDispatchKey> {
120    endpoint_payload_flow_parts(payload).map(|parts| EndpointFlowDispatchKey(parts.hash()))
121}
122
123/// Classify an app-owned endpoint payload for queue admission and pressure policy.
124pub fn classify_endpoint_payload(payload: &[u8]) -> EndpointPayloadClass {
125    const IPPROTO_ICMP: u8 = 1;
126    const IPPROTO_TCP: u8 = 6;
127    const IPPROTO_ICMPV6: u8 = 58;
128
129    match parse_endpoint_payload_ip_proto(payload) {
130        Some((IPPROTO_ICMP, _)) => EndpointPayloadClass::default(),
131        Some((IPPROTO_ICMPV6, _)) => EndpointPayloadClass::default(),
132        Some((IPPROTO_TCP, offset)) => {
133            let latency_sensitive = endpoint_tcp_payload_is_latency_sensitive(payload, offset);
134            EndpointPayloadClass {
135                lane: if latency_sensitive {
136                    EndpointPayloadLane::Priority
137                } else {
138                    EndpointPayloadLane::Bulk
139                },
140                drop_on_backpressure: false,
141            }
142        }
143        _ => EndpointPayloadClass {
144            lane: EndpointPayloadLane::Bulk,
145            drop_on_backpressure: true,
146        },
147    }
148}
149
150/// Return true when an app-owned endpoint payload should retain priority-lane progress.
151///
152/// Embedders that stage packets before calling `FipsEndpoint::send*_to_peer`
153/// can use this to apply the same priority/bulk policy as the FIPS endpoint
154/// command queue without duplicating IP/TCP parsing.
155pub fn endpoint_payload_is_latency_sensitive(payload: &[u8]) -> bool {
156    classify_endpoint_payload(payload).is_latency_sensitive()
157}
158
159#[cfg(test)]
160pub(crate) fn endpoint_command_lane_for_payload(payload: &[u8]) -> EndpointCommandLane {
161    if endpoint_payload_is_latency_sensitive(payload) {
162        EndpointCommandLane::Priority
163    } else {
164        EndpointCommandLane::Bulk
165    }
166}
167
168/// Endpoint payload bytes plus the traffic policy selected at app ingress.
169#[derive(Clone, Debug, PartialEq, Eq)]
170pub(crate) struct EndpointDataPayload {
171    bytes: Vec<u8>,
172    traffic_class: EndpointPayloadClass,
173}
174
175impl EndpointDataPayload {
176    pub(crate) fn new(bytes: Vec<u8>) -> Self {
177        let traffic_class = classify_endpoint_payload(&bytes);
178        Self {
179            bytes,
180            traffic_class,
181        }
182    }
183
184    pub(crate) fn from_classified(bytes: Vec<u8>, traffic_class: EndpointPayloadClass) -> Self {
185        Self {
186            bytes,
187            traffic_class,
188        }
189    }
190
191    pub(crate) fn lane(&self) -> EndpointCommandLane {
192        self.traffic_class.lane().command_lane()
193    }
194
195    pub(crate) fn bulk_endpoint_data(&self) -> bool {
196        self.traffic_class.lane() == EndpointPayloadLane::Bulk
197    }
198
199    pub(crate) fn drop_on_backpressure(&self) -> bool {
200        self.traffic_class.drop_on_backpressure()
201    }
202
203    pub(crate) fn as_slice(&self) -> &[u8] {
204        &self.bytes
205    }
206
207    pub(crate) fn len(&self) -> usize {
208        self.bytes.len()
209    }
210}
211
212impl From<Vec<u8>> for EndpointDataPayload {
213    fn from(bytes: Vec<u8>) -> Self {
214        Self::new(bytes)
215    }
216}
217
218/// Outbound endpoint data plus the peer identity it is bound to.
219#[derive(Debug)]
220pub(crate) struct EndpointDataSend {
221    dest_addr: NodeAddr,
222    dest_pubkey: secp256k1::PublicKey,
223    payload: EndpointDataPayload,
224}
225
226impl EndpointDataSend {
227    pub(crate) fn new(remote: PeerIdentity, payload: EndpointDataPayload) -> Self {
228        Self {
229            dest_addr: *remote.node_addr(),
230            dest_pubkey: remote.pubkey_full(),
231            payload,
232        }
233    }
234
235    pub(crate) fn dest_addr(&self) -> NodeAddr {
236        self.dest_addr
237    }
238
239    pub(crate) fn dest_pubkey(&self) -> secp256k1::PublicKey {
240        self.dest_pubkey
241    }
242
243    pub(crate) fn payload(&self) -> &EndpointDataPayload {
244        &self.payload
245    }
246
247    pub(crate) fn into_payload(self) -> EndpointDataPayload {
248        self.payload
249    }
250}
251
252/// Admission result for a bounded pending endpoint-data queue.
253#[derive(Clone, Copy, Debug, PartialEq, Eq)]
254pub(crate) struct PendingEndpointDataQueueAdmission {
255    dropped_oldest: bool,
256}
257
258impl PendingEndpointDataQueueAdmission {
259    pub(crate) fn dropped_oldest(&self) -> bool {
260        self.dropped_oldest
261    }
262}
263
264/// Per-destination endpoint payloads waiting for session establishment.
265#[derive(Debug, Default)]
266pub(crate) struct PendingEndpointDataQueue {
267    payloads: VecDeque<EndpointDataPayload>,
268}
269
270impl PendingEndpointDataQueue {
271    pub(crate) fn push_bounded(
272        &mut self,
273        payload: EndpointDataPayload,
274        capacity: usize,
275    ) -> PendingEndpointDataQueueAdmission {
276        let dropped_oldest = self.payloads.len() >= capacity;
277        if dropped_oldest {
278            self.payloads.pop_front();
279        }
280        self.payloads.push_back(payload);
281        PendingEndpointDataQueueAdmission { dropped_oldest }
282    }
283
284    pub(crate) fn len(&self) -> usize {
285        self.payloads.len()
286    }
287
288    pub(crate) fn into_payloads(self) -> VecDeque<EndpointDataPayload> {
289        self.payloads
290    }
291
292    #[cfg(test)]
293    pub(crate) fn iter(&self) -> impl Iterator<Item = &EndpointDataPayload> {
294        self.payloads.iter()
295    }
296}
297
298/// Admission result for a bounded pending TUN packet queue.
299#[derive(Clone, Copy, Debug, PartialEq, Eq)]
300pub(crate) struct PendingTunPacketQueueAdmission {
301    dropped_oldest: bool,
302}
303
304impl PendingTunPacketQueueAdmission {
305    pub(crate) fn dropped_oldest(&self) -> bool {
306        self.dropped_oldest
307    }
308}
309
310/// Per-destination TUN packets waiting for session establishment.
311#[derive(Debug, Default)]
312pub(crate) struct PendingTunPacketQueue {
313    packets: VecDeque<Vec<u8>>,
314}
315
316impl PendingTunPacketQueue {
317    pub(crate) fn push_bounded(
318        &mut self,
319        packet: Vec<u8>,
320        capacity: usize,
321    ) -> PendingTunPacketQueueAdmission {
322        let dropped_oldest = self.packets.len() >= capacity;
323        if dropped_oldest {
324            self.packets.pop_front();
325        }
326        self.packets.push_back(packet);
327        PendingTunPacketQueueAdmission { dropped_oldest }
328    }
329
330    pub(crate) fn len(&self) -> usize {
331        self.packets.len()
332    }
333
334    pub(crate) fn into_packets(self) -> VecDeque<Vec<u8>> {
335        self.packets
336    }
337
338    #[cfg(test)]
339    pub(crate) fn iter(&self) -> impl Iterator<Item = &Vec<u8>> {
340        self.packets.iter()
341    }
342}
343
344/// Admission result for pending session-establishment traffic.
345#[derive(Clone, Copy, Debug, PartialEq, Eq)]
346pub(crate) struct PendingSessionTrafficAdmission {
347    destination_dropped: bool,
348    dropped_oldest: bool,
349}
350
351impl PendingSessionTrafficAdmission {
352    pub(crate) fn destination_dropped(&self) -> bool {
353        self.destination_dropped
354    }
355
356    pub(crate) fn dropped_oldest(&self) -> bool {
357        self.dropped_oldest
358    }
359}
360
361/// Queued TUN and endpoint traffic removed for one destination.
362#[derive(Debug, Default)]
363pub(crate) struct PendingDestinationTraffic {
364    tun_packets: Option<PendingTunPacketQueue>,
365    endpoint_data: Option<PendingEndpointDataQueue>,
366}
367
368impl PendingDestinationTraffic {
369    pub(crate) fn tun_packets(&self) -> Option<&PendingTunPacketQueue> {
370        self.tun_packets.as_ref()
371    }
372
373    pub(crate) fn into_tun_packets(self) -> Option<PendingTunPacketQueue> {
374        self.tun_packets
375    }
376
377    pub(crate) fn endpoint_data(&self) -> Option<&PendingEndpointDataQueue> {
378        self.endpoint_data.as_ref()
379    }
380}
381
382/// Pending traffic waiting for session establishment.
383#[derive(Debug, Default)]
384pub(crate) struct PendingSessionTrafficQueues {
385    pending_destinations: HashSet<NodeAddr>,
386    tun_packets: HashMap<NodeAddr, PendingTunPacketQueue>,
387    endpoint_data: HashMap<NodeAddr, PendingEndpointDataQueue>,
388}
389
390impl PendingSessionTrafficQueues {
391    pub(crate) fn push_tun_packet(
392        &mut self,
393        dest_addr: NodeAddr,
394        packet: Vec<u8>,
395        max_destinations: usize,
396        packets_per_dest: usize,
397    ) -> PendingSessionTrafficAdmission {
398        if !self.tun_packets.contains_key(&dest_addr) && self.tun_packets.len() >= max_destinations
399        {
400            return PendingSessionTrafficAdmission {
401                destination_dropped: true,
402                dropped_oldest: false,
403            };
404        }
405
406        let admission = self
407            .tun_packets
408            .entry(dest_addr)
409            .or_default()
410            .push_bounded(packet, packets_per_dest);
411        self.pending_destinations.insert(dest_addr);
412        PendingSessionTrafficAdmission {
413            destination_dropped: false,
414            dropped_oldest: admission.dropped_oldest(),
415        }
416    }
417
418    pub(crate) fn push_endpoint_data(
419        &mut self,
420        dest_addr: NodeAddr,
421        payload: impl Into<EndpointDataPayload>,
422        max_destinations: usize,
423        packets_per_dest: usize,
424    ) -> PendingSessionTrafficAdmission {
425        if !self.endpoint_data.contains_key(&dest_addr)
426            && self.endpoint_data.len() >= max_destinations
427        {
428            return PendingSessionTrafficAdmission {
429                destination_dropped: true,
430                dropped_oldest: false,
431            };
432        }
433
434        let admission = self
435            .endpoint_data
436            .entry(dest_addr)
437            .or_default()
438            .push_bounded(payload.into(), packets_per_dest);
439        self.pending_destinations.insert(dest_addr);
440        PendingSessionTrafficAdmission {
441            destination_dropped: false,
442            dropped_oldest: admission.dropped_oldest(),
443        }
444    }
445
446    pub(crate) fn remove_destination(&mut self, dest_addr: &NodeAddr) -> PendingDestinationTraffic {
447        self.pending_destinations.remove(dest_addr);
448        PendingDestinationTraffic {
449            tun_packets: self.tun_packets.remove(dest_addr),
450            endpoint_data: self.endpoint_data.remove(dest_addr),
451        }
452    }
453
454    pub(crate) fn take_tun_packets(
455        &mut self,
456        dest_addr: &NodeAddr,
457    ) -> Option<PendingTunPacketQueue> {
458        let packets = self.tun_packets.remove(dest_addr);
459        if packets.is_some() && !self.endpoint_data.contains_key(dest_addr) {
460            self.pending_destinations.remove(dest_addr);
461        }
462        packets
463    }
464
465    pub(crate) fn take_endpoint_data(
466        &mut self,
467        dest_addr: &NodeAddr,
468    ) -> Option<PendingEndpointDataQueue> {
469        let payloads = self.endpoint_data.remove(dest_addr);
470        if payloads.is_some() && !self.tun_packets.contains_key(dest_addr) {
471            self.pending_destinations.remove(dest_addr);
472        }
473        payloads
474    }
475
476    pub(crate) fn has_traffic_for(&self, dest_addr: &NodeAddr) -> bool {
477        self.pending_destinations.contains(dest_addr)
478    }
479
480    pub(crate) fn tun_packets_for(&self, dest_addr: &NodeAddr) -> Option<&PendingTunPacketQueue> {
481        self.tun_packets.get(dest_addr)
482    }
483
484    pub(crate) fn endpoint_data_for(
485        &self,
486        dest_addr: &NodeAddr,
487    ) -> Option<&PendingEndpointDataQueue> {
488        self.endpoint_data.get(dest_addr)
489    }
490
491    pub(crate) fn tun_destination_count(&self) -> usize {
492        self.tun_packets.len()
493    }
494
495    pub(crate) fn tun_packet_count(&self) -> usize {
496        self.tun_packets.values().map(|q| q.len()).sum()
497    }
498}
499
500fn endpoint_tcp_payload_is_latency_sensitive(payload: &[u8], tcp_offset: usize) -> bool {
501    const TCP_MIN_HEADER_LEN: usize = 20;
502    const TCP_FLAG_FIN: u8 = 0x01;
503    const TCP_FLAG_SYN: u8 = 0x02;
504    const TCP_FLAG_RST: u8 = 0x04;
505    const INTERACTIVE_TCP_PAYLOAD_MAX: usize = 256;
506
507    if payload.len() < tcp_offset + TCP_MIN_HEADER_LEN {
508        return true;
509    }
510
511    let tcp_header_len = usize::from(payload[tcp_offset + 12] >> 4) * 4;
512    if tcp_header_len < TCP_MIN_HEADER_LEN || payload.len() < tcp_offset + tcp_header_len {
513        return true;
514    }
515
516    let flags = payload[tcp_offset + 13];
517    if flags & (TCP_FLAG_FIN | TCP_FLAG_SYN | TCP_FLAG_RST) != 0 {
518        return true;
519    }
520
521    let payload_len = endpoint_ip_payload_len(payload)
522        .and_then(|ip_payload_len| ip_payload_len.checked_sub(tcp_header_len))
523        .unwrap_or_else(|| payload.len().saturating_sub(tcp_offset + tcp_header_len));
524    payload_len <= INTERACTIVE_TCP_PAYLOAD_MAX
525}
526
527fn endpoint_ip_payload_len(payload: &[u8]) -> Option<usize> {
528    const IPV4_MIN_HEADER_LEN: usize = 20;
529    const IPV6_HEADER_LEN: usize = 40;
530
531    let version_ihl = payload.first().copied()?;
532    match version_ihl >> 4 {
533        4 => {
534            if payload.len() < IPV4_MIN_HEADER_LEN {
535                return None;
536            }
537            let header_len = usize::from(version_ihl & 0x0f) * 4;
538            if header_len < IPV4_MIN_HEADER_LEN || payload.len() < header_len {
539                return None;
540            }
541            let total_len = usize::from(u16::from_be_bytes([payload[2], payload[3]]));
542            total_len.checked_sub(header_len)
543        }
544        6 => {
545            if payload.len() < IPV6_HEADER_LEN {
546                return None;
547            }
548            Some(usize::from(u16::from_be_bytes([payload[4], payload[5]])))
549        }
550        _ => None,
551    }
552}
553
554fn parse_endpoint_payload_ip_proto(payload: &[u8]) -> Option<(u8, usize)> {
555    const IPV4_MIN_HEADER_LEN: usize = 20;
556
557    let version_ihl = payload.first().copied()?;
558
559    match version_ihl >> 4 {
560        4 => {
561            if payload.len() < IPV4_MIN_HEADER_LEN {
562                return None;
563            }
564            let header_len = usize::from(version_ihl & 0x0f) * 4;
565            if header_len >= IPV4_MIN_HEADER_LEN && payload.len() >= header_len {
566                Some((payload[9], header_len))
567            } else {
568                None
569            }
570        }
571        6 => ipv6_payload_next_header(payload),
572        _ => None,
573    }
574}
575
576#[derive(Clone, Copy)]
577struct EndpointFlowParts<'a> {
578    version: u8,
579    proto: u8,
580    src: &'a [u8],
581    dst: &'a [u8],
582    ports: Option<[u8; 4]>,
583}
584
585impl EndpointFlowParts<'_> {
586    fn hash(self) -> u64 {
587        let mut h = EndpointFlowHasher::default();
588        h.write_u8(self.version);
589        h.write_u8(self.proto);
590        h.write(self.src);
591        h.write(self.dst);
592        if let Some(ports) = self.ports {
593            h.write(&ports);
594        }
595        h.finish()
596    }
597}
598
599#[derive(Clone, Copy)]
600struct EndpointFlowHasher(u64);
601
602impl Default for EndpointFlowHasher {
603    fn default() -> Self {
604        Self(0x9ae1_6a3b_2f90_404f)
605    }
606}
607
608impl EndpointFlowHasher {
609    fn write_u8(&mut self, value: u8) {
610        self.write(&[value]);
611    }
612
613    fn write(&mut self, bytes: &[u8]) {
614        for byte in bytes {
615            self.0 ^= u64::from(*byte);
616            self.0 = self.0.wrapping_mul(0x1000_0000_01b3);
617            self.0 ^= self.0 >> 32;
618        }
619    }
620
621    fn finish(self) -> u64 {
622        self.0
623    }
624}
625
626fn endpoint_payload_flow_parts(payload: &[u8]) -> Option<EndpointFlowParts<'_>> {
627    const IPV4_MIN_HEADER_LEN: usize = 20;
628    const IPV6_HEADER_LEN: usize = 40;
629
630    let version = payload.first().copied()? >> 4;
631    match version {
632        4 => {
633            if payload.len() < IPV4_MIN_HEADER_LEN {
634                return None;
635            }
636            let header_len = usize::from(payload[0] & 0x0f) * 4;
637            if header_len < IPV4_MIN_HEADER_LEN || payload.len() < header_len {
638                return None;
639            }
640            let fragment_bits = u16::from_be_bytes([payload[6], payload[7]]) & 0x3fff;
641            Some(EndpointFlowParts {
642                version,
643                proto: payload[9],
644                src: &payload[12..16],
645                dst: &payload[16..20],
646                ports: if fragment_bits == 0 {
647                    endpoint_transport_ports(payload, payload[9], header_len)
648                } else {
649                    None
650                },
651            })
652        }
653        6 => {
654            if payload.len() < IPV6_HEADER_LEN {
655                return None;
656            }
657            let (proto, offset, fragmented) = ipv6_payload_next_header_with_fragment(payload)?;
658            Some(EndpointFlowParts {
659                version,
660                proto,
661                src: &payload[8..24],
662                dst: &payload[24..40],
663                ports: if fragmented {
664                    None
665                } else {
666                    endpoint_transport_ports(payload, proto, offset)
667                },
668            })
669        }
670        _ => None,
671    }
672}
673
674fn endpoint_transport_ports(payload: &[u8], proto: u8, transport_offset: usize) -> Option<[u8; 4]> {
675    const IPPROTO_TCP: u8 = 6;
676    const IPPROTO_UDP: u8 = 17;
677    const IPPROTO_SCTP: u8 = 132;
678
679    if !matches!(proto, IPPROTO_TCP | IPPROTO_UDP | IPPROTO_SCTP) {
680        return None;
681    }
682    let ports = payload.get(transport_offset..transport_offset + 4)?;
683    Some([ports[0], ports[1], ports[2], ports[3]])
684}
685
686#[cfg(test)]
687pub(in crate::node) fn endpoint_payload_is_tcp(payload: &[u8]) -> bool {
688    const IPPROTO_TCP: u8 = 6;
689    parse_endpoint_payload_ip_proto(payload).is_some_and(|(proto, _)| proto == IPPROTO_TCP)
690}
691
692fn ipv6_payload_next_header(payload: &[u8]) -> Option<(u8, usize)> {
693    ipv6_payload_next_header_with_fragment(payload)
694        .map(|(next_header, offset, _)| (next_header, offset))
695}
696
697fn ipv6_payload_next_header_with_fragment(payload: &[u8]) -> Option<(u8, usize, bool)> {
698    const IPV6_HEADER_LEN: usize = 40;
699    const IPV6_FRAGMENT_HEADER_LEN: usize = 8;
700
701    if payload.len() < IPV6_HEADER_LEN || payload[0] >> 4 != 6 {
702        return None;
703    }
704
705    let mut next_header = payload[6];
706    let mut offset = IPV6_HEADER_LEN;
707    let mut extension_count = 0usize;
708    let mut fragmented = false;
709    while ipv6_extension_header_is_skippable(next_header) {
710        if next_header == 44 {
711            if payload.len() < offset + IPV6_FRAGMENT_HEADER_LEN {
712                return None;
713            }
714            fragmented = true;
715            next_header = payload[offset];
716            offset += IPV6_FRAGMENT_HEADER_LEN;
717        } else if next_header == 51 {
718            if payload.len() < offset + 2 {
719                return None;
720            }
721            let header_len = (usize::from(payload[offset + 1]) + 2) * 4;
722            if payload.len() < offset + header_len {
723                return None;
724            }
725            next_header = payload[offset];
726            offset += header_len;
727        } else {
728            if payload.len() < offset + 2 {
729                return None;
730            }
731            let header_len = (usize::from(payload[offset + 1]) + 1) * 8;
732            if payload.len() < offset + header_len {
733                return None;
734            }
735            next_header = payload[offset];
736            offset += header_len;
737        }
738        extension_count += 1;
739        if extension_count > 8 {
740            return None;
741        }
742    }
743
744    Some((next_header, offset, fragmented))
745}
746
747fn ipv6_extension_header_is_skippable(next_header: u8) -> bool {
748    matches!(next_header, 0 | 43 | 44 | 51 | 60 | 135)
749}