Files
DomiStream/crates/domistream/src/rtsp/server/mod.rs
T

403 lines
17 KiB
Rust

//! The host's RTSP session (`docs/PROTOCOL.md` 2.2, 2.5), the mirror of [`super::client`]: OPTIONS → DESCRIBE →
//! SETUP audio, video and control (any order, each once) → ANNOUNCE → PLAY.
//!
//! The caller accepts TCP on the RTSP port, cuts each connection's bytes with [`super::RtspFramer::for_requests`],
//! feeds every whole request to [`RtspServer::handle_request`], writes the [`ServerReply`] back, and reads
//! [`ServerEvent`]s from [`RtspServer::poll_event`]. One [`RtspServer`] belongs to one launched session, not to one
//! TCP connection: a client may open a connection per request (UNKNOWN U5, `docs/PROTOCOL.md` 2.5), so the caller
//! routes every connection of that session to the same machine.
//!
//! Every request gets an answer. A request that is malformed, out of order or for another session gets an RTSP error
//! status and leaves the state unchanged; [`ServerReply::error`] says why, and the caller decides whether to close the
//! connection. Nothing here panics on any input.
mod announce;
mod describe;
pub use announce::{
ChromaSampling, MAX_ANNOUNCE_ATTRIBUTES, MAX_ANNOUNCE_BYTES, MAX_ANNOUNCE_LINE_BYTES, MAX_ANNOUNCE_LINES,
MAX_AUDIO_PACKET_DURATION_MS, MAX_BITRATE_KBPS, MAX_DIMENSION, MAX_FPS, MAX_PACKET_SIZE, MIN_PACKET_SIZE,
StreamConfig, SurroundSettings, parse_announce, write_announce,
};
pub use describe::{HostOffer, build_describe};
use std::collections::VecDeque;
use super::client::{StreamPorts, VideoCodec};
use super::sdp::EncryptionFlags;
use super::{MAX_RTSP_HEADERS, MAX_RTSP_MESSAGE_BYTES, Method, RtspRequest, RtspResponse, parse_request};
use crate::util::{hex_encode, malformed, parse_u32};
use crate::{Error, RandomSource, Result};
/// `timeout` of the `Session` header in SETUP answers, in seconds (`docs/PROTOCOL.md` 2.2 \[M\]).
pub const DEFAULT_SESSION_TIMEOUT_SECS: u32 = 90;
/// Random bytes in a session id (RFC 2326 section 3.4: at least eight octets, chosen at random); written as hex.
pub const SESSION_ID_BYTES: usize = 8;
/// How the host answers.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServerConfig {
/// The UDP ports answered to SETUP audio, video and control (`Transport: server_port=<port>`).
pub ports: StreamPorts,
/// What DESCRIBE offers and ANNOUNCE is checked against.
pub offer: HostOffer,
/// Encryption the client must turn on in ANNOUNCE (Lumen: at least control V2); must be offered.
pub required_encryption: EncryptionFlags,
/// Refuse requests after the first SETUP that carry no `Session` header. Off by default: whether clients echo
/// it is UNKNOWN U5, and a known host does not read it (`docs/PROTOCOL.md` 2.5). A `Session` that is present is
/// always checked.
pub require_session_header: bool,
/// `timeout` in the `Session` header, seconds, 1.. ([`DEFAULT_SESSION_TIMEOUT_SECS`]).
pub session_timeout_secs: u32,
}
/// Which request the session expects next.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RtspServerState {
/// OPTIONS.
Options,
/// DESCRIBE.
Describe,
/// SETUP of the streams not set up yet.
Setup,
/// ANNOUNCE.
Announce,
/// PLAY.
Play,
/// PLAY answered: the streams start. Only OPTIONS is still answered with 200.
Playing,
}
/// What the session tells the caller.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ServerEvent {
/// ANNOUNCE accepted: the stream settings the client asked for.
Announced(StreamConfig),
/// PLAY accepted: start the streams (video and audio wait for the client's PING, control for ENet).
PlayRequested,
}
/// The answer to one request.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServerReply {
/// The whole RTSP answer to write to the connection.
pub bytes: Vec<u8>,
/// Its status code (200, or 400, 451, 454, 455 or 501).
pub status: u16,
/// Why the request was refused; `None` with status 200.
pub error: Option<Error>,
}
/// The host side of one session's RTSP negotiation.
#[derive(Debug)]
pub struct RtspServer {
config: ServerConfig,
session_id: String,
/// The DESCRIBE payload, built once from the offer.
describe: Vec<u8>,
state: RtspServerState,
/// SETUP answered for audio, video, control.
set_up: [bool; 3],
/// A SETUP was answered, so the session id is known to the client.
session_issued: bool,
announced: Option<StreamConfig>,
/// At most two events ever (one ANNOUNCE, one PLAY).
events: VecDeque<ServerEvent>,
}
/// `Public` in the OPTIONS answer (RFC 2326 section 10.1 example form).
const PUBLIC: &str = "OPTIONS, DESCRIBE, SETUP, ANNOUNCE, PLAY";
/// The streams of SETUP, in the order of `RtspServer::set_up` (`docs/PROTOCOL.md` 2.2).
const STREAMS: [&str; 3] = ["audio", "video", "control"];
/// The CSeq, headers and payload of a 200 answer.
type Answer = (u32, Vec<(String, String)>, Vec<u8>);
/// A refused request: the status, the CSeq to echo if one was readable, and why.
struct Refusal {
status: u16,
cseq: Option<u32>,
error: Error,
}
impl RtspServer {
/// Checks `config` and draws a fresh session id from `rng`.
///
/// # Errors
/// [`Error::Malformed`] for a zero port or session timeout, or required encryption the offer lacks; any error
/// of [`build_describe`] for the offer.
pub fn new(config: ServerConfig, rng: &mut dyn RandomSource) -> Result<Self> {
let p = config.ports;
if p.audio == 0 || p.video == 0 || p.control == 0 {
return Err(malformed("rtsp server: stream port 0"));
}
if config.session_timeout_secs == 0 {
return Err(malformed("rtsp server: session timeout 0"));
}
if !config.offer.encryption_supported.contains(config.required_encryption.0) {
return Err(malformed("rtsp server: required encryption is not offered"));
}
let describe = build_describe(&config.offer)?;
let mut id = [0u8; SESSION_ID_BYTES];
rng.fill(&mut id);
Ok(Self {
config,
session_id: hex_encode(&id),
describe,
state: RtspServerState::Options,
set_up: [false; 3],
session_issued: false,
announced: None,
events: VecDeque::new(),
})
}
/// Answers one whole request (see [`super::RtspFramer::for_requests`]). Never panics; a refusal leaves the
/// state as it was.
pub fn handle_request(&mut self, message: &[u8]) -> ServerReply {
match self.answer(message) {
Ok((cseq, headers, body)) => reply(200, Some(cseq), headers, body, None),
Err(r) => reply(r.status, r.cseq, Vec::new(), Vec::new(), Some(r.error)),
}
}
/// The headers and payload of a 200 answer, or why the request is refused.
fn answer(&mut self, message: &[u8]) -> core::result::Result<Answer, Refusal> {
let request = parse_request(message).map_err(|error| {
let status = if matches!(error, Error::UnexpectedValue { what: "rtsp method", .. }) { 501 } else { 400 };
Refusal { status, cseq: salvage_cseq(message), error }
})?;
let cseq = request_cseq(&request).map_err(|error| Refusal { status: 400, cseq: None, error })?;
let refuse = |status: u16, error: Error| Refusal { status, cseq: Some(cseq), error };
self.check_session(&request).map_err(|(status, error)| refuse(status, error))?;
let mut headers = Vec::new();
let mut body = Vec::new();
match request.method {
Method::Options => {
// OPTIONS may come at any time and changes nothing else (RFC 2326 section 10.1).
if self.state == RtspServerState::Options {
self.state = RtspServerState::Describe;
}
headers.push(("Public".to_owned(), PUBLIC.to_owned()));
}
Method::Describe => {
self.expect(RtspServerState::Describe, "DESCRIBE after OPTIONS").map_err(|e| refuse(455, e))?;
headers.push(("Content-Type".to_owned(), "application/sdp".to_owned()));
body.clone_from(&self.describe);
self.state = RtspServerState::Setup;
}
Method::Setup => {
self.expect(RtspServerState::Setup, "SETUP after DESCRIBE").map_err(|e| refuse(455, e))?;
// A Transport header must be present; its value is not interpreted (`docs/PROTOCOL.md` 2.2 [M]).
if request.header("Transport").is_none() {
return Err(refuse(400, malformed("rtsp SETUP without Transport")));
}
let index = setup_stream(&request.target).map_err(|e| refuse(400, e))?;
let port = self.port(index).ok_or(refuse(400, malformed("rtsp SETUP stream")))?;
let slot = self.set_up.get_mut(index).ok_or(refuse(400, malformed("rtsp SETUP stream")))?;
if *slot {
return Err(refuse(455, Error::State { expected: "one SETUP per stream" }));
}
*slot = true;
self.session_issued = true;
if self.set_up.iter().all(|done| *done) {
self.state = RtspServerState::Announce;
}
let session = format!("{};timeout = {}", self.session_id, self.config.session_timeout_secs);
headers.push(("Session".to_owned(), session));
headers.push(("Transport".to_owned(), format!("server_port={port}")));
}
Method::Announce => {
self.expect(RtspServerState::Announce, "ANNOUNCE after the three SETUPs")
.map_err(|e| refuse(455, e))?;
let config = parse_announce(&request.body).map_err(|e| refuse(400, e))?;
self.check_offer(&config).map_err(|e| refuse(451, e))?;
self.events.push_back(ServerEvent::Announced(config.clone()));
self.announced = Some(config);
self.state = RtspServerState::Play;
}
Method::Play => {
self.expect(RtspServerState::Play, "PLAY after ANNOUNCE").map_err(|e| refuse(455, e))?;
self.events.push_back(ServerEvent::PlayRequested);
self.state = RtspServerState::Playing;
}
}
Ok((cseq, headers, body))
}
fn expect(&self, state: RtspServerState, expected: &'static str) -> Result<()> {
if self.state == state { Ok(()) } else { Err(Error::State { expected }) }
}
/// The UDP port answered for stream `index` (audio, video, control).
fn port(&self, index: usize) -> Option<u16> {
let p = self.config.ports;
[p.audio, p.video, p.control].get(index).copied()
}
/// `Session` checks (`docs/PROTOCOL.md` 2.5): a present id must be the one issued in SETUP; a missing one is
/// refused only when the config asks for it.
fn check_session(&self, request: &RtspRequest) -> core::result::Result<(), (u16, Error)> {
let mut ids = request
.headers
.iter()
.filter(|(n, _)| n.eq_ignore_ascii_case("session"))
.map(|(_, v)| v.split(';').next().unwrap_or("").trim_matches([' ', '\t']));
let first = ids.next();
if let Some(id) = first
&& ids.any(|other| other != id)
{
return Err((400, malformed("rtsp: two different Session headers")));
}
match first {
Some(id) if !self.session_issued || id != self.session_id => {
Err((454, malformed("rtsp: Session is not this session's id")))
}
None if self.config.require_session_header && self.session_issued && request.method != Method::Options => {
Err((454, malformed("rtsp: Session missing")))
}
_ => Ok(()),
}
}
/// What ANNOUNCE asks for must be in the offer.
fn check_offer(&self, config: &StreamConfig) -> Result<()> {
let offer = &self.config.offer;
let codec_offered = match config.codec {
VideoCodec::H264 => offer.h264,
VideoCodec::Hevc => offer.hevc,
VideoCodec::Av1 => offer.av1,
};
if !codec_offered {
return Err(Error::Unsupported { what: "the requested video codec" });
}
if config.encryption.0 & !offer.encryption_supported.0 != 0 {
return Err(Error::Unsupported { what: "encryption the host did not offer" });
}
if !config.encryption.contains(self.config.required_encryption.0) {
return Err(Error::Unsupported { what: "a stream without the encryption the host requires" });
}
// 0 is SDR (`docs/PROTOCOL.md` 2.5 [M]); any other value is "not SDR", without a settled meaning (U6).
if config.dynamic_range_mode != 0 && !offer.hdr {
return Err(Error::Unsupported { what: "HDR" });
}
if config.chroma == ChromaSampling::Yuv444 && !offer.yuv444 {
return Err(Error::Unsupported { what: "4:4:4 chroma" });
}
Ok(())
}
/// The next event, if any.
pub fn poll_event(&mut self) -> Option<ServerEvent> {
self.events.pop_front()
}
/// Which request the session expects next.
#[must_use]
pub const fn state(&self) -> RtspServerState {
self.state
}
/// The session id sent in SETUP answers.
#[must_use]
pub fn session_id(&self) -> &str {
&self.session_id
}
/// The accepted ANNOUNCE, once there is one.
#[must_use]
pub const fn announced(&self) -> Option<&StreamConfig> {
self.announced.as_ref()
}
/// The configuration the session answers with.
#[must_use]
pub const fn config(&self) -> &ServerConfig {
&self.config
}
}
/// The reason phrase of each status the session sends (RFC 2326 section 7.1.1).
const fn reason(status: u16) -> &'static str {
match status {
200 => "OK",
400 => "Bad Request",
451 => "Parameter Not Understood",
454 => "Session Not Found",
455 => "Method Not Valid in This State",
501 => "Not Implemented",
_ => "Internal Server Error",
}
}
/// Builds the answer: `CSeq` first (when known), the given headers, then `Content-Length` (always, so the client's
/// framer never has to wait for the connection to close, `docs/PROTOCOL.md` 2.1 U5).
fn reply(
status: u16,
cseq: Option<u32>,
extra: Vec<(String, String)>,
body: Vec<u8>,
error: Option<Error>,
) -> ServerReply {
let mut headers = Vec::with_capacity(extra.len() + 2);
if let Some(c) = cseq {
headers.push(("CSeq".to_owned(), c.to_string()));
}
headers.extend(extra);
headers.push(("Content-Length".to_owned(), body.len().to_string()));
match (RtspResponse { status, reason: reason(status).to_owned(), headers, body }).encode() {
Ok(bytes) => ServerReply { bytes, status, error },
// Only an answer over the message cap could fail, and none is that large; answer 500 rather than panic.
Err(e) => ServerReply {
bytes: b"RTSP/1.0 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n".to_vec(),
status: 500,
error: Some(e),
},
}
}
/// The request's CSeq: present, plain decimal `u32`, every copy equal.
fn request_cseq(request: &RtspRequest) -> Result<u32> {
let mut found = None;
for (_, v) in request.headers.iter().filter(|(n, _)| n.eq_ignore_ascii_case("cseq")) {
let n = parse_u32("rtsp CSeq", v)?;
if found.is_some_and(|f| f != n) {
return Err(malformed("rtsp: two different CSeq values"));
}
found = Some(n);
}
found.ok_or(malformed("rtsp request without CSeq"))
}
/// The CSeq of a request that did not parse, if a header line says it plainly, so the refusal can still echo it.
/// Reads at most the header section, at most [`MAX_RTSP_HEADERS`] lines, and allocates nothing.
fn salvage_cseq(message: &[u8]) -> Option<u32> {
let head = message.get(..message.len().min(MAX_RTSP_MESSAGE_BYTES))?;
for raw in head.split(|&b| b == b'\n').skip(1).take(MAX_RTSP_HEADERS) {
let line = raw.strip_suffix(b"\r").unwrap_or(raw);
if line.is_empty() {
break;
}
let Ok(text) = core::str::from_utf8(line) else { continue };
if let Some((name, value)) = text.split_once(':')
&& name.eq_ignore_ascii_case("cseq")
{
return parse_u32("rtsp CSeq", value.trim_matches([' ', '\t'])).ok();
}
}
None
}
/// The stream a SETUP target names: exactly one `streamid=` followed by `audio`, `video` or `control`, ended by
/// `/`, `?`, `&`, `;` or the end (`docs/PROTOCOL.md` 2.2 \[M\], 2.5). Index into [`STREAMS`].
fn setup_stream(target: &str) -> Result<usize> {
let mut parts = target.split("streamid=");
parts.next();
let after = parts.next().ok_or(malformed("rtsp SETUP target without streamid"))?;
if parts.next().is_some() {
return Err(malformed("rtsp SETUP target with two streamid"));
}
let name = after.split(['/', '?', '&', ';']).next().unwrap_or("");
STREAMS.iter().position(|s| *s == name).ok_or(malformed("rtsp SETUP streamid"))
}