webrtc_unreliable/
client.rs

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
use std::{
    collections::VecDeque,
    error::Error,
    fmt,
    io::{Error as IoError, ErrorKind as IoErrorKind, Read, Write},
    iter::Iterator,
    mem,
    net::SocketAddr,
    time::{Duration, Instant},
};

use openssl::{
    error::ErrorStack as OpenSslErrorStack,
    ssl::{
        Error as SslError, ErrorCode, HandshakeError, MidHandshakeSslStream, ShutdownResult,
        SslAcceptor, SslStream,
    },
};
use rand::{thread_rng, Rng};

use crate::buffer_pool::{BufferPool, OwnedBuffer};
use crate::sctp::{
    read_sctp_packet, write_sctp_packet, SctpChunk, SctpPacket, SctpWriteError,
    SCTP_FLAG_BEGIN_FRAGMENT, SCTP_FLAG_COMPLETE_UNRELIABLE, SCTP_FLAG_END_FRAGMENT,
};

/// Heartbeat packets will be generated at a maximum of this rate (if the connection is otherwise
/// idle).
pub const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(3);

// Maximum theoretical UDP payload size
pub const MAX_UDP_PAYLOAD_SIZE: usize = 65507;

// Derived through experimentation, any larger and openssl reports 'dtls message too big'.
pub const MAX_DTLS_MESSAGE_SIZE: usize = 16384;

pub const MAX_SCTP_PACKET_SIZE: usize = MAX_DTLS_MESSAGE_SIZE;

// The overhead of sending a single SCTP packet with a single data message.
pub const SCTP_MESSAGE_OVERHEAD: usize = 28;

/// Maximum supported theoretical size of a single WebRTC message, based on DTLS and SCTP packet
/// size limits.
///
/// WebRTC makes no attempt at packet fragmentation and re-assembly or to support fragmented
/// received messages, all sent and received unreliable messages must fit into a single SCTP packet.
/// As such, this maximum size is almost certainly too large for browsers to actually support.
/// Start with a much lower MTU (around 1200) and test it.
pub const MAX_MESSAGE_LEN: usize = MAX_SCTP_PACKET_SIZE - SCTP_MESSAGE_OVERHEAD;

#[derive(Debug)]
pub enum ClientError {
    TlsError(SslError),
    OpenSslError(OpenSslErrorStack),
    NotConnected,
    NotEstablished,
    IncompletePacketRead,
    IncompletePacketWrite,
}

impl fmt::Display for ClientError {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match self {
            ClientError::TlsError(err) => fmt::Display::fmt(err, f),
            ClientError::OpenSslError(err) => fmt::Display::fmt(err, f),
            ClientError::NotConnected => write!(f, "client is not connected"),
            ClientError::NotEstablished => {
                write!(f, "client does not have an established WebRTC data channel")
            }
            ClientError::IncompletePacketRead => {
                write!(f, "WebRTC connection packet not completely read")
            }
            ClientError::IncompletePacketWrite => {
                write!(f, "WebRTC connection packet not completely written")
            }
        }
    }
}

impl Error for ClientError {}

#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum MessageType {
    Text,
    Binary,
}

pub struct Client {
    buffer_pool: BufferPool,
    remote_addr: SocketAddr,
    ssl_state: ClientSslState,
    client_state: ClientState,
}

impl Client {
    pub fn new(
        ssl_acceptor: &SslAcceptor,
        buffer_pool: BufferPool,
        remote_addr: SocketAddr,
    ) -> Result<Client, OpenSslErrorStack> {
        match ssl_acceptor.accept(ClientSslPackets {
            buffer_pool: buffer_pool.clone(),
            incoming_udp: VecDeque::new(),
            outgoing_udp: VecDeque::new(),
        }) {
            Ok(_) => unreachable!("handshake cannot finish with no incoming packets"),
            Err(HandshakeError::SetupFailure(err)) => return Err(err),
            Err(HandshakeError::Failure(_)) => {
                unreachable!("handshake cannot fail before starting")
            }
            Err(HandshakeError::WouldBlock(mid_handshake)) => Ok(Client {
                buffer_pool,
                remote_addr,
                ssl_state: ClientSslState::Handshake(mid_handshake),
                client_state: ClientState {
                    last_activity: Instant::now(),
                    last_sent: Instant::now(),
                    received_messages: Vec::new(),
                    sctp_state: SctpState::Shutdown,
                    sctp_local_port: 0,
                    sctp_remote_port: 0,
                    sctp_local_verification_tag: 0,
                    sctp_remote_verification_tag: 0,
                    sctp_local_tsn: 0,
                    sctp_remote_tsn: 0,
                },
            }),
        }
    }

