1use std::collections::HashMap;
26use std::time::{Duration, Instant};
27
28use rtsp_types::{Message, Method, Request, StatusCode, Version, headers};
29
30use crate::auth::{Authenticator, Credentials, RequestContext};
31use crate::error::{Error, Result};
32use crate::interleaved::{self, MAGIC};
33use crate::state::{SessionState, client_next_state};
34use crate::transport::Transport;
35
36type Body = Vec<u8>;
38
39const DEFAULT_SESSION_TIMEOUT_SECS: u64 = 60;
41
42const KEEPALIVE_FRACTION_DEN: u32 = 2;
45
46pub const MAX_SESSION_WARNINGS: usize = 16;
49
50pub const MIN_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(1);
54
55const MAX_INBOUND_BYTES: usize = 1024 * 1024;
62
63#[derive(Debug, Clone)]
65struct Pending {
66 method: Method,
67 uri: String,
68 request: Request<Body>,
70 auth_retried: bool,
72}
73
74#[non_exhaustive]
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct RtpInfoEntry {
78 pub uri: String,
80 pub seq: Option<u16>,
82 pub rtptime: Option<u32>,
84}
85
86#[non_exhaustive]
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub enum ClientEvent {
90 Response {
92 cseq: u32,
94 method: Method,
96 status: StatusCode,
98 body: Vec<u8>,
100 },
101 AuthRetry {
104 method: Method,
106 cseq: u32,
108 request: Vec<u8>,
110 },
111 MediaData {
113 channel: u8,
115 data: Vec<u8>,
117 },
118}
119
120#[must_use = "an unchecked outcome silently ignores a terminal protocol error"]
125#[derive(Debug)]
126pub struct HandleOutcome {
127 pub events: Vec<ClientEvent>,
129 pub error: Option<Error>,
131}
132
133impl HandleOutcome {
134 pub fn into_result(self) -> Result<Vec<ClientEvent>> {
138 match self.error {
139 Some(e) => Err(e),
140 None => Ok(self.events),
141 }
142 }
143}
144
145#[derive(Debug)]
147pub struct ClientSession {
148 state: SessionState,
149 next_cseq: u32,
150 session_id: Option<String>,
151 session_timeout: Option<u64>,
152 credentials: Option<Credentials>,
153 authenticator: Option<Authenticator>,
154 negotiated_transport: Option<Transport>,
155 pending: HashMap<u32, Pending>,
156 inbound: Vec<u8>,
159 user_agent: String,
160 last_activity: Option<Instant>,
162 last_uri: Option<String>,
164 session_warnings: Vec<String>,
166 session_warning_total: usize,
168 scanned: usize,
170 skip_until: usize,
172 last_challenge: Option<String>,
174 content_base: Option<String>,
176 redirect_location: Option<String>,
178 rtp_info: Vec<RtpInfoEntry>,
179}
180
181impl Default for ClientSession {
182 fn default() -> Self {
183 Self::new()
184 }
185}
186
187impl ClientSession {
188 pub fn new() -> Self {
191 ClientSession {
192 state: SessionState::Init,
193 next_cseq: 1,
194 session_id: None,
195 session_timeout: None,
196 credentials: None,
197 authenticator: None,
198 negotiated_transport: None,
199 pending: HashMap::new(),
200 inbound: Vec::new(),
201 user_agent: "rtsp-runtime".to_string(),
202 last_activity: None,
203 last_uri: None,
204 session_warnings: Vec::new(),
205 session_warning_total: 0,
206 scanned: 0,
207 skip_until: 0,
208 last_challenge: None,
209 content_base: None,
210 redirect_location: None,
211 rtp_info: Vec::new(),
212 }
213 }
214
215 pub fn with_credentials(mut self, credentials: Credentials) -> Self {
217 self.credentials = Some(credentials);
218 self
219 }
220
221 pub fn last_challenge(&self) -> Option<&str> {
225 self.last_challenge.as_deref()
226 }
227
228 pub fn authenticate_with(
235 &mut self,
236 credentials: Credentials,
237 challenge: Option<&str>,
238 ) -> Result<()> {
239 let line = challenge
240 .map(str::to_string)
241 .or_else(|| self.last_challenge.clone());
242 self.authenticator = match line {
243 Some(line) => Some(Authenticator::from_challenge(&line, credentials.clone())?),
244 None => None,
245 };
246 self.credentials = Some(credentials);
247 Ok(())
248 }
249
250 pub fn with_user_agent(mut self, ua: impl Into<String>) -> Self {
252 self.user_agent = ua.into();
253 self
254 }
255
256 pub fn state(&self) -> SessionState {
258 self.state
259 }
260
261 pub fn peek_next_cseq(&self) -> u32 {
267 self.next_cseq
268 }
269
270 fn record_session_warning(&mut self, w: String) {
271 self.session_warning_total += 1;
272 if self.session_warnings.len() >= MAX_SESSION_WARNINGS {
273 self.session_warnings.remove(0);
274 }
275 self.session_warnings.push(w);
276 }
277
278 #[cfg(test)]
281 pub(crate) fn session_warning_count(&self) -> usize {
282 self.session_warning_total
283 }
284
285 pub fn session_warnings(&self) -> &[String] {
288 &self.session_warnings
289 }
290
291 pub fn has_buffered_input(&self) -> bool {
295 !self.inbound.is_empty()
296 }
297
298 pub fn mark_activity(&mut self, now: Instant) {
303 self.last_activity = Some(now);
304 }
305
306 pub fn poll_timeout(&self) -> Option<Instant> {
311 self.session_id.as_ref()?;
312 let timeout =
313 Duration::from_secs(self.session_timeout.unwrap_or(DEFAULT_SESSION_TIMEOUT_SECS));
314 self.last_activity?
316 .checked_add((timeout / KEEPALIVE_FRACTION_DEN).max(MIN_KEEPALIVE_INTERVAL))
317 }
318
319 pub fn handle_timeout(&mut self, now: Instant) -> Result<Option<Vec<u8>>> {
323 match self.poll_timeout() {
324 Some(deadline) if now >= deadline => {}
325 _ => return Ok(None),
326 }
327 let Some(uri) = self.last_uri.clone() else {
328 return Ok(None);
329 };
330 let bytes = self.get_parameter(&uri, b"")?;
331 self.last_activity = Some(now);
332 Ok(Some(bytes))
333 }
334
335 pub fn session_id(&self) -> Option<&str> {
337 self.session_id.as_deref()
338 }
339
340 pub fn session_timeout(&self) -> Option<u64> {
342 self.session_timeout
343 }
344
345 pub fn negotiated_transport(&self) -> Option<&Transport> {
347 self.negotiated_transport.as_ref()
348 }
349
350 pub fn take_rtp_info(&mut self) -> Vec<RtpInfoEntry> {
353 core::mem::take(&mut self.rtp_info)
354 }
355
356 pub fn take_negotiated_transport(&mut self) -> Option<Transport> {
359 self.negotiated_transport.take()
360 }
361
362 pub fn content_base(&self) -> Option<&str> {
366 self.content_base.as_deref()
367 }
368
369 pub fn redirect_location(&self) -> Option<&str> {
373 self.redirect_location.as_deref()
374 }
375
376 pub fn options(&mut self, uri: &str) -> Result<Vec<u8>> {
380 self.build_request(Method::Options, uri, None, &[])
381 }
382
383 pub fn describe(&mut self, uri: &str) -> Result<Vec<u8>> {
385 self.build_request(
386 Method::Describe,
387 uri,
388 None,
389 &[(headers::ACCEPT, "application/sdp".to_string())],
390 )
391 }
392
393 pub fn setup(&mut self, uri: &str, transport: &Transport) -> Result<Vec<u8>> {
395 self.build_request(
396 Method::Setup,
397 uri,
398 None,
399 &[(headers::TRANSPORT, transport.to_header_value()?)],
400 )
401 }
402
403 pub fn play(&mut self, uri: &str) -> Result<Vec<u8>> {
405 self.build_request(Method::Play, uri, None, &[])
406 }
407
408 pub fn pause(&mut self, uri: &str) -> Result<Vec<u8>> {
410 self.build_request(Method::Pause, uri, None, &[])
411 }
412
413 pub fn teardown(&mut self, uri: &str) -> Result<Vec<u8>> {
415 self.build_request(Method::Teardown, uri, None, &[])
416 }
417
418 pub fn announce(&mut self, uri: &str, sdp: &str) -> Result<Vec<u8>> {
420 self.build_request_with_body(
421 Method::Announce,
422 uri,
423 sdp.as_bytes(),
424 &[(headers::CONTENT_TYPE, "application/sdp".to_string())],
425 )
426 }
427
428 pub fn record(&mut self, uri: &str) -> Result<Vec<u8>> {
430 self.build_request(Method::Record, uri, None, &[])
431 }
432
433 pub fn get_parameter(&mut self, uri: &str, body: &[u8]) -> Result<Vec<u8>> {
436 self.build_request_with_body(Method::GetParameter, uri, body, &[])
437 }
438
439 fn build_request(
440 &mut self,
441 method: Method,
442 uri: &str,
443 _range: Option<&str>,
444 extra: &[(headers::HeaderName, String)],
445 ) -> Result<Vec<u8>> {
446 self.build_request_with_body(method, uri, &[], extra)
447 }
448
449 fn build_request_with_body(
450 &mut self,
451 method: Method,
452 uri: &str,
453 body: &[u8],
454 extra: &[(headers::HeaderName, String)],
455 ) -> Result<Vec<u8>> {
456 client_next_state(self.state, &method)?;
458
459 let cseq = self.next_cseq;
460 let request = self.assemble(method.clone(), uri, cseq, body, extra)?;
461 let bytes = serialize(&Message::from(request.clone()))?;
462 self.next_cseq += 1;
463 self.last_uri = Some(uri.to_string());
464 self.pending.insert(
465 cseq,
466 Pending {
467 method,
468 uri: uri.to_string(),
469 request,
470 auth_retried: false,
471 },
472 );
473 Ok(bytes)
474 }
475
476 fn assemble(
479 &mut self,
480 method: Method,
481 uri: &str,
482 cseq: u32,
483 body: &[u8],
484 extra: &[(headers::HeaderName, String)],
485 ) -> Result<Request<Body>> {
486 let url = rtsp_types::Url::parse(uri)
487 .map_err(|e| Error::TransportParse(format!("invalid request URI {uri:?}: {e}")))?;
488 let mut builder = Request::builder(method.clone(), Version::V1_0)
489 .request_uri(url)
490 .header(headers::CSEQ, cseq.to_string())
491 .header(headers::USER_AGENT, self.user_agent.clone());
492 if let Some(sid) = &self.session_id {
493 builder = builder.header(headers::SESSION, sid.clone());
494 }
495 for (name, value) in extra {
496 builder = builder.header(name.clone(), value.clone());
497 }
498 if let Some(auth) = &mut self.authenticator {
499 let ctx = RequestContext::new(<&str>::from(&method), uri);
500 let value = auth.authorization(&ctx)?;
501 builder = builder.header(headers::AUTHORIZATION, value);
502 }
503 let request = if body.is_empty() {
504 builder.build(Vec::new())
505 } else {
506 builder.build(body.to_vec())
507 };
508 Ok(request)
509 }
510
511 pub fn handle_data(&mut self, data: &[u8]) -> HandleOutcome {
526 let mut events = Vec::new();
527 let error = self.handle_data_into(data, &mut events).err();
528 HandleOutcome { events, error }
529 }
530
531 pub fn handle_data_strict(&mut self, data: &[u8]) -> Result<Vec<ClientEvent>> {
538 self.handle_data(data).into_result()
539 }
540
541 fn handle_data_into(&mut self, data: &[u8], events: &mut Vec<ClientEvent>) -> Result<()> {
542 self.inbound.extend_from_slice(data);
543 if self.inbound.len() > MAX_INBOUND_BYTES {
544 return Err(Error::MessageParse(format!(
545 "inbound buffer of {} bytes exceeds the {MAX_INBOUND_BYTES}-byte maximum \
546 (unterminated header or an unfulfilled Content-Length)",
547 self.inbound.len()
548 )));
549 }
550 let mut pos = 0;
555 let result = self.decode_from(&mut pos, events);
556 self.inbound.drain(..pos);
557 result
558 }
559
560 fn decode_from(&mut self, pos: &mut usize, events: &mut Vec<ClientEvent>) -> Result<()> {
563 loop {
564 let rest = &self.inbound[*pos..];
565 if rest.is_empty() {
566 break;
567 }
568 if rest[0] == MAGIC {
569 match interleaved::InterleavedFrame::parse(rest)? {
571 Some((frame, consumed)) => {
572 events.push(ClientEvent::MediaData {
573 channel: frame.channel,
574 data: frame.payload,
575 });
576 *pos += consumed;
577 }
578 None => break, }
580 continue;
581 }
582
583 if rest.len() < self.skip_until {
586 break;
587 }
588 if crate::framing::head_end(rest, self.scanned)?.is_none() {
589 self.scanned = rest.len();
590 break;
591 }
592 match Message::<Body>::parse(rest) {
593 Ok((message, consumed)) => {
594 *pos += consumed;
595 self.scanned = 0;
596 self.skip_until = 0;
597 self.process_message(message, events)?;
598 }
599 Err(rtsp_types::ParseError::Incomplete(needed)) => {
600 if let Some(more) = needed {
601 self.skip_until = rest.len().saturating_add(more.get());
602 }
603 break;
604 }
605 Err(rtsp_types::ParseError::Error) => {
606 return Err(Error::MessageParse("malformed RTSP message".into()));
607 }
608 }
609 }
610 Ok(())
611 }
612
613 fn process_message(
614 &mut self,
615 message: Message<Body>,
616 events: &mut Vec<ClientEvent>,
617 ) -> Result<()> {
618 match message {
619 Message::Response(response) => {
620 let Some(cseq) = header_value(response.header(&headers::CSEQ))
627 .and_then(|s| s.trim().parse::<u32>().ok())
628 else {
629 return Ok(());
630 };
631 let status = response.status();
632
633 if let Some(challenge) = header_value(response.header(&headers::WWW_AUTHENTICATE))
634 .or_else(|| header_value(response.header(&headers::PROXY_AUTHENTICATE)))
635 {
636 self.last_challenge = Some(challenge.to_string());
637 }
638
639 if status == StatusCode::Unauthorized
641 && let Some(retry) = self.try_auth_retry(cseq, &response)?
642 {
643 events.push(retry);
644 return Ok(());
645 }
646
647 let Some(pending) = self.pending.remove(&cseq) else {
651 return Ok(());
652 };
653
654 if let Some(session_hdr) = header_value(response.header(&headers::SESSION)) {
658 match crate::session_header::SessionHeader::parse_with_warnings(session_hdr) {
659 Ok((parsed, warnings)) => {
660 for w in warnings {
661 self.record_session_warning(w);
662 }
663 self.session_id = Some(parsed.id);
664 if let Some(t) = parsed.timeout {
665 self.session_timeout = Some(t.as_secs());
666 }
667 }
668 Err(e) => {
669 let w = format!("unusable Session header {session_hdr:?}: {e}");
670 self.record_session_warning(w);
671 }
672 }
673 }
674 if pending.method == Method::Setup
676 && let Some(t) = header_value(response.header(&headers::TRANSPORT))
677 {
678 self.negotiated_transport = Some(Transport::parse(t)?);
679 }
680
681 if pending.method == Method::Play && status.is_success() {
682 self.rtp_info = response
683 .typed_header::<headers::RtpInfos>()
684 .ok()
685 .flatten()
686 .and_then(|infos| infos.try_into_v1().ok())
687 .map(|infos| match infos {
688 headers::RtpInfos::V1(list) => list
689 .into_iter()
690 .map(|i| RtpInfoEntry {
691 uri: i.uri.to_string(),
692 seq: i.seq,
693 rtptime: i.rtptime,
694 })
695 .collect(),
696 _ => Vec::new(),
697 })
698 .unwrap_or_default();
699 }
700
701 self.redirect_location = status
702 .is_redirection()
703 .then(|| header_value(response.header(&headers::LOCATION)))
704 .flatten()
705 .map(|v| v.trim().to_string());
706
707 if pending.method == Method::Describe && status.is_success() {
708 self.content_base = header_value(response.header(&headers::CONTENT_BASE))
709 .or_else(|| header_value(response.header(&headers::CONTENT_LOCATION)))
710 .map(|v| v.trim().to_string());
711 }
712
713 if status.is_success() {
715 self.state = client_next_state(self.state, &pending.method)?;
716 if pending.method == Method::Teardown {
718 self.session_id = None;
719 self.session_timeout = None;
720 self.authenticator = None;
721 }
722 } else if status.is_redirection() {
723 self.state = SessionState::Init;
724 }
725 events.push(ClientEvent::Response {
728 cseq,
729 method: pending.method,
730 status,
731 body: response.into_body(),
732 });
733 Ok(())
734 }
735 Message::Data(data) => {
736 events.push(ClientEvent::MediaData {
737 channel: data.channel_id(),
738 data: data.into_body(),
739 });
740 Ok(())
741 }
742 Message::Request(_) => {
743 Ok(())
746 }
747 }
748 }
749
750 fn try_auth_retry(
754 &mut self,
755 cseq: u32,
756 response: &rtsp_types::Response<Body>,
757 ) -> Result<Option<ClientEvent>> {
758 let creds = match &self.credentials {
759 Some(c) => c.clone(),
760 None => return Ok(None),
761 };
762 let (method, uri, already) = match self.pending.get(&cseq) {
764 Some(p) => (p.method.clone(), p.uri.clone(), p.auth_retried),
765 None => return Ok(None),
766 };
767
768 let challenge = header_value(response.header(&headers::WWW_AUTHENTICATE))
769 .ok_or(Error::MissingAuthChallenge)?;
770 let stale = crate::headers_util::challenge_is_stale(challenge);
771
772 self.authenticator = Some(Authenticator::from_challenge(challenge, creds)?);
779 if already && !stale {
785 return Ok(None);
786 }
787
788 let (body, extra) = self.replay_extra(cseq);
794 self.pending.remove(&cseq);
795 let new_cseq = self.next_cseq;
796 let request = self.assemble(method.clone(), &uri, new_cseq, &body, &extra)?;
797 let bytes = serialize(&Message::from(request.clone()))?;
798 self.next_cseq += 1;
799 self.pending.insert(
800 new_cseq,
801 Pending {
802 method: method.clone(),
803 uri,
804 request,
805 auth_retried: true,
806 },
807 );
808 Ok(Some(ClientEvent::AuthRetry {
809 method,
810 cseq: new_cseq,
811 request: bytes,
812 }))
813 }
814
815 fn replay_extra(&self, old_cseq: u32) -> (Vec<u8>, Vec<(headers::HeaderName, String)>) {
821 let Some(p) = self.pending.get(&old_cseq) else {
822 return (Vec::new(), Vec::new());
823 };
824 let hop_by_hop = [
825 headers::CSEQ,
826 headers::SESSION,
827 headers::AUTHORIZATION,
828 headers::USER_AGENT,
829 headers::CONTENT_LENGTH,
830 ];
831 let extra = p
832 .request
833 .headers()
834 .filter(|(name, _)| !hop_by_hop.iter().any(|h| h == *name))
835 .map(|(name, value)| (name.clone(), value.as_str().to_string()))
836 .collect();
837 (p.request.body().clone(), extra)
838 }
839}
840
841fn header_value(h: Option<&headers::HeaderValue>) -> Option<&str> {
843 h.map(|v| v.as_str())
844}
845
846fn serialize(message: &Message<Body>) -> Result<Vec<u8>> {
848 let mut out = Vec::new();
849 message
850 .write(&mut out)
851 .map_err(|e| Error::MessageWrite(e.to_string()))?;
852 Ok(out)
853}
854
855#[cfg(test)]
856mod tests {
857 use super::*;
858
859 #[test]
860 fn play_in_init_bites() {
861 let mut c = ClientSession::new();
862 assert!(matches!(
863 c.play("rtsp://h/s"),
864 Err(crate::error::Error::MethodNotValidInState { .. })
865 ));
866 }
867
868 #[test]
869 fn setup_allowed_in_init() {
870 let mut c = ClientSession::new();
871 let t = Transport::single(crate::transport::TransportSpec::rtp_avp_tcp_interleaved(
872 0, 1,
873 ));
874 assert!(c.setup("rtsp://h/s", &t).is_ok());
875 }
876
877 #[test]
878 fn cseq_increments() {
879 let mut c = ClientSession::new();
880 let a = c.options("rtsp://h/s").unwrap();
881 let b = c.describe("rtsp://h/s").unwrap();
882 assert!(String::from_utf8_lossy(&a).contains("CSeq: 1"));
883 assert!(String::from_utf8_lossy(&b).contains("CSeq: 2"));
884 }
885
886 #[test]
887 fn announce_emits_request_with_sdp_content_type() {
888 let mut c = ClientSession::new();
889 let sdp = "v=0\r\no=- 0 0 IN IP4 0.0.0.0\r\ns=Test\r\n";
890 let bytes = c.announce("rtsp://h/s", sdp).unwrap();
891 let s = String::from_utf8_lossy(&bytes);
892 assert!(s.contains("ANNOUNCE rtsp://h/s"));
893 assert!(s.contains("Content-Type: application/sdp"));
894 assert!(s.contains(sdp));
895 }
896
897 #[test]
898 fn redirect_location_is_taken_from_a_3xx_and_cleared_by_the_next_response() {
899 let mut c = ClientSession::new();
900 c.describe("rtsp://h/s").unwrap();
901 assert_eq!(c.redirect_location(), None);
902 let _ = c.handle_data(b"RTSP/1.0 302 Found\r\nCSeq: 1\r\nLocation: rtsp://other/s\r\n\r\n");
903 assert_eq!(c.redirect_location(), Some("rtsp://other/s"));
904 c.describe("rtsp://other/s").unwrap();
905 let _ = c.handle_data(b"RTSP/1.0 200 OK\r\nCSeq: 2\r\n\r\n");
906 assert_eq!(c.redirect_location(), None);
907 }
908
909 fn wire_401(challenge: &str) -> Vec<u8> {
910 format!("RTSP/1.0 401 Unauthorized\r\nCSeq: 1\r\nWWW-Authenticate: {challenge}\r\n\r\n")
911 .into_bytes()
912 }
913
914 #[test]
915 fn challenge_is_recorded_without_credentials() {
916 let mut c = ClientSession::new();
917 c.describe("rtsp://h/s").unwrap();
918 assert_eq!(c.last_challenge(), None);
919 let events = c
920 .handle_data_strict(&wire_401("Basic realm=\"cam\""))
921 .unwrap();
922 assert!(matches!(
923 events.as_slice(),
924 [ClientEvent::Response {
925 status: StatusCode::Unauthorized,
926 ..
927 }]
928 ));
929 assert_eq!(c.last_challenge(), Some("Basic realm=\"cam\""));
930 }
931
932 #[test]
933 fn authenticate_with_makes_next_request_authorized() {
934 let mut c = ClientSession::new();
935 c.describe("rtsp://h/s").unwrap();
936 c.handle_data_strict(&wire_401("Basic realm=\"cam\""))
937 .unwrap();
938 let before = c.describe("rtsp://h/s").unwrap();
939 assert!(!String::from_utf8_lossy(&before).contains("Authorization"));
940 c.authenticate_with(Credentials::new("u", "p"), None)
941 .unwrap();
942 let after = String::from_utf8_lossy(&c.describe("rtsp://h/s").unwrap()).into_owned();
943 assert!(after.contains("Authorization: Basic dTpw"), "got: {after}");
944 }
945
946 #[test]
947 fn authenticate_with_explicit_challenge_overrides_recorded_one() {
948 let mut c = ClientSession::new();
949 c.authenticate_with(Credentials::new("u", "p"), Some("Basic realm=\"x\""))
950 .unwrap();
951 let req = String::from_utf8_lossy(&c.options("rtsp://h/s").unwrap()).into_owned();
952 assert!(req.contains("Authorization: Basic dTpw"), "got: {req}");
953 }
954
955 #[test]
956 fn a_401_without_a_challenge_cannot_be_answered() {
957 let mut c = ClientSession::new();
958 c.authenticate_with(Credentials::new("u", "p"), Some("Basic realm=\"x\""))
959 .unwrap();
960 c.describe("rtsp://h/s").unwrap();
961 assert_eq!(
962 c.handle_data_strict(b"RTSP/1.0 401 Unauthorized\r\nCSeq: 1\r\n\r\n")
963 .unwrap_err(),
964 Error::MissingAuthChallenge
965 );
966 }
967
968 #[test]
969 fn a_broadcast_auth_failure_keeps_its_source() {
970 assert_eq!(
971 Error::from(broadcast_auth::Error::InvalidBearerToken),
972 Error::Auth(broadcast_auth::Error::InvalidBearerToken)
973 );
974 }
975
976 fn setup_request(c: &mut ClientSession) {
977 let t = Transport::single(crate::transport::TransportSpec::rtp_avp_tcp_interleaved(
978 0, 1,
979 ));
980 c.setup("rtsp://h/s/trackID=1", &t).unwrap();
981 }
982
983 fn feed(c: &mut ClientSession, text: &str) {
984 c.handle_data_strict(text.replace('\n', "\r\n").as_bytes())
985 .unwrap();
986 }
987
988 #[test]
989 fn content_base_is_taken_from_the_describe_response() {
990 let mut c = ClientSession::new();
991 assert_eq!(c.content_base(), None);
992 c.describe("rtsp://h/s").unwrap();
993 feed(
994 &mut c,
995 "RTSP/1.0 200 OK\nCSeq: 1\nContent-Base: rtsp://h/s/\nContent-Location: rtsp://h/loc/\n\n",
996 );
997 assert_eq!(c.content_base(), Some("rtsp://h/s/"));
998 c.describe("rtsp://h/s").unwrap();
999 feed(
1000 &mut c,
1001 "RTSP/1.0 200 OK\nCSeq: 2\nContent-Location: rtsp://h/loc/\n\n",
1002 );
1003 assert_eq!(c.content_base(), Some("rtsp://h/loc/"));
1004 c.describe("rtsp://h/s").unwrap();
1005 feed(&mut c, "RTSP/1.0 200 OK\nCSeq: 3\n\n");
1006 assert_eq!(c.content_base(), None);
1007 }
1008
1009 #[test]
1010 fn take_negotiated_transport_only_returns_the_latest_setup_reply() {
1011 let mut c = ClientSession::new();
1012 setup_request(&mut c);
1013 feed(
1014 &mut c,
1015 "RTSP/1.0 200 OK\nCSeq: 1\nSession: A1\nTransport: RTP/AVP/TCP;unicast;interleaved=0-1\n\n",
1016 );
1017 let first = c
1018 .take_negotiated_transport()
1019 .expect("first reply carries one");
1020 assert_eq!(first.first().and_then(|s| s.interleaved), Some((0, 1)));
1021 assert!(c.take_negotiated_transport().is_none(), "taken once");
1022 setup_request(&mut c);
1023 feed(&mut c, "RTSP/1.0 200 OK\nCSeq: 2\nSession: A1\n\n");
1024 assert!(
1025 c.take_negotiated_transport().is_none(),
1026 "a reply without Transport negotiates nothing"
1027 );
1028 }
1029
1030 #[test]
1031 fn take_rtp_info_returns_the_play_response_entries_once() {
1032 let mut c = ClientSession::new();
1033 setup_request(&mut c);
1034 feed(
1035 &mut c,
1036 "RTSP/1.0 200 OK\nCSeq: 1\nSession: A1\nTransport: RTP/AVP/TCP;unicast;interleaved=0-1\n\n",
1037 );
1038 c.play("rtsp://h/s").unwrap();
1039 feed(
1040 &mut c,
1041 "RTSP/1.0 200 OK\nCSeq: 2\nSession: A1\nRTP-Info: url=rtsp://h/s/t1;seq=7;rtptime=100,url=rtsp://h/s/t2;seq=9;rtptime=4294967295\n\n",
1042 );
1043 let info = c.take_rtp_info();
1044 assert_eq!(info.len(), 2);
1045 assert_eq!(info[0].uri, "rtsp://h/s/t1");
1046 assert_eq!(info[0].seq, Some(7));
1047 assert_eq!(info[0].rtptime, Some(100));
1048 assert_eq!(info[1].rtptime, Some(u32::MAX));
1049 assert!(c.take_rtp_info().is_empty(), "taken once");
1050 }
1051
1052 #[test]
1058 fn unknown_cseq_is_skipped_without_discarding_earlier_events() {
1059 fn wire(s: &str) -> Vec<u8> {
1060 s.replace('\n', "\r\n").into_bytes()
1061 }
1062 let mut c = ClientSession::new();
1063 c.options("rtsp://h/s").unwrap(); c.describe("rtsp://h/s").unwrap(); let mut batch = wire("RTSP/1.0 200 OK\nCSeq: 1\n\n");
1070 batch.extend(wire("RTSP/1.0 200 OK\nCSeq: 99\n\n"));
1071 batch.extend(wire("RTSP/1.0 200 OK\nCSeq: 2\n\n"));
1072
1073 let events = c
1074 .handle_data_strict(&batch)
1075 .expect("an unmatched CSeq must not fail the whole batch");
1076 let cseqs: Vec<u32> = events
1077 .into_iter()
1078 .map(|e| match e {
1079 ClientEvent::Response { cseq, .. } => cseq,
1080 other => panic!("unexpected event: {other:?}"),
1081 })
1082 .collect();
1083 assert_eq!(
1084 cseqs,
1085 vec![1, 2],
1086 "expected both real responses despite the unmatched CSeq 99"
1087 );
1088 }
1089
1090 #[test]
1094 fn many_interleaved_frames_in_one_read_decode_in_order_and_keep_the_tail() {
1095 const FRAMES: usize = 600;
1096 const PAYLOAD: usize = 800;
1097 let mut wire = Vec::new();
1098 for i in 0..FRAMES {
1099 let payload = vec![(i % 251) as u8; PAYLOAD];
1100 wire.extend(
1101 interleaved::InterleavedFrame::slice_to_bytes((i % 2) as u8, &payload).unwrap(),
1102 );
1103 }
1104 let split = wire.len() - 100; let mut c = ClientSession::new();
1106 let first = c.handle_data(&wire[..split]);
1107 assert!(first.error.is_none());
1108 assert_eq!(first.events.len(), FRAMES - 1);
1109 let second = c.handle_data(&wire[split..]);
1110 assert!(second.error.is_none());
1111 assert_eq!(second.events.len(), 1);
1112 for (i, e) in first.events.iter().chain(second.events.iter()).enumerate() {
1113 match e {
1114 ClientEvent::MediaData { channel, data } => {
1115 assert_eq!(*channel as usize, i % 2);
1116 assert_eq!(data.len(), PAYLOAD);
1117 assert!(data.iter().all(|b| *b == (i % 251) as u8));
1118 }
1119 other => panic!("unexpected {other:?}"),
1120 }
1121 }
1122 assert!(!c.has_buffered_input());
1123 }
1124
1125 #[test]
1129 fn inbound_buffer_is_capped_against_an_unterminated_header() {
1130 let mut c = ClientSession::new();
1131 c.options("rtsp://h/s").unwrap();
1132 let chunk = vec![b'A'; 64 * 1024];
1133 let mut last = Ok(Vec::new());
1134 for _ in 0..(MAX_INBOUND_BYTES / chunk.len() + 2) {
1135 last = c.handle_data_strict(&chunk);
1136 if last.is_err() {
1137 break;
1138 }
1139 }
1140 assert!(
1141 matches!(last, Err(crate::error::Error::MessageParse(..))),
1142 "expected the oversized inbound buffer to be rejected, not grown forever"
1143 );
1144 }
1145
1146 #[test]
1147 fn record_fails_from_init_state() {
1148 let mut c = ClientSession::new();
1149 assert!(matches!(
1150 c.record("rtsp://h/s"),
1151 Err(crate::error::Error::MethodNotValidInState { .. })
1152 ));
1153 }
1154
1155 #[test]
1156 fn record_transitions_to_recording_state() {
1157 fn wire(s: &str) -> Vec<u8> {
1159 s.replace('\n', "\r\n").into_bytes()
1160 }
1161 let mut c = ClientSession::new();
1162 let t = Transport::single(crate::transport::TransportSpec::rtp_avp_tcp_interleaved(
1164 0, 1,
1165 ));
1166 c.setup("rtsp://h/s", &t).unwrap();
1167 c.handle_data_strict(&wire(
1168 "RTSP/1.0 200 OK\nCSeq: 1\nSession: 42\nTransport: RTP/AVP/TCP;interleaved=0-1\n\n",
1169 ))
1170 .unwrap();
1171 assert_eq!(c.state(), SessionState::Ready);
1172
1173 c.record("rtsp://h/s").unwrap();
1175 assert_eq!(c.state(), SessionState::Ready);
1176 c.handle_data_strict(&wire("RTSP/1.0 200 OK\nCSeq: 2\nSession: 42\n\n"))
1178 .unwrap();
1179 assert_eq!(c.state(), SessionState::Recording);
1180 }
1181
1182 #[test]
1187 fn auth_retry_replays_original_body_and_content_type() {
1188 fn wire(s: &str) -> Vec<u8> {
1189 s.replace('\n', "\r\n").into_bytes()
1190 }
1191 let mut c = ClientSession::new().with_credentials(Credentials::new("admin", "12345"));
1192 let sdp = "v=0\r\no=- 0 0 IN IP4 0.0.0.0\r\ns=Test\r\n";
1193 let first = c.announce("rtsp://h/s", sdp).unwrap();
1194 assert!(String::from_utf8_lossy(&first).contains("CSeq: 1"));
1195
1196 let events = c
1197 .handle_data_strict(&wire(
1198 "RTSP/1.0 401 Unauthorized\nCSeq: 1\nWWW-Authenticate: Digest realm=\"cam\",nonce=\"abc123\",qop=\"auth\"\n\n",
1199 ))
1200 .unwrap();
1201 let retry = events
1202 .into_iter()
1203 .find_map(|e| match e {
1204 ClientEvent::AuthRetry { request, .. } => Some(request),
1205 _ => None,
1206 })
1207 .expect("expected an AuthRetry event");
1208 let retry = String::from_utf8_lossy(&retry);
1209
1210 assert!(retry.contains("ANNOUNCE rtsp://h/s"), "{retry}");
1211 assert!(retry.contains("Authorization: Digest "), "{retry}");
1212 assert!(
1213 retry.contains("Content-Type: application/sdp"),
1214 "Content-Type dropped on auth retry: {retry}"
1215 );
1216 assert!(
1217 retry.contains(sdp),
1218 "SDP body dropped on auth retry: {retry}"
1219 );
1220 let expected_len = format!("Content-Length: {}", sdp.len());
1221 assert!(
1222 retry.contains(&expected_len),
1223 "expected {expected_len:?} in: {retry}"
1224 );
1225 }
1226
1227 #[test]
1236 fn nonce_rotation_without_stale_is_picked_up_on_the_first_retry() {
1237 fn wire(s: &str) -> Vec<u8> {
1238 s.replace('\n', "\r\n").into_bytes()
1239 }
1240 let mut c = ClientSession::new().with_credentials(Credentials::new("admin", "12345"));
1241
1242 c.options("rtsp://h/s").unwrap(); let events = c
1245 .handle_data_strict(&wire(
1246 "RTSP/1.0 401 Unauthorized\nCSeq: 1\nWWW-Authenticate: Digest realm=\"cam\",nonce=\"nonce-1\",qop=\"auth\"\n\n",
1247 ))
1248 .unwrap();
1249 assert!(
1250 events
1251 .iter()
1252 .any(|e| matches!(e, ClientEvent::AuthRetry { cseq: 2, .. })),
1253 "{events:?}"
1254 );
1255 c.handle_data_strict(&wire("RTSP/1.0 200 OK\nCSeq: 2\n\n"))
1256 .unwrap();
1257
1258 c.options("rtsp://h/s").unwrap(); let events = c
1262 .handle_data_strict(&wire(
1263 "RTSP/1.0 401 Unauthorized\nCSeq: 3\nWWW-Authenticate: Digest realm=\"cam\",nonce=\"nonce-2\",qop=\"auth\"\n\n",
1264 ))
1265 .unwrap();
1266 let retry = events
1267 .into_iter()
1268 .find_map(|e| match e {
1269 ClientEvent::AuthRetry {
1270 cseq: 4, request, ..
1271 } => Some(request),
1272 _ => None,
1273 })
1274 .expect("expected a retry (CSeq 4), not a give-up");
1275 let retry = String::from_utf8_lossy(&retry);
1276 assert!(
1277 retry.contains("nonce=\"nonce-2\""),
1278 "retry signed with the stale nonce instead of the rotated one: {retry}"
1279 );
1280 }
1281
1282 fn established(timeout: Option<u64>) -> ClientSession {
1283 let mut c = ClientSession::new();
1284 let _ = c
1285 .setup(
1286 "rtsp://h/s",
1287 &Transport::single(crate::transport::TransportSpec::rtp_avp_tcp_interleaved(
1288 0, 1,
1289 )),
1290 )
1291 .unwrap();
1292 let sess = match timeout {
1293 Some(t) => format!("abc;timeout={t}"),
1294 None => "abc".into(),
1295 };
1296 let resp = format!(
1297 "RTSP/1.0 200 OK\r\nCSeq: 1\r\nSession: {sess}\r\nTransport: RTP/AVP/TCP;unicast;interleaved=0-1\r\n\r\n"
1298 );
1299 c.handle_data_strict(resp.as_bytes()).unwrap();
1300 c
1301 }
1302
1303 #[test]
1304 fn the_keepalive_interval_is_floored_and_fires_at_most_once_per_interval() {
1305 let t0 = Instant::now();
1307 let mut c = established(Some(1));
1308 c.mark_activity(t0);
1309 assert_eq!(c.poll_timeout(), Some(t0 + MIN_KEEPALIVE_INTERVAL));
1310 assert!(
1311 c.handle_timeout(t0 + Duration::from_millis(500))
1312 .unwrap()
1313 .is_none()
1314 );
1315 let mut sent = 0;
1317 let tick = t0 + MIN_KEEPALIVE_INTERVAL;
1318 for _ in 0..1000 {
1319 if c.handle_timeout(tick).unwrap().is_some() {
1320 sent += 1;
1321 }
1322 }
1323 assert_eq!(sent, 1, "keepalive must not busy-loop");
1324 }
1325
1326 #[test]
1327 fn a_zero_timeout_is_a_warning_and_the_default_not_a_busy_loop() {
1328 let t0 = Instant::now();
1329 let mut c = ClientSession::new();
1330 let _ = c
1331 .setup(
1332 "rtsp://h/s",
1333 &Transport::single(crate::transport::TransportSpec::rtp_avp_tcp_interleaved(
1334 0, 1,
1335 )),
1336 )
1337 .unwrap();
1338 c.handle_data_strict(
1339 b"RTSP/1.0 200 OK\r\nCSeq: 1\r\nSession: abc;timeout=0\r\nTransport: RTP/AVP/TCP;unicast;interleaved=0-1\r\n\r\n",
1340 )
1341 .unwrap();
1342 assert_eq!(c.session_warnings().len(), 1, "{:?}", c.session_warnings());
1343 assert!(c.session_warnings()[0].contains("timeout"));
1344 c.mark_activity(t0);
1345 assert_eq!(c.poll_timeout(), Some(t0 + Duration::from_secs(30)));
1346 }
1347
1348 #[test]
1351 fn odd_received_session_ids_are_echoed_verbatim() {
1352 for (hdr, id) in [
1353 ("\"weird\"", "\"weird\""),
1354 ("a b;timeout=30", "a b"),
1355 ("abc,def", "abc,def"),
1356 ("ab\"c", "ab\"c"),
1357 ] {
1358 let mut c = ClientSession::new();
1359 let _ = c
1360 .setup(
1361 "rtsp://h/s",
1362 &Transport::single(crate::transport::TransportSpec::rtp_avp_tcp_interleaved(
1363 0, 1,
1364 )),
1365 )
1366 .unwrap();
1367 let resp = format!(
1368 "RTSP/1.0 200 OK\r\nCSeq: 1\r\nSession: {hdr}\r\nTransport: RTP/AVP/TCP;unicast;interleaved=0-1\r\n\r\n"
1369 );
1370 c.handle_data_strict(resp.as_bytes()).unwrap();
1371 assert_eq!(c.session_id(), Some(id), "{hdr}");
1372 let play = String::from_utf8(c.play("rtsp://h/s").unwrap()).unwrap();
1373 assert!(
1374 play.contains(&format!("Session: {id}\r\n")),
1375 "{hdr}: {play}"
1376 );
1377 }
1378 }
1379
1380 #[test]
1381 fn session_warnings_are_capped_but_counted() {
1382 let mut c = ClientSession::new();
1383 for i in 1..=(MAX_SESSION_WARNINGS as u32 + 10) {
1384 let _ = c.options("rtsp://h/s").unwrap();
1385 c.handle_data_strict(
1386 format!("RTSP/1.0 200 OK\r\nCSeq: {i}\r\nSession: abc;timeout=x\r\n\r\n")
1387 .as_bytes(),
1388 )
1389 .unwrap();
1390 }
1391 assert_eq!(c.session_warnings().len(), MAX_SESSION_WARNINGS);
1392 assert_eq!(c.session_warning_count(), MAX_SESSION_WARNINGS + 10);
1393 }
1394
1395 #[test]
1396 fn an_unusable_session_header_is_observable_not_silent() {
1397 let mut c = ClientSession::new();
1398 let _ = c.options("rtsp://h/s").unwrap();
1399 c.handle_data_strict(b"RTSP/1.0 200 OK\r\nCSeq: 1\r\nSession: ;timeout=5\r\n\r\n")
1400 .unwrap();
1401 assert!(c.session_id().is_none());
1402 assert_eq!(c.session_warnings().len(), 1);
1403 }
1404
1405 #[test]
1406 fn keepalive_is_due_at_half_the_session_timeout() {
1407 let t0 = Instant::now();
1408 let mut c = established(Some(20));
1409 assert_eq!(c.poll_timeout(), None, "no activity recorded yet");
1410 c.mark_activity(t0);
1411 assert_eq!(c.poll_timeout(), Some(t0 + Duration::from_secs(10)));
1412 assert!(
1413 c.handle_timeout(t0 + Duration::from_secs(9))
1414 .unwrap()
1415 .is_none()
1416 );
1417 let req = c
1418 .handle_timeout(t0 + Duration::from_secs(10))
1419 .unwrap()
1420 .expect("keepalive due");
1421 let text = String::from_utf8(req).unwrap();
1422 assert!(
1423 text.starts_with("GET_PARAMETER rtsp://h/s RTSP/1.0"),
1424 "{text}"
1425 );
1426 assert!(text.contains("Session: abc"), "{text}");
1427 assert_eq!(
1429 c.poll_timeout(),
1430 Some(t0 + Duration::from_secs(10) + Duration::from_secs(10))
1431 );
1432 }
1433
1434 #[test]
1435 fn keepalive_uses_the_rfc_default_timeout_when_none_was_declared() {
1436 let t0 = Instant::now();
1437 let mut c = established(None);
1438 c.mark_activity(t0);
1439 assert_eq!(c.poll_timeout(), Some(t0 + Duration::from_secs(30))); }
1441
1442 #[test]
1443 fn no_keepalive_before_setup_or_after_teardown() {
1444 let t0 = Instant::now();
1445 let mut c = ClientSession::new();
1446 c.mark_activity(t0);
1447 assert_eq!(c.poll_timeout(), None);
1448 assert!(
1449 c.handle_timeout(t0 + Duration::from_secs(3600))
1450 .unwrap()
1451 .is_none()
1452 );
1453 }
1454
1455 #[test]
1456 fn head_cap_holds_for_a_70_kib_run_of_a_and_for_9000_header_lines() {
1457 let mut c = ClientSession::new();
1458 assert!(matches!(
1459 c.handle_data_strict(&vec![b'A'; 70 * 1024]),
1460 Err(Error::MessageParse(_))
1461 ));
1462 let mut c = ClientSession::new();
1463 let mut junk = b"RTSP/1.0 200 OK\r\n".to_vec();
1464 junk.extend(b"X-A: b\r\n".repeat(9000));
1465 assert!(matches!(
1466 c.handle_data_strict(&junk),
1467 Err(Error::MessageParse(_))
1468 ));
1469 }
1470
1471 #[test]
1472 fn a_response_fed_one_byte_at_a_time_is_still_decoded() {
1473 let mut c = ClientSession::new();
1474 let _ = c.options("rtsp://h/s").unwrap();
1475 let resp = b"RTSP/1.0 200 OK\r\nCSeq: 1\r\nPublic: OPTIONS\r\n\r\n";
1476 let mut got = 0;
1477 for b in resp {
1478 got += c.handle_data_strict(&[*b]).unwrap().len();
1479 }
1480 assert_eq!(got, 1);
1481 }
1482
1483 #[test]
1484 fn an_unterminated_header_over_the_head_cap_is_rejected() {
1485 let mut c = ClientSession::new();
1486 let mut junk = b"RTSP/1.0 200 OK\r\nX-Pad: ".to_vec();
1487 junk.extend(std::iter::repeat_n(b'a', 70 * 1024)); let err = c
1489 .handle_data_strict(&junk)
1490 .expect_err("header phase is capped at 64 KiB");
1491 assert!(matches!(err, Error::MessageParse(_)), "{err:?}");
1492 }
1493
1494 #[test]
1495 fn stale_quoted_rechallenge_refreshes_nonce_after_a_prior_retry() {
1496 fn wire(s: &str) -> Vec<u8> {
1497 s.replace('\n', "\r\n").into_bytes()
1498 }
1499 let mut c = ClientSession::new().with_credentials(Credentials::new("admin", "12345"));
1500 c.options("rtsp://h/s").unwrap(); c.handle_data_strict(&wire(
1504 "RTSP/1.0 401 Unauthorized\nCSeq: 1\nWWW-Authenticate: Digest realm=\"cam\",nonce=\"nonce-1\",qop=\"auth\"\n\n",
1505 )).unwrap();
1506
1507 let events = c
1510 .handle_data_strict(&wire(
1511 "RTSP/1.0 401 Unauthorized\nCSeq: 2\nWWW-Authenticate: Digest realm=\"cam\",nonce=\"nonce-2\",qop=\"auth\",stale=\"True\"\n\n",
1512 ))
1513 .unwrap();
1514 let retry = events
1515 .into_iter()
1516 .find_map(|e| match e {
1517 ClientEvent::AuthRetry {
1518 cseq: 3, request, ..
1519 } => Some(request),
1520 _ => None,
1521 })
1522 .expect("a quoted stale=true re-challenge must trigger a retry");
1523 let retry = String::from_utf8_lossy(&retry);
1524 assert!(
1525 retry.contains("nonce=\"nonce-2\""),
1526 "quoted stale=\"True\" was not detected: {retry}"
1527 );
1528 }
1529
1530 #[test]
1534 fn client_session_debug_does_not_leak_embedded_credentials_secret() {
1535 let c = ClientSession::new()
1536 .with_credentials(Credentials::new("admin", "extremely-secret-password"));
1537 let debug = format!("{c:?}");
1538 assert!(
1539 !debug.contains("extremely-secret-password"),
1540 "leaked via ClientSession Debug: {debug}"
1541 );
1542 assert!(debug.contains("***"), "expected redaction marker: {debug}");
1543 }
1544}