//! Drives DomiStream's `RtspClient` over real TCP and records what U5 needs: whether answers carry //! `Content-Length`, whether the host closes the connection after each answer, and every header it sends. use std::io::{self, Read, Write}; use std::net::{IpAddr, SocketAddr, TcpStream}; use std::time::{Duration, Instant}; use domistream::rtsp::client::{RtspClientState, StreamConfig}; use domistream::rtsp::{DEFAULT_RTSP_PORT, NegotiatedStream, RtspClient, RtspFramer, RtspProgress, parse_response}; use crate::log::{J, Kind, Log, text}; /// A whole exchange may take this long. const ANSWER_TIMEOUT: Duration = Duration::from_secs(15); /// With headers in and no `Content-Length`, an open connection that stays quiet this long ends the message. const IDLE_CUT: Duration = Duration::from_secs(2); const POLL: Duration = Duration::from_millis(200); /// Where to connect for RTSP and the URL the requests name. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Target { pub addr: SocketAddr, pub url: String, /// Set when the host named another address than the one the probe talks to (it is never used). pub foreign_host: Option, /// `sessionUrl0` was missing and port 48010 was assumed (U4). pub assumed_port: bool, } /// The RTSP target from the launch answer. The probe only ever connects to `connect_ip`; the host part of /// `sessionUrl0` is compared with `host` and otherwise ignored. pub fn target(session_url: Option<&str>, host: IpAddr, connect_ip: IpAddr) -> Result { let Some(url) = session_url else { let url = format!("rtsp://{}", SocketAddr::new(host, DEFAULT_RTSP_PORT)); return Ok(Target { addr: SocketAddr::new(connect_ip, DEFAULT_RTSP_PORT), url, foreign_host: None, assumed_port: true, }); }; let rest = url.strip_prefix("rtsp://").ok_or_else(|| format!("sessionUrl0 '{url}' is not rtsp://"))?; let authority = rest.split('/').next().unwrap_or(""); let (h, p) = authority.rsplit_once(':').ok_or_else(|| format!("sessionUrl0 '{url}' has no port"))?; let port: u16 = p.parse().map_err(|_| format!("sessionUrl0 '{url}' has a bad port"))?; if port == 0 { return Err(format!("sessionUrl0 '{url}' has port 0")); } let named = h.trim_start_matches('[').trim_end_matches(']'); let foreign_host = match named.parse::() { Ok(ip) if ip == host => None, _ => Some(named.to_owned()), }; Ok(Target { addr: SocketAddr::new(connect_ip, port), url: url.to_owned(), foreign_host, assumed_port: false }) } fn state_name(s: RtspClientState) -> &'static str { match s { RtspClientState::Options => "options", RtspClientState::Describe => "describe", RtspClientState::SetupAudio => "setup_audio", RtspClientState::SetupVideo => "setup_video", RtspClientState::SetupControl => "setup_control", RtspClientState::Announce => "announce", RtspClientState::Play => "play", RtspClientState::Ready => "ready", RtspClientState::Failed => "failed", } } fn unknowns(s: RtspClientState) -> &'static [&'static str] { match s { RtspClientState::Describe => &["U5", "U26"], RtspClientState::SetupAudio | RtspClientState::SetupVideo | RtspClientState::SetupControl => &["U5", "U7"], RtspClientState::Announce => &["U5", "U6"], _ => &["U5"], } } /// How an answer's end was found. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum End { /// Headers plus `Content-Length` (the connection stays open). Length, /// The host closed the connection. Closed, /// No `Content-Length`; the open connection went quiet ([`IDLE_CUT`]). Idle, } fn connect(addr: SocketAddr) -> io::Result { let s = TcpStream::connect_timeout(&addr, Duration::from_secs(5))?; s.set_read_timeout(Some(POLL))?; s.set_nodelay(true)?; Ok(s) } fn read_answer(s: &mut TcpStream) -> Result<(Vec, End), String> { let started = Instant::now(); let mut last_data = Instant::now(); let mut framer = RtspFramer::new(); let mut buf = [0u8; 8192]; loop { match s.read(&mut buf) { Ok(0) => { return match framer.finish() { Ok(Some(m)) => Ok((m, End::Closed)), Ok(None) => Err("closed with no answer".into()), Err(e) => Err(format!("closed inside an answer: {e}")), }; } Ok(n) => { framer.push(buf.get(..n).unwrap_or(&[])).map_err(|e| e.to_string())?; if let Some(m) = framer.next_message().map_err(|e| e.to_string())? { return Ok((m, End::Length)); } last_data = Instant::now(); } Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => { if framer.buffered() > 0 && last_data.elapsed() >= IDLE_CUT { // Complete headers without Content-Length: the message ends here. Otherwise keep waiting. if let Ok(Some(m)) = framer.finish() { return Ok((m, End::Idle)); } } } Err(e) if e.kind() == io::ErrorKind::Interrupted => {} Err(e) => return Err(format!("read failed: {e}")), } if started.elapsed() >= ANSWER_TIMEOUT { return Err(format!( "no complete answer within {} s ({} bytes buffered)", ANSWER_TIMEOUT.as_secs(), framer.buffered() )); } } } /// OPTIONS … PLAY. Every request and answer goes to the log in full (RTSP carries no secrets). pub fn negotiate(log: &mut Log, t: &Target, config: StreamConfig) -> Result { let mut client = RtspClient::new(&t.url, config).map_err(|e| format!("rtsp setup: {e}"))?; let mut conn: Option = None; let mut connections = 0u32; while let Some(req) = client.poll_request() { let state = client.state(); let step = format!("rtsp.{}", state_name(state)); let us = unknowns(state); log.record(&step, Kind::Send, us, J::O(vec![("to", J::s(t.addr.to_string())), ("message", text(&req))])); let mut retried = false; let (answer, end) = loop { let reused = conn.is_some(); if conn.is_none() { let s = connect(t.addr).map_err(|e| { let m = format!("RTSP connect to {} failed: {e}", t.addr); log.stop(&step, us, m.clone(), J::Null); m })?; connections += 1; log.note(&step, &["U5"], format!("TCP connection #{connections} to {}", t.addr)); conn = Some(s); } let Some(s) = conn.as_mut() else { return Err("no RTSP connection".into()) }; let result = s.write_all(&req).map_err(|e| format!("write failed: {e}")).and_then(|()| read_answer(s)); match result { Ok(x) => break x, Err(e) if reused && !retried => { log.note( &step, &["U5"], format!("the kept connection failed ({e}); the host closes between requests; reconnecting"), ); conn = None; retried = true; } Err(e) => { let m = format!("RTSP {}: {e}", state_name(state)); log.stop(&step, us, m.clone(), J::Null); return Err(m); } } }; if end == End::Closed { conn = None; } let parsed = parse_response(&answer).ok(); let has_length = parsed.as_ref().is_some_and(|r| r.headers.iter().any(|(n, _)| n.eq_ignore_ascii_case("content-length"))); let headers = parsed .map(|r| J::A(r.headers.iter().map(|(n, v)| J::A(vec![J::s(n.clone()), J::s(v.clone())])).collect())) .unwrap_or(J::Null); log.record( &step, Kind::Recv, us, J::O(vec![ ("end", J::s(format!("{end:?}"))), ("content_length_header", J::Bool(has_length)), ("headers", headers), ("message", text(&answer)), ]), ); match client.handle_response(&answer) { Ok(RtspProgress::Continue) => {} Ok(RtspProgress::Ready(n)) => { log.note("rtsp.ready", &["U5"], format!("negotiated over {connections} TCP connection(s)")); return Ok(n); } Err(e) => { log.parse_error(&step, us, &e, text(&answer)); let m = format!("RTSP {} answer refused: {e}", state_name(state)); log.stop(&step, us, m.clone(), J::Null); return Err(m); } } } Err("RTSP ended without a request to send".into()) } #[cfg(test)] mod tests { use super::*; fn ip(s: &str) -> IpAddr { s.parse().unwrap() } #[test] fn session_url_port_is_used_with_the_given_address_only() { let t = target(Some("rtsp://192.168.100.140:48010"), ip("192.168.100.140"), ip("192.168.100.140")).unwrap(); assert_eq!((t.addr, t.foreign_host, t.assumed_port), ("192.168.100.140:48010".parse().unwrap(), None, false)); let t = target(Some("rtsp://10.0.0.9:48011"), ip("192.168.100.140"), ip("192.168.100.140")).unwrap(); assert_eq!(t.addr, "192.168.100.140:48011".parse().unwrap()); assert_eq!(t.foreign_host.as_deref(), Some("10.0.0.9")); assert_eq!(t.url, "rtsp://10.0.0.9:48011"); } #[test] fn relay_and_ipv6() { let t = target(Some("rtsp://[::1]:48010"), ip("::1"), ip("127.0.0.1")).unwrap(); assert_eq!((t.addr, t.foreign_host), ("127.0.0.1:48010".parse().unwrap(), None)); } #[test] fn missing_session_url_assumes_48010() { let t = target(None, ip("192.168.100.140"), ip("192.168.100.140")).unwrap(); assert_eq!((t.url.as_str(), t.assumed_port), ("rtsp://192.168.100.140:48010", true)); } #[test] fn bad_session_urls_are_refused() { let h = ip("192.168.100.140"); assert!(target(Some("http://x:1"), h, h).is_err()); assert!(target(Some("rtsp://x"), h, h).is_err()); assert!(target(Some("rtsp://x:0"), h, h).is_err()); assert!(target(Some("rtsp://x:99999"), h, h).is_err()); } }