Skip to main content

rtci_sctp/chunk/
mod.rs

1#[cfg(test)]
2mod chunk_test;
3
4pub(crate) mod chunk_abort;
5pub(crate) mod chunk_cookie_ack;
6pub(crate) mod chunk_cookie_echo;
7pub(crate) mod chunk_error;
8pub(crate) mod chunk_forward_tsn;
9pub(crate) mod chunk_header;
10pub(crate) mod chunk_heartbeat;
11pub(crate) mod chunk_heartbeat_ack;
12pub(crate) mod chunk_i_forward_tsn;
13pub(crate) mod chunk_init;
14pub(crate) mod chunk_padding;
15pub mod chunk_payload_data;
16pub(crate) mod chunk_reconfig;
17pub(crate) mod chunk_selective_ack;
18pub(crate) mod chunk_shutdown;
19pub(crate) mod chunk_shutdown_ack;
20pub(crate) mod chunk_shutdown_complete;
21pub(crate) mod chunk_type;
22pub(crate) mod chunk_unknown;
23
24use crate::util::get_padding_size;
25use chunk_header::*;
26use shared::error::{Error, Result};
27
28use bytes::{Buf, BufMut, Bytes, BytesMut};
29use std::marker::Sized;
30use std::{any::Any, fmt};
31
32pub(crate) trait Chunk: fmt::Display + fmt::Debug + Send + Sync {
33    fn header(&self) -> ChunkHeader;
34    fn unmarshal(raw: &Bytes) -> Result<Self>
35    where
36        Self: Sized;
37    fn marshal_to(&self, buf: &mut BytesMut) -> Result<usize>;
38    fn check(&self) -> Result<()>;
39    fn value_length(&self) -> usize;
40    fn as_any(&self) -> &dyn Any;
41
42    fn marshal(&self) -> Result<Bytes> {
43        let capacity = CHUNK_HEADER_SIZE + self.value_length();
44        let mut buf = BytesMut::with_capacity(capacity);
45        self.marshal_to(&mut buf)?;
46        Ok(buf.freeze())
47    }
48}
49
50/// ErrorCauseCode is a cause code that appears in either a ERROR or ABORT chunk
51#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
52pub struct ErrorCauseCode(pub(crate) u16);
53
54pub(crate) const INVALID_STREAM_IDENTIFIER: ErrorCauseCode = ErrorCauseCode(1);
55pub(crate) const MISSING_MANDATORY_PARAMETER: ErrorCauseCode = ErrorCauseCode(2);
56pub(crate) const STALE_COOKIE_ERROR: ErrorCauseCode = ErrorCauseCode(3);
57pub(crate) const OUT_OF_RESOURCE: ErrorCauseCode = ErrorCauseCode(4);
58pub(crate) const UNRESOLVABLE_ADDRESS: ErrorCauseCode = ErrorCauseCode(5);
59pub(crate) const UNRECOGNIZED_CHUNK_TYPE: ErrorCauseCode = ErrorCauseCode(6);
60pub(crate) const INVALID_MANDATORY_PARAMETER: ErrorCauseCode = ErrorCauseCode(7);
61pub(crate) const UNRECOGNIZED_PARAMETERS: ErrorCauseCode = ErrorCauseCode(8);
62pub(crate) const NO_USER_DATA: ErrorCauseCode = ErrorCauseCode(9);
63pub(crate) const COOKIE_RECEIVED_WHILE_SHUTTING_DOWN: ErrorCauseCode = ErrorCauseCode(10);
64pub(crate) const RESTART_OF_AN_ASSOCIATION_WITH_NEW_ADDRESSES: ErrorCauseCode = ErrorCauseCode(11);
65pub(crate) const USER_INITIATED_ABORT: ErrorCauseCode = ErrorCauseCode(12);
66pub(crate) const PROTOCOL_VIOLATION: ErrorCauseCode = ErrorCauseCode(13);
67
68impl ErrorCauseCode {
69    /// The cause code's number (RFC 9260 3.3.10).
70    pub fn value(&self) -> u16 {
71        self.0
72    }
73}
74
75impl fmt::Display for ErrorCauseCode {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        let others = format!("Unknown CauseCode: {}", self.0);
78        let s = match *self {
79            INVALID_STREAM_IDENTIFIER => "Invalid Stream Identifier",
80            MISSING_MANDATORY_PARAMETER => "Missing Mandatory Parameter",
81            STALE_COOKIE_ERROR => "Stale Cookie Error",
82            OUT_OF_RESOURCE => "Out Of Resource",
83            UNRESOLVABLE_ADDRESS => "Unresolvable IP",
84            UNRECOGNIZED_CHUNK_TYPE => "Unrecognized Chunk Type",
85            INVALID_MANDATORY_PARAMETER => "Invalid Mandatory Parameter",
86            UNRECOGNIZED_PARAMETERS => "Unrecognized Parameters",
87            NO_USER_DATA => "No User Data",
88            COOKIE_RECEIVED_WHILE_SHUTTING_DOWN => "Cookie Received While Shutting Down",
89            RESTART_OF_AN_ASSOCIATION_WITH_NEW_ADDRESSES => {
90                "Restart Of An Association With New Addresses"
91            }
92            USER_INITIATED_ABORT => "User Initiated Abort",
93            PROTOCOL_VIOLATION => "Protocol Violation",
94            _ => others.as_str(),
95        };
96        write!(f, "{}", s)
97    }
98}
99
100impl From<u16> for ErrorCauseCode {
101    fn from(v: u16) -> Self {
102        ErrorCauseCode(v)
103    }
104}
105
106/// ErrorCauseHeader represents the shared header that is shared by all error causes
107#[derive(Debug, Clone, Default)]
108pub(crate) struct ErrorCause {
109    pub(crate) code: ErrorCauseCode,
110    pub(crate) raw: Bytes,
111}
112
113/// ErrorCauseInvalidMandatoryParameter represents an SCTP error cause
114pub(crate) type ErrorCauseInvalidMandatoryParameter = ErrorCause;
115
116/// ErrorCauseUnrecognizedChunkType represents an SCTP error cause
117pub(crate) type ErrorCauseUnrecognizedChunkType = ErrorCause;
118
119///
120/// This error cause MAY be included in ABORT chunks that are sent
121/// because an SCTP endpoint detects a protocol violation of the peer
122/// that is not covered by the error causes described in Section 3.3.10.1
123/// to Section 3.3.10.12.  An implementation MAY provide additional
124/// information specifying what kind of protocol violation has been
125/// detected.
126///      0                   1                   2                   3
127///      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
128///     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
129///     |         Cause Code=13         |      Cause Length=Variable    |
130///     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
131///     /                    Additional Information                     /
132///     \                                                               \
133///     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
134///
135pub(crate) type ErrorCauseProtocolViolation = ErrorCause;
136
137pub(crate) const ERROR_CAUSE_HEADER_LENGTH: usize = 4;
138
139/// makes ErrorCauseHeader printable
140impl fmt::Display for ErrorCause {
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        write!(f, "{}", self.code)
143    }
144}
145
146/// The bytes `causes` take in a chunk: every cause but the last is padded to four bytes
147/// (RFC 9260 3.2: the chunk length leaves out the padding of the last one).
148pub(crate) fn error_causes_length(causes: &[ErrorCause]) -> usize {
149    let mut length = 0;
150    for (i, cause) in causes.iter().enumerate() {
151        length += cause.length();
152        if i + 1 != causes.len() {
153            length += get_padding_size(cause.length());
154        }
155    }
156    length
157}
158
159/// Writes `causes` as [`error_causes_length`] counts them.
160pub(crate) fn marshal_error_causes(causes: &[ErrorCause], writer: &mut BytesMut) {
161    for (i, cause) in causes.iter().enumerate() {
162        cause.marshal_to(writer);
163        if i + 1 != causes.len() {
164            writer.put_bytes(0, get_padding_size(cause.length()));
165        }
166    }
167}
168
169impl ErrorCause {
170    pub(crate) fn unmarshal(buf: &Bytes) -> Result<Self> {
171        if buf.len() < ERROR_CAUSE_HEADER_LENGTH {
172            return Err(Error::ErrErrorCauseTooSmall);
173        }
174
175        let reader = &mut buf.clone();
176
177        let code = ErrorCauseCode(reader.get_u16());
178        let len = reader.get_u16();
179
180        if len < ERROR_CAUSE_HEADER_LENGTH as u16 {
181            return Err(Error::ErrErrorCauseTooSmall);
182        }
183        // The cause length is the peer's; it must fit the chunk it came in.
184        if len as usize > buf.len() {
185            return Err(Error::ErrErrorCauseTooSmall);
186        }
187
188        let value_length = len as usize - ERROR_CAUSE_HEADER_LENGTH;
189        let raw = buf.slice(ERROR_CAUSE_HEADER_LENGTH..ERROR_CAUSE_HEADER_LENGTH + value_length);
190
191        Ok(ErrorCause { code, raw })
192    }
193
194    pub(crate) fn marshal(&self) -> Bytes {
195        let mut buf = BytesMut::with_capacity(self.length());
196        let _ = self.marshal_to(&mut buf);
197        buf.freeze()
198    }
199
200    pub(crate) fn marshal_to(&self, writer: &mut BytesMut) -> usize {
201        let len = self.raw.len() + ERROR_CAUSE_HEADER_LENGTH;
202        writer.put_u16(self.code.0);
203        writer.put_u16(len as u16);
204        writer.extend_from_slice(&self.raw);
205        writer.len()
206    }
207
208    pub(crate) fn length(&self) -> usize {
209        self.raw.len() + ERROR_CAUSE_HEADER_LENGTH
210    }
211
212    pub(crate) fn error_cause_code(&self) -> ErrorCauseCode {
213        self.code
214    }
215}