//! RTSP stream negotiation (`docs/PROTOCOL.md` section 2): message codec, a framer for the TCP byte stream, SDP, //! the client state machine and the host's session ([`server`], section 2.5). pub mod client; pub mod sdp; pub mod server; pub use client::{NegotiatedStream, RtspClient, RtspClientState, RtspProgress, StreamConfig, StreamPorts}; pub use sdp::{EncryptionFlags, HostCapabilities, OpusConfig, Sdp}; pub use server::{HostOffer, RtspServer, RtspServerState, ServerConfig, ServerEvent, ServerReply}; use crate::util::{cap, malformed, parse_dec}; use crate::{Error, Result}; /// Default RTSP port. pub const DEFAULT_RTSP_PORT: u16 = 48010; /// Maximum size of one RTSP message (start line + headers + payload), in bytes. pub const MAX_RTSP_MESSAGE_BYTES: usize = 64 * 1024; /// Maximum length of one start or header line, in bytes (without CRLF). pub const MAX_RTSP_LINE_BYTES: usize = 4096; /// Maximum number of header lines in one message. pub const MAX_RTSP_HEADERS: usize = 64; /// The only protocol version spoken. const VERSION: &str = "RTSP/1.0"; /// The methods this client sends. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Method { /// `OPTIONS`. Options, /// `DESCRIBE`. Describe, /// `SETUP`. Setup, /// `ANNOUNCE`. Announce, /// `PLAY`. Play, } impl Method { /// The method token. #[must_use] pub const fn as_str(self) -> &'static str { match self { Self::Options => "OPTIONS", Self::Describe => "DESCRIBE", Self::Setup => "SETUP", Self::Announce => "ANNOUNCE", Self::Play => "PLAY", } } fn from_token(t: &str) -> Option { [Self::Options, Self::Describe, Self::Setup, Self::Announce, Self::Play].into_iter().find(|m| m.as_str() == t) } } /// An RTSP request. #[derive(Clone, Debug, PartialEq, Eq)] pub struct RtspRequest { /// The method. pub method: Method, /// The target, e.g. `rtsp://192.0.2.10:48010` or `streamid=video/0/0`. pub target: String, /// Header lines in order, `CSeq` included. pub headers: Vec<(String, String)>, /// The payload (SDP for ANNOUNCE), possibly empty. pub body: Vec, } fn is_token(b: u8) -> bool { b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b) } impl RtspRequest { /// Serializes the request (CRLF line ends, empty line, payload) with exactly the given headers. Refuses CR or /// LF inside a target, header name or value, whitespace in the target, and header names that are not tokens. /// /// # Errors /// [`Error::Malformed`] for a forbidden character, [`Error::TooLarge`] over [`MAX_RTSP_MESSAGE_BYTES`]. pub fn encode(&self) -> Result> { if self.target.is_empty() || self.target.bytes().any(|b| b.is_ascii_whitespace() || b.is_ascii_control()) { return Err(malformed("rtsp target")); } let mut out = format!("{} {} {VERSION}\r\n", self.method.as_str(), self.target); for (name, value) in &self.headers { if name.is_empty() || !name.bytes().all(is_token) { return Err(malformed("rtsp header name")); } if value.bytes().any(|b| b == b'\r' || b == b'\n') { return Err(malformed("rtsp header value")); } out.push_str(name); out.push_str(": "); out.push_str(value); out.push_str("\r\n"); } out.push_str("\r\n"); let mut bytes = out.into_bytes(); cap("rtsp request", MAX_RTSP_MESSAGE_BYTES, bytes.len().saturating_add(self.body.len()))?; bytes.extend_from_slice(&self.body); Ok(bytes) } /// The first header with this name, compared case-insensitively. #[must_use] pub fn header(&self, name: &str) -> Option<&str> { header(&self.headers, name) } } /// An RTSP response. #[derive(Clone, Debug, PartialEq, Eq)] pub struct RtspResponse { /// Status code, e.g. 200. pub status: u16, /// Reason phrase. pub reason: String, /// Header lines in order. pub headers: Vec<(String, String)>, /// The payload (SDP for DESCRIBE), possibly empty. pub body: Vec, } fn header<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> { headers.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str()) } impl RtspResponse { /// The first header with this name, compared case-insensitively. #[must_use] pub fn header(&self, name: &str) -> Option<&str> { header(&self.headers, name) } /// Serializes the response (`RTSP/1.0 `, CRLF line ends, empty line, payload) with exactly the /// given headers. The host side's mirror of [`RtspRequest::encode`]. /// /// # Errors /// [`Error::Malformed`] for a status outside 100..=999, CR, LF or another control character in the reason, a /// header name that is not a token, or CR or LF in a header value; [`Error::TooLarge`] over /// [`MAX_RTSP_MESSAGE_BYTES`]. pub fn encode(&self) -> Result> { if !(100..=999).contains(&self.status) || self.reason.bytes().any(|b| b.is_ascii_control()) { return Err(malformed("rtsp status line")); } let mut out = format!("{VERSION} {} {}\r\n", self.status, self.reason); for (name, value) in &self.headers { if name.is_empty() || !name.bytes().all(is_token) { return Err(malformed("rtsp header name")); } if value.bytes().any(|b| b == b'\r' || b == b'\n') { return Err(malformed("rtsp header value")); } out.push_str(name); out.push_str(": "); out.push_str(value); out.push_str("\r\n"); } out.push_str("\r\n"); let mut bytes = out.into_bytes(); cap("rtsp response", MAX_RTSP_MESSAGE_BYTES, bytes.len().saturating_add(self.body.len()))?; bytes.extend_from_slice(&self.body); Ok(bytes) } } /// A message split into start line, headers and payload. struct Message { start: String, headers: Vec<(String, String)>, body: Vec, } /// One CRLF-terminated line at `pos`: (line without CRLF, position after CRLF). `None` when no LF follows. fn line(data: &[u8], pos: usize) -> Result> { let rest = data.get(pos..).unwrap_or(&[]); let Some(lf) = rest.iter().take(MAX_RTSP_LINE_BYTES + 2).position(|&b| b == b'\n') else { if rest.len() > MAX_RTSP_LINE_BYTES + 1 { return Err(Error::TooLarge { what: "rtsp line", max: MAX_RTSP_LINE_BYTES, actual: rest.len() }); } return Ok(None); }; let raw = rest.get(..lf).unwrap_or(&[]); let text = raw.strip_suffix(b"\r").ok_or(malformed("rtsp line without CRLF"))?; cap("rtsp line", MAX_RTSP_LINE_BYTES, text.len())?; if text.contains(&b'\r') { return Err(malformed("rtsp: CR inside a line")); } let text = core::str::from_utf8(text).map_err(|_| malformed("rtsp: not UTF-8"))?; Ok(Some((text, pos + lf + 1))) } /// Parses headers from `pos` up to the empty line: (headers, position of the payload). fn headers_from(data: &[u8], mut pos: usize) -> Result<(Vec<(String, String)>, usize)> { let mut headers = Vec::new(); loop { let (text, next) = line(data, pos)?.ok_or(Error::Truncated { what: "rtsp headers", needed: data.len().saturating_add(2), actual: data.len(), })?; pos = next; if text.is_empty() { return Ok((headers, pos)); } let (name, value) = text.split_once(':').ok_or(malformed("rtsp header without :"))?; if name.is_empty() || !name.bytes().all(is_token) { return Err(malformed("rtsp header name")); } headers.push((name.to_owned(), value.trim_matches([' ', '\t']).to_owned())); cap("rtsp headers", MAX_RTSP_HEADERS, headers.len())?; } } /// The message's Content-Length, if any: strict digits, all copies equal, within the cap. fn content_length(headers: &[(String, String)], head_len: usize) -> Result> { let mut found: Option = None; for (_, v) in headers.iter().filter(|(n, _)| n.eq_ignore_ascii_case("content-length")) { let n = parse_dec("rtsp Content-Length", v)?; if found.is_some_and(|f| f != n) { return Err(malformed("rtsp: two different Content-Length values")); } found = Some(n); } let Some(n) = found else { return Ok(None) }; let total = usize::try_from(n).unwrap_or(usize::MAX).saturating_add(head_len); cap("rtsp message", MAX_RTSP_MESSAGE_BYTES, total)?; Ok(Some(total - head_len)) } fn split_message(msg: &[u8]) -> Result { cap("rtsp message", MAX_RTSP_MESSAGE_BYTES, msg.len())?; let (start, pos) = line(msg, 0)?.ok_or(malformed("rtsp: no start line"))?; if start.is_empty() { return Err(malformed("rtsp: empty start line")); } let start = start.to_owned(); let (headers, body_at) = headers_from(msg, pos)?; let rest = msg.get(body_at..).unwrap_or(&[]); let body = match content_length(&headers, body_at)? { None => rest.to_vec(), Some(n) if rest.len() < n => { return Err(Error::Truncated { what: "rtsp payload", needed: body_at + n, actual: msg.len() }); } Some(n) if rest.len() > n => return Err(malformed("rtsp: bytes after the payload")), Some(_) => rest.to_vec(), }; Ok(Message { start, headers, body }) } /// Parses one complete response (as cut by [`RtspFramer`]). /// /// # Errors /// [`Error::TooLarge`] over [`MAX_RTSP_MESSAGE_BYTES`], [`MAX_RTSP_LINE_BYTES`] or [`MAX_RTSP_HEADERS`], /// [`Error::Malformed`] for a bad start line, header line or `Content-Length`, [`Error::Truncated`] when the headers /// or the payload end early. pub fn parse_response(message: &[u8]) -> Result { let m = split_message(message)?; let rest = m.start.strip_prefix("RTSP/1.0 ").ok_or(malformed("rtsp: not an RTSP/1.0 response"))?; let (code, reason) = rest.split_once(' ').unwrap_or((rest, "")); if code.len() != 3 || !code.bytes().all(|b| b.is_ascii_digit()) { return Err(malformed("rtsp status code")); } let status = crate::util::parse_u16("rtsp status code", code)?; Ok(RtspResponse { status, reason: reason.to_owned(), headers: m.headers, body: m.body }) } /// Parses one complete request. Not used by the client; here for the fuzz harness and the Lumen host (Day 3). /// /// # Errors /// As [`parse_response`], plus [`Error::UnexpectedValue`] for an unknown method. pub fn parse_request(message: &[u8]) -> Result { let m = split_message(message)?; let mut parts = m.start.splitn(3, ' '); let (Some(method), Some(target), Some(version)) = (parts.next(), parts.next(), parts.next()) else { return Err(malformed("rtsp request line")); }; if method.is_empty() || target.is_empty() || version != VERSION { return Err(malformed("rtsp request line")); } let method = Method::from_token(method).ok_or(Error::UnexpectedValue { what: "rtsp method", value: 0 })?; Ok(RtspRequest { method, target: target.to_owned(), headers: m.headers, body: m.body }) } /// Cuts a TCP byte stream into whole messages. /// /// A message ends after its headers plus `Content-Length` payload bytes. Without `Content-Length`, a framer made /// with [`RtspFramer::new`] (the client reading the host's answers) ends the message when the host closes the /// connection ([`RtspFramer::finish`]) (UNKNOWN U5); one made with [`RtspFramer::for_requests`] (the host reading /// a client's requests) takes a missing `Content-Length` as zero, as RFC 2326 section 4.4 says, so the message /// ends at the empty line (`docs/PROTOCOL.md` 2.5). Never buffers more than [`MAX_RTSP_MESSAGE_BYTES`]. #[derive(Debug, Default)] pub struct RtspFramer { buffer: Vec, /// A missing `Content-Length` means "no payload" (requests) instead of "until close" (answers). missing_length_is_zero: bool, } impl RtspFramer { /// An empty framer for the host's answers (client side). #[must_use] pub const fn new() -> Self { Self { buffer: Vec::new(), missing_length_is_zero: false } } /// An empty framer for a client's requests (host side): a request without `Content-Length` has no payload. #[must_use] pub const fn for_requests() -> Self { Self { buffer: Vec::new(), missing_length_is_zero: true } } /// Appends received bytes. /// /// # Errors /// [`Error::TooLarge`] when the buffered bytes would exceed [`MAX_RTSP_MESSAGE_BYTES`] (nothing is appended). pub fn push(&mut self, bytes: &[u8]) -> Result<()> { cap("rtsp stream", MAX_RTSP_MESSAGE_BYTES, self.buffer.len().saturating_add(bytes.len()))?; self.buffer.extend_from_slice(bytes); Ok(()) } /// Where the buffered header section ends and the message's Content-Length, if the headers are complete. fn head(&self) -> Result)>> { let Some(end) = self.buffer.windows(4).position(|w| w == b"\r\n\r\n") else { return Ok(None) }; let head_len = end + 4; let head = self.buffer.get(..head_len).unwrap_or(&[]); let mut headers = Vec::new(); for raw in head.split(|&b| b == b'\n').skip(1) { let text = core::str::from_utf8(raw.strip_suffix(b"\r").unwrap_or(raw)).unwrap_or(""); if let Some((n, v)) = text.split_once(':') && n.eq_ignore_ascii_case("content-length") { headers.push((n.to_owned(), v.trim_matches([' ', '\t']).to_owned())); } } let length = content_length(&headers, head_len)?; Ok(Some((head_len, if self.missing_length_is_zero { Some(length.unwrap_or(0)) } else { length }))) } /// Takes the next complete message, if one is buffered. /// /// # Errors /// [`Error::Malformed`] for a bad `Content-Length`, [`Error::TooLarge`] when it announces a message over the cap. pub fn next_message(&mut self) -> Result>> { match self.head()? { Some((head, Some(len))) if self.buffer.len() >= head + len => { let rest = self.buffer.split_off(head + len); Ok(Some(core::mem::replace(&mut self.buffer, rest))) } _ => Ok(None), } } /// The host closed the connection: returns what is buffered as the last message, if anything. /// /// # Errors /// [`Error::Truncated`] when the headers never ended or a `Content-Length` promised more. pub fn finish(&mut self) -> Result>> { if self.buffer.is_empty() { return Ok(None); } match self.head()? { None => Err(Error::Truncated { what: "rtsp headers at close", needed: self.buffer.len().saturating_add(4), actual: self.buffer.len(), }), Some((head, Some(len))) if self.buffer.len() < head + len => { Err(Error::Truncated { what: "rtsp payload at close", needed: head + len, actual: self.buffer.len() }) } Some(_) => Ok(Some(core::mem::take(&mut self.buffer))), } } /// Bytes buffered but not yet returned. #[must_use] pub fn buffered(&self) -> usize { self.buffer.len() } }