Skip to main content

rtc_dtls/conn/
mod.rs

1//! The DTLS association.
2//!
3//! [`DTLSConn`](crate::conn::DTLSConn) joins the handshake state machine to the record layer for one peer: inbound
4//! datagrams go in through [`read`](crate::conn::DTLSConn::read), application data comes out through
5//! [`incoming_application_data`](crate::conn::DTLSConn::incoming_application_data), and whatever should go on
6//! the wire is collected from [`outgoing_raw_packet`](crate::conn::DTLSConn::outgoing_raw_packet).
7//!
8//! Normally an application drives [`Endpoint`](crate::endpoint::Endpoint) instead, which owns one
9//! of these per remote address.
10#[cfg(test)]
11mod conn_test;
12
13use crate::alert::*;
14use crate::application_data::*;
15use crate::content::*;
16use crate::curve::named_curve::NamedCurve;
17use crate::extension::extension_use_srtp::*;
18use crate::flight::flight0::*;
19use crate::flight::flight1::*;
20use crate::flight::flight5::*;
21use crate::flight::flight6::*;
22use crate::flight::*;
23use crate::fragment_buffer::*;
24use crate::handshake::handshake_cache::*;
25use crate::handshake::handshake_header::HandshakeHeader;
26use crate::handshake::*;
27use crate::handshaker::*;
28use crate::record_layer::record_layer_header::*;
29use crate::record_layer::*;
30use crate::state::*;
31use std::collections::VecDeque;
32
33use shared::{error::*, replay_detector::*};
34
35use crate::config::HandshakeConfig;
36use bytes::BytesMut;
37use log::*;
38use std::io::BufWriter;
39use std::sync::Arc;
40use std::time::{Duration, Instant};
41
42pub(crate) const INITIAL_TICKER_INTERVAL: Duration = Duration::from_secs(1);
43pub(crate) const COOKIE_LENGTH: usize = 20;
44pub(crate) const DEFAULT_NAMED_CURVE: NamedCurve = NamedCurve::X25519;
45pub(crate) const INBOUND_BUFFER_SIZE: usize = 8192;
46// Default replay protection window is specified by RFC 6347 Section 4.1.2.6
47pub(crate) const DEFAULT_REPLAY_PROTECTION_WINDOW: usize = 64;
48
49pub(crate) static INVALID_KEYING_LABELS: &[&str] = &[
50    "client finished",
51    "server finished",
52    "master secret",
53    "key expansion",
54];
55
56// Conn represents a DTLS connection
57/// One DTLS association: the handshake state machine plus the record layer around it.
58pub struct DTLSConn {
59    is_client: bool,
60    maximum_transmission_unit: usize,
61    pub(crate) maximum_retransmit_number: usize,
62    replay_protection_window: usize,
63    replay_detector: Vec<Box<dyn ReplayDetector>>,
64    incoming_decrypted_packets: VecDeque<BytesMut>, // Decrypted Application Data or error, pull by calling `Read`
65    incoming_encrypted_packets: VecDeque<Vec<u8>>,
66    fragment_buffer: FragmentBuffer,
67    pub(crate) cache: HandshakeCache, // caching of handshake messages for verifyData generation
68    pub(crate) outgoing_packets: VecDeque<Packet>,
69    outgoing_queued_packets: VecDeque<Packet>,
70    outgoing_compacted_raw_packets: VecDeque<BytesMut>,
71
72    pub(crate) state: State, // Internal state
73
74    handshake_completed: bool,
75    connection_closed_by_user: bool,
76    // closeLock              sync.Mutex
77    closed: bool, //  *closer.Closer
78    //handshakeLoopsFinished sync.WaitGroup
79
80    //readDeadline  :deadline.Deadline,
81    //writeDeadline :deadline.Deadline,
82
83    //log logging.LeveledLogger
84    /*
85    reading               chan struct{}
86    handshakeRecv         chan chan struct{}
87    cancelHandshaker      func()
88    cancelHandshakeReader func()
89    */
90    pub(crate) current_handshake_state: HandshakeState,
91    pub(crate) current_retransmit_timer: Option<Instant>,
92    pub(crate) current_retransmit_count: usize,
93
94    pub(crate) current_flight: Box<dyn Flight>,
95    pub(crate) flights: Option<Vec<Packet>>,
96    pub(crate) handshake_config: Arc<HandshakeConfig>,
97    pub(crate) retransmit: bool,
98    pub(crate) handshake_rx: Option<()>,
99}
100
101impl DTLSConn {
102    /// Creates a connection in the given role, ready to handshake.
103    ///
104    /// # Errors
105    ///
106    /// Fails if the configuration is invalid — no certificate for a server, or an unusable cipher
107    /// suite list.
108    pub fn new(
109        handshake_config: Arc<HandshakeConfig>,
110        is_client: bool,
111        initial_state: Option<State>,
112    ) -> Self {
113        let (state, flight, initial_fsm_state) = if let Some(state) = initial_state {
114            let flight = if is_client {
115                Box::new(Flight5 {}) as Box<dyn Flight>
116            } else {
117                Box::new(Flight6 {}) as Box<dyn Flight>
118            };
119
120            (state, flight, HandshakeState::Finished)
121        } else {
122            let flight = if is_client {
123                Box::new(Flight1 {}) as Box<dyn Flight>
124            } else {
125                Box::new(Flight0 {}) as Box<dyn Flight>
126            };
127
128            (
129                State {
130                    is_client,
131                    ..Default::default()
132                },
133                flight,
134                HandshakeState::Preparing,
135            )
136        };
137
138        Self {
139            is_client,
140            maximum_transmission_unit: handshake_config.maximum_transmission_unit,
141            maximum_retransmit_number: handshake_config.maximum_retransmit_number,
142            replay_protection_window: handshake_config.replay_protection_window,
143            replay_detector: vec![],
144            incoming_decrypted_packets: VecDeque::new(),
145            incoming_encrypted_packets: VecDeque::new(),
146            fragment_buffer: FragmentBuffer::new(),
147            outgoing_packets: VecDeque::new(),
148            outgoing_queued_packets: VecDeque::new(),
149            outgoing_compacted_raw_packets: VecDeque::new(),
150
151            cache: HandshakeCache::new(),
152            state,
153            handshake_completed: false,
154            connection_closed_by_user: false,
155            closed: false,
156
157            current_handshake_state: initial_fsm_state,
158            current_retransmit_timer: None,
159            current_retransmit_count: 0,
160
161            current_flight: flight,
162            flights: None,
163            handshake_config,
164            retransmit: false,
165            handshake_rx: None,
166        }
167    }
168
169    // Read reads data from the connection.
170    /// Takes the next decrypted application payload, if one is ready.
171    pub fn incoming_application_data(&mut self) -> Option<BytesMut> {
172        if !self.is_handshake_completed() {
173            None
174        } else {
175            self.incoming_decrypted_packets.pop_front()
176        }
177    }
178
179    /// Takes the next datagram the caller should send.
180    pub fn outgoing_raw_packet(&mut self) -> Option<BytesMut> {
181        if let Err(err) = self.handle_outgoing_packets() {
182            warn!(
183                "handle_outgoing_packets [{}] with error {}",
184                srv_cli_str(self.is_client),
185                err
186            );
187        }
188        self.outgoing_compacted_raw_packets.pop_front()
189    }
190
191    // Write writes p to the DTLS connection
192    /// Queues `p` as application data, encrypting it once the handshake has completed.
193    ///
194    /// # Errors
195    ///
196    /// Fails if the connection is closed or the handshake has not finished.
197    pub fn write(&mut self, p: &[u8]) -> Result<()> {
198        if self.is_connection_closed() {
199            return Err(Error::ErrConnClosed);
200        }
201
202        let pkt = Packet {
203            record: RecordLayer::new(
204                PROTOCOL_VERSION1_2,
205                self.get_local_epoch(),
206                Content::ApplicationData(ApplicationData {
207                    data: BytesMut::from(p),
208                }),
209            ),
210            should_encrypt: true,
211            reset_local_sequence_number: false,
212        };
213
214        if self.is_handshake_completed() {
215            self.write_packets(vec![pkt]);
216        } else {
217            self.outgoing_queued_packets.push_back(pkt);
218        }
219
220        Ok(())
221    }
222
223    // Close closes the connection.
224    /// Begins an orderly shutdown by queueing a `close_notify` alert.
225    pub fn close(&mut self) {
226        if !self.closed {
227            self.closed = true;
228
229            // Discard error from notify() to return non-error on the first user call of Close()
230            // even if the underlying connection is already closed.
231            self.notify(AlertLevel::Warning, AlertDescription::CloseNotify);
232        }
233    }
234
235    /// connection_state returns basic DTLS details about the connection.
236    /// Note that this replaced the `Export` function of v1.
237    pub fn connection_state(&self) -> &State {
238        &self.state
239    }
240
241    // selected_srtp_protection_profile returns the selected SRTPProtectionProfile
242    pub(crate) fn selected_srtp_protection_profile(&self) -> SrtpProtectionProfile {
243        self.state.srtp_protection_profile
244    }
245
246    pub(crate) fn notify(&mut self, level: AlertLevel, desc: AlertDescription) {
247        self.write_packets(vec![Packet {
248            record: RecordLayer::new(
249                PROTOCOL_VERSION1_2,
250                self.get_local_epoch(),
251                Content::Alert(Alert {
252                    alert_level: level,
253                    alert_description: desc,
254                }),
255            ),
256            should_encrypt: self.is_handshake_completed(),
257            reset_local_sequence_number: false,
258        }]);
259    }
260
261    pub(crate) fn write_packets(&mut self, pkts: Vec<Packet>) {
262        for pkt in pkts {
263            self.outgoing_packets.push_back(pkt);
264        }
265    }
266
267    fn handle_outgoing_packets(&mut self) -> Result<()> {
268        if self.is_handshake_completed() {
269            while let Some(mut pkt) = self.outgoing_queued_packets.pop_front() {
270                pkt.record.record_layer_header.epoch = self.get_local_epoch();
271                self.write_packets(vec![pkt]);
272            }
273        }
274
275        let mut raw_packets = vec![];
276        while let Some(p) = self.outgoing_packets.pop_front() {
277            if let Content::Handshake(h) = &p.record.content {
278                let mut handshake_raw = vec![];
279                {
280                    let mut writer = BufWriter::<&mut Vec<u8>>::new(handshake_raw.as_mut());
281                    p.record.marshal(&mut writer)?;
282                }
283                debug!(
284                    "Send [handshake:{}] -> {} (epoch: {}, seq: {})",
285                    srv_cli_str(self.is_client),
286                    h.handshake_header.handshake_type,
287                    p.record.record_layer_header.epoch,
288                    h.handshake_header.message_sequence
289                );
290                self.cache.push(
291                    handshake_raw[RECORD_LAYER_HEADER_SIZE..].to_vec(),
292                    p.record.record_layer_header.epoch,
293                    h.handshake_header.message_sequence,
294                    h.handshake_header.handshake_type,
295                    self.is_client,
296                );
297
298                let raw_handshake_packets = self.process_handshake_packet(&p, h)?;
299                raw_packets.extend_from_slice(&raw_handshake_packets);
300            } else {
301                /*if let Content::Alert(a) = &p.record.content {
302                    if a.alert_description == AlertDescription::CloseNotify {
303                        closed = true;
304                    }
305                }*/
306
307                let raw_packet = self.process_packet(p)?;
308                raw_packets.push(raw_packet);
309            }
310        }
311
312        if !raw_packets.is_empty() {
313            let compacted_raw_packets =
314                compact_raw_packets(&raw_packets, self.maximum_transmission_unit);
315
316            for compacted_raw_packets in compacted_raw_packets {
317                self.outgoing_compacted_raw_packets
318                    .push_back(compacted_raw_packets);
319            }
320        }
321
322        Ok(())
323    }
324
325    fn process_packet(&mut self, mut p: Packet) -> Result<Vec<u8>> {
326        let epoch = p.record.record_layer_header.epoch as usize;
327        let seq = {
328            while self.state.local_sequence_number.len() <= epoch {
329                self.state.local_sequence_number.push(0);
330            }
331
332            self.state.local_sequence_number[epoch] += 1;
333            self.state.local_sequence_number[epoch] - 1
334        };
335        //debug!("{}: seq = {}", srv_cli_str(is_client), seq);
336
337        if seq > MAX_SEQUENCE_NUMBER {
338            // RFC 6347 Section 4.1.0
339            // The implementation must either abandon an association or rehandshake
340            // prior to allowing the sequence number to wrap.
341            return Err(Error::ErrSequenceNumberOverflow);
342        }
343        p.record.record_layer_header.sequence_number = seq;
344
345        // Marshal straight into the Vec: `BufWriter` would heap-allocate an
346        // 8 KiB staging buffer for every outbound record.
347        let mut raw_packet = vec![];
348        p.record.marshal(&mut raw_packet)?;
349
350        if p.should_encrypt
351            && let Some(cipher_suite) = &self.state.cipher_suite
352        {
353            raw_packet = cipher_suite.encrypt(&p.record.record_layer_header, &raw_packet)?;
354        }
355
356        Ok(raw_packet)
357    }
358
359    fn process_handshake_packet(&mut self, p: &Packet, h: &Handshake) -> Result<Vec<Vec<u8>>> {
360        let mut raw_packets = vec![];
361
362        let handshake_fragments = DTLSConn::fragment_handshake(self.maximum_transmission_unit, h)?;
363
364        let epoch = p.record.record_layer_header.epoch as usize;
365
366        while self.state.local_sequence_number.len() <= epoch {
367            self.state.local_sequence_number.push(0);
368        }
369
370        for handshake_fragment in &handshake_fragments {
371            let seq = {
372                self.state.local_sequence_number[epoch] += 1;
373                self.state.local_sequence_number[epoch] - 1
374            };
375            //debug!("seq = {}", seq);
376            if seq > MAX_SEQUENCE_NUMBER {
377                return Err(Error::ErrSequenceNumberOverflow);
378            }
379
380            let record_layer_header = RecordLayerHeader {
381                protocol_version: p.record.record_layer_header.protocol_version,
382                content_type: p.record.record_layer_header.content_type,
383                content_len: handshake_fragment.len() as u16,
384                epoch: p.record.record_layer_header.epoch,
385                sequence_number: seq,
386            };
387
388            let mut record_layer_header_bytes = vec![];
389            {
390                let mut writer = BufWriter::<&mut Vec<u8>>::new(record_layer_header_bytes.as_mut());
391                record_layer_header.marshal(&mut writer)?;
392            }
393
394            //p.record.record_layer_header = record_layer_header;
395
396            let mut raw_packet = vec![];
397            raw_packet.extend_from_slice(&record_layer_header_bytes);
398            raw_packet.extend_from_slice(handshake_fragment);
399            if p.should_encrypt
400                && let Some(cipher_suite) = &self.state.cipher_suite
401            {
402                raw_packet = cipher_suite.encrypt(&record_layer_header, &raw_packet)?;
403            }
404
405            raw_packets.push(raw_packet);
406        }
407
408        Ok(raw_packets)
409    }
410
411    fn fragment_handshake(maximum_transmission_unit: usize, h: &Handshake) -> Result<Vec<Vec<u8>>> {
412        let mut content = vec![];
413        {
414            let mut writer = BufWriter::<&mut Vec<u8>>::new(content.as_mut());
415            h.handshake_message.marshal(&mut writer)?;
416        }
417
418        let mut fragmented_handshakes = vec![];
419
420        let mut content_fragments = split_bytes(&content, maximum_transmission_unit);
421        if content_fragments.is_empty() {
422            content_fragments = vec![vec![]];
423        }
424
425        let mut offset = 0;
426        for content_fragment in &content_fragments {
427            let content_fragment_len = content_fragment.len();
428
429            let handshake_header_fragment = HandshakeHeader {
430                handshake_type: h.handshake_header.handshake_type,
431                length: h.handshake_header.length,
432                message_sequence: h.handshake_header.message_sequence,
433                fragment_offset: offset as u32,
434                fragment_length: content_fragment_len as u32,
435            };
436
437            offset += content_fragment_len;
438
439            let mut handshake_header_fragment_raw = vec![];
440            {
441                let mut writer =
442                    BufWriter::<&mut Vec<u8>>::new(handshake_header_fragment_raw.as_mut());
443                handshake_header_fragment.marshal(&mut writer)?;
444            }
445
446            let mut fragmented_handshake = vec![];
447            fragmented_handshake.extend_from_slice(&handshake_header_fragment_raw);
448            fragmented_handshake.extend_from_slice(content_fragment);
449
450            fragmented_handshakes.push(fragmented_handshake);
451        }
452
453        Ok(fragmented_handshakes)
454    }
455
456    pub(crate) fn set_handshake_completed(&mut self) {
457        self.handshake_completed = true;
458    }
459
460    pub(crate) fn is_handshake_completed(&self) -> bool {
461        self.handshake_completed
462    }
463
464    /// Feeds one received datagram into the connection.
465    ///
466    /// # Errors
467    ///
468    /// Fails if the record is malformed or fails authentication.
469    pub fn read(&mut self, buf: &[u8]) -> Result<()> {
470        // Per RFC 6347: buffer future-epoch packets only until Finished is received
471        // (i.e. until handshake completes). After that, discard them.
472        let enqueue = !self.is_handshake_completed();
473        for pkt in unpack_datagram(buf)? {
474            let (hs, alert, err) = self.handle_incoming_packet(pkt, enqueue);
475            if let Some(alert) = alert {
476                self.outgoing_packets.push_back(Packet {
477                    record: RecordLayer::new(
478                        PROTOCOL_VERSION1_2,
479                        self.state.local_epoch,
480                        Content::Alert(Alert {
481                            alert_level: alert.alert_level,
482                            alert_description: alert.alert_description,
483                        }),
484                    ),
485                    should_encrypt: self.is_handshake_completed(),
486                    reset_local_sequence_number: false,
487                });
488
489                if alert.alert_level == AlertLevel::Fatal
490                    || alert.alert_description == AlertDescription::CloseNotify
491                {
492                    return Err(Error::ErrAlertFatalOrClose);
493                }
494            }
495
496            if let Some(err) = err {
497                return Err(err);
498            }
499
500            if hs {
501                self.handshake_rx = Some(());
502            }
503        }
504
505        Ok(())
506    }
507
508    pub(crate) fn handle_incoming_queued_packets(&mut self) -> Result<bool> {
509        // Drain queued future-epoch packets once the cipher suite is initialized,
510        // which may happen before handshake_completed (e.g. Finished arrived before
511        // ChangeCipherSpec bumped remote_epoch, so Finished was queued).
512        let cipher_ready = self
513            .state
514            .cipher_suite
515            .as_ref()
516            .is_some_and(|cs| cs.is_initialized());
517        let mut is_handshake = false;
518        if cipher_ready {
519            while let Some(p) = self.incoming_encrypted_packets.pop_front() {
520                let (hs, alert, err) = self.handle_incoming_packet(p, false); // don't re-enqueue
521                if hs {
522                    is_handshake = true;
523                    self.handshake_rx = Some(());
524                }
525                if let Some(alert) = alert {
526                    self.outgoing_packets.push_back(Packet {
527                        record: RecordLayer::new(
528                            PROTOCOL_VERSION1_2,
529                            self.state.local_epoch,
530                            Content::Alert(Alert {
531                                alert_level: alert.alert_level,
532                                alert_description: alert.alert_description,
533                            }),
534                        ),
535                        should_encrypt: self.is_handshake_completed(),
536                        reset_local_sequence_number: false,
537                    });
538
539                    if alert.alert_level == AlertLevel::Fatal
540                        || alert.alert_description == AlertDescription::CloseNotify
541                    {
542                        return Err(Error::ErrAlertFatalOrClose);
543                    }
544                }
545
546                if let Some(err) = err {
547                    return Err(err);
548                }
549            }
550        }
551
552        Ok(is_handshake)
553    }
554
555    fn handle_incoming_packet(
556        &mut self,
557        mut pkt: Vec<u8>,
558        enqueue: bool,
559    ) -> (bool, Option<Alert>, Option<Error>) {
560        // Parse the 13-byte header from the slice directly: `BufReader` would
561        // heap-allocate an 8 KiB buffer for every inbound record.
562        let mut reader = pkt.as_slice();
563        let h = match RecordLayerHeader::unmarshal(&mut reader) {
564            Ok(h) => h,
565            Err(err) => {
566                // Decode error must be silently discarded
567                // [RFC6347 Section-4.1.2.7]
568                debug!(
569                    "{}: discarded broken packet: {}",
570                    srv_cli_str(self.is_client),
571                    err
572                );
573                return (false, None, None);
574            }
575        };
576
577        // Validate epoch
578        let epoch = self.state.remote_epoch;
579        if h.epoch > epoch {
580            if h.epoch > epoch + 1 {
581                debug!(
582                    "{}: discarded future packet (epoch: {}, seq: {})",
583                    srv_cli_str(self.is_client),
584                    h.epoch,
585                    h.sequence_number,
586                );
587                return (false, None, None);
588            }
589            if enqueue {
590                debug!(
591                    "{}: received packet of next epoch, queuing packet",
592                    srv_cli_str(self.is_client)
593                );
594                self.incoming_encrypted_packets.push_back(pkt);
595            }
596            return (false, None, None);
597        }
598
599        // Anti-replay protection
600        while self.replay_detector.len() <= h.epoch as usize {
601            self.replay_detector
602                .push(Box::new(SlidingWindowDetector::new(
603                    self.replay_protection_window,
604                    MAX_SEQUENCE_NUMBER,
605                )));
606        }
607
608        let ok = self.replay_detector[h.epoch as usize].check(h.sequence_number);
609        if !ok {
610            debug!(
611                "{}: discarded duplicated packet (epoch: {}, seq: {})",
612                srv_cli_str(self.is_client),
613                h.epoch,
614                h.sequence_number,
615            );
616            return (false, None, None);
617        }
618
619        // Decrypt
620        if h.epoch != 0 {
621            let invalid_cipher_suite = {
622                if let Some(cipher_suite) = &self.state.cipher_suite {
623                    !cipher_suite.is_initialized()
624                } else {
625                    true
626                }
627            };
628            if invalid_cipher_suite {
629                if enqueue {
630                    debug!(
631                        "{}: handshake not finished, queuing packet",
632                        srv_cli_str(self.is_client)
633                    );
634                    self.incoming_encrypted_packets.push_back(pkt);
635                }
636                return (false, None, None);
637            }
638
639            if let Some(cipher_suite) = &self.state.cipher_suite {
640                pkt = match cipher_suite.decrypt(&pkt) {
641                    Ok(pkt) => pkt,
642                    Err(err) => {
643                        debug!("{}: decrypt failed: {}", srv_cli_str(self.is_client), err);
644
645                        // If we get an error for PSK we need to return an error.
646                        if cipher_suite.is_psk() {
647                            return (
648                                false,
649                                Some(Alert {
650                                    alert_level: AlertLevel::Fatal,
651                                    alert_description: AlertDescription::UnknownPskIdentity,
652                                }),
653                                None,
654                            );
655                        } else {
656                            return (false, None, None);
657                        }
658                    }
659                };
660            }
661        }
662
663        let is_handshake = match self.fragment_buffer.push(&pkt) {
664            Ok(is_handshake) => is_handshake,
665            Err(err) => {
666                // Decode error must be silently discarded
667                // [RFC6347 Section-4.1.2.7]
668                debug!(
669                    "{}: defragment failed: {}",
670                    srv_cli_str(self.is_client),
671                    err
672                );
673                return (false, None, None);
674            }
675        };
676        if is_handshake {
677            self.replay_detector[h.epoch as usize].accept();
678            while let Ok((out, epoch)) = self.fragment_buffer.pop() {
679                //log::debug!("Extension Debug: out.len()={}", out.len());
680                let mut reader = out.as_slice();
681                let raw_handshake = match Handshake::unmarshal(&mut reader) {
682                    Ok(rh) => {
683                        debug!(
684                            "Recv [handshake:{}] -> {} (epoch: {}, seq: {})",
685                            srv_cli_str(self.is_client),
686                            rh.handshake_header.handshake_type,
687                            h.epoch,
688                            rh.handshake_header.message_sequence
689                        );
690                        rh
691                    }
692                    Err(err) => {
693                        debug!(
694                            "{}: handshake parse failed: {}",
695                            srv_cli_str(self.is_client),
696                            err
697                        );
698                        continue;
699                    }
700                };
701
702                self.cache.push(
703                    out,
704                    epoch,
705                    raw_handshake.handshake_header.message_sequence,
706                    raw_handshake.handshake_header.handshake_type,
707                    !self.is_client,
708                );
709            }
710
711            return (true, None, None);
712        }
713
714        let mut reader = pkt.as_slice();
715        let r = match RecordLayer::unmarshal(&mut reader) {
716            Ok(r) => r,
717            Err(err) => {
718                return (
719                    false,
720                    Some(Alert {
721                        alert_level: AlertLevel::Fatal,
722                        alert_description: AlertDescription::DecodeError,
723                    }),
724                    Some(err),
725                );
726            }
727        };
728
729        match r.content {
730            Content::Alert(mut a) => {
731                debug!("{}: <- {}", srv_cli_str(self.is_client), a);
732                if a.alert_description == AlertDescription::CloseNotify {
733                    // Respond with a close_notify [RFC5246 Section 7.2.1]
734                    a = Alert {
735                        alert_level: AlertLevel::Warning,
736                        alert_description: AlertDescription::CloseNotify,
737                    };
738                }
739                self.replay_detector[h.epoch as usize].accept();
740                return (
741                    false,
742                    Some(a),
743                    Some(Error::Other(format!("Error of Alert {a}"))),
744                );
745            }
746            Content::ChangeCipherSpec(_) => {
747                let invalid_cipher_suite = {
748                    if let Some(cipher_suite) = &self.state.cipher_suite {
749                        !cipher_suite.is_initialized()
750                    } else {
751                        true
752                    }
753                };
754
755                if invalid_cipher_suite {
756                    if enqueue {
757                        debug!(
758                            "{}: CipherSuite not initialized, queuing packet",
759                            srv_cli_str(self.is_client)
760                        );
761                        self.incoming_encrypted_packets.push_back(pkt);
762                    }
763                    return (false, None, None);
764                }
765
766                let new_remote_epoch = h.epoch + 1;
767                debug!(
768                    "{}: <- ChangeCipherSpec (epoch: {})",
769                    srv_cli_str(self.is_client),
770                    new_remote_epoch
771                );
772
773                if epoch + 1 == new_remote_epoch {
774                    self.state.remote_epoch = new_remote_epoch;
775                    self.replay_detector[h.epoch as usize].accept();
776                }
777            }
778            Content::ApplicationData(a) => {
779                if h.epoch == 0 {
780                    warn!(
781                        "{}: <- Unexpected ApplicationData Message",
782                        srv_cli_str(self.is_client),
783                    );
784                    return (
785                        false,
786                        Some(Alert {
787                            alert_level: AlertLevel::Fatal,
788                            alert_description: AlertDescription::UnexpectedMessage,
789                        }),
790                        Some(Error::ErrApplicationDataEpochZero),
791                    );
792                }
793
794                self.replay_detector[h.epoch as usize].accept();
795
796                self.incoming_decrypted_packets.push_back(a.data);
797            }
798            _ => {
799                warn!(
800                    "{}: <- Unexpected Handshake Message",
801                    srv_cli_str(self.is_client),
802                );
803                return (
804                    false,
805                    Some(Alert {
806                        alert_level: AlertLevel::Fatal,
807                        alert_description: AlertDescription::UnexpectedMessage,
808                    }),
809                    Some(Error::ErrUnhandledContextType),
810                );
811            }
812        };
813
814        (false, None, None)
815    }
816
817    fn is_connection_closed(&self) -> bool {
818        self.closed
819    }
820
821    pub(crate) fn set_local_epoch(&mut self, epoch: u16) {
822        self.state.local_epoch = epoch;
823    }
824
825    pub(crate) fn get_local_epoch(&self) -> u16 {
826        self.state.local_epoch
827    }
828}
829
830fn compact_raw_packets(raw_packets: &[Vec<u8>], maximum_transmission_unit: usize) -> Vec<BytesMut> {
831    let mut combined_raw_packets = vec![];
832    let mut current_combined_raw_packet = BytesMut::new();
833
834    for raw_packet in raw_packets {
835        if !current_combined_raw_packet.is_empty()
836            && current_combined_raw_packet.len() + raw_packet.len() >= maximum_transmission_unit
837        {
838            combined_raw_packets.push(current_combined_raw_packet);
839            current_combined_raw_packet = BytesMut::new();
840        }
841        current_combined_raw_packet.extend_from_slice(raw_packet);
842    }
843
844    if !current_combined_raw_packet.is_empty() {
845        combined_raw_packets.push(current_combined_raw_packet);
846    }
847
848    combined_raw_packets
849}
850
851fn split_bytes(bytes: &[u8], split_len: usize) -> Vec<Vec<u8>> {
852    let mut splits = vec![];
853    let num_bytes = bytes.len();
854    for i in (0..num_bytes).step_by(split_len) {
855        let mut j = i + split_len;
856        if j > num_bytes {
857            j = num_bytes;
858        }
859
860        splits.push(bytes[i..j].to_vec());
861    }
862
863    splits
864}