    /// DTLS and SCTP states are established, and RTC messages may be sent
    pub fn is_established(&self) -> bool {
        match (&self.ssl_state, self.client_state.sctp_state) {
            (ClientSslState::Established(_), SctpState::Established) => true,
            _ => false,
        }
    }

    /// Time of last activity that indicates a working connection
    pub fn last_activity(&self) -> Instant {
        self.client_state.last_activity
    }

    /// Request SCTP and DTLS shutdown, connection immediately becomes un-established
    pub fn start_shutdown(&mut self) -> Result<bool, ClientError> {
        let started;
        self.ssl_state = match mem::replace(&mut self.ssl_state, ClientSslState::Shutdown) {
            ClientSslState::Established(mut ssl_stream) => {
                started = true;
                if self.client_state.sctp_state != SctpState::Shutdown {
                    // TODO: For now, we just do an immediate one-sided SCTP abort
                    send_sctp_packet(
                        &self.buffer_pool,
                        &mut ssl_stream,
                        SctpPacket {
                            source_port: self.client_state.sctp_local_port,
                            dest_port: self.client_state.sctp_remote_port,
                            verification_tag: self.client_state.sctp_remote_verification_tag,
                            chunks: &[SctpChunk::Abort],
                        },
                    )?;
                    self.client_state.last_sent = Instant::now();
                    self.client_state.sctp_state = SctpState::Shutdown;
                }
                match ssl_stream.shutdown() {
                    Err(err) => {
                        if err.code() == ErrorCode::ZERO_RETURN {
                            ClientSslState::Shutdown
                        } else {
                            return Err(ssl_err_to_client_err(err));
                        }
                    }
                    Ok(res) => ClientSslState::ShuttingDown(ssl_stream, res),
                }
            }
            prev_state => {
                started = false;
                prev_state
            }
        };
        Ok(started)
    }

    /// Returns true if the shutdown process has been started or has already finished.
    pub fn shutdown_started(&self) -> bool {
        match &self.ssl_state {
            ClientSslState::ShuttingDown(_, _) | ClientSslState::Shutdown => true,
            _ => false,
        }
    }

    /// Connection has finished shutting down.
    pub fn is_shutdown(&self) -> bool {
        match &self.ssl_state {
            ClientSslState::ShuttingDown(_, ShutdownResult::Received)
            | ClientSslState::Shutdown => true,
            _ => false,
        }
    }

    /// Generate any periodic packets, currently only heartbeat packets.
    pub fn generate_periodic(&mut self) -> Result<(), ClientError> {
        // We send heartbeat packets if the last sent packet was more than HEARTBEAT_INTERVAL ago
        if self.client_state.last_sent.elapsed() > HEARTBEAT_INTERVAL {
            match &mut self.ssl_state {
                ClientSslState::Established(ssl_stream) => {
                    if self.client_state.sctp_state == SctpState::Established {
                        send_sctp_packet(
                            &self.buffer_pool,
                            ssl_stream,
                            SctpPacket {
                                source_port: self.client_state.sctp_local_port,
                                dest_port: self.client_state.sctp_remote_port,
                                verification_tag: self.client_state.sctp_remote_verification_tag,
                                chunks: &[SctpChunk::Heartbeat {
                                    heartbeat_info: Some(SCTP_HEARTBEAT),
                                }],
                            },
                        )?;
                        self.client_state.last_sent = Instant::now();
                    }
                }
                _ => {}
            }
        }
        Ok(())
    }

