diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index b8a5c41..22f3e97 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -25,6 +25,7 @@ mod version; pub(crate) use connection::*; pub use errors::Error; pub use ledstate::LightState; +pub use login::MaxEncryption; pub use motion::{MotionData, MotionStatus}; pub use pirstate::PirState; pub use ptz::Direction; diff --git a/crates/core/src/bc_protocol/connection/udpsource.rs b/crates/core/src/bc_protocol/connection/udpsource.rs index 550eeda..70b99cb 100644 --- a/crates/core/src/bc_protocol/connection/udpsource.rs +++ b/crates/core/src/bc_protocol/connection/udpsource.rs @@ -217,29 +217,33 @@ pub(crate) struct UdpPayloadSource { impl UdpPayloadSource { fn build_send_ack(&self) -> UdpAck { - assert!(self.packets_want > 0); - let start: u32 = self.packets_want - 1; - let missing_ids = if let Some(end) = self.recieved.keys().max() { - let mut vec = vec![]; - // From last contiguous packet to last recieved packet - // create a payload of `00` (unreceived) and `01` (received) - // that can be used to form the `UdpAck` packet - for i in (start + 1)..(end + 1) { - if self.recieved.contains_key(&i) { - vec.push(1) - } else { - vec.push(0) + if self.packets_want > 0 { + let start: u32 = self.packets_want - 1; + let missing_ids = if let Some(end) = self.recieved.keys().max() { + let mut vec = vec![]; + // From last contiguous packet to last recieved packet + // create a payload of `00` (unreceived) and `01` (received) + // that can be used to form the `UdpAck` packet + for i in (start + 1)..(end + 1) { + if self.recieved.contains_key(&i) { + vec.push(1) + } else { + vec.push(0) + } } - } - vec - } else { - vec![] - }; + vec + } else { + vec![] + }; - UdpAck { - connection_id: self.camera_id, - packet_id: start, - payload: missing_ids, + UdpAck { + connection_id: self.camera_id, + packet_id: start, + group_id: 0, + payload: missing_ids, + } + } else { + UdpAck::empty(self.camera_id) } } @@ -262,17 +266,10 @@ impl UdpPayloadSource { for (_, resend) in self.sent.iter() { self.send_buffer.push_back(BcUdp::Data(resend.clone())); } - if self.packets_want == 0 { - // When no packets have been recieved the - // ACK is different specifically unknown_b - // is set to -1 and packet_id is also set to - // -1 - // TODO Add this style of ACK - } else { - trace!("UDPSource.RecievedPacket: QueueingAck"); - let ack = BcUdp::Ack(self.build_send_ack()); - self.send_buffer.push_back(ack); - } + + let ack = BcUdp::Ack(self.build_send_ack()); + trace!("UDPSource.RecievedPacket: QueueingAck"); + self.send_buffer.push_back(ack); self.state = State::Flushing; } } diff --git a/crates/core/src/bc_protocol/login.rs b/crates/core/src/bc_protocol/login.rs index 13aeda7..363d5aa 100644 --- a/crates/core/src/bc_protocol/login.rs +++ b/crates/core/src/bc_protocol/login.rs @@ -2,11 +2,35 @@ use super::{md5_string, BcCamera, Error, Result, Truncate, ZeroLast}; use crate::bc::{model::*, xml::*}; use std::sync::atomic::Ordering; +/// The requested encryption level to request +/// to the camera +/// +/// The camera may use a lower one depending on support +/// +/// Note the reolink camera only encrypt the control messages +/// the camera feed is always accessible +#[derive(Debug, Clone, Copy)] +pub enum MaxEncryption { + /// No encryption + None, + /// BCEncrypt is a simple XOR algortirhm with a fixed key + /// used in many older models + BcEncrypt, + /// AES is used in newer model + Aes, +} + impl BcCamera { /// Login to the camera. /// /// This should be called before most other commands pub async fn login(&self) -> Result { + self.login_with_maxenc(MaxEncryption::Aes).await + } + /// Login to the camera. + /// + /// This should be called before most other commands + pub async fn login_with_maxenc(&self, max_encryption: MaxEncryption) -> Result { let device_info; // This { is here due to the connection and set_credentials both requiring a mutable borrow { @@ -31,13 +55,18 @@ impl BcCamera { .map(|p| md5_string(p, ZeroLast)) .unwrap_or_else(|| EMPTY_LEGACY_PASSWORD.to_owned()); + let enc_byte = match max_encryption { + MaxEncryption::None => 0xdc00, + MaxEncryption::BcEncrypt => 0xdc01, + MaxEncryption::Aes => 0xdc02, + }; let legacy_login = Bc { meta: BcMeta { msg_id: MSG_ID_LOGIN, channel_id: self.channel_id, msg_num, stream_type: 0, - response_code: 0xdc02, + response_code: enc_byte, class: 0x6514, }, body: BcBody::LegacyMsg(LegacyMsg::LoginMsg { diff --git a/crates/core/src/bcudp/de.rs b/crates/core/src/bcudp/de.rs index f946820..0e3ce1b 100644 --- a/crates/core/src/bcudp/de.rs +++ b/crates/core/src/bcudp/de.rs @@ -89,8 +89,10 @@ fn udp_ack(buf: &[u8]) -> IResult<&[u8], UdpAck> { let (buf, connection_id) = error_context("ACK: Missing connect ID", le_i32)(buf)?; let (buf, _unknown_a) = error_context("ACK: Unable to verify UnknowA", verify(le_u32, |&x| x == 0))(buf)?; - let (buf, _unknown_b) = - error_context("ACK: Unable to verify UnknowB", verify(le_u32, |&x| x == 0))(buf)?; + let (buf, group_id) = error_context( + "ACK: Unable to verify UnknowB", + verify(le_u32, |&x| x == 0 || x == 0xffffffff), + )(buf)?; let (buf, packet_id) = error_context("Missing packet_id", le_u32)(buf)?; // This is the point at which the camera has contigious // packets to let (buf, _unknown) = error_context("ACK: Missing unknown", le_u32)(buf)?; @@ -109,6 +111,7 @@ fn udp_ack(buf: &[u8]) -> IResult<&[u8], UdpAck> { let data = UdpAck { connection_id, packet_id, + group_id, payload, }; Ok((buf, data)) diff --git a/crates/core/src/bcudp/model.rs b/crates/core/src/bcudp/model.rs index 2b1c84f..53f03a2 100644 --- a/crates/core/src/bcudp/model.rs +++ b/crates/core/src/bcudp/model.rs @@ -63,7 +63,9 @@ pub struct UdpAck { /// register and then download the same connection id from the register_address /// it comes back in an xml that is encoded as i32 (i.e. can be negative string) pub connection_id: i32, - // Unknown 4 bytes always 0 + /// Unknown 4 bytes always 0 for normal ack or -1 for signalling no packets received yet + /// Tentativly assigned as a kinda group id + pub group_id: u32, /// The ID of the last data packet [`UdpData`] pub packet_id: u32, // 2 Bytes Unknown: Observed values `00000000`, `d6010000`, `d7160000` `09e00000` @@ -76,6 +78,19 @@ pub struct UdpAck { pub payload: Vec, } +impl UdpAck { + /// Create an empty ack packet to signifiy no packets recieved yet + /// These are a little different in that they also set `group_id` + pub fn empty(connection_id: i32) -> Self { + Self { + connection_id, + group_id: 0xffffffff, + packet_id: 0xffffffff, + payload: vec![], + } + } +} + /// Magic for the UDP Data packet pub const MAGIC_HEADER_UDP_DATA: u32 = 0x2a87cf10; diff --git a/crates/core/src/bcudp/ser.rs b/crates/core/src/bcudp/ser.rs index 5489d41..b566d8a 100644 --- a/crates/core/src/bcudp/ser.rs +++ b/crates/core/src/bcudp/ser.rs @@ -50,7 +50,7 @@ fn bcudp_ack<'a, W: 'a + Write>( le_u32(MAGIC_HEADER_UDP_ACK), le_i32(payload.connection_id), le_u32(0), - le_u32(0), + le_u32(payload.group_id), le_u32(payload.packet_id), le_u32(0), le_u32(binary_payload.len() as u32), diff --git a/src/config.rs b/src/config.rs index cbd5bcd..b947a91 100644 --- a/src/config.rs +++ b/src/config.rs @@ -11,6 +11,8 @@ lazy_static! { static ref RE_TLS_CLIENT_AUTH: Regex = Regex::new(r"^(none|request|require)$").unwrap(); static ref RE_PAUSE_MODE: Regex = Regex::new(r"^(black|still|test|none)$").unwrap(); static ref RE_DISC_SRC: Regex = Regex::new(r"^([nN]one|[lL]ocal|[rR]emote|[rR]elay)$").unwrap(); + static ref RE_MAXENC_SRC: Regex = + Regex::new(r"^([nN]one|[Aa][Ee][Ss]|[Bb][Cc][Ee][Nn][Cc][Rr][Yy][Pp][Tt])$").unwrap(); } #[derive(Debug, Deserialize, Validate, Clone)] @@ -84,6 +86,14 @@ pub(crate) struct CameraConfig { code = "discovery" ))] pub(crate) discovery: String, + + #[serde(default = "default_maxenc")] + #[validate(regex( + path = "RE_MAXENC_SRC", + message = "Invalid maximum encryption method", + code = "max_encryption" + ))] + pub(crate) max_encryption: String, } #[derive(Debug, Deserialize, Validate, Clone)] @@ -132,6 +142,10 @@ fn default_discovery() -> String { "Relay".to_string() } +fn default_maxenc() -> String { + "Aes".to_string() +} + #[derive(Debug, Deserialize, Validate, Clone)] pub(crate) struct PauseConfig { #[serde(default = "default_on_motion")] diff --git a/src/rtsp/states/loggedin.rs b/src/rtsp/states/loggedin.rs index 6bb1532..79ffdb0 100644 --- a/src/rtsp/states/loggedin.rs +++ b/src/rtsp/states/loggedin.rs @@ -15,7 +15,7 @@ pub(crate) struct LoggedIn {} #[async_trait] impl CameraState for LoggedIn { async fn setup(&mut self, shared: &Shared) -> Result<(), anyhow::Error> { - shared.camera.login().await?; + shared.camera.login_with_maxenc(shared.max_encryption).await?; Ok(()) } diff --git a/src/rtsp/states/mod.rs b/src/rtsp/states/mod.rs index 7be6b56..bd24742 100644 --- a/src/rtsp/states/mod.rs +++ b/src/rtsp/states/mod.rs @@ -6,7 +6,7 @@ use log::*; use std::collections::HashSet; use std::sync::Arc; -use neolink_core::bc_protocol::{MotionData, StreamKind as Stream}; +use neolink_core::bc_protocol::{MaxEncryption, MotionData, StreamKind as Stream}; use crate::config::{CameraConfig, UserConfig}; use crate::rtsp::gst::RtspServer; @@ -111,6 +111,12 @@ impl RtspCamera { None => ["anonymous".to_string()].iter().cloned().collect(), }; + let max_encryption = match config.max_encryption.to_lowercase().as_str() { + "none" => MaxEncryption::None, + "bcencrypt" => MaxEncryption::BcEncrypt, + "aes" => MaxEncryption::Aes, + _ => MaxEncryption::Aes, + }; let shared = Shared { camera: Arc::new(camera), addr: camera_addr, @@ -122,6 +128,7 @@ impl RtspCamera { streams, rtsp, permitted_users, + max_encryption, }; let mut state: Connected = Default::default(); diff --git a/src/rtsp/states/shared.rs b/src/rtsp/states/shared.rs index 7caf32f..71127fe 100644 --- a/src/rtsp/states/shared.rs +++ b/src/rtsp/states/shared.rs @@ -7,7 +7,7 @@ use async_trait::async_trait; use std::collections::HashSet; use std::sync::Arc; -use neolink_core::bc_protocol::{BcCamera, StreamKind as Stream}; +use neolink_core::bc_protocol::{BcCamera, MaxEncryption, StreamKind as Stream}; use crate::config::PauseConfig; use crate::rtsp::gst::RtspServer; @@ -25,6 +25,7 @@ pub(crate) struct Shared { pub(super) rtsp: Arc, pub(super) permitted_users: HashSet, pub(super) pause: PauseConfig, + pub(super) max_encryption: MaxEncryption, } impl Shared { diff --git a/src/utils.rs b/src/utils.rs index fc62c0b..92952c8 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -4,7 +4,7 @@ use log::*; use super::config::{CameraConfig, Config}; use anyhow::{anyhow, Context, Error, Result}; -use neolink_core::bc_protocol::{BcCamera, DiscoveryMethods}; +use neolink_core::bc_protocol::{BcCamera, DiscoveryMethods, MaxEncryption}; use std::fmt::{Display, Error as FmtError, Formatter}; pub(crate) enum AddressOrUid { @@ -97,9 +97,15 @@ pub(crate) async fn connect_and_login(camera_config: &CameraConfig) -> Result MaxEncryption::None, + "bcencrypt" => MaxEncryption::BcEncrypt, + "aes" => MaxEncryption::Aes, + _ => MaxEncryption::Aes, + }; info!("{}: Logging in", camera_config.name); camera - .login() + .login_with_maxenc(max_encryption) .await .with_context(|| format!("Failed to login to {}", camera_config.name))?;