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_bridge::{FlvTagWriter, unpack_aggregate};
70use crate::handshake::Handshake;
71use crate::message::{LimitType, ProtocolControl, UserControl, msg_type};
72
73type Result<T> = core::result::Result<T, RtmpError>;
74
75pub const DEFAULT_CHUNK_SIZE: u32 = 4096;
81pub const DEFAULT_WINDOW_ACK_SIZE: u32 = 2_500_000;
84pub const DEFAULT_PEER_BANDWIDTH: u32 = 2_500_000;
86
87const FIRST_STREAM_ID: u32 = 1;
91
92const COMMAND_CHUNK_STREAM_ID: u32 = 3;
96
97const MAX_FAILED_PUBLISH_ATTEMPTS: u32 = 3;
102
103const FMS_VERSION: &str = "FMS/3,0,1,123";
109const CAPABILITIES: f64 = 31.0;
112
113#[non_exhaustive]
119#[derive(Clone)]
120#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
121pub struct ServerConfig {
122 pub chunk_size: u32,
124 pub window_ack_size: u32,
128 pub peer_bandwidth: u32,
130 pub expected_stream_key: Option<String>,
139 pub max_in_progress_bytes: usize,
145}
146
147impl core::fmt::Debug for ServerConfig {
150 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
151 f.debug_struct("ServerConfig")
152 .field("chunk_size", &self.chunk_size)
153 .field("window_ack_size", &self.window_ack_size)
154 .field("peer_bandwidth", &self.peer_bandwidth)
155 .field(
156 "expected_stream_key",
157 &self.expected_stream_key.as_ref().map(|_| "<redacted>"),
158 )
159 .field("max_in_progress_bytes", &self.max_in_progress_bytes)
160 .finish()
161 }
162}
163
164impl Default for ServerConfig {
165 fn default() -> Self {
166 Self {
167 chunk_size: DEFAULT_CHUNK_SIZE,
168 window_ack_size: DEFAULT_WINDOW_ACK_SIZE,
169 peer_bandwidth: DEFAULT_PEER_BANDWIDTH,
170 expected_stream_key: None,
171 max_in_progress_bytes: DEFAULT_MAX_IN_PROGRESS_BYTES,
172 }
173 }
174}
175
176impl ServerConfig {
177 #[must_use]
182 pub fn with_expected_stream_key(mut self, expected_stream_key: Option<String>) -> Self {
183 self.expected_stream_key = expected_stream_key;
184 self
185 }
186
187 #[must_use]
189 pub fn with_chunk_size(mut self, chunk_size: u32) -> Self {
190 self.chunk_size = chunk_size;
191 self
192 }
193
194 #[must_use]
196 pub fn with_max_in_progress_bytes(mut self, max_in_progress_bytes: usize) -> Self {
197 self.max_in_progress_bytes = max_in_progress_bytes;
198 self
199 }
200}
201
202#[non_exhaustive]
204#[derive(Clone, PartialEq)]
205#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
206pub enum ServerEvent {
207 Connected {
209 app: String,
211 },
212 Publish {
215 app: String,
217 stream_key: String,
219 stream_id: u32,
222 },
223 Media {
229 flv: Vec<u8>,
232 },
233 Eof,
235 Unsupported {
243 message_type_id: u8,
245 },
246}
247
248impl core::fmt::Debug for ServerEvent {
252 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
253 match self {
254 ServerEvent::Connected { app } => {
255 f.debug_struct("Connected").field("app", app).finish()
256 }
257 ServerEvent::Publish { app, stream_id, .. } => f
258 .debug_struct("Publish")
259 .field("app", app)
260 .field("stream_key", &"<redacted>")
261 .field("stream_id", stream_id)
262 .finish(),
263 ServerEvent::Media { flv } => f
264 .debug_struct("Media")
265 .field("flv_len", &flv.len())
266 .finish(),
267 ServerEvent::Eof => f.write_str("Eof"),
268 ServerEvent::Unsupported { message_type_id } => f
269 .debug_struct("Unsupported")
270 .field("message_type_id", message_type_id)
271 .finish(),
272 }
273 }
274}
275
276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
279enum State {
280 Init,
282 Connected,
285 Publishing,
288 Closed,
290}
291
292#[derive(Debug)]
297pub struct ServerSession {
298 config: ServerConfig,
299 handshake: Handshake,
300 handshake_buf: Vec<u8>,
304 assembler: ChunkAssembler,
305 writer: ChunkWriter,
306 state: State,
307 app: Option<String>,
308 next_stream_id: u32,
309 created_stream_id: Option<u32>,
314 ack_threshold: u32,
321 peer_bandwidth: Option<u32>,
325 bytes_received: u64,
327 bytes_acked: u64,
329 flv: FlvTagWriter,
332 failed_publish_attempts: u32,
336}
337
338fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
345 if a.len() != b.len() {
346 return false;
347 }
348 bool::from(subtle::ConstantTimeEq::ct_eq(a, b))
349}
350
351impl ServerSession {
352 #[must_use]
354 pub fn new(config: ServerConfig) -> Self {
355 let ack_threshold = config.window_ack_size;
356 let max_in_progress_bytes = config.max_in_progress_bytes;
357 Self {
358 config,
359 handshake: Handshake::new(),
360 handshake_buf: Vec::new(),
361 assembler: ChunkAssembler::new().with_max_in_progress_bytes(max_in_progress_bytes),
362 writer: ChunkWriter::new(),
363 state: State::Init,
364 app: None,
365 next_stream_id: FIRST_STREAM_ID,
366 created_stream_id: None,
367 ack_threshold,
368 peer_bandwidth: None,
369 bytes_received: 0,
370 bytes_acked: 0,
371 flv: FlvTagWriter::default(),
372 failed_publish_attempts: 0,
373 }
374 }
375
376 #[must_use]
378 pub fn with_defaults() -> Self {
379 Self::new(ServerConfig::default())
380 }
381
382 pub fn handle_data(&mut self, input: &[u8]) -> Result<(Vec<u8>, Vec<ServerEvent>)> {
396 let mut out = Vec::new();
397 let mut events = Vec::new();
398
399 let chunk_input = match self.drive_handshake(input, &mut out)? {
400 Some(bytes) => bytes,
401 None => return Ok((out, events)),
402 };
403
404 self.bytes_received = self.bytes_received.saturating_add(chunk_input.len() as u64);
405
406 self.assembler.feed(&chunk_input);
417 while let Some(msg) = self.assembler.next_message()? {
418 self.dispatch_message(&msg, &mut out, &mut events)?;
419 }
420
421 self.maybe_ack(&mut out);
422
423 Ok((out, events))
424 }
425
426 fn drive_handshake<'a>(
432 &mut self,
433 input: &'a [u8],
434 out: &mut Vec<u8>,
435 ) -> Result<Option<std::borrow::Cow<'a, [u8]>>> {
436 if self.handshake.is_done() {
437 return Ok(Some(std::borrow::Cow::Borrowed(input)));
441 }
442
443 self.handshake_buf.extend_from_slice(input);
444 loop {
445 match self.handshake.read(&self.handshake_buf) {
446 Ok((reply, consumed, done)) => {
447 out.extend_from_slice(&reply);
448 self.handshake_buf.drain(..consumed);
449 if done {
450 break;
451 }
452 }
453 Err(RtmpError::BufferTooShort(..)) => break,
454 Err(e) => return Err(e),
455 }
456 }
457
458 if self.handshake.is_done() {
459 Ok(Some(std::borrow::Cow::Owned(core::mem::take(
460 &mut self.handshake_buf,
461 ))))
462 } else {
463 Ok(None)
464 }
465 }
466
467 fn maybe_ack(&mut self, out: &mut Vec<u8>) {
471 let threshold = u64::from(self.ack_threshold.max(1));
472 if self.bytes_received.saturating_sub(self.bytes_acked) >= threshold {
473 self.bytes_acked = self.bytes_received;
474 let seq = self.bytes_received as u32;
475 let ack_msg = ProtocolControl::Acknowledgement(seq).to_message();
476 out.extend_from_slice(
477 &self
478 .writer
479 .write(&ack_msg)
480 .expect("an Acknowledgement control message (4 bytes) never exceeds the 24-bit message_length field"),
481 );
482 }
483 }
484
485 fn dispatch_message(
487 &mut self,
488 msg: &Message,
489 out: &mut Vec<u8>,
490 events: &mut Vec<ServerEvent>,
491 ) -> Result<()> {
492 if let Some(pc) = ProtocolControl::from_message(msg)? {
493 self.handle_protocol_control(pc);
494 return Ok(());
495 }
496
497 match msg.message_type_id {
498 msg_type::USER_CONTROL => {
499 let _ = UserControl::parse(&msg.payload);
504 Ok(())
505 }
506 msg_type::COMMAND_AMF0 => {
507 let command = Command::parse(&msg.payload)?;
508 self.handle_command(&command, msg, out, events)
509 }
510 msg_type::COMMAND_AMF3 => {
517 let body =
518 msg.payload
519 .get(1..)
520 .ok_or(RtmpError::BufferTooShort(BufferTooShort {
521 need: 1,
522 have: msg.payload.len(),
523 what: "AMF3 command encoding marker byte",
524 }))?;
525 let command = Command::parse(body)?;
526 self.handle_command(&command, msg, out, events)
527 }
528 msg_type::AUDIO | msg_type::VIDEO | msg_type::DATA_AMF0 => self
529 .emit_media_if_publishing(msg.message_type_id, msg.timestamp, &msg.payload, events),
530 msg_type::AGGREGATE => self.deliver_aggregate(msg, events),
537 other => {
543 events.push(ServerEvent::Unsupported {
544 message_type_id: other,
545 });
546 Ok(())
547 }
548 }
549 }
550
551 fn handle_protocol_control(&mut self, pc: ProtocolControl) {
555 match pc {
556 ProtocolControl::SetChunkSize(n) => self.assembler.set_chunk_size(n),
557 ProtocolControl::WindowAckSize(w) => self.ack_threshold = w,
558 ProtocolControl::SetPeerBandwidth {
562 ack_window_size, ..
563 } => self.peer_bandwidth = Some(ack_window_size),
564 ProtocolControl::Abort { chunk_stream_id } => self.assembler.abort(chunk_stream_id),
566 ProtocolControl::Acknowledgement(_) => {}
567 }
568 }
569
570 fn handle_command(
572 &mut self,
573 command: &Command,
574 msg: &Message,
575 out: &mut Vec<u8>,
576 events: &mut Vec<ServerEvent>,
577 ) -> Result<()> {
578 match command.name.as_str() {
579 "connect" => self.handle_connect(command, msg, out, events),
580 "releaseStream" | "FCPublish" => {
581 self.reply_result(command, msg, vec![Amf0Value::Undefined], out)
582 }
583 "createStream" => self.handle_create_stream(command, msg, out),
584 "publish" => self.handle_publish(command, msg, out, events),
585 "deleteStream" | "FCUnpublish" => {
586 self.state = State::Closed;
587 events.push(ServerEvent::Eof);
588 Ok(())
589 }
590 _ => Ok(()),
593 }
594 }
595
596 fn handle_connect(
608 &mut self,
609 command: &Command,
610 msg: &Message,
611 out: &mut Vec<u8>,
612 events: &mut Vec<ServerEvent>,
613 ) -> Result<()> {
614 if self.state == State::Closed {
615 return Err(RtmpError::UnexpectedState {
616 what: "connect received after the session was closed",
617 });
618 }
619
620 let Some(Amf0Value::Object(pairs)) = command.arguments.first() else {
621 return Err(RtmpError::Malformed {
622 what: "connect command object / app",
623 });
624 };
625 let Some(app) = pairs.iter().find_map(|(k, v)| {
626 if k == "app" {
627 match v {
628 Amf0Value::String(s) => Some(s.clone()),
629 _ => None,
630 }
631 } else {
632 None
633 }
634 }) else {
635 return Err(RtmpError::Malformed {
636 what: "connect command object / app",
637 });
638 };
639
640 self.app = Some(app.clone());
641 self.state = State::Connected;
642
643 let window_ack = ProtocolControl::WindowAckSize(self.config.window_ack_size).to_message();
644 out.extend_from_slice(&self.writer.write(&window_ack)?);
645
646 let peer_bandwidth = ProtocolControl::SetPeerBandwidth {
647 ack_window_size: self.config.peer_bandwidth,
648 limit_type: LimitType::Dynamic,
649 }
650 .to_message();
651 out.extend_from_slice(&self.writer.write(&peer_bandwidth)?);
652
653 let set_chunk_size =
654 ProtocolControl::SetChunkSize(self.config.chunk_size).try_to_message()?;
655 out.extend_from_slice(&self.writer.write(&set_chunk_size)?);
656 self.writer.set_chunk_size(self.config.chunk_size);
657
658 let result = Command {
659 name: "_result".to_string(),
660 transaction_id: command.transaction_id,
661 arguments: vec![
662 Amf0Value::Object(vec![
663 (
664 "fmsVer".to_string(),
665 Amf0Value::String(FMS_VERSION.to_string()),
666 ),
667 ("capabilities".to_string(), Amf0Value::Number(CAPABILITIES)),
668 ]),
669 Amf0Value::Object(vec![
670 ("level".to_string(), Amf0Value::String("status".to_string())),
671 (
672 "code".to_string(),
673 Amf0Value::String("NetConnection.Connect.Success".to_string()),
674 ),
675 (
676 "description".to_string(),
677 Amf0Value::String("Connection succeeded.".to_string()),
678 ),
679 ]),
680 ],
681 };
682 out.extend_from_slice(&self.writer.write(&self.command_message(msg, &result)?)?);
683
684 events.push(ServerEvent::Connected { app });
685 Ok(())
686 }
687
688 fn handle_create_stream(
696 &mut self,
697 command: &Command,
698 msg: &Message,
699 out: &mut Vec<u8>,
700 ) -> Result<()> {
701 if self.state != State::Connected {
702 return Err(RtmpError::UnexpectedState {
703 what: "createStream received before a successful connect (or after the session was closed)",
704 });
705 }
706
707 let stream_id = self.next_stream_id;
708 self.next_stream_id = self.next_stream_id.saturating_add(1);
709 self.created_stream_id = Some(stream_id);
710
711 let result = Command {
712 name: "_result".to_string(),
713 transaction_id: command.transaction_id,
714 arguments: vec![Amf0Value::Null, Amf0Value::Number(f64::from(stream_id))],
715 };
716 out.extend_from_slice(&self.writer.write(&self.command_message(msg, &result)?)?);
717 Ok(())
718 }
719
720 fn handle_publish(
734 &mut self,
735 command: &Command,
736 msg: &Message,
737 out: &mut Vec<u8>,
738 events: &mut Vec<ServerEvent>,
739 ) -> Result<()> {
740 if self.state != State::Connected || self.created_stream_id.is_none() {
741 return Err(RtmpError::UnexpectedState {
742 what: "publish received before a successful connect+createStream (or after the session was closed)",
743 });
744 }
745 if self.failed_publish_attempts >= MAX_FAILED_PUBLISH_ATTEMPTS {
746 self.state = State::Closed;
747 return Err(RtmpError::UnexpectedState {
748 what: "publish rejected too many times on this connection (stream key mismatch); session closed",
749 });
750 }
751 let app = self
752 .app
753 .clone()
754 .expect("state == Connected implies app was captured by connect");
755
756 let stream_key = match command.arguments.get(1) {
757 Some(Amf0Value::String(s)) => s.clone(),
758 _ => {
759 return Err(RtmpError::Malformed {
760 what: "publish command missing its publishing-name (string) argument",
761 });
762 }
763 };
764 let stream_id = msg.message_stream_id;
765
766 if let Some(expected) = &self.config.expected_stream_key
767 && !constant_time_eq(expected.as_bytes(), stream_key.as_bytes())
768 {
769 self.failed_publish_attempts += 1;
770 let on_status = Command {
771 name: "onStatus".to_string(),
772 transaction_id: 0.0,
773 arguments: vec![
774 Amf0Value::Null,
775 Amf0Value::Object(vec![
776 ("level".to_string(), Amf0Value::String("error".to_string())),
777 (
778 "code".to_string(),
779 Amf0Value::String("NetStream.Publish.BadName".to_string()),
780 ),
781 (
782 "description".to_string(),
783 Amf0Value::String("Stream key mismatch.".to_string()),
784 ),
785 ]),
786 ],
787 };
788 out.extend_from_slice(&self.writer.write(&self.command_message(msg, &on_status)?)?);
789 return Ok(());
791 }
792
793 let stream_begin = UserControl::StreamBegin(stream_id).to_message();
794 out.extend_from_slice(&self.writer.write(&stream_begin)?);
795
796 let on_status = Command {
797 name: "onStatus".to_string(),
798 transaction_id: 0.0,
799 arguments: vec![
800 Amf0Value::Null,
801 Amf0Value::Object(vec![
802 ("level".to_string(), Amf0Value::String("status".to_string())),
803 (
804 "code".to_string(),
805 Amf0Value::String("NetStream.Publish.Start".to_string()),
806 ),
807 (
808 "description".to_string(),
809 Amf0Value::String(format!("{stream_key} is now published.")),
810 ),
811 ]),
812 ],
813 };
814 out.extend_from_slice(&self.writer.write(&self.command_message(msg, &on_status)?)?);
815
816 self.state = State::Publishing;
817 events.push(ServerEvent::Publish {
818 app,
819 stream_key,
820 stream_id,
821 });
822 Ok(())
823 }
824
825 fn reply_result(
829 &mut self,
830 command: &Command,
831 msg: &Message,
832 arguments: Vec<Amf0Value>,
833 out: &mut Vec<u8>,
834 ) -> Result<()> {
835 let result = Command {
836 name: "_result".to_string(),
837 transaction_id: command.transaction_id,
838 arguments,
839 };
840 out.extend_from_slice(&self.writer.write(&self.command_message(msg, &result)?)?);
841 Ok(())
842 }
843
844 fn command_message(&self, request: &Message, command: &Command) -> Result<Message> {
848 Ok(Message {
849 chunk_stream_id: COMMAND_CHUNK_STREAM_ID,
850 timestamp: 0,
851 message_type_id: msg_type::COMMAND_AMF0,
852 message_stream_id: request.message_stream_id,
853 payload: command.to_body()?,
854 })
855 }
856
857 fn emit_media_if_publishing(
862 &mut self,
863 tag_type: u8,
864 timestamp: u32,
865 payload: &[u8],
866 events: &mut Vec<ServerEvent>,
867 ) -> Result<()> {
868 if self.state != State::Publishing {
869 return Ok(());
870 }
871
872 let flv = self.flv.tag(tag_type, timestamp, payload)?;
873 events.push(ServerEvent::Media { flv });
874 Ok(())
875 }
876
877 fn deliver_aggregate(&mut self, msg: &Message, events: &mut Vec<ServerEvent>) -> Result<()> {
887 unpack_aggregate(msg, |tag_type, timestamp, payload| {
888 self.emit_media_if_publishing(tag_type, timestamp, payload, events)
889 })
890 }
891}
892
893#[cfg(test)]
894mod tests {
895 use super::*;
896 use crate::flv_bridge::{
897 FLV_HEADER_SIZE, FLV_PREV_TAG_SIZE_LEN, FLV_TAG_HEADER_LEN, flv_file_header,
898 };
899 use crate::handshake::{HANDSHAKE_PACKET_LEN, RTMP_VERSION};
900 use crate::message::CONTROL_CHUNK_STREAM_ID as CTRL_CSID;
901 use broadcast_common::Serialize;
902
903 const CLIENT_CSID: u32 = 3;
906
907 fn build_c0_c1() -> Vec<u8> {
908 let mut v = vec![0u8; 1 + HANDSHAKE_PACKET_LEN];
909 v[0] = RTMP_VERSION;
910 v
911 }
912
913 fn build_c2() -> Vec<u8> {
914 vec![0u8; HANDSHAKE_PACKET_LEN]
915 }
916
917 fn command_message(
918 csid: u32,
919 stream_id: u32,
920 name: &str,
921 txn: f64,
922 args: Vec<Amf0Value>,
923 ) -> Message {
924 let body = Command {
925 name: name.to_string(),
926 transaction_id: txn,
927 arguments: args,
928 }
929 .to_body()
930 .unwrap();
931 Message {
932 chunk_stream_id: csid,
933 timestamp: 0,
934 message_type_id: msg_type::COMMAND_AMF0,
935 message_stream_id: stream_id,
936 payload: body,
937 }
938 }
939
940 fn connect_bytes(app: &str) -> Vec<u8> {
941 let args = vec![Amf0Value::Object(vec![
942 ("app".to_string(), Amf0Value::String(app.to_string())),
943 (
944 "type".to_string(),
945 Amf0Value::String("nonprivate".to_string()),
946 ),
947 ])];
948 let msg = command_message(CLIENT_CSID, 0, "connect", 1.0, args);
949 ChunkWriter::new().write(&msg).unwrap()
950 }
951
952 fn connect_bytes_no_args() -> Vec<u8> {
953 let msg = command_message(CLIENT_CSID, 0, "connect", 1.0, vec![]);
954 ChunkWriter::new().write(&msg).unwrap()
955 }
956
957 fn create_stream_bytes() -> Vec<u8> {
958 let msg = command_message(CLIENT_CSID, 0, "createStream", 2.0, vec![Amf0Value::Null]);
959 ChunkWriter::new().write(&msg).unwrap()
960 }
961
962 fn publish_bytes(stream_id: u32, stream_key: &str) -> Vec<u8> {
963 let args = vec![
964 Amf0Value::Null,
965 Amf0Value::String(stream_key.to_string()),
966 Amf0Value::String("live".to_string()),
967 ];
968 let msg = command_message(CLIENT_CSID, stream_id, "publish", 3.0, args);
969 ChunkWriter::new().write(&msg).unwrap()
970 }
971
972 fn av_bytes(
973 stream_id: u32,
974 message_type_id: u8,
975 csid: u32,
976 timestamp: u32,
977 payload: Vec<u8>,
978 ) -> Vec<u8> {
979 let msg = Message {
980 chunk_stream_id: csid,
981 timestamp,
982 message_type_id,
983 message_stream_id: stream_id,
984 payload,
985 };
986 ChunkWriter::new().write(&msg).unwrap()
987 }
988
989 fn decode_messages(bytes: &[u8]) -> Vec<Message> {
998 let mut assembler = ChunkAssembler::new();
999 assembler.set_chunk_size(65536);
1000 assembler.push(bytes).expect("well-formed reply stream")
1001 }
1002
1003 fn decode_commands(bytes: &[u8]) -> Vec<Command> {
1004 decode_messages(bytes)
1005 .iter()
1006 .filter(|m| m.message_type_id == msg_type::COMMAND_AMF0)
1007 .map(|m| Command::parse(&m.payload).expect("well-formed command reply"))
1008 .collect()
1009 }
1010
1011 fn onstatus_code(cmd: &Command) -> Option<String> {
1012 cmd.arguments.iter().find_map(|v| match v {
1013 Amf0Value::Object(pairs) => pairs.iter().find_map(|(k, v)| {
1014 if k == "code" {
1015 match v {
1016 Amf0Value::String(s) => Some(s.clone()),
1017 _ => None,
1018 }
1019 } else {
1020 None
1021 }
1022 }),
1023 _ => None,
1024 })
1025 }
1026
1027 fn publish_flow(
1030 config: ServerConfig,
1031 stream_key: &str,
1032 ) -> (ServerSession, Vec<u8>, Vec<ServerEvent>) {
1033 let mut session = ServerSession::new(config);
1034 let mut all_out = Vec::new();
1039 let mut all_events = Vec::new();
1040
1041 session.handle_data(&build_c0_c1()).unwrap();
1042 session.handle_data(&build_c2()).unwrap();
1043
1044 let (out, events) = session.handle_data(&connect_bytes("live")).unwrap();
1045 all_out.extend(out);
1046 all_events.extend(events);
1047
1048 let (out, events) = session.handle_data(&create_stream_bytes()).unwrap();
1049 all_out.extend(out);
1050 all_events.extend(events);
1051
1052 let (out, events) = session.handle_data(&publish_bytes(1, stream_key)).unwrap();
1054 all_out.extend(out);
1055 all_events.extend(events);
1056
1057 (session, all_out, all_events)
1058 }
1059
1060 #[test]
1063 fn handshake_completes_and_reply_contains_s0_s1_s2() {
1064 let mut session = ServerSession::with_defaults();
1065 let (out1, events1) = session.handle_data(&build_c0_c1()).unwrap();
1066 assert_eq!(
1067 out1.len(),
1068 1 + HANDSHAKE_PACKET_LEN + HANDSHAKE_PACKET_LEN,
1069 "S0+S1+S2 must be a single 3073-byte reply"
1070 );
1071 assert!(events1.is_empty());
1072
1073 let (out2, events2) = session.handle_data(&build_c2()).unwrap();
1074 assert!(out2.is_empty(), "C2 receipt produces no reply bytes itself");
1075 assert!(events2.is_empty());
1076 }
1077
1078 #[test]
1079 fn handshake_split_across_calls_still_completes() {
1080 let mut session = ServerSession::with_defaults();
1081 let c0c1 = build_c0_c1();
1082 let (out1, _) = session.handle_data(&c0c1[..500]).unwrap();
1083 assert!(out1.is_empty(), "partial C0+C1 produces no reply yet");
1084 let (out2, _) = session.handle_data(&c0c1[500..]).unwrap();
1085 assert_eq!(out2.len(), 1 + 2 * HANDSHAKE_PACKET_LEN);
1086 let (_out3, _) = session.handle_data(&build_c2()).unwrap();
1087 }
1088
1089 #[test]
1090 fn c2_pipelined_with_connect_chunk_in_one_call_still_parses_connect() {
1091 let mut session = ServerSession::with_defaults();
1098 session.handle_data(&build_c0_c1()).unwrap();
1099
1100 let mut pipelined = build_c2();
1101 pipelined.extend_from_slice(&connect_bytes("live"));
1102
1103 let (_out, events) = session.handle_data(&pipelined).unwrap();
1104 assert_eq!(
1105 events,
1106 vec![ServerEvent::Connected {
1107 app: "live".to_string()
1108 }],
1109 "C2 pipelined with the connect chunk in one handle_data call must \
1110 still yield Connected from that call (leftover bytes must not be dropped)"
1111 );
1112 }
1113
1114 #[test]
1117 fn connect_emits_connected_event_and_result_reply() {
1118 let mut session = ServerSession::with_defaults();
1119 session.handle_data(&build_c0_c1()).unwrap();
1120 session.handle_data(&build_c2()).unwrap();
1121
1122 let (out, events) = session.handle_data(&connect_bytes("live")).unwrap();
1123 assert_eq!(
1124 events,
1125 vec![ServerEvent::Connected {
1126 app: "live".to_string()
1127 }]
1128 );
1129
1130 let commands = decode_commands(&out);
1131 assert!(
1132 commands.iter().any(|c| c.name == "_result"),
1133 "connect reply must contain a _result command"
1134 );
1135 }
1136
1137 #[test]
1140 fn connect_with_invalid_configured_chunk_size_errors_not_panics() {
1141 let mut session = ServerSession::new(ServerConfig::default().with_chunk_size(0));
1142 session.handle_data(&build_c0_c1()).unwrap();
1143 session.handle_data(&build_c2()).unwrap();
1144 let err = session.handle_data(&connect_bytes("live")).unwrap_err();
1145 assert!(matches!(err, RtmpError::Malformed { .. }), "{err:?}");
1146 }
1147
1148 #[test]
1153 fn amf3_connect_is_answered_like_amf0() {
1154 let mut session = ServerSession::with_defaults();
1155 session.handle_data(&build_c0_c1()).unwrap();
1156 session.handle_data(&build_c2()).unwrap();
1157
1158 let args = vec![Amf0Value::Object(vec![(
1159 "app".to_string(),
1160 Amf0Value::String("live".to_string()),
1161 )])];
1162 let amf0_body = Command {
1163 name: "connect".to_string(),
1164 transaction_id: 1.0,
1165 arguments: args,
1166 }
1167 .to_body()
1168 .unwrap();
1169 let mut amf3_body = vec![0x00]; amf3_body.extend(amf0_body);
1171 let msg = Message {
1172 chunk_stream_id: CLIENT_CSID,
1173 timestamp: 0,
1174 message_type_id: msg_type::COMMAND_AMF3,
1175 message_stream_id: 0,
1176 payload: amf3_body,
1177 };
1178 let bytes = ChunkWriter::new().write(&msg).unwrap();
1179
1180 let (out, events) = session.handle_data(&bytes).unwrap();
1181 assert_eq!(
1182 events,
1183 vec![ServerEvent::Connected {
1184 app: "live".to_string()
1185 }]
1186 );
1187 let commands = decode_commands(&out);
1188 assert!(
1189 commands.iter().any(|c| c.name == "_result"),
1190 "AMF3 connect must still get a _result reply"
1191 );
1192 }
1193
1194 #[test]
1202 fn aggregate_message_surfaces_unsupported_event() {
1203 let mut session = ServerSession::with_defaults();
1204 session.handle_data(&build_c0_c1()).unwrap();
1205 session.handle_data(&build_c2()).unwrap();
1206 session.handle_data(&connect_bytes("live")).unwrap();
1207
1208 let msg = Message {
1209 chunk_stream_id: CLIENT_CSID,
1210 timestamp: 0,
1211 message_type_id: msg_type::AGGREGATE,
1212 message_stream_id: 0,
1213 payload: vec![0xAA; 20], };
1215 let bytes = ChunkWriter::new().write(&msg).unwrap();
1216
1217 let err = session.handle_data(&bytes).unwrap_err();
1218 assert!(
1219 matches!(err, RtmpError::Malformed { .. }),
1220 "a garbage aggregate body must now be a Malformed error, got {err:?}"
1221 );
1222 }
1223
1224 fn aggregate_body(subs: &[(u8, u32, &[u8])]) -> Vec<u8> {
1229 let mut body = Vec::new();
1230 for &(tag_type, timestamp, data) in subs {
1231 let data_size = data.len() as u32;
1232 body.push(tag_type);
1233 body.push((data_size >> 16) as u8);
1234 body.push((data_size >> 8) as u8);
1235 body.push(data_size as u8);
1236 body.push((timestamp >> 16) as u8);
1237 body.push((timestamp >> 8) as u8);
1238 body.push(timestamp as u8);
1239 body.push((timestamp >> 24) as u8);
1240 body.extend_from_slice(&[0, 0, 0]); body.extend_from_slice(data);
1242 let back_pointer = (11 + data.len()) as u32;
1243 body.extend_from_slice(&back_pointer.to_be_bytes());
1244 }
1245 body
1246 }
1247
1248 fn first_flv_tag_header(flv: &[u8]) -> (u8, u32) {
1251 let tag = if flv.len() > 13 && flv.starts_with(b"FLV") {
1252 &flv[13..]
1253 } else {
1254 flv
1255 };
1256 let ts_low24 = u32::from_be_bytes([0, tag[4], tag[5], tag[6]]);
1257 (tag[0], ts_low24 | (u32::from(tag[7]) << 24))
1258 }
1259
1260 fn publishing_session() -> ServerSession {
1263 let mut session = ServerSession::new(ServerConfig::default());
1264 session.handle_data(&build_c0_c1()).unwrap();
1265 session.handle_data(&build_c2()).unwrap();
1266 session.handle_data(&connect_bytes("live")).unwrap();
1267 session.handle_data(&create_stream_bytes()).unwrap();
1268 session.handle_data(&publish_bytes(1, "mystream")).unwrap();
1269 session
1270 }
1271
1272 #[test]
1276 fn aggregate_message_is_unpacked_into_media_events() {
1277 let mut session = publishing_session();
1278 let body = aggregate_body(&[
1279 (msg_type::VIDEO, 1000, &[0x17, 0x01, 0xAA, 0xBB]),
1280 (msg_type::VIDEO, 1040, &[0x27, 0x01, 0xCC]),
1281 (msg_type::AUDIO, 1005, &[0xAF, 0x01, 0xDD, 0xEE]),
1282 ]);
1283 let msg = Message {
1284 chunk_stream_id: CLIENT_CSID,
1285 timestamp: 1000, message_type_id: msg_type::AGGREGATE,
1287 message_stream_id: 1,
1288 payload: body,
1289 };
1290 let bytes = ChunkWriter::new().write(&msg).unwrap();
1291 let (_out, events) = session.handle_data(&bytes).unwrap();
1292 let tags: Vec<(u8, u32)> = events
1293 .iter()
1294 .map(|e| match e {
1295 ServerEvent::Media { flv } => first_flv_tag_header(flv),
1296 other => panic!("expected only Media events, got {other:?}"),
1297 })
1298 .collect();
1299 assert_eq!(
1300 tags,
1301 vec![
1302 (msg_type::VIDEO, 1000),
1303 (msg_type::VIDEO, 1040),
1304 (msg_type::AUDIO, 1005),
1305 ]
1306 );
1307 }
1308
1309 #[test]
1313 fn aggregate_timestamps_are_renormalized_against_the_aggregate() {
1314 let mut session = publishing_session();
1315 let body = aggregate_body(&[
1316 (msg_type::VIDEO, 50, &[0x17, 0x01]),
1317 (msg_type::AUDIO, 60, &[0xAF, 0x01]),
1318 ]);
1319 let msg = Message {
1320 chunk_stream_id: CLIENT_CSID,
1321 timestamp: 100,
1322 message_type_id: msg_type::AGGREGATE,
1323 message_stream_id: 1,
1324 payload: body,
1325 };
1326 let bytes = ChunkWriter::new().write(&msg).unwrap();
1327 let (_out, events) = session.handle_data(&bytes).unwrap();
1328 let tags: Vec<(u8, u32)> = events
1329 .iter()
1330 .map(|e| match e {
1331 ServerEvent::Media { flv } => first_flv_tag_header(flv),
1332 other => panic!("expected only Media events, got {other:?}"),
1333 })
1334 .collect();
1335 assert_eq!(tags, vec![(msg_type::VIDEO, 100), (msg_type::AUDIO, 110)]);
1337 }
1338
1339 #[test]
1343 fn truncated_aggregate_message_errors() {
1344 let mut session = publishing_session();
1345 let mut body = aggregate_body(&[(msg_type::VIDEO, 0, &[0x17, 0x01, 0xAA])]);
1346 body.truncate(body.len() - 5);
1349 let msg = Message {
1350 chunk_stream_id: CLIENT_CSID,
1351 timestamp: 0,
1352 message_type_id: msg_type::AGGREGATE,
1353 message_stream_id: 1,
1354 payload: body,
1355 };
1356 let bytes = ChunkWriter::new().write(&msg).unwrap();
1357 let err = session.handle_data(&bytes).unwrap_err();
1358 assert!(
1359 matches!(err, RtmpError::Malformed { .. }),
1360 "a truncated aggregate must be Malformed, got {err:?}"
1361 );
1362 }
1363
1364 #[test]
1367 fn aggregate_with_bad_back_pointer_errors() {
1368 let mut session = publishing_session();
1369 let mut body = aggregate_body(&[(msg_type::VIDEO, 0, &[0x17, 0x01, 0xAA])]);
1370 let back_at = body.len() - 4;
1371 body[back_at] = 0xFF; let msg = Message {
1373 chunk_stream_id: CLIENT_CSID,
1374 timestamp: 0,
1375 message_type_id: msg_type::AGGREGATE,
1376 message_stream_id: 1,
1377 payload: body,
1378 };
1379 let bytes = ChunkWriter::new().write(&msg).unwrap();
1380 let err = session.handle_data(&bytes).unwrap_err();
1381 assert!(
1382 matches!(err, RtmpError::Malformed { .. }),
1383 "a lying Back Pointer must be Malformed, got {err:?}"
1384 );
1385 }
1386
1387 #[test]
1388 fn connect_without_command_object_is_malformed() {
1389 let mut session = ServerSession::with_defaults();
1390 session.handle_data(&build_c0_c1()).unwrap();
1391 session.handle_data(&build_c2()).unwrap();
1392
1393 let err = session.handle_data(&connect_bytes_no_args()).unwrap_err();
1395 assert!(
1396 matches!(err, RtmpError::Malformed { .. }),
1397 "connect with no command-object argument must error, not default app to \"\""
1398 );
1399 }
1400
1401 #[test]
1404 fn connect_with_object_missing_app_key_is_malformed() {
1405 let mut session = ServerSession::with_defaults();
1406 session.handle_data(&build_c0_c1()).unwrap();
1407 session.handle_data(&build_c2()).unwrap();
1408
1409 let args = vec![Amf0Value::Object(vec![(
1411 "type".to_string(),
1412 Amf0Value::String("nonprivate".to_string()),
1413 )])];
1414 let msg = command_message(CLIENT_CSID, 0, "connect", 1.0, args);
1415 let bytes = ChunkWriter::new().write(&msg).unwrap();
1416
1417 let err = session.handle_data(&bytes).unwrap_err();
1418 assert!(
1419 matches!(err, RtmpError::Malformed { .. }),
1420 "connect with object missing 'app' key must error"
1421 );
1422 }
1423
1424 #[test]
1427 fn connect_with_app_as_number_is_malformed() {
1428 let mut session = ServerSession::with_defaults();
1429 session.handle_data(&build_c0_c1()).unwrap();
1430 session.handle_data(&build_c2()).unwrap();
1431
1432 let args = vec![Amf0Value::Object(vec![
1434 ("app".to_string(), Amf0Value::Number(123.0)),
1435 (
1436 "type".to_string(),
1437 Amf0Value::String("nonprivate".to_string()),
1438 ),
1439 ])];
1440 let msg = command_message(CLIENT_CSID, 0, "connect", 1.0, args);
1441 let bytes = ChunkWriter::new().write(&msg).unwrap();
1442
1443 let err = session.handle_data(&bytes).unwrap_err();
1444 assert!(
1445 matches!(err, RtmpError::Malformed { .. }),
1446 "connect with app as Number must error, not accept numeric value"
1447 );
1448 }
1449
1450 #[test]
1453 fn create_stream_replies_result_with_stream_id() {
1454 let mut session = ServerSession::with_defaults();
1455 session.handle_data(&build_c0_c1()).unwrap();
1456 session.handle_data(&build_c2()).unwrap();
1457 session.handle_data(&connect_bytes("live")).unwrap();
1458
1459 let (out, _events) = session.handle_data(&create_stream_bytes()).unwrap();
1460 let commands = decode_commands(&out);
1461 let result = commands
1462 .iter()
1463 .find(|c| c.name == "_result")
1464 .expect("createStream _result reply");
1465 assert_eq!(
1466 result.arguments.get(1),
1467 Some(&Amf0Value::Number(1.0)),
1468 "first allocated stream id must be 1"
1469 );
1470 }
1471
1472 #[test]
1473 fn create_stream_before_connect_is_unexpected_state() {
1474 let mut session = ServerSession::with_defaults();
1475 session.handle_data(&build_c0_c1()).unwrap();
1476 session.handle_data(&build_c2()).unwrap();
1477
1478 let err = session.handle_data(&create_stream_bytes()).unwrap_err();
1479 assert!(matches!(err, RtmpError::UnexpectedState { .. }));
1480 }
1481
1482 #[test]
1489 fn oversized_publish_name_errors_instead_of_panicking() {
1490 for len in [65_518usize, 65_530, 65_535] {
1491 let mut session = ServerSession::new(ServerConfig::default());
1492 session.handle_data(&build_c0_c1()).unwrap();
1493 session.handle_data(&build_c2()).unwrap();
1494 session.handle_data(&connect_bytes("live")).unwrap();
1495 session.handle_data(&create_stream_bytes()).unwrap();
1496 let key = "k".repeat(len);
1497 let err = session
1498 .handle_data(&publish_bytes(1, &key))
1499 .expect_err("overflowing onStatus description must be an Err");
1500 assert!(
1501 matches!(err, RtmpError::Unsupported { .. }),
1502 "len {len}: {err:?}"
1503 );
1504 }
1505 }
1506
1507 #[test]
1508 fn publish_reaches_publishing_emits_event_and_stream_begin_plus_onstatus() {
1509 let (_session, out, events) = publish_flow(ServerConfig::default(), "testkey");
1510
1511 assert!(events.contains(&ServerEvent::Publish {
1512 app: "live".to_string(),
1513 stream_key: "testkey".to_string(),
1514 stream_id: 1,
1515 }));
1516
1517 let messages = decode_messages(&out);
1518 let has_stream_begin = messages.iter().any(|m| {
1519 m.message_type_id == msg_type::USER_CONTROL
1520 && matches!(
1521 UserControl::parse(&m.payload),
1522 Ok(UserControl::StreamBegin(1))
1523 )
1524 });
1525 assert!(
1526 has_stream_begin,
1527 "publish reply must include StreamBegin(1)"
1528 );
1529
1530 let commands = decode_commands(&out);
1531 let on_status = commands
1532 .iter()
1533 .find(|c| c.name == "onStatus")
1534 .expect("onStatus reply to publish");
1535 assert_eq!(
1536 onstatus_code(on_status).as_deref(),
1537 Some("NetStream.Publish.Start")
1538 );
1539 }
1540
1541 #[test]
1542 fn publish_before_connect_is_unexpected_state() {
1543 let mut session = ServerSession::with_defaults();
1544 session.handle_data(&build_c0_c1()).unwrap();
1545 session.handle_data(&build_c2()).unwrap();
1546
1547 let err = session
1548 .handle_data(&publish_bytes(1, "testkey"))
1549 .unwrap_err();
1550 assert!(matches!(err, RtmpError::UnexpectedState { .. }));
1551 }
1552
1553 #[test]
1554 fn publish_without_create_stream_is_unexpected_state() {
1555 let mut session = ServerSession::with_defaults();
1556 session.handle_data(&build_c0_c1()).unwrap();
1557 session.handle_data(&build_c2()).unwrap();
1558 session.handle_data(&connect_bytes("live")).unwrap();
1559
1560 let err = session
1562 .handle_data(&publish_bytes(1, "testkey"))
1563 .unwrap_err();
1564 assert!(matches!(err, RtmpError::UnexpectedState { .. }));
1565 }
1566
1567 #[test]
1568 fn create_stream_after_closed_is_unexpected_state() {
1569 let mut session = ServerSession::with_defaults();
1570 session.handle_data(&build_c0_c1()).unwrap();
1571 session.handle_data(&build_c2()).unwrap();
1572 session.handle_data(&connect_bytes("live")).unwrap();
1573 session.handle_data(&create_stream_bytes()).unwrap();
1574 session.handle_data(&publish_bytes(1, "testkey")).unwrap();
1575
1576 let delete_stream = command_message(
1577 CLIENT_CSID,
1578 1,
1579 "deleteStream",
1580 4.0,
1581 vec![Amf0Value::Null, Amf0Value::Number(1.0)],
1582 );
1583 let (_out, events) = session
1584 .handle_data(&ChunkWriter::new().write(&delete_stream).unwrap())
1585 .unwrap();
1586 assert_eq!(events, vec![ServerEvent::Eof]);
1587
1588 let err = session.handle_data(&create_stream_bytes()).unwrap_err();
1589 assert!(
1590 matches!(err, RtmpError::UnexpectedState { .. }),
1591 "createStream after State::Closed must be rejected, not silently re-allowed"
1592 );
1593 }
1594
1595 #[test]
1598 fn audio_and_video_emit_media_first_carries_flv_file_header() {
1599 let (mut session, _out, _events) = publish_flow(ServerConfig::default(), "testkey");
1600
1601 let (_out1, events1) = session
1602 .handle_data(&av_bytes(
1603 1,
1604 msg_type::AUDIO,
1605 4,
1606 0,
1607 vec![0xAF, 0x01, 0xDE, 0xAD],
1608 ))
1609 .unwrap();
1610 assert_eq!(events1.len(), 1);
1611 let ServerEvent::Media { flv } = &events1[0] else {
1612 panic!("expected Media event");
1613 };
1614 assert!(
1615 flv.starts_with(b"FLV"),
1616 "the first Media event must carry the FLV file header"
1617 );
1618
1619 let (_out2, events2) = session
1620 .handle_data(&av_bytes(
1621 1,
1622 msg_type::VIDEO,
1623 6,
1624 40,
1625 vec![0x17, 0x01, 0x00, 0x00, 0x00, 0xDE, 0xAD, 0xBE, 0xEF],
1626 ))
1627 .unwrap();
1628 assert_eq!(events2.len(), 1);
1629 let ServerEvent::Media { flv } = &events2[0] else {
1630 panic!("expected Media event");
1631 };
1632 assert!(
1633 !flv.starts_with(b"FLV"),
1634 "only the first Media event carries the file header"
1635 );
1636 }
1637
1638 #[test]
1639 fn concatenated_media_forms_structurally_valid_flv() {
1640 let (mut session, _out, _events) = publish_flow(ServerConfig::default(), "testkey");
1641
1642 let mut flv_stream = Vec::new();
1643 let (_out1, events1) = session
1644 .handle_data(&av_bytes(
1645 1,
1646 msg_type::AUDIO,
1647 4,
1648 0,
1649 vec![0xAF, 0x01, 1, 2, 3],
1650 ))
1651 .unwrap();
1652 let (_out2, events2) = session
1653 .handle_data(&av_bytes(
1654 1,
1655 msg_type::VIDEO,
1656 6,
1657 33,
1658 vec![0x17, 0x01, 0, 0, 0, 4, 5, 6],
1659 ))
1660 .unwrap();
1661 for e in events1.into_iter().chain(events2) {
1662 if let ServerEvent::Media { flv } = e {
1663 flv_stream.extend(flv);
1664 }
1665 }
1666
1667 assert_eq!(&flv_stream[0..3], b"FLV");
1669 assert_eq!(flv_stream[3], 1, "FLV version");
1670 assert_eq!(flv_stream[4], 0b0000_0101, "audio+video TypeFlags");
1671 assert_eq!(
1672 u32::from_be_bytes(flv_stream[5..9].try_into().unwrap()),
1673 9,
1674 "DataOffset (header size)"
1675 );
1676 assert_eq!(
1677 u32::from_be_bytes(flv_stream[9..13].try_into().unwrap()),
1678 0,
1679 "PreviousTagSize0"
1680 );
1681
1682 let tag1 = &flv_stream[13..];
1684 assert_eq!(tag1[0], msg_type::AUDIO);
1685 let data_size1 =
1686 (u32::from(tag1[1]) << 16) | (u32::from(tag1[2]) << 8) | u32::from(tag1[3]);
1687 assert_eq!(data_size1, 5);
1688 let tag1_total = FLV_TAG_HEADER_LEN + 5 + FLV_PREV_TAG_SIZE_LEN;
1689 let prev_tag_size1 = u32::from_be_bytes(
1690 flv_stream[13 + tag1_total - 4..13 + tag1_total]
1691 .try_into()
1692 .unwrap(),
1693 );
1694 assert_eq!(prev_tag_size1 as usize, FLV_TAG_HEADER_LEN + 5);
1695
1696 let tag2 = &flv_stream[13 + tag1_total..];
1698 assert_eq!(tag2[0], msg_type::VIDEO);
1699 let data_size2 =
1700 (u32::from(tag2[1]) << 16) | (u32::from(tag2[2]) << 8) | u32::from(tag2[3]);
1701 assert_eq!(data_size2, 8);
1702 assert_eq!(
1703 flv_stream.len(),
1704 13 + tag1_total + FLV_TAG_HEADER_LEN + 8 + FLV_PREV_TAG_SIZE_LEN
1705 );
1706 }
1707
1708 #[test]
1709 fn data_amf0_onmetadata_emits_media_with_script_tag_type() {
1710 let (mut session, _out, _events) = publish_flow(ServerConfig::default(), "testkey");
1711
1712 let mut payload = Amf0Value::String("onMetaData".to_string())
1717 .try_to_bytes()
1718 .unwrap();
1719 payload.extend(
1720 Amf0Value::Object(vec![
1721 ("width".to_string(), Amf0Value::Number(1920.0)),
1722 ("height".to_string(), Amf0Value::Number(1080.0)),
1723 ])
1724 .try_to_bytes()
1725 .unwrap(),
1726 );
1727
1728 let (_out, events) = session
1729 .handle_data(&av_bytes(1, msg_type::DATA_AMF0, 4, 0, payload))
1730 .unwrap();
1731
1732 assert_eq!(events.len(), 1);
1733 let ServerEvent::Media { flv } = &events[0] else {
1734 panic!("expected Media event");
1735 };
1736 assert!(
1737 flv.starts_with(b"FLV"),
1738 "the first Media event must carry the FLV file header"
1739 );
1740 let tag_type = flv[FLV_HEADER_SIZE as usize + FLV_PREV_TAG_SIZE_LEN];
1741 assert_eq!(
1742 tag_type,
1743 msg_type::DATA_AMF0,
1744 "Data-AMF0 message must produce a script(18) FLV tag"
1745 );
1746 }
1747
1748 #[test]
1749 fn media_before_publishing_is_silently_dropped() {
1750 let mut session = ServerSession::with_defaults();
1751 session.handle_data(&build_c0_c1()).unwrap();
1752 session.handle_data(&build_c2()).unwrap();
1753 session.handle_data(&connect_bytes("live")).unwrap();
1754 session.handle_data(&create_stream_bytes()).unwrap();
1755
1756 let (_out, events) = session
1758 .handle_data(&av_bytes(1, msg_type::AUDIO, 4, 0, vec![0xAF, 0x01]))
1759 .unwrap();
1760 assert!(events.is_empty());
1761 }
1762
1763 #[test]
1766 fn stream_key_mismatch_suppresses_publish_and_media_events() {
1767 let config = ServerConfig {
1768 expected_stream_key: Some("rightkey".to_string()),
1769 ..ServerConfig::default()
1770 };
1771 let (mut session, out, events) = publish_flow(config, "wrongkey");
1772
1773 assert!(
1774 !events
1775 .iter()
1776 .any(|e| matches!(e, ServerEvent::Publish { .. })),
1777 "mismatched stream key must not emit Publish"
1778 );
1779
1780 let commands = decode_commands(&out);
1781 let on_status = commands
1782 .iter()
1783 .find(|c| c.name == "onStatus")
1784 .expect("onStatus reply on mismatch");
1785 assert_eq!(
1786 onstatus_code(on_status).as_deref(),
1787 Some("NetStream.Publish.BadName")
1788 );
1789
1790 let (_out2, events2) = session
1792 .handle_data(&av_bytes(1, msg_type::AUDIO, 4, 0, vec![0xAF, 0x01]))
1793 .unwrap();
1794 assert!(
1795 events2.is_empty(),
1796 "no Media may be emitted after a rejected publish"
1797 );
1798 }
1799
1800 #[test]
1801 fn stream_key_match_still_publishes_with_key_configured() {
1802 let config = ServerConfig {
1803 expected_stream_key: Some("rightkey".to_string()),
1804 ..ServerConfig::default()
1805 };
1806 let (_session, _out, events) = publish_flow(config, "rightkey");
1807 assert!(
1808 events.contains(&ServerEvent::Publish {
1809 app: "live".to_string(),
1810 stream_key: "rightkey".to_string(),
1811 stream_id: 1,
1812 }),
1813 "a stream key matching expected_stream_key must still publish"
1814 );
1815 }
1816
1817 #[test]
1818 fn too_many_failed_publish_attempts_closes_the_session() {
1819 let config = ServerConfig {
1820 expected_stream_key: Some("rightkey".to_string()),
1821 ..ServerConfig::default()
1822 };
1823 let mut session = ServerSession::new(config);
1824 session.handle_data(&build_c0_c1()).unwrap();
1825 session.handle_data(&build_c2()).unwrap();
1826 session.handle_data(&connect_bytes("live")).unwrap();
1827 session.handle_data(&create_stream_bytes()).unwrap();
1828
1829 for attempt in 1..=MAX_FAILED_PUBLISH_ATTEMPTS {
1830 let (_out, events) = session.handle_data(&publish_bytes(1, "wrongkey")).unwrap_or_else(|e| {
1831 panic!("attempt {attempt} of {MAX_FAILED_PUBLISH_ATTEMPTS} must still be rejected, not error out: {e}")
1832 });
1833 assert!(
1834 !events
1835 .iter()
1836 .any(|e| matches!(e, ServerEvent::Publish { .. })),
1837 "attempt {attempt} must not publish"
1838 );
1839 }
1840
1841 let err = session
1844 .handle_data(&publish_bytes(1, "wrongkey"))
1845 .expect_err("the attempt beyond MAX_FAILED_PUBLISH_ATTEMPTS must close the session");
1846 assert!(matches!(err, RtmpError::UnexpectedState { .. }));
1847
1848 let err = session
1850 .handle_data(&publish_bytes(1, "rightkey"))
1851 .expect_err(
1852 "publish must be rejected once the session was closed for too many failures",
1853 );
1854 assert!(matches!(err, RtmpError::UnexpectedState { .. }));
1855 }
1856
1857 #[test]
1858 fn constant_time_eq_matches_naive_equality() {
1859 assert!(constant_time_eq(b"rightkey", b"rightkey"));
1860 assert!(!constant_time_eq(b"rightkey", b"wrongkey"));
1861 assert!(!constant_time_eq(b"short", b"muchlonger"));
1862 assert!(constant_time_eq(b"", b""));
1863 }
1864
1865 #[test]
1868 fn ack_written_once_window_ack_size_is_crossed() {
1869 let config = ServerConfig {
1870 window_ack_size: 32,
1871 ..ServerConfig::default()
1872 };
1873 let mut session = ServerSession::new(config);
1874 session.handle_data(&build_c0_c1()).unwrap();
1875 session.handle_data(&build_c2()).unwrap();
1876
1877 let (out, _events) = session.handle_data(&connect_bytes("live")).unwrap();
1879 let messages = decode_messages(&out);
1880 let has_ack = messages.iter().any(|m| {
1881 matches!(
1882 ProtocolControl::from_message(m),
1883 Ok(Some(ProtocolControl::Acknowledgement(_)))
1884 )
1885 });
1886 assert!(
1887 has_ack,
1888 "crossing window_ack_size must produce an Acknowledgement"
1889 );
1890 }
1891
1892 #[test]
1893 fn no_ack_below_window_ack_size() {
1894 let config = ServerConfig {
1895 window_ack_size: 10_000_000,
1896 ..ServerConfig::default()
1897 };
1898 let mut session = ServerSession::new(config);
1899 session.handle_data(&build_c0_c1()).unwrap();
1900 let (out, _events) = session.handle_data(&build_c2()).unwrap();
1901 let messages = decode_messages(&out);
1902 assert!(
1903 !messages.iter().any(|m| matches!(
1904 ProtocolControl::from_message(m),
1905 Ok(Some(ProtocolControl::Acknowledgement(_)))
1906 )),
1907 "no Acknowledgement should be due yet"
1908 );
1909 }
1910
1911 #[test]
1914 fn garbage_command_payload_after_handshake_is_error_not_panic() {
1915 let mut session = ServerSession::with_defaults();
1916 session.handle_data(&build_c0_c1()).unwrap();
1917 session.handle_data(&build_c2()).unwrap();
1918
1919 let bogus = Message {
1923 chunk_stream_id: CLIENT_CSID,
1924 timestamp: 0,
1925 message_type_id: msg_type::COMMAND_AMF0,
1926 message_stream_id: 0,
1927 payload: vec![0xFF, 0xFF, 0xFF, 0xFF],
1928 };
1929 let bytes = ChunkWriter::new().write(&bogus).unwrap();
1930 let err = session.handle_data(&bytes).unwrap_err();
1931 assert!(matches!(
1932 err,
1933 RtmpError::Unsupported { .. }
1934 | RtmpError::Malformed { .. }
1935 | RtmpError::BufferTooShort(..)
1936 ));
1937 }
1938
1939 #[test]
1940 fn truncated_post_handshake_bytes_do_not_panic() {
1941 let mut session = ServerSession::with_defaults();
1942 session.handle_data(&build_c0_c1()).unwrap();
1943 session.handle_data(&build_c2()).unwrap();
1944
1945 let (out, events) = session.handle_data(&[0x03, 0x01, 0x02]).unwrap();
1947 assert!(out.is_empty());
1948 assert!(events.is_empty());
1949 }
1950
1951 #[test]
1954 fn mutation_check_publish_event_must_echo_actual_stream_key() {
1955 let (_session, _out, events) = publish_flow(ServerConfig::default(), "specific-key-xyz");
1956 let publish_event = events
1957 .iter()
1958 .find_map(|e| match e {
1959 ServerEvent::Publish { stream_key, .. } => Some(stream_key.clone()),
1960 _ => None,
1961 })
1962 .expect("Publish event");
1963 assert_eq!(
1964 publish_event, "specific-key-xyz",
1965 "a hardcoded/ignored stream_key would fail this"
1966 );
1967 }
1968
1969 #[test]
1970 fn mutation_check_flv_file_header_bytes_are_exact() {
1971 let header = flv_file_header();
1972 assert_eq!(
1973 header,
1974 vec![
1975 b'F',
1976 b'L',
1977 b'V', 1, 0b0000_0101, 0,
1981 0,
1982 0,
1983 9, 0,
1985 0,
1986 0,
1987 0, ]
1989 );
1990 }
1991
1992 #[test]
1995 fn client_set_chunk_size_takes_effect_before_next_message_in_same_call() {
1996 let (mut session, _out, _events) = publish_flow(ServerConfig::default(), "testkey");
2005
2006 const NEW_CHUNK_SIZE: u32 = 4096;
2007 let set_chunk_size_bytes = ChunkWriter::new()
2008 .write(&ProtocolControl::SetChunkSize(NEW_CHUNK_SIZE).to_message())
2009 .unwrap();
2010
2011 let big_payload = vec![0x17u8; 300];
2016 let mut client_writer = ChunkWriter::new();
2017 client_writer.set_chunk_size(NEW_CHUNK_SIZE);
2018 let video_bytes = client_writer
2019 .write(&Message {
2020 chunk_stream_id: 6,
2021 timestamp: 0,
2022 message_type_id: msg_type::VIDEO,
2023 message_stream_id: 1,
2024 payload: big_payload.clone(),
2025 })
2026 .unwrap();
2027
2028 let mut combined = set_chunk_size_bytes;
2029 combined.extend_from_slice(&video_bytes);
2030
2031 let (_out, events) = session.handle_data(&combined).expect(
2034 "SetChunkSize must take effect before parsing the message that follows it \
2035 in the same handle_data call, not only on a subsequent call",
2036 );
2037
2038 let media = events
2039 .iter()
2040 .find_map(|e| match e {
2041 ServerEvent::Media { flv } => Some(flv.clone()),
2042 _ => None,
2043 })
2044 .expect("the video message must still be parsed into a Media event");
2045 assert!(
2046 media
2047 .windows(big_payload.len())
2048 .any(|w| w == big_payload.as_slice()),
2049 "the video payload must survive intact through the chunk-size change"
2050 );
2051 }
2052
2053 #[test]
2054 fn control_chunk_stream_id_constant_matches_message_module() {
2055 assert_ne!(COMMAND_CHUNK_STREAM_ID, CTRL_CSID);
2058 }
2059
2060 #[test]
2061 fn next_stream_id_saturates_instead_of_overflowing() {
2062 let mut session = ServerSession::with_defaults();
2067 session.handle_data(&build_c0_c1()).unwrap();
2068 session.handle_data(&build_c2()).unwrap();
2069 session.handle_data(&connect_bytes("live")).unwrap();
2070
2071 session.next_stream_id = u32::MAX;
2072 let (out, _events) = session
2073 .handle_data(&create_stream_bytes())
2074 .expect("createStream must not panic when next_stream_id is already u32::MAX");
2075
2076 let commands = decode_commands(&out);
2077 let result = commands
2078 .iter()
2079 .find(|c| c.name == "_result")
2080 .expect("createStream _result reply");
2081 assert_eq!(
2082 result.arguments.get(1),
2083 Some(&Amf0Value::Number(f64::from(u32::MAX))),
2084 "the stream id allocated at the u32::MAX boundary must still be u32::MAX"
2085 );
2086 assert_eq!(
2087 session.next_stream_id,
2088 u32::MAX,
2089 "next_stream_id must saturate at u32::MAX, not wrap to 0"
2090 );
2091 }
2092
2093 #[cfg(feature = "serde")]
2096 #[test]
2097 fn server_config_and_server_event_serde_round_trip() {
2098 let config = ServerConfig::default()
2099 .with_chunk_size(8192)
2100 .with_expected_stream_key(Some("k".to_string()));
2101 let json = serde_json::to_string(&config).expect("serialize ServerConfig");
2102 let back: ServerConfig = serde_json::from_str(&json).expect("deserialize ServerConfig");
2103 assert_eq!(back.chunk_size, config.chunk_size);
2104 assert_eq!(back.expected_stream_key, config.expected_stream_key);
2105
2106 let event = ServerEvent::Publish {
2107 app: "live".to_string(),
2108 stream_key: "testkey".to_string(),
2109 stream_id: 1,
2110 };
2111 let json = serde_json::to_string(&event).expect("serialize ServerEvent");
2112 let back: ServerEvent = serde_json::from_str(&json).expect("deserialize ServerEvent");
2113 assert_eq!(back, event);
2114 }
2115}