    /// Pushes an available UDP packet.  Will error if called when the client is currently in the
    /// shutdown state.
    pub fn receive_incoming_packet(&mut self, udp_packet: OwnedBuffer) -> Result<(), ClientError> {
        self.ssl_state = match mem::replace(&mut self.ssl_state, ClientSslState::Shutdown) {
            ClientSslState::Handshake(mut mid_handshake) => {
                mid_handshake.get_mut().incoming_udp.push_back(udp_packet);
                match mid_handshake.handshake() {
                    Ok(ssl_stream) => {
                        log::info!("DTLS handshake finished for remote {}", self.remote_addr);
                        ClientSslState::Established(ssl_stream)
                    }
                    Err(handshake_error) => match handshake_error {
                        HandshakeError::SetupFailure(err) => {
                            return Err(ClientError::OpenSslError(err));
                        }
                        HandshakeError::Failure(mid_handshake) => {
                            log::warn!(
                                "SSL handshake failure with remote {}: {}",
                                self.remote_addr,
                                mid_handshake.error()
                            );
                            ClientSslState::Handshake(mid_handshake)
                        }
                        HandshakeError::WouldBlock(mid_handshake) => {
                            ClientSslState::Handshake(mid_handshake)
                        }
                    },
                }
            }
            ClientSslState::Established(mut ssl_stream) => {
                ssl_stream.get_mut().incoming_udp.push_back(udp_packet);
                ClientSslState::Established(ssl_stream)
            }
            ClientSslState::ShuttingDown(mut ssl_stream, shutdown_result) => {
                ssl_stream.get_mut().incoming_udp.push_back(udp_packet);
                match ssl_stream.shutdown() {
                    Err(err) => {
                        if err.code() == ErrorCode::WANT_READ {
                            ClientSslState::ShuttingDown(ssl_stream, shutdown_result)
                        } else if err.code() == ErrorCode::ZERO_RETURN {
                            ClientSslState::Shutdown
                        } else {
                            return Err(ssl_err_to_client_err(err));
                        }
                    }
                    Ok(res) => ClientSslState::ShuttingDown(ssl_stream, res),
                }
            }
            ClientSslState::Shutdown => ClientSslState::Shutdown,
        };

        while let ClientSslState::Established(ssl_stream) = &mut self.ssl_state {
            let mut ssl_buffer = self.buffer_pool.acquire();
            ssl_buffer.resize(MAX_SCTP_PACKET_SIZE, 0);
            match ssl_stream.ssl_read(&mut ssl_buffer) {
                Ok(size) => {
                    let mut sctp_chunks = [SctpChunk::Abort; SCTP_MAX_CHUNKS];
                    match read_sctp_packet(&ssl_buffer[0..size], false, &mut sctp_chunks) {
                        Ok(sctp_packet) => {
                            if !receive_sctp_packet(
                                &self.buffer_pool,
                                ssl_stream,
                                &mut self.client_state,
                                &sctp_packet,
                            )? {
                                drop(ssl_buffer);
                                self.start_shutdown()?;
                            }
                        }
                        Err(err) => {
                            log::debug!("sctp read error on packet received over DTLS: {}", err);
                        }
                    }
                }
                Err(err) => {
                    if err.code() == ErrorCode::WANT_READ {
                        break;
                    } else if err.code() == ErrorCode::ZERO_RETURN {
                        log::info!("DTLS received close notify");
                        drop(ssl_buffer);
                        self.start_shutdown()?;
                    } else {
                        return Err(ssl_err_to_client_err(err));
                    }
                }
            }
        }

        Ok(())
    }

    pub fn take_outgoing_packets<'a>(&'a mut self) -> impl Iterator<Item = OwnedBuffer> + 'a {
        (match &mut self.ssl_state {
            ClientSslState::Handshake(mid_handshake) => {
                Some(mid_handshake.get_mut().outgoing_udp.drain(..))
            }
            ClientSslState::Established(ssl_stream)
            | ClientSslState::ShuttingDown(ssl_stream, _) => {
                Some(ssl_stream.get_mut().outgoing_udp.drain(..))
            }
            ClientSslState::Shutdown => None,
        })
        .into_iter()
        .flatten()
    }

    pub fn send_message(
        &mut self,
        message_type: MessageType,
        message: &[u8],
    ) -> Result<(), ClientError> {
        let ssl_stream = match &mut self.ssl_state {
            ClientSslState::Established(ssl_stream) => ssl_stream,
            _ => {
                return Err(ClientError::NotConnected);
            }
        };

        if self.client_state.sctp_state != SctpState::Established {
            return Err(ClientError::NotEstablished);
        }

        let proto_id = if message_type == MessageType::Text {
            DATA_CHANNEL_PROTO_STRING
        } else {
            DATA_CHANNEL_PROTO_BINARY
        };

        send_sctp_packet(
            &self.buffer_pool,
            ssl_stream,
            SctpPacket {
                source_port: self.client_state.sctp_local_port,
                dest_port: self.client_state.sctp_remote_port,
                verification_tag: self.client_state.sctp_remote_verification_tag,
                chunks: &[SctpChunk::Data {
                    chunk_flags: SCTP_FLAG_COMPLETE_UNRELIABLE,
                    tsn: self.client_state.sctp_local_tsn,
                    stream_id: 0,
                    stream_seq: 0,
                    proto_id,
                    user_data: message,
                }],
            },
        )?;
        self.client_state.sctp_local_tsn = self.client_state.sctp_local_tsn.wrapping_add(1);

        Ok(())
    }

    pub fn receive_messages<'a>(
        &'a mut self,
    ) -> impl Iterator<Item = (MessageType, OwnedBuffer)> + 'a {
        self.client_state.received_messages.drain(..)
    }
}

pub struct ClientState {
    last_activity: Instant,
    last_sent: Instant,

    received_messages: Vec<(MessageType, OwnedBuffer)>,

    sctp_state: SctpState,

    sctp_local_port: u16,
    sctp_remote_port: u16,

    sctp_local_verification_tag: u32,
    sctp_remote_verification_tag: u32,

    sctp_local_tsn: u32,
    sctp_remote_tsn: u32,
}

enum ClientSslState {
    Handshake(MidHandshakeSslStream<ClientSslPackets>),
    Established(SslStream<ClientSslPackets>),
    ShuttingDown(SslStream<ClientSslPackets>, ShutdownResult),
    Shutdown,
}

#[derive(Debug)]
struct ClientSslPackets {
    buffer_pool: BufferPool,
    incoming_udp: VecDeque<OwnedBuffer>,
    outgoing_udp: VecDeque<OwnedBuffer>,
}

impl Read for ClientSslPackets {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, IoError> {
        if let Some(next_packet) = self.incoming_udp.pop_front() {
            let next_packet = self.buffer_pool.adopt(next_packet);
            if next_packet.len() > buf.len() {
                return Err(IoError::new(
                    IoErrorKind::Other,
                    ClientError::IncompletePacketRead,
                ));
            }
            buf[0..next_packet.len()].copy_from_slice(&next_packet);
            Ok(next_packet.len())
        } else {
            Err(IoErrorKind::WouldBlock.into())
        }
    }
}

impl Write for ClientSslPackets {
    fn write(&mut self, buf: &[u8]) -> Result<usize, IoError> {
        let mut buffer = self.buffer_pool.acquire();
        buffer.extend_from_slice(buf);
        self.outgoing_udp.push_back(buffer.into_owned());
        Ok(buf.len())
    }

    fn flush(&mut self) -> Result<(), IoError> {
        Ok(())
    }
}

const SCTP_COOKIE: &[u8] = b"WEBRTC-UNRELIABLE-COOKIE";
const SCTP_HEARTBEAT: &[u8] = b"WEBRTC-UNRELIABLE-HEARTBEAT";
const SCTP_MAX_CHUNKS: usize = 16;
const SCTP_BUFFER_SIZE: u32 = 0x40000;

const DATA_CHANNEL_PROTO_CONTROL: u32 = 50;
const DATA_CHANNEL_PROTO_STRING: u32 = 51;
const DATA_CHANNEL_PROTO_BINARY: u32 = 53;

const DATA_CHANNEL_MESSAGE_ACK: u8 = 2;
const DATA_CHANNEL_MESSAGE_OPEN: u8 = 3;

#[derive(Debug, Eq, PartialEq, Copy, Clone)]
enum SctpState {
    Shutdown,
    InitAck,
    Established,
}

fn ssl_err_to_client_err(err: SslError) -> ClientError {
    if let Some(io_err) = err.io_error() {
        if let Some(inner) = io_err.get_ref() {
            if inner.is::<ClientError>() {
                return *err
                    .into_io_error()
                    .unwrap()
                    .into_inner()
                    .unwrap()
                    .downcast()
                    .unwrap();
            }
        }
    }

    ClientError::TlsError(err)
}

fn max_tsn(a: u32, b: u32) -> u32 {
    if a > b {
        if a - b < (1 << 31) {
            a
        } else {
            b
        }
    } else {
        if b - a < (1 << 31) {
            b
        } else {
            a
        }
    }
}

fn send_sctp_packet(
    buffer_pool: &BufferPool,
    ssl_stream: &mut SslStream<ClientSslPackets>,
    sctp_packet: SctpPacket,
) -> Result<(), ClientError> {
    let mut sctp_buffer = buffer_pool.acquire();
    sctp_buffer.resize(MAX_SCTP_PACKET_SIZE, 0);

    let packet_len = match write_sctp_packet(&mut sctp_buffer, sctp_packet) {
        Ok(len) => len,
        Err(SctpWriteError::BufferSize) => {
            return Err(ClientError::IncompletePacketWrite);
        }
        Err(err) => panic!("error writing SCTP packet: {}", err),
    };

    assert_eq!(
        ssl_stream
            .ssl_write(&sctp_buffer[0..packet_len])
            .map_err(ssl_err_to_client_err)?,
        packet_len
    );

    Ok(())
}

fn receive_sctp_packet(
    buffer_pool: &BufferPool,
    ssl_stream: &mut SslStream<ClientSslPackets>,
    client_state: &mut ClientState,
    sctp_packet: &SctpPacket,
) -> Result<bool, ClientError> {
    for chunk in sctp_packet.chunks {
        match *chunk {
            SctpChunk::Init {
                initiate_tag,
                window_credit: _,
                num_outbound_streams,
                num_inbound_streams,
                initial_tsn,
                support_unreliable,
            } => {
                if !support_unreliable {
                    log::warn!("peer does not support selective unreliability, abort connection");
                    client_state.sctp_state = SctpState::Shutdown;
                    return Ok(false);
                }

                let mut rng = thread_rng();

                client_state.sctp_local_port = sctp_packet.dest_port;
                client_state.sctp_remote_port = sctp_packet.source_port;

                client_state.sctp_local_verification_tag = rng.gen();
                client_state.sctp_remote_verification_tag = initiate_tag;

                client_state.sctp_local_tsn = rng.gen();
                client_state.sctp_remote_tsn = initial_tsn;

                send_sctp_packet(
                    &buffer_pool,
                    ssl_stream,
                    SctpPacket {
                        source_port: client_state.sctp_local_port,
                        dest_port: client_state.sctp_remote_port,
                        verification_tag: client_state.sctp_remote_verification_tag,
                        chunks: &[SctpChunk::InitAck {
                            initiate_tag: client_state.sctp_local_verification_tag,
                            window_credit: SCTP_BUFFER_SIZE,
                            num_outbound_streams: num_outbound_streams,
                            num_inbound_streams: num_inbound_streams,
                            initial_tsn: client_state.sctp_local_tsn,
                            state_cookie: SCTP_COOKIE,
                        }],
                    },
                )?;

                client_state.sctp_state = SctpState::InitAck;
                client_state.last_activity = Instant::now();
                client_state.last_sent = Instant::now();
            }
            SctpChunk::CookieEcho { state_cookie } => {
                if state_cookie == SCTP_COOKIE && client_state.sctp_state != SctpState::Shutdown {
                    send_sctp_packet(
                        &buffer_pool,
                        ssl_stream,
                        SctpPacket {
                            source_port: client_state.sctp_local_port,
                            dest_port: client_state.sctp_remote_port,
                            verification_tag: client_state.sctp_remote_verification_tag,
                            chunks: &[SctpChunk::CookieAck],
                        },
                    )?;
                    client_state.last_sent = Instant::now();

                    if client_state.sctp_state == SctpState::InitAck {
                        client_state.sctp_state = SctpState::Established;
                        client_state.last_activity = Instant::now();
                    }
                }
            }
            SctpChunk::Data {
                chunk_flags,
                tsn,
                stream_id,
                stream_seq: _,
                proto_id,
                user_data,
            } => {
                if chunk_flags & SCTP_FLAG_BEGIN_FRAGMENT == 0
                    || chunk_flags & SCTP_FLAG_END_FRAGMENT == 0
                {
                    log::debug!("received fragmented SCTP packet, dropping");
                } else {
                    client_state.sctp_remote_tsn = max_tsn(client_state.sctp_remote_tsn, tsn);

                    if proto_id == DATA_CHANNEL_PROTO_CONTROL {
                        if !user_data.is_empty() {
                            if user_data[0] == DATA_CHANNEL_MESSAGE_OPEN {
                                send_sctp_packet(
                                    &buffer_pool,
                                    ssl_stream,
                                    SctpPacket {
                                        source_port: client_state.sctp_local_port,
                                        dest_port: client_state.sctp_remote_port,
                                        verification_tag: client_state.sctp_remote_verification_tag,
                                        chunks: &[SctpChunk::Data {
                                            chunk_flags: SCTP_FLAG_COMPLETE_UNRELIABLE,
                                            tsn: client_state.sctp_local_tsn,
                                            stream_id,
                                            stream_seq: 0,
                                            proto_id: DATA_CHANNEL_PROTO_CONTROL,
                                            user_data: &[DATA_CHANNEL_MESSAGE_ACK],
                                        }],
                                    },
                                )?;
                                client_state.sctp_local_tsn =
                                    client_state.sctp_local_tsn.wrapping_add(1);
                            }
                        }
                    } else if proto_id == DATA_CHANNEL_PROTO_STRING {
                        let mut msg_buffer = buffer_pool.acquire();
                        msg_buffer.extend(user_data);
                        client_state
                            .received_messages
                            .push((MessageType::Text, msg_buffer.into_owned()));
                    } else if proto_id == DATA_CHANNEL_PROTO_BINARY {
                        let mut msg_buffer = buffer_pool.acquire();
                        msg_buffer.extend(user_data);
                        client_state
                            .received_messages
                            .push((MessageType::Binary, msg_buffer.into_owned()));
                    }

                    send_sctp_packet(
                        &buffer_pool,
                        ssl_stream,
                        SctpPacket {
                            source_port: client_state.sctp_local_port,
                            dest_port: client_state.sctp_remote_port,
                            verification_tag: client_state.sctp_remote_verification_tag,
                            chunks: &[SctpChunk::SAck {
                                cumulative_tsn_ack: client_state.sctp_remote_tsn,
                                adv_recv_window: SCTP_BUFFER_SIZE,
                                num_gap_ack_blocks: 0,
                                num_dup_tsn: 0,
                            }],
                        },
                    )?;

                    client_state.last_activity = Instant::now();
                    client_state.last_sent = Instant::now();
                }
            }
            SctpChunk::Heartbeat { heartbeat_info } => {
                send_sctp_packet(
                    &buffer_pool,
                    ssl_stream,
                    SctpPacket {
                        source_port: client_state.sctp_local_port,
                        dest_port: client_state.sctp_remote_port,
                        verification_tag: client_state.sctp_remote_verification_tag,
                        chunks: &[SctpChunk::HeartbeatAck { heartbeat_info }],
                    },
                )?;
                client_state.last_activity = Instant::now();
                client_state.last_sent = Instant::now();
            }
            SctpChunk::HeartbeatAck { .. } => {
                client_state.last_activity = Instant::now();
            }
            SctpChunk::SAck {
                cumulative_tsn_ack: _,
                adv_recv_window: _,
                num_gap_ack_blocks,
                num_dup_tsn: _,
            } => {
                if num_gap_ack_blocks > 0 {
                    send_sctp_packet(
                        &buffer_pool,
                        ssl_stream,
                        SctpPacket {
                            source_port: client_state.sctp_local_port,
                            dest_port: client_state.sctp_remote_port,
                            verification_tag: client_state.sctp_remote_verification_tag,
                            chunks: &[SctpChunk::ForwardTsn {
                                new_cumulative_tsn: client_state.sctp_local_tsn,
                            }],
                        },
                    )?;
                    client_state.last_sent = Instant::now();
                }
                client_state.last_activity = Instant::now();
            }
            SctpChunk::Shutdown { .. } => {
                send_sctp_packet(
                    &buffer_pool,
                    ssl_stream,
                    SctpPacket {
                        source_port: client_state.sctp_local_port,
                        dest_port: client_state.sctp_remote_port,
                        verification_tag: client_state.sctp_remote_verification_tag,
                        chunks: &[SctpChunk::ShutdownAck],
                    },
                )?;
            }
            SctpChunk::ShutdownAck { .. } | SctpChunk::Abort => {
                client_state.sctp_state = SctpState::Shutdown;
                return Ok(false);
            }
            SctpChunk::ForwardTsn { new_cumulative_tsn } => {
                client_state.sctp_remote_tsn = new_cumulative_tsn;
            }
            SctpChunk::InitAck { .. } | SctpChunk::CookieAck => {}
            SctpChunk::Error {
                first_param_type,
                first_param_data,
            } => {
                log::warn!(
                    "SCTP error chunk received: {} {:?}",
                    first_param_type,
                    first_param_data
                );
            }
            chunk => log::debug!("unhandled SCTP chunk {:?}", chunk),
        }
    }

    Ok(true)
}