1use broadcast_common::Parse;
64use broadcast_common::error::BufferTooShort;
65
66use crate::RtmpError;
67use crate::amf0::{Amf0Value, Command};
68use crate::chunk::{ChunkAssembler, ChunkWriter, DEFAULT_MAX_IN_PROGRESS_BYTES, Message};
69use crate::flv::{FlvTagWriter, unpack_aggregate};
70use crate::handshake::Handshake;
71use crate::message::{LimitType, ProtocolControl, UserControl, msg_type};
72use alloc::format;
73use alloc::string::{String, ToString};
74use alloc::vec;
75use alloc::vec::Vec;
76
77type Result<T> = core::result::Result<T, RtmpError>;
78
79pub const DEFAULT_CHUNK_SIZE: u32 = 4096;
85pub const DEFAULT_WINDOW_ACK_SIZE: u32 = 2_500_000;
88pub const DEFAULT_PEER_BANDWIDTH: u32 = 2_500_000;
90
91const FIRST_STREAM_ID: u32 = 1;
95
96const COMMAND_CHUNK_STREAM_ID: u32 = 3;
100
101const MAX_FAILED_PUBLISH_ATTEMPTS: u32 = 3;
106
107const FMS_VERSION: &str = "FMS/3,0,1,123";
113const CAPABILITIES: f64 = 31.0;
116
117#[non_exhaustive]
123#[derive(Clone)]
124#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
125pub struct ServerConfig {
126 pub chunk_size: u32,
128 pub window_ack_size: u32,
132 pub peer_bandwidth: u32,
134 pub expected_stream_key: Option<String>,
143 pub max_in_progress_bytes: usize,
149}
150
151impl core::fmt::Debug for ServerConfig {
154 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
155 f.debug_struct("ServerConfig")
156 .field("chunk_size", &self.chunk_size)
157 .field("window_ack_size", &self.window_ack_size)
158 .field("peer_bandwidth", &self.peer_bandwidth)
159 .field(
160 "expected_stream_key",
161 &self.expected_stream_key.as_ref().map(|_| "<redacted>"),
162 )
163 .field("max_in_progress_bytes", &self.max_in_progress_bytes)
164 .finish()
165 }
166}
167
168impl Default for ServerConfig {
169 fn default() -> Self {
170 Self {
171 chunk_size: DEFAULT_CHUNK_SIZE,
172 window_ack_size: DEFAULT_WINDOW_ACK_SIZE,
173 peer_bandwidth: DEFAULT_PEER_BANDWIDTH,
174 expected_stream_key: None,
175 max_in_progress_bytes: DEFAULT_MAX_IN_PROGRESS_BYTES,
176 }
177 }
178}
179
180impl ServerConfig {
181 #[must_use]
186 pub fn with_expected_stream_key(mut self, expected_stream_key: Option<String>) -> Self {
187 self.expected_stream_key = expected_stream_key;
188 self
189 }
190
191 #[must_use]
193 pub fn with_chunk_size(mut self, chunk_size: u32) -> Self {
194 self.chunk_size = chunk_size;
195 self
196 }
197
198 #[must_use]
200 pub fn with_max_in_progress_bytes(mut self, max_in_progress_bytes: usize) -> Self {
201 self.max_in_progress_bytes = max_in_progress_bytes;
202 self
203 }
204}
205
206#[non_exhaustive]
208#[derive(Clone, PartialEq)]
209#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
210pub enum ServerEvent {
211 Connected {
213 app: String,
215 },
216 Publish {
219 app: String,
221 stream_key: String,
223 stream_id: u32,
226 },
227 Media {
233 flv: Vec<u8>,
236 },
237 Eof,
239 Unsupported {
247 message_type_id: u8,
249 },
250}
251
252impl core::fmt::Debug for ServerEvent {
256 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
257 match self {
258 ServerEvent::Connected { app } => {
259 f.debug_struct("Connected").field("app", app).finish()
260 }
261 ServerEvent::Publish { app, stream_id, .. } => f
262 .debug_struct("Publish")
263 .field("app", app)
264 .field("stream_key", &"<redacted>")
265 .field("stream_id", stream_id)
266 .finish(),
267 ServerEvent::Media { flv } => f
268 .debug_struct("Media")
269 .field("flv_len", &flv.len())
270 .finish(),
271 ServerEvent::Eof => f.write_str("Eof"),
272 ServerEvent::Unsupported { message_type_id } => f
273 .debug_struct("Unsupported")
274 .field("message_type_id", message_type_id)
275 .finish(),
276 }
277 }
278}
279
280#[derive(Debug, Clone, Copy, PartialEq, Eq)]
283enum State {
284 Init,
286 Connected,
289 Publishing,
292 Closed,
294}
295
296#[derive(Debug)]
301pub struct ServerSession {
302 config: ServerConfig,
303 handshake: Handshake,
304 handshake_buf: Vec<u8>,
308 assembler: ChunkAssembler,
309 writer: ChunkWriter,
310 state: State,
311 app: Option<String>,
312 next_stream_id: u32,
313 created_stream_id: Option<u32>,
318 ack_threshold: u32,
325 peer_bandwidth: Option<u32>,
329 bytes_received: u64,
331 bytes_acked: u64,
333 flv: FlvTagWriter,
336 failed_publish_attempts: u32,
340}
341
342fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
349 if a.len() != b.len() {
350 return false;
351 }
352 bool::from(subtle::ConstantTimeEq::ct_eq(a, b))
353}
354
355impl ServerSession {
356 #[must_use]
358 pub fn new(config: ServerConfig) -> Self {
359 let ack_threshold = config.window_ack_size;
360 let max_in_progress_bytes = config.max_in_progress_bytes;
361 Self {
362 config,
363 handshake: Handshake::new(),
364 handshake_buf: Vec::new(),
365 assembler: ChunkAssembler::new().with_max_in_progress_bytes(max_in_progress_bytes),
366 writer: ChunkWriter::new(),
367 state: State::Init,
368 app: None,
369 next_stream_id: FIRST_STREAM_ID,
370 created_stream_id: None,
371 ack_threshold,
372 peer_bandwidth: None,
373 bytes_received: 0,
374 bytes_acked: 0,
375 flv: FlvTagWriter::default(),
376 failed_publish_attempts: 0,
377 }
378 }
379
380 #[must_use]
382 pub fn with_defaults() -> Self {
383 Self::new(ServerConfig::default())
384 }
385
386 pub fn handle_data(&mut self, input: &[u8]) -> Result<(Vec<u8>, Vec<ServerEvent>)> {
400 let mut out = Vec::new();
401 let mut events = Vec::new();
402
403 let chunk_input = match self.drive_handshake(input, &mut out)? {
404 Some(bytes) => bytes,
405 None => return Ok((out, events)),
406 };
407
408 self.bytes_received = self.bytes_received.saturating_add(chunk_input.len() as u64);
409
410 self.assembler.feed(&chunk_input);
421 while let Some(msg) = self.assembler.next_message()? {
422 self.dispatch_message(&msg, &mut out, &mut events)?;
423 }
424
425 self.maybe_ack(&mut out);
426
427 Ok((out, events))
428 }
429
430 fn drive_handshake<'a>(
436 &mut self,
437 input: &'a [u8],
438 out: &mut Vec<u8>,
439 ) -> Result<Option<alloc::borrow::Cow<'a, [u8]>>> {
440 if self.handshake.is_done() {
441 return Ok(Some(alloc::borrow::Cow::Borrowed(input)));
445 }
446
447 self.handshake_buf.extend_from_slice(input);
448 loop {
449 match self.handshake.read(&self.handshake_buf) {
450 Ok((reply, consumed, done)) => {
451 out.extend_from_slice(&reply);
452 self.handshake_buf.drain(..consumed);
453 if done {
454 break;
455 }
456 }
457 Err(RtmpError::BufferTooShort(..)) => break,
458 Err(e) => return Err(e),
459 }
460 }
461
462 if self.handshake.is_done() {
463 Ok(Some(alloc::borrow::Cow::Owned(core::mem::take(
464 &mut self.handshake_buf,
465 ))))
466 } else {
467 Ok(None)
468 }
469 }
470
471 fn maybe_ack(&mut self, out: &mut Vec<u8>) {
475 let threshold = u64::from(self.ack_threshold.max(1));
476 if self.bytes_received.saturating_sub(self.bytes_acked) >= threshold {
477 self.bytes_acked = self.bytes_received;
478 let seq = self.bytes_received as u32;
479 let ack_msg = ProtocolControl::Acknowledgement(seq).to_message();
480 out.extend_from_slice(
481 &self
482 .writer
483 .write(&ack_msg)
484 .expect("an Acknowledgement control message (4 bytes) never exceeds the 24-bit message_length field"),
485 );
486 }
487 }
488
489 fn dispatch_message(
491 &mut self,
492 msg: &Message,
493 out: &mut Vec<u8>,
494 events: &mut Vec<ServerEvent>,
495 ) -> Result<()> {
496 if let Some(pc) = ProtocolControl::from_message(msg)? {
497 self.handle_protocol_control(pc);
498 return Ok(());
499 }
500
501 match msg.message_type_id {
502 msg_type::USER_CONTROL => {
503 let _ = UserControl::parse(&msg.payload);
508 Ok(())
509 }
510 msg_type::COMMAND_AMF0 => {
511 let command = Command::parse(&msg.payload)?;
512 self.handle_command(&command, msg, out, events)
513 }
514 msg_type::COMMAND_AMF3 => {
521 let body =
522 msg.payload
523 .get(1..)
524 .ok_or(RtmpError::BufferTooShort(BufferTooShort {
525 need: 1,
526 have: msg.payload.len(),
527 what: "AMF3 command encoding marker byte",
528 }))?;
529 let command = Command::parse(body)?;
530 self.handle_command(&command, msg, out, events)
531 }
532 msg_type::AUDIO | msg_type::VIDEO | msg_type::DATA_AMF0 => self
533 .emit_media_if_publishing(msg.message_type_id, msg.timestamp, &msg.payload, events),
534 msg_type::AGGREGATE => self.deliver_aggregate(msg, events),
541 other => {
547 events.push(ServerEvent::Unsupported {
548 message_type_id: other,
549 });
550 Ok(())
551 }
552 }
553 }
554
555 fn handle_protocol_control(&mut self, pc: ProtocolControl) {
559 match pc {
560 ProtocolControl::SetChunkSize(n) => self.assembler.set_chunk_size(n),
561 ProtocolControl::WindowAckSize(w) => self.ack_threshold = w,
562 ProtocolControl::SetPeerBandwidth {
566 ack_window_size, ..
567 } => self.peer_bandwidth = Some(ack_window_size),
568 ProtocolControl::Abort { chunk_stream_id } => self.assembler.abort(chunk_stream_id),
570 ProtocolControl::Acknowledgement(_) => {}
571 }
572 }
573
574 fn handle_command(
576 &mut self,
577 command: &Command,
578 msg: &Message,
579 out: &mut Vec<u8>,
580 events: &mut Vec<ServerEvent>,
581 ) -> Result<()> {
582 match command.name.as_str() {
583 "connect" => self.handle_connect(command, msg, out, events),
584 "releaseStream" | "FCPublish" => {
585 self.reply_result(command, msg, vec![Amf0Value::Undefined], out)
586 }
587 "createStream" => self.handle_create_stream(command, msg, out),
588 "publish" => self.handle_publish(command, msg, out, events),
589 "deleteStream" | "FCUnpublish" => {
590 self.state = State::Closed;
591 events.push(ServerEvent::Eof);
592 Ok(())
593 }
594 _ => Ok(()),
597 }
598 }
599
600 fn handle_connect(
614 &mut self,
615 command: &Command,
616 msg: &Message,
617 out: &mut Vec<u8>,
618 events: &mut Vec<ServerEvent>,
619 ) -> Result<()> {
620 if self.state == State::Closed {
621 return Err(RtmpError::UnexpectedState {
622 what: "connect received after the session was closed",
623 });
624 }
625 if self.state == State::Publishing {
626 return Err(RtmpError::UnexpectedState {
627 what: "connect received while publishing",
628 });
629 }
630
631 let Some(Amf0Value::Object(pairs)) = command.arguments.first() else {
632 return Err(RtmpError::Malformed {
633 what: "connect command object / app",
634 });
635 };
636 let Some(app) = pairs.iter().find_map(|(k, v)| {
637 if k == "app" {
638 match v {
639 Amf0Value::String(s) => Some(s.clone()),
640 _ => None,
641 }
642 } else {
643 None
644 }
645 }) else {
646 return Err(RtmpError::Malformed {
647 what: "connect command object / app",
648 });
649 };
650
651 self.app = Some(app.clone());
652 self.state = State::Connected;
653
654 let window_ack = ProtocolControl::WindowAckSize(self.config.window_ack_size).to_message();
655 out.extend_from_slice(&self.writer.write(&window_ack)?);
656
657 let peer_bandwidth = ProtocolControl::SetPeerBandwidth {
658 ack_window_size: self.config.peer_bandwidth,
659 limit_type: LimitType::Dynamic,
660 }
661 .to_message();
662 out.extend_from_slice(&self.writer.write(&peer_bandwidth)?);
663
664 let set_chunk_size =
665 ProtocolControl::SetChunkSize(self.config.chunk_size).try_to_message()?;
666 out.extend_from_slice(&self.writer.write(&set_chunk_size)?);
667 self.writer.set_chunk_size(self.config.chunk_size);
668
669 let result = Command {
670 name: "_result".to_string(),
671 transaction_id: command.transaction_id,
672 arguments: vec![
673 Amf0Value::Object(vec![
674 (
675 "fmsVer".to_string(),
676 Amf0Value::String(FMS_VERSION.to_string()),
677 ),
678 ("capabilities".to_string(), Amf0Value::Number(CAPABILITIES)),
679 ]),
680 Amf0Value::Object(vec![
681 ("level".to_string(), Amf0Value::String("status".to_string())),
682 (
683 "code".to_string(),
684 Amf0Value::String("NetConnection.Connect.Success".to_string()),
685 ),
686 (
687 "description".to_string(),
688 Amf0Value::String("Connection succeeded.".to_string()),
689 ),
690 ]),
691 ],
692 };
693 out.extend_from_slice(&self.writer.write(&self.command_message(msg, &result)?)?);
694
695 events.push(ServerEvent::Connected { app });
696 Ok(())
697 }
698
699 fn handle_create_stream(
707 &mut self,
708 command: &Command,
709 msg: &Message,
710 out: &mut Vec<u8>,
711 ) -> Result<()> {
712 if self.state != State::Connected {
713 return Err(RtmpError::UnexpectedState {
714 what: "createStream received before a successful connect (or after the session was closed)",
715 });
716 }
717
718 let stream_id = self.next_stream_id;
719 self.next_stream_id = self.next_stream_id.saturating_add(1);
720 self.created_stream_id = Some(stream_id);
721
722 let result = Command {
723 name: "_result".to_string(),
724 transaction_id: command.transaction_id,
725 arguments: vec![Amf0Value::Null, Amf0Value::Number(f64::from(stream_id))],
726 };
727 out.extend_from_slice(&self.writer.write(&self.command_message(msg, &result)?)?);
728 Ok(())
729 }
730
731 fn handle_publish(
745 &mut self,
746 command: &Command,
747 msg: &Message,
748 out: &mut Vec<u8>,
749 events: &mut Vec<ServerEvent>,
750 ) -> Result<()> {
751 if self.state != State::Connected || self.created_stream_id.is_none() {
752 return Err(RtmpError::UnexpectedState {
753 what: "publish received before a successful connect+createStream (or after the session was closed)",
754 });
755 }
756 if self.failed_publish_attempts >= MAX_FAILED_PUBLISH_ATTEMPTS {
757 self.state = State::Closed;
758 return Err(RtmpError::UnexpectedState {
759 what: "publish rejected too many times on this connection (stream key mismatch); session closed",
760 });
761 }
762 let app = self
763 .app
764 .clone()
765 .expect("state == Connected implies app was captured by connect");
766
767 let stream_key = match command.arguments.get(1) {
768 Some(Amf0Value::String(s)) => s.clone(),
769 _ => {
770 return Err(RtmpError::Malformed {
771 what: "publish command missing its publishing-name (string) argument",
772 });
773 }
774 };
775 let stream_id = msg.message_stream_id;
776
777 if let Some(expected) = &self.config.expected_stream_key
778 && !constant_time_eq(expected.as_bytes(), stream_key.as_bytes())
779 {
780 self.failed_publish_attempts += 1;
781 let on_status = Command {
782 name: "onStatus".to_string(),
783 transaction_id: 0.0,
784 arguments: vec![
785 Amf0Value::Null,
786 Amf0Value::Object(vec![
787 ("level".to_string(), Amf0Value::String("error".to_string())),
788 (
789 "code".to_string(),
790 Amf0Value::String("NetStream.Publish.BadName".to_string()),
791 ),
792 (
793 "description".to_string(),
794 Amf0Value::String("Stream key mismatch.".to_string()),
795 ),
796 ]),
797 ],
798 };
799 out.extend_from_slice(&self.writer.write(&self.command_message(msg, &on_status)?)?);
800 return Ok(());
802 }
803
804 let stream_begin = UserControl::StreamBegin(stream_id).to_message();
805 out.extend_from_slice(&self.writer.write(&stream_begin)?);
806
807 let on_status = Command {
808 name: "onStatus".to_string(),
809 transaction_id: 0.0,
810 arguments: vec![
811 Amf0Value::Null,
812 Amf0Value::Object(vec![
813 ("level".to_string(), Amf0Value::String("status".to_string())),
814 (
815 "code".to_string(),
816 Amf0Value::String("NetStream.Publish.Start".to_string()),
817 ),
818 (
819 "description".to_string(),
820 Amf0Value::String(format!("{stream_key} is now published.")),
821 ),
822 ]),
823 ],
824 };
825 out.extend_from_slice(&self.writer.write(&self.command_message(msg, &on_status)?)?);
826
827 self.state = State::Publishing;
828 events.push(ServerEvent::Publish {
829 app,
830 stream_key,
831 stream_id,
832 });
833 Ok(())
834 }
835
836 fn reply_result(
840 &mut self,
841 command: &Command,
842 msg: &Message,
843 arguments: Vec<Amf0Value>,
844 out: &mut Vec<u8>,
845 ) -> Result<()> {
846 let result = Command {
847 name: "_result".to_string(),
848 transaction_id: command.transaction_id,
849 arguments,
850 };
851 out.extend_from_slice(&self.writer.write(&self.command_message(msg, &result)?)?);
852 Ok(())
853 }
854
855 fn command_message(&self, request: &Message, command: &Command) -> Result<Message> {
859 Ok(Message {
860 chunk_stream_id: COMMAND_CHUNK_STREAM_ID,
861 timestamp: 0,
862 message_type_id: msg_type::COMMAND_AMF0,
863 message_stream_id: request.message_stream_id,
864 payload: command.to_body()?,
865 })
866 }
867
868 fn emit_media_if_publishing(
873 &mut self,
874 tag_type: u8,
875 timestamp: u32,
876 payload: &[u8],
877 events: &mut Vec<ServerEvent>,
878 ) -> Result<()> {
879 if self.state != State::Publishing {
880 return Ok(());
881 }
882
883 let flv = self.flv.tag(tag_type, timestamp, payload)?;
884 events.push(ServerEvent::Media { flv });
885 Ok(())
886 }
887
888 fn deliver_aggregate(&mut self, msg: &Message, events: &mut Vec<ServerEvent>) -> Result<()> {
898 unpack_aggregate(msg, |tag_type, timestamp, payload| {
899 self.emit_media_if_publishing(tag_type, timestamp, payload, events)
900 })
901 }
902}
903
904#[cfg(test)]
905mod tests {
906 use super::*;
907 use crate::flv::{FLV_HEADER_LEN, FLV_PREV_TAG_SIZE_LEN, FLV_TAG_HEADER_LEN, FlvHeader};
908 use crate::handshake::{HANDSHAKE_PACKET_LEN, RTMP_VERSION};
909 use crate::message::CONTROL_CHUNK_STREAM_ID as CTRL_CSID;
910 use broadcast_common::Serialize;
911
912 const CLIENT_CSID: u32 = 3;
915
916 fn build_c0_c1() -> Vec<u8> {
917 let mut v = vec![0u8; 1 + HANDSHAKE_PACKET_LEN];
918 v[0] = RTMP_VERSION;
919 v
920 }
921
922 fn build_c2() -> Vec<u8> {
923 vec![0u8; HANDSHAKE_PACKET_LEN]
924 }
925
926 fn command_message(
927 csid: u32,
928 stream_id: u32,
929 name: &str,
930 txn: f64,
931 args: Vec<Amf0Value>,
932 ) -> Message {
933 let body = Command {
934 name: name.to_string(),
935 transaction_id: txn,
936 arguments: args,
937 }
938 .to_body()
939 .unwrap();
940 Message {
941 chunk_stream_id: csid,
942 timestamp: 0,
943 message_type_id: msg_type::COMMAND_AMF0,
944 message_stream_id: stream_id,
945 payload: body,
946 }
947 }
948
949 fn connect_bytes(app: &str) -> Vec<u8> {
950 let args = vec![Amf0Value::Object(vec![
951 ("app".to_string(), Amf0Value::String(app.to_string())),
952 (
953 "type".to_string(),
954 Amf0Value::String("nonprivate".to_string()),
955 ),
956 ])];
957 let msg = command_message(CLIENT_CSID, 0, "connect", 1.0, args);
958 ChunkWriter::new().write(&msg).unwrap()
959 }
960
961 fn connect_bytes_no_args() -> Vec<u8> {
962 let msg = command_message(CLIENT_CSID, 0, "connect", 1.0, vec![]);
963 ChunkWriter::new().write(&msg).unwrap()
964 }
965
966 fn create_stream_bytes() -> Vec<u8> {
967 let msg = command_message(CLIENT_CSID, 0, "createStream", 2.0, vec![Amf0Value::Null]);
968 ChunkWriter::new().write(&msg).unwrap()
969 }
970
971 fn publish_bytes(stream_id: u32, stream_key: &str) -> Vec<u8> {
972 let args = vec![
973 Amf0Value::Null,
974 Amf0Value::String(stream_key.to_string()),
975 Amf0Value::String("live".to_string()),
976 ];
977 let msg = command_message(CLIENT_CSID, stream_id, "publish", 3.0, args);
978 ChunkWriter::new().write(&msg).unwrap()
979 }
980
981 fn av_bytes(
982 stream_id: u32,
983 message_type_id: u8,
984 csid: u32,
985 timestamp: u32,
986 payload: Vec<u8>,
987 ) -> Vec<u8> {
988 let msg = Message {
989 chunk_stream_id: csid,
990 timestamp,
991 message_type_id,
992 message_stream_id: stream_id,
993 payload,
994 };
995 ChunkWriter::new().write(&msg).unwrap()
996 }
997
998 fn decode_messages(bytes: &[u8]) -> Vec<Message> {
1007 let mut assembler = ChunkAssembler::new();
1008 assembler.set_chunk_size(65536);
1009 assembler.push(bytes).expect("well-formed reply stream")
1010 }
1011
1012 fn decode_commands(bytes: &[u8]) -> Vec<Command> {
1013 decode_messages(bytes)
1014 .iter()
1015 .filter(|m| m.message_type_id == msg_type::COMMAND_AMF0)
1016 .map(|m| Command::parse(&m.payload).expect("well-formed command reply"))
1017 .collect()
1018 }
1019
1020 fn onstatus_code(cmd: &Command) -> Option<String> {
1021 cmd.arguments.iter().find_map(|v| match v {
1022 Amf0Value::Object(pairs) => pairs.iter().find_map(|(k, v)| {
1023 if k == "code" {
1024 match v {
1025 Amf0Value::String(s) => Some(s.clone()),
1026 _ => None,
1027 }
1028 } else {
1029 None
1030 }
1031 }),
1032 _ => None,
1033 })
1034 }
1035
1036 fn publish_flow(
1039 config: ServerConfig,
1040 stream_key: &str,
1041 ) -> (ServerSession, Vec<u8>, Vec<ServerEvent>) {
1042 let mut session = ServerSession::new(config);
1043 let mut all_out = Vec::new();
1048 let mut all_events = Vec::new();
1049
1050 session.handle_data(&build_c0_c1()).unwrap();
1051 session.handle_data(&build_c2()).unwrap();
1052
1053 let (out, events) = session.handle_data(&connect_bytes("live")).unwrap();
1054 all_out.extend(out);
1055 all_events.extend(events);
1056
1057 let (out, events) = session.handle_data(&create_stream_bytes()).unwrap();
1058 all_out.extend(out);
1059 all_events.extend(events);
1060
1061 let (out, events) = session.handle_data(&publish_bytes(1, stream_key)).unwrap();
1063 all_out.extend(out);
1064 all_events.extend(events);
1065
1066 (session, all_out, all_events)
1067 }
1068
1069 #[test]
1072 fn handshake_completes_and_reply_contains_s0_s1_s2() {
1073 let mut session = ServerSession::with_defaults();
1074 let (out1, events1) = session.handle_data(&build_c0_c1()).unwrap();
1075 assert_eq!(
1076 out1.len(),
1077 1 + HANDSHAKE_PACKET_LEN + HANDSHAKE_PACKET_LEN,
1078 "S0+S1+S2 must be a single 3073-byte reply"
1079 );
1080 assert!(events1.is_empty());
1081
1082 let (out2, events2) = session.handle_data(&build_c2()).unwrap();
1083 assert!(out2.is_empty(), "C2 receipt produces no reply bytes itself");
1084 assert!(events2.is_empty());
1085 }
1086
1087 #[test]
1088 fn handshake_split_across_calls_still_completes() {
1089 let mut session = ServerSession::with_defaults();
1090 let c0c1 = build_c0_c1();
1091 let (out1, _) = session.handle_data(&c0c1[..500]).unwrap();
1092 assert!(out1.is_empty(), "partial C0+C1 produces no reply yet");
1093 let (out2, _) = session.handle_data(&c0c1[500..]).unwrap();
1094 assert_eq!(out2.len(), 1 + 2 * HANDSHAKE_PACKET_LEN);
1095 let (_out3, _) = session.handle_data(&build_c2()).unwrap();
1096 }
1097
1098 #[test]
1099 fn c2_pipelined_with_connect_chunk_in_one_call_still_parses_connect() {
1100 let mut session = ServerSession::with_defaults();
1107 session.handle_data(&build_c0_c1()).unwrap();
1108
1109 let mut pipelined = build_c2();
1110 pipelined.extend_from_slice(&connect_bytes("live"));
1111
1112 let (_out, events) = session.handle_data(&pipelined).unwrap();
1113 assert_eq!(
1114 events,
1115 vec![ServerEvent::Connected {
1116 app: "live".to_string()
1117 }],
1118 "C2 pipelined with the connect chunk in one handle_data call must \
1119 still yield Connected from that call (leftover bytes must not be dropped)"
1120 );
1121 }
1122
1123 #[test]
1126 fn connect_emits_connected_event_and_result_reply() {
1127 let mut session = ServerSession::with_defaults();
1128 session.handle_data(&build_c0_c1()).unwrap();
1129 session.handle_data(&build_c2()).unwrap();
1130
1131 let (out, events) = session.handle_data(&connect_bytes("live")).unwrap();
1132 assert_eq!(
1133 events,
1134 vec![ServerEvent::Connected {
1135 app: "live".to_string()
1136 }]
1137 );
1138
1139 let commands = decode_commands(&out);
1140 assert!(
1141 commands.iter().any(|c| c.name == "_result"),
1142 "connect reply must contain a _result command"
1143 );
1144 }
1145
1146 #[test]
1149 fn connect_with_invalid_configured_chunk_size_errors_not_panics() {
1150 let mut session = ServerSession::new(ServerConfig::default().with_chunk_size(0));
1151 session.handle_data(&build_c0_c1()).unwrap();
1152 session.handle_data(&build_c2()).unwrap();
1153 let err = session.handle_data(&connect_bytes("live")).unwrap_err();
1154 assert!(matches!(err, RtmpError::Malformed { .. }), "{err:?}");
1155 }
1156
1157 #[test]
1162 fn amf3_connect_is_answered_like_amf0() {
1163 let mut session = ServerSession::with_defaults();
1164 session.handle_data(&build_c0_c1()).unwrap();
1165 session.handle_data(&build_c2()).unwrap();
1166
1167 let args = vec![Amf0Value::Object(vec![(
1168 "app".to_string(),
1169 Amf0Value::String("live".to_string()),
1170 )])];
1171 let amf0_body = Command {
1172 name: "connect".to_string(),
1173 transaction_id: 1.0,
1174 arguments: args,
1175 }
1176 .to_body()
1177 .unwrap();
1178 let mut amf3_body = vec![0x00]; amf3_body.extend(amf0_body);
1180 let msg = Message {
1181 chunk_stream_id: CLIENT_CSID,
1182 timestamp: 0,
1183 message_type_id: msg_type::COMMAND_AMF3,
1184 message_stream_id: 0,
1185 payload: amf3_body,
1186 };
1187 let bytes = ChunkWriter::new().write(&msg).unwrap();
1188
1189 let (out, events) = session.handle_data(&bytes).unwrap();
1190 assert_eq!(
1191 events,
1192 vec![ServerEvent::Connected {
1193 app: "live".to_string()
1194 }]
1195 );
1196 let commands = decode_commands(&out);
1197 assert!(
1198 commands.iter().any(|c| c.name == "_result"),
1199 "AMF3 connect must still get a _result reply"
1200 );
1201 }
1202
1203 #[test]
1211 fn aggregate_message_surfaces_unsupported_event() {
1212 let mut session = ServerSession::with_defaults();
1213 session.handle_data(&build_c0_c1()).unwrap();
1214 session.handle_data(&build_c2()).unwrap();
1215 session.handle_data(&connect_bytes("live")).unwrap();
1216
1217 let msg = Message {
1218 chunk_stream_id: CLIENT_CSID,
1219 timestamp: 0,
1220 message_type_id: msg_type::AGGREGATE,
1221 message_stream_id: 0,
1222 payload: vec![0xAA; 20], };
1224 let bytes = ChunkWriter::new().write(&msg).unwrap();
1225
1226 let err = session.handle_data(&bytes).unwrap_err();
1227 assert!(
1228 matches!(err, RtmpError::Malformed { .. }),
1229 "a garbage aggregate body must now be a Malformed error, got {err:?}"
1230 );
1231 }
1232
1233 fn aggregate_body(subs: &[(u8, u32, &[u8])]) -> Vec<u8> {
1238 let mut body = Vec::new();
1239 for &(tag_type, timestamp, data) in subs {
1240 let data_size = data.len() as u32;
1241 body.push(tag_type);
1242 body.push((data_size >> 16) as u8);
1243 body.push((data_size >> 8) as u8);
1244 body.push(data_size as u8);
1245 body.push((timestamp >> 16) as u8);
1246 body.push((timestamp >> 8) as u8);
1247 body.push(timestamp as u8);
1248 body.push((timestamp >> 24) as u8);
1249 body.extend_from_slice(&[0, 0, 0]); body.extend_from_slice(data);
1251 let back_pointer = (11 + data.len()) as u32;
1252 body.extend_from_slice(&back_pointer.to_be_bytes());
1253 }
1254 body
1255 }
1256
1257 fn first_flv_tag_header(flv: &[u8]) -> (u8, u32) {
1260 let tag = if flv.len() > 13 && flv.starts_with(b"FLV") {
1261 &flv[13..]
1262 } else {
1263 flv
1264 };
1265 let ts_low24 = u32::from_be_bytes([0, tag[4], tag[5], tag[6]]);
1266 (tag[0], ts_low24 | (u32::from(tag[7]) << 24))
1267 }
1268
1269 fn publishing_session() -> ServerSession {
1272 let mut session = ServerSession::new(ServerConfig::default());
1273 session.handle_data(&build_c0_c1()).unwrap();
1274 session.handle_data(&build_c2()).unwrap();
1275 session.handle_data(&connect_bytes("live")).unwrap();
1276 session.handle_data(&create_stream_bytes()).unwrap();
1277 session.handle_data(&publish_bytes(1, "mystream")).unwrap();
1278 session
1279 }
1280
1281 #[test]
1285 fn aggregate_message_is_unpacked_into_media_events() {
1286 let mut session = publishing_session();
1287 let body = aggregate_body(&[
1288 (msg_type::VIDEO, 1000, &[0x17, 0x01, 0xAA, 0xBB]),
1289 (msg_type::VIDEO, 1040, &[0x27, 0x01, 0xCC]),
1290 (msg_type::AUDIO, 1005, &[0xAF, 0x01, 0xDD, 0xEE]),
1291 ]);
1292 let msg = Message {
1293 chunk_stream_id: CLIENT_CSID,
1294 timestamp: 1000, message_type_id: msg_type::AGGREGATE,
1296 message_stream_id: 1,
1297 payload: body,
1298 };
1299 let bytes = ChunkWriter::new().write(&msg).unwrap();
1300 let (_out, events) = session.handle_data(&bytes).unwrap();
1301 let tags: Vec<(u8, u32)> = events
1302 .iter()
1303 .map(|e| match e {
1304 ServerEvent::Media { flv } => first_flv_tag_header(flv),
1305 other => panic!("expected only Media events, got {other:?}"),
1306 })
1307 .collect();
1308 assert_eq!(
1309 tags,
1310 vec![
1311 (msg_type::VIDEO, 1000),
1312 (msg_type::VIDEO, 1040),
1313 (msg_type::AUDIO, 1005),
1314 ]
1315 );
1316 }
1317
1318 #[test]
1322 fn aggregate_timestamps_are_renormalized_against_the_aggregate() {
1323 let mut session = publishing_session();
1324 let body = aggregate_body(&[
1325 (msg_type::VIDEO, 50, &[0x17, 0x01]),
1326 (msg_type::AUDIO, 60, &[0xAF, 0x01]),
1327 ]);
1328 let msg = Message {
1329 chunk_stream_id: CLIENT_CSID,
1330 timestamp: 100,
1331 message_type_id: msg_type::AGGREGATE,
1332 message_stream_id: 1,
1333 payload: body,
1334 };
1335 let bytes = ChunkWriter::new().write(&msg).unwrap();
1336 let (_out, events) = session.handle_data(&bytes).unwrap();
1337 let tags: Vec<(u8, u32)> = events
1338 .iter()
1339 .map(|e| match e {
1340 ServerEvent::Media { flv } => first_flv_tag_header(flv),
1341 other => panic!("expected only Media events, got {other:?}"),
1342 })
1343 .collect();
1344 assert_eq!(tags, vec![(msg_type::VIDEO, 100), (msg_type::AUDIO, 110)]);
1346 }
1347
1348 #[test]
1352 fn truncated_aggregate_message_errors() {
1353 let mut session = publishing_session();
1354 let mut body = aggregate_body(&[(msg_type::VIDEO, 0, &[0x17, 0x01, 0xAA])]);
1355 body.truncate(body.len() - 5);
1358 let msg = Message {
1359 chunk_stream_id: CLIENT_CSID,
1360 timestamp: 0,
1361 message_type_id: msg_type::AGGREGATE,
1362 message_stream_id: 1,
1363 payload: body,
1364 };
1365 let bytes = ChunkWriter::new().write(&msg).unwrap();
1366 let err = session.handle_data(&bytes).unwrap_err();
1367 assert!(
1368 matches!(err, RtmpError::Malformed { .. }),
1369 "a truncated aggregate must be Malformed, got {err:?}"
1370 );
1371 }
1372
1373 #[test]
1376 fn aggregate_with_bad_back_pointer_errors() {
1377 let mut session = publishing_session();
1378 let mut body = aggregate_body(&[(msg_type::VIDEO, 0, &[0x17, 0x01, 0xAA])]);
1379 let back_at = body.len() - 4;
1380 body[back_at] = 0xFF; let msg = Message {
1382 chunk_stream_id: CLIENT_CSID,
1383 timestamp: 0,
1384 message_type_id: msg_type::AGGREGATE,
1385 message_stream_id: 1,
1386 payload: body,
1387 };
1388 let bytes = ChunkWriter::new().write(&msg).unwrap();
1389 let err = session.handle_data(&bytes).unwrap_err();
1390 assert!(
1391 matches!(err, RtmpError::Malformed { .. }),
1392 "a lying Back Pointer must be Malformed, got {err:?}"
1393 );
1394 }
1395
1396 #[test]
1397 fn connect_without_command_object_is_malformed() {
1398 let mut session = ServerSession::with_defaults();
1399 session.handle_data(&build_c0_c1()).unwrap();
1400 session.handle_data(&build_c2()).unwrap();
1401
1402 let err = session.handle_data(&connect_bytes_no_args()).unwrap_err();
1404 assert!(
1405 matches!(err, RtmpError::Malformed { .. }),
1406 "connect with no command-object argument must error, not default app to \"\""
1407 );
1408 }
1409
1410 #[test]
1413 fn connect_with_object_missing_app_key_is_malformed() {
1414 let mut session = ServerSession::with_defaults();
1415 session.handle_data(&build_c0_c1()).unwrap();
1416 session.handle_data(&build_c2()).unwrap();
1417
1418 let args = vec![Amf0Value::Object(vec![(
1420 "type".to_string(),
1421 Amf0Value::String("nonprivate".to_string()),
1422 )])];
1423 let msg = command_message(CLIENT_CSID, 0, "connect", 1.0, args);
1424 let bytes = ChunkWriter::new().write(&msg).unwrap();
1425
1426 let err = session.handle_data(&bytes).unwrap_err();
1427 assert!(
1428 matches!(err, RtmpError::Malformed { .. }),
1429 "connect with object missing 'app' key must error"
1430 );
1431 }
1432
1433 #[test]
1436 fn connect_with_app_as_number_is_malformed() {
1437 let mut session = ServerSession::with_defaults();
1438 session.handle_data(&build_c0_c1()).unwrap();
1439 session.handle_data(&build_c2()).unwrap();
1440
1441 let args = vec![Amf0Value::Object(vec![
1443 ("app".to_string(), Amf0Value::Number(123.0)),
1444 (
1445 "type".to_string(),
1446 Amf0Value::String("nonprivate".to_string()),
1447 ),
1448 ])];
1449 let msg = command_message(CLIENT_CSID, 0, "connect", 1.0, args);
1450 let bytes = ChunkWriter::new().write(&msg).unwrap();
1451
1452 let err = session.handle_data(&bytes).unwrap_err();
1453 assert!(
1454 matches!(err, RtmpError::Malformed { .. }),
1455 "connect with app as Number must error, not accept numeric value"
1456 );
1457 }
1458
1459 #[test]
1462 fn create_stream_replies_result_with_stream_id() {
1463 let mut session = ServerSession::with_defaults();
1464 session.handle_data(&build_c0_c1()).unwrap();
1465 session.handle_data(&build_c2()).unwrap();
1466 session.handle_data(&connect_bytes("live")).unwrap();
1467
1468 let (out, _events) = session.handle_data(&create_stream_bytes()).unwrap();
1469 let commands = decode_commands(&out);
1470 let result = commands
1471 .iter()
1472 .find(|c| c.name == "_result")
1473 .expect("createStream _result reply");
1474 assert_eq!(
1475 result.arguments.get(1),
1476 Some(&Amf0Value::Number(1.0)),
1477 "first allocated stream id must be 1"
1478 );
1479 }
1480
1481 #[test]
1482 fn create_stream_before_connect_is_unexpected_state() {
1483 let mut session = ServerSession::with_defaults();
1484 session.handle_data(&build_c0_c1()).unwrap();
1485 session.handle_data(&build_c2()).unwrap();
1486
1487 let err = session.handle_data(&create_stream_bytes()).unwrap_err();
1488 assert!(matches!(err, RtmpError::UnexpectedState { .. }));
1489 }
1490
1491 #[test]
1498 fn oversized_publish_name_errors_instead_of_panicking() {
1499 for len in [65_518usize, 65_530, 65_535] {
1500 let mut session = ServerSession::new(ServerConfig::default());
1501 session.handle_data(&build_c0_c1()).unwrap();
1502 session.handle_data(&build_c2()).unwrap();
1503 session.handle_data(&connect_bytes("live")).unwrap();
1504 session.handle_data(&create_stream_bytes()).unwrap();
1505 let key = "k".repeat(len);
1506 let err = session
1507 .handle_data(&publish_bytes(1, &key))
1508 .expect_err("overflowing onStatus description must be an Err");
1509 assert!(
1510 matches!(err, RtmpError::Unsupported { .. }),
1511 "len {len}: {err:?}"
1512 );
1513 }
1514 }
1515
1516 #[test]
1517 fn publish_reaches_publishing_emits_event_and_stream_begin_plus_onstatus() {
1518 let (_session, out, events) = publish_flow(ServerConfig::default(), "testkey");
1519
1520 assert!(events.contains(&ServerEvent::Publish {
1521 app: "live".to_string(),
1522 stream_key: "testkey".to_string(),
1523 stream_id: 1,
1524 }));
1525
1526 let messages = decode_messages(&out);
1527 let has_stream_begin = messages.iter().any(|m| {
1528 m.message_type_id == msg_type::USER_CONTROL
1529 && matches!(
1530 UserControl::parse(&m.payload),
1531 Ok(UserControl::StreamBegin(1))
1532 )
1533 });
1534 assert!(
1535 has_stream_begin,
1536 "publish reply must include StreamBegin(1)"
1537 );
1538
1539 let commands = decode_commands(&out);
1540 let on_status = commands
1541 .iter()
1542 .find(|c| c.name == "onStatus")
1543 .expect("onStatus reply to publish");
1544 assert_eq!(
1545 onstatus_code(on_status).as_deref(),
1546 Some("NetStream.Publish.Start")
1547 );
1548 }
1549
1550 #[test]
1551 fn publish_before_connect_is_unexpected_state() {
1552 let mut session = ServerSession::with_defaults();
1553 session.handle_data(&build_c0_c1()).unwrap();
1554 session.handle_data(&build_c2()).unwrap();
1555
1556 let err = session
1557 .handle_data(&publish_bytes(1, "testkey"))
1558 .unwrap_err();
1559 assert!(matches!(err, RtmpError::UnexpectedState { .. }));
1560 }
1561
1562 #[test]
1563 fn publish_without_create_stream_is_unexpected_state() {
1564 let mut session = ServerSession::with_defaults();
1565 session.handle_data(&build_c0_c1()).unwrap();
1566 session.handle_data(&build_c2()).unwrap();
1567 session.handle_data(&connect_bytes("live")).unwrap();
1568
1569 let err = session
1571 .handle_data(&publish_bytes(1, "testkey"))
1572 .unwrap_err();
1573 assert!(matches!(err, RtmpError::UnexpectedState { .. }));
1574 }
1575
1576 #[test]
1577 fn create_stream_after_closed_is_unexpected_state() {
1578 let mut session = ServerSession::with_defaults();
1579 session.handle_data(&build_c0_c1()).unwrap();
1580 session.handle_data(&build_c2()).unwrap();
1581 session.handle_data(&connect_bytes("live")).unwrap();
1582 session.handle_data(&create_stream_bytes()).unwrap();
1583 session.handle_data(&publish_bytes(1, "testkey")).unwrap();
1584
1585 let delete_stream = command_message(
1586 CLIENT_CSID,
1587 1,
1588 "deleteStream",
1589 4.0,
1590 vec![Amf0Value::Null, Amf0Value::Number(1.0)],
1591 );
1592 let (_out, events) = session
1593 .handle_data(&ChunkWriter::new().write(&delete_stream).unwrap())
1594 .unwrap();
1595 assert_eq!(events, vec![ServerEvent::Eof]);
1596
1597 let err = session.handle_data(&create_stream_bytes()).unwrap_err();
1598 assert!(
1599 matches!(err, RtmpError::UnexpectedState { .. }),
1600 "createStream after State::Closed must be rejected, not silently re-allowed"
1601 );
1602 }
1603
1604 #[test]
1607 fn audio_and_video_emit_media_first_carries_flv_file_header() {
1608 let (mut session, _out, _events) = publish_flow(ServerConfig::default(), "testkey");
1609
1610 let (_out1, events1) = session
1611 .handle_data(&av_bytes(
1612 1,
1613 msg_type::AUDIO,
1614 4,
1615 0,
1616 vec![0xAF, 0x01, 0xDE, 0xAD],
1617 ))
1618 .unwrap();
1619 assert_eq!(events1.len(), 1);
1620 let ServerEvent::Media { flv } = &events1[0] else {
1621 panic!("expected Media event");
1622 };
1623 assert!(
1624 flv.starts_with(b"FLV"),
1625 "the first Media event must carry the FLV file header"
1626 );
1627
1628 let (_out2, events2) = session
1629 .handle_data(&av_bytes(
1630 1,
1631 msg_type::VIDEO,
1632 6,
1633 40,
1634 vec![0x17, 0x01, 0x00, 0x00, 0x00, 0xDE, 0xAD, 0xBE, 0xEF],
1635 ))
1636 .unwrap();
1637 assert_eq!(events2.len(), 1);
1638 let ServerEvent::Media { flv } = &events2[0] else {
1639 panic!("expected Media event");
1640 };
1641 assert!(
1642 !flv.starts_with(b"FLV"),
1643 "only the first Media event carries the file header"
1644 );
1645 }
1646
1647 #[test]
1648 fn second_connect_while_publishing_is_rejected_and_media_keeps_flowing() {
1649 let (mut session, _out, _events) = publish_flow(ServerConfig::default(), "testkey");
1650
1651 let err = session.handle_data(&connect_bytes("live")).unwrap_err();
1652 assert!(matches!(err, RtmpError::UnexpectedState { .. }));
1653
1654 let (_out, events) = session
1655 .handle_data(&av_bytes(
1656 1,
1657 msg_type::AUDIO,
1658 4,
1659 0,
1660 vec![0xAF, 0x01, 0xDE, 0xAD],
1661 ))
1662 .unwrap();
1663 assert!(
1664 events
1665 .iter()
1666 .any(|e| matches!(e, ServerEvent::Media { .. })),
1667 "the rejected connect must not demote the session out of Publishing"
1668 );
1669 }
1670
1671 #[test]
1672 fn concatenated_media_forms_structurally_valid_flv() {
1673 let (mut session, _out, _events) = publish_flow(ServerConfig::default(), "testkey");
1674
1675 let mut flv_stream = Vec::new();
1676 let (_out1, events1) = session
1677 .handle_data(&av_bytes(
1678 1,
1679 msg_type::AUDIO,
1680 4,
1681 0,
1682 vec![0xAF, 0x01, 1, 2, 3],
1683 ))
1684 .unwrap();
1685 let (_out2, events2) = session
1686 .handle_data(&av_bytes(
1687 1,
1688 msg_type::VIDEO,
1689 6,
1690 33,
1691 vec![0x17, 0x01, 0, 0, 0, 4, 5, 6],
1692 ))
1693 .unwrap();
1694 for e in events1.into_iter().chain(events2) {
1695 if let ServerEvent::Media { flv } = e {
1696 flv_stream.extend(flv);
1697 }
1698 }
1699
1700 assert_eq!(&flv_stream[0..3], b"FLV");
1702 assert_eq!(flv_stream[3], 1, "FLV version");
1703 assert_eq!(flv_stream[4], 0b0000_0101, "audio+video TypeFlags");
1704 assert_eq!(
1705 u32::from_be_bytes(flv_stream[5..9].try_into().unwrap()),
1706 9,
1707 "DataOffset (header size)"
1708 );
1709 assert_eq!(
1710 u32::from_be_bytes(flv_stream[9..13].try_into().unwrap()),
1711 0,
1712 "PreviousTagSize0"
1713 );
1714
1715 let tag1 = &flv_stream[13..];
1717 assert_eq!(tag1[0], msg_type::AUDIO);
1718 let data_size1 =
1719 (u32::from(tag1[1]) << 16) | (u32::from(tag1[2]) << 8) | u32::from(tag1[3]);
1720 assert_eq!(data_size1, 5);
1721 let tag1_total = FLV_TAG_HEADER_LEN + 5 + FLV_PREV_TAG_SIZE_LEN;
1722 let prev_tag_size1 = u32::from_be_bytes(
1723 flv_stream[13 + tag1_total - 4..13 + tag1_total]
1724 .try_into()
1725 .unwrap(),
1726 );
1727 assert_eq!(prev_tag_size1 as usize, FLV_TAG_HEADER_LEN + 5);
1728
1729 let tag2 = &flv_stream[13 + tag1_total..];
1731 assert_eq!(tag2[0], msg_type::VIDEO);
1732 let data_size2 =
1733 (u32::from(tag2[1]) << 16) | (u32::from(tag2[2]) << 8) | u32::from(tag2[3]);
1734 assert_eq!(data_size2, 8);
1735 assert_eq!(
1736 flv_stream.len(),
1737 13 + tag1_total + FLV_TAG_HEADER_LEN + 8 + FLV_PREV_TAG_SIZE_LEN
1738 );
1739 }
1740
1741 #[test]
1742 fn data_amf0_onmetadata_emits_media_with_script_tag_type() {
1743 let (mut session, _out, _events) = publish_flow(ServerConfig::default(), "testkey");
1744
1745 let mut payload = Amf0Value::String("onMetaData".to_string())
1750 .try_to_bytes()
1751 .unwrap();
1752 payload.extend(
1753 Amf0Value::Object(vec![
1754 ("width".to_string(), Amf0Value::Number(1920.0)),
1755 ("height".to_string(), Amf0Value::Number(1080.0)),
1756 ])
1757 .try_to_bytes()
1758 .unwrap(),
1759 );
1760
1761 let (_out, events) = session
1762 .handle_data(&av_bytes(1, msg_type::DATA_AMF0, 4, 0, payload))
1763 .unwrap();
1764
1765 assert_eq!(events.len(), 1);
1766 let ServerEvent::Media { flv } = &events[0] else {
1767 panic!("expected Media event");
1768 };
1769 assert!(
1770 flv.starts_with(b"FLV"),
1771 "the first Media event must carry the FLV file header"
1772 );
1773 let tag_type = flv[FLV_HEADER_LEN + FLV_PREV_TAG_SIZE_LEN];
1774 assert_eq!(
1775 tag_type,
1776 msg_type::DATA_AMF0,
1777 "Data-AMF0 message must produce a script(18) FLV tag"
1778 );
1779 }
1780
1781 #[test]
1782 fn set_data_frame_prefix_is_stripped_from_the_script_tag() {
1783 let (mut session, _out, _events) = publish_flow(ServerConfig::default(), "testkey");
1784 let mut payload = Amf0Value::String("@setDataFrame".to_string())
1785 .try_to_bytes()
1786 .unwrap();
1787 let metadata = Amf0Value::String("onMetaData".to_string())
1788 .try_to_bytes()
1789 .unwrap();
1790 payload.extend(&metadata);
1791 payload.extend(
1792 Amf0Value::Object(vec![("width".to_string(), Amf0Value::Number(1920.0))])
1793 .try_to_bytes()
1794 .unwrap(),
1795 );
1796
1797 let (_out, events) = session
1798 .handle_data(&av_bytes(1, msg_type::DATA_AMF0, 4, 0, payload))
1799 .unwrap();
1800 let ServerEvent::Media { flv } = &events[0] else {
1801 panic!("expected Media event");
1802 };
1803 let body_at = FLV_HEADER_LEN + FLV_PREV_TAG_SIZE_LEN + FLV_TAG_HEADER_LEN;
1804 assert_eq!(
1805 &flv[body_at..body_at + metadata.len()],
1806 metadata.as_slice(),
1807 "the script tag must start with the onMetaData name, not @setDataFrame"
1808 );
1809 }
1810
1811 #[test]
1812 fn media_before_publishing_is_silently_dropped() {
1813 let mut session = ServerSession::with_defaults();
1814 session.handle_data(&build_c0_c1()).unwrap();
1815 session.handle_data(&build_c2()).unwrap();
1816 session.handle_data(&connect_bytes("live")).unwrap();
1817 session.handle_data(&create_stream_bytes()).unwrap();
1818
1819 let (_out, events) = session
1821 .handle_data(&av_bytes(1, msg_type::AUDIO, 4, 0, vec![0xAF, 0x01]))
1822 .unwrap();
1823 assert!(events.is_empty());
1824 }
1825
1826 #[test]
1829 fn stream_key_mismatch_suppresses_publish_and_media_events() {
1830 let config = ServerConfig {
1831 expected_stream_key: Some("rightkey".to_string()),
1832 ..ServerConfig::default()
1833 };
1834 let (mut session, out, events) = publish_flow(config, "wrongkey");
1835
1836 assert!(
1837 !events
1838 .iter()
1839 .any(|e| matches!(e, ServerEvent::Publish { .. })),
1840 "mismatched stream key must not emit Publish"
1841 );
1842
1843 let commands = decode_commands(&out);
1844 let on_status = commands
1845 .iter()
1846 .find(|c| c.name == "onStatus")
1847 .expect("onStatus reply on mismatch");
1848 assert_eq!(
1849 onstatus_code(on_status).as_deref(),
1850 Some("NetStream.Publish.BadName")
1851 );
1852
1853 let (_out2, events2) = session
1855 .handle_data(&av_bytes(1, msg_type::AUDIO, 4, 0, vec![0xAF, 0x01]))
1856 .unwrap();
1857 assert!(
1858 events2.is_empty(),
1859 "no Media may be emitted after a rejected publish"
1860 );
1861 }
1862
1863 #[test]
1864 fn stream_key_match_still_publishes_with_key_configured() {
1865 let config = ServerConfig {
1866 expected_stream_key: Some("rightkey".to_string()),
1867 ..ServerConfig::default()
1868 };
1869 let (_session, _out, events) = publish_flow(config, "rightkey");
1870 assert!(
1871 events.contains(&ServerEvent::Publish {
1872 app: "live".to_string(),
1873 stream_key: "rightkey".to_string(),
1874 stream_id: 1,
1875 }),
1876 "a stream key matching expected_stream_key must still publish"
1877 );
1878 }
1879
1880 #[test]
1881 fn too_many_failed_publish_attempts_closes_the_session() {
1882 let config = ServerConfig {
1883 expected_stream_key: Some("rightkey".to_string()),
1884 ..ServerConfig::default()
1885 };
1886 let mut session = ServerSession::new(config);
1887 session.handle_data(&build_c0_c1()).unwrap();
1888 session.handle_data(&build_c2()).unwrap();
1889 session.handle_data(&connect_bytes("live")).unwrap();
1890 session.handle_data(&create_stream_bytes()).unwrap();
1891
1892 for attempt in 1..=MAX_FAILED_PUBLISH_ATTEMPTS {
1893 let (_out, events) = session.handle_data(&publish_bytes(1, "wrongkey")).unwrap_or_else(|e| {
1894 panic!("attempt {attempt} of {MAX_FAILED_PUBLISH_ATTEMPTS} must still be rejected, not error out: {e}")
1895 });
1896 assert!(
1897 !events
1898 .iter()
1899 .any(|e| matches!(e, ServerEvent::Publish { .. })),
1900 "attempt {attempt} must not publish"
1901 );
1902 }
1903
1904 let err = session
1907 .handle_data(&publish_bytes(1, "wrongkey"))
1908 .expect_err("the attempt beyond MAX_FAILED_PUBLISH_ATTEMPTS must close the session");
1909 assert!(matches!(err, RtmpError::UnexpectedState { .. }));
1910
1911 let err = session
1913 .handle_data(&publish_bytes(1, "rightkey"))
1914 .expect_err(
1915 "publish must be rejected once the session was closed for too many failures",
1916 );
1917 assert!(matches!(err, RtmpError::UnexpectedState { .. }));
1918 }
1919
1920 #[test]
1921 fn constant_time_eq_matches_naive_equality() {
1922 assert!(constant_time_eq(b"rightkey", b"rightkey"));
1923 assert!(!constant_time_eq(b"rightkey", b"wrongkey"));
1924 assert!(!constant_time_eq(b"short", b"muchlonger"));
1925 assert!(constant_time_eq(b"", b""));
1926 }
1927
1928 #[test]
1931 fn ack_written_once_window_ack_size_is_crossed() {
1932 let config = ServerConfig {
1933 window_ack_size: 32,
1934 ..ServerConfig::default()
1935 };
1936 let mut session = ServerSession::new(config);
1937 session.handle_data(&build_c0_c1()).unwrap();
1938 session.handle_data(&build_c2()).unwrap();
1939
1940 let (out, _events) = session.handle_data(&connect_bytes("live")).unwrap();
1942 let messages = decode_messages(&out);
1943 let has_ack = messages.iter().any(|m| {
1944 matches!(
1945 ProtocolControl::from_message(m),
1946 Ok(Some(ProtocolControl::Acknowledgement(_)))
1947 )
1948 });
1949 assert!(
1950 has_ack,
1951 "crossing window_ack_size must produce an Acknowledgement"
1952 );
1953 }
1954
1955 #[test]
1956 fn no_ack_below_window_ack_size() {
1957 let config = ServerConfig {
1958 window_ack_size: 10_000_000,
1959 ..ServerConfig::default()
1960 };
1961 let mut session = ServerSession::new(config);
1962 session.handle_data(&build_c0_c1()).unwrap();
1963 let (out, _events) = session.handle_data(&build_c2()).unwrap();
1964 let messages = decode_messages(&out);
1965 assert!(
1966 !messages.iter().any(|m| matches!(
1967 ProtocolControl::from_message(m),
1968 Ok(Some(ProtocolControl::Acknowledgement(_)))
1969 )),
1970 "no Acknowledgement should be due yet"
1971 );
1972 }
1973
1974 #[test]
1977 fn garbage_command_payload_after_handshake_is_error_not_panic() {
1978 let mut session = ServerSession::with_defaults();
1979 session.handle_data(&build_c0_c1()).unwrap();
1980 session.handle_data(&build_c2()).unwrap();
1981
1982 let bogus = Message {
1986 chunk_stream_id: CLIENT_CSID,
1987 timestamp: 0,
1988 message_type_id: msg_type::COMMAND_AMF0,
1989 message_stream_id: 0,
1990 payload: vec![0xFF, 0xFF, 0xFF, 0xFF],
1991 };
1992 let bytes = ChunkWriter::new().write(&bogus).unwrap();
1993 let err = session.handle_data(&bytes).unwrap_err();
1994 assert!(matches!(
1995 err,
1996 RtmpError::Unsupported { .. }
1997 | RtmpError::Malformed { .. }
1998 | RtmpError::BufferTooShort(..)
1999 ));
2000 }
2001
2002 #[test]
2003 fn truncated_post_handshake_bytes_do_not_panic() {
2004 let mut session = ServerSession::with_defaults();
2005 session.handle_data(&build_c0_c1()).unwrap();
2006 session.handle_data(&build_c2()).unwrap();
2007
2008 let (out, events) = session.handle_data(&[0x03, 0x01, 0x02]).unwrap();
2010 assert!(out.is_empty());
2011 assert!(events.is_empty());
2012 }
2013
2014 #[test]
2017 fn mutation_check_publish_event_must_echo_actual_stream_key() {
2018 let (_session, _out, events) = publish_flow(ServerConfig::default(), "specific-key-xyz");
2019 let publish_event = events
2020 .iter()
2021 .find_map(|e| match e {
2022 ServerEvent::Publish { stream_key, .. } => Some(stream_key.clone()),
2023 _ => None,
2024 })
2025 .expect("Publish event");
2026 assert_eq!(
2027 publish_event, "specific-key-xyz",
2028 "a hardcoded/ignored stream_key would fail this"
2029 );
2030 }
2031
2032 #[test]
2033 fn mutation_check_flv_file_header_bytes_are_exact() {
2034 let header = FlvHeader::new(true, true).try_to_bytes().unwrap();
2035 assert_eq!(
2036 header,
2037 vec![
2038 b'F',
2039 b'L',
2040 b'V', 1, 0b0000_0101, 0,
2044 0,
2045 0,
2046 9, 0,
2048 0,
2049 0,
2050 0, ]
2052 );
2053 }
2054
2055 #[test]
2058 fn client_set_chunk_size_takes_effect_before_next_message_in_same_call() {
2059 let (mut session, _out, _events) = publish_flow(ServerConfig::default(), "testkey");
2068
2069 const NEW_CHUNK_SIZE: u32 = 4096;
2070 let set_chunk_size_bytes = ChunkWriter::new()
2071 .write(&ProtocolControl::SetChunkSize(NEW_CHUNK_SIZE).to_message())
2072 .unwrap();
2073
2074 let big_payload = vec![0x17u8; 300];
2079 let mut client_writer = ChunkWriter::new();
2080 client_writer.set_chunk_size(NEW_CHUNK_SIZE);
2081 let video_bytes = client_writer
2082 .write(&Message {
2083 chunk_stream_id: 6,
2084 timestamp: 0,
2085 message_type_id: msg_type::VIDEO,
2086 message_stream_id: 1,
2087 payload: big_payload.clone(),
2088 })
2089 .unwrap();
2090
2091 let mut combined = set_chunk_size_bytes;
2092 combined.extend_from_slice(&video_bytes);
2093
2094 let (_out, events) = session.handle_data(&combined).expect(
2097 "SetChunkSize must take effect before parsing the message that follows it \
2098 in the same handle_data call, not only on a subsequent call",
2099 );
2100
2101 let media = events
2102 .iter()
2103 .find_map(|e| match e {
2104 ServerEvent::Media { flv } => Some(flv.clone()),
2105 _ => None,
2106 })
2107 .expect("the video message must still be parsed into a Media event");
2108 assert!(
2109 media
2110 .windows(big_payload.len())
2111 .any(|w| w == big_payload.as_slice()),
2112 "the video payload must survive intact through the chunk-size change"
2113 );
2114 }
2115
2116 #[test]
2117 fn control_chunk_stream_id_constant_matches_message_module() {
2118 assert_ne!(COMMAND_CHUNK_STREAM_ID, CTRL_CSID);
2121 }
2122
2123 #[test]
2124 fn next_stream_id_saturates_instead_of_overflowing() {
2125 let mut session = ServerSession::with_defaults();
2130 session.handle_data(&build_c0_c1()).unwrap();
2131 session.handle_data(&build_c2()).unwrap();
2132 session.handle_data(&connect_bytes("live")).unwrap();
2133
2134 session.next_stream_id = u32::MAX;
2135 let (out, _events) = session
2136 .handle_data(&create_stream_bytes())
2137 .expect("createStream must not panic when next_stream_id is already u32::MAX");
2138
2139 let commands = decode_commands(&out);
2140 let result = commands
2141 .iter()
2142 .find(|c| c.name == "_result")
2143 .expect("createStream _result reply");
2144 assert_eq!(
2145 result.arguments.get(1),
2146 Some(&Amf0Value::Number(f64::from(u32::MAX))),
2147 "the stream id allocated at the u32::MAX boundary must still be u32::MAX"
2148 );
2149 assert_eq!(
2150 session.next_stream_id,
2151 u32::MAX,
2152 "next_stream_id must saturate at u32::MAX, not wrap to 0"
2153 );
2154 }
2155
2156 #[cfg(feature = "serde")]
2159 #[test]
2160 fn server_config_and_server_event_serde_round_trip() {
2161 let config = ServerConfig::default()
2162 .with_chunk_size(8192)
2163 .with_expected_stream_key(Some("k".to_string()));
2164 let json = serde_json::to_string(&config).expect("serialize ServerConfig");
2165 let back: ServerConfig = serde_json::from_str(&json).expect("deserialize ServerConfig");
2166 assert_eq!(back.chunk_size, config.chunk_size);
2167 assert_eq!(back.expected_stream_key, config.expected_stream_key);
2168
2169 let event = ServerEvent::Publish {
2170 app: "live".to_string(),
2171 stream_key: "testkey".to_string(),
2172 stream_id: 1,
2173 };
2174 let json = serde_json::to_string(&event).expect("serialize ServerEvent");
2175 let back: ServerEvent = serde_json::from_str(&json).expect("deserialize ServerEvent");
2176 assert_eq!(back, event);
2177 }
2178}