From 4ff53b73afbf9cdb2e373bda60e67dce0dd37b30 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Thu, 8 Oct 2020 13:59:55 +0700 Subject: [PATCH] Refractored bc connection to treat binary as a generic payload --- clippy.toml | 1 - src/bc/de.rs | 87 ++++++++++++++------------------- src/bc/model.rs | 25 +++++++--- src/bc/ser.rs | 28 ++++++++--- src/bc/xml.rs | 32 +++++++++--- src/bc_protocol.rs | 44 ++++++++++++----- src/bc_protocol/media_packet.rs | 17 +++---- src/bc_protocol/time.rs | 18 +++++-- src/main.rs | 1 + 9 files changed, 155 insertions(+), 98 deletions(-) delete mode 100644 clippy.toml diff --git a/clippy.toml b/clippy.toml deleted file mode 100644 index 3217898..0000000 --- a/clippy.toml +++ /dev/null @@ -1 +0,0 @@ -enum-variant-size-threshold = 700 diff --git a/src/bc/de.rs b/src/bc/de.rs index 2a7dfec..7f01b17 100644 --- a/src/bc/de.rs +++ b/src/bc/de.rs @@ -1,5 +1,5 @@ use super::model::*; -use super::xml::{AllTopXmls, Extension}; +use super::xml::{BcPayloads, BcXml, BcXmls}; use super::xml_crypto; use err_derive::Error; use log::*; @@ -116,74 +116,59 @@ fn bc_modern_msg<'a, 'b>( Err, }; - let mut in_bin_mode = context.in_bin_mode.contains(&header.msg_id); - - // We'd like to know where the XML stops, but we haven't parsed the XML yet to see if the - // binaryData offset in the header is valid - let end_of_xml = if in_bin_mode { - 0 - } else { - match header.bin_offset { - Some(off) if off > 0 => off, - _ => header.body_len, - } + let xml_len = match header.bin_offset { + Some(off) => off, + _ => header.body_len, }; - let (mut buf, body_buf) = take(end_of_xml)(buf)?; + let (buf, xml_buf) = take(xml_len)(buf)?; + let payload_len = header.body_len - xml_len; + let (buf, payload_buf) = take(payload_len)(buf)?; let decrypted; - let processed_body_buf = if !header.is_encrypted() { - buf + let processed_xml_buf = if !header.is_encrypted() { + xml_buf } else { - decrypted = xml_crypto::crypt(header.enc_offset, body_buf); + decrypted = xml_crypto::crypt(header.enc_offset, xml_buf); &decrypted }; // Now we'll take the buffer that Nom gave a ref to and parse it. - let mut xml = None; - let mut binary = None; - if end_of_xml > 0 { + let xml; + if xml_len > 0 { // Apply the XML parse function, but throw away the reference to decrypted in the Ok and // Err case. This error-error-error thing is the same idiom Nom uses internally. - let parsed = AllTopXmls::try_parse(processed_body_buf) + let parsed = BcXmls::try_parse(processed_xml_buf) .map_err(|_| Err::Error(make_error(buf, ErrorKind::MapRes)))?; - - // If this is the first message containing binary, the Extension message puts the message - // ID into binary mode, then the first binary is sent after the XML. All remaining - // messages for that ID are pure binary. - match parsed { - AllTopXmls::BcXml(x) => { - xml = Some(x); - } - AllTopXmls::Extension(Extension { binary_data: _ }) => { - in_bin_mode = true; - } - } + xml = Some(parsed); + } else { + xml = None; } - // If we are in binary mode, extract it - if in_bin_mode { - if let Some(bin_offset) = header.bin_offset { - // Extract remainder of message as binary, if it exists - let (buf_after, payload) = - map(take(header.body_len - bin_offset), |x: &[u8]| x.to_vec())(buf)?; - - // Since the parser operates in streaming mode, must wait until after we successfully - // receive enough bytes before modifying the context (otherwise we'll alter the - // behavior of future passes of this function even if we didn't yet consume the - // message). - context.in_bin_mode.insert(header.msg_id); - - binary = Some(payload); - buf = buf_after; + // Now to handle the payload block + // This block can either be xml or binary depending on what the message expects. + // For our purposes we use try_parse and if all xml based parsers fail we treat + // As binary + let payload; + if payload_len > 0 { + // Extract remainder of message as binary, if it exists + let decrypted; + let processed_payload_buf = if !header.is_encrypted() { + xml_buf } else { - // Seriously, Nom, what even is this - error!("Expected header to contain a binary offset, but there was none"); - return Err(Err::Error(make_error(buf, ErrorKind::Verify))); + decrypted = xml_crypto::crypt(header.enc_offset, payload_buf); + &decrypted + }; + if let Ok(xml) = BcXml::try_parse(processed_payload_buf) { + payload = Some(BcPayloads::BcXml(xml)); + } else { + payload = Some(BcPayloads::Binary(payload_buf.to_vec())); } + } else { + payload = None; } - Ok((buf, ModernMsg { xml, binary })) + Ok((buf, ModernMsg { xml, payload })) } fn bc_header(buf: &[u8]) -> IResult<&[u8], BcHeader> { diff --git a/src/bc/model.rs b/src/bc/model.rs index 006f7fd..06bb234 100644 --- a/src/bc/model.rs +++ b/src/bc/model.rs @@ -1,4 +1,4 @@ -use super::xml::{BcXml, Extension, TopBcXmls}; +pub use super::xml::{BcXml, Extension, BcXmls, BcPayloads}; use std::collections::HashSet; pub(super) const MAGIC_HEADER: u32 = 0xabcdef0; @@ -19,6 +19,7 @@ pub struct Bc { } #[derive(Debug, PartialEq, Eq)] +#[allow(clippy::large_enum_variant)] pub enum BcBody { LegacyMsg(LegacyMsg), ModernMsg(ModernMsg), @@ -26,8 +27,8 @@ pub enum BcBody { #[derive(Debug, Default, PartialEq, Eq)] pub struct ModernMsg { - pub xml: Option, - pub binary: Option>, + pub xml: Option, + pub payload: Option, } #[derive(Debug, PartialEq, Eq)] @@ -76,8 +77,8 @@ impl Bc { Bc { meta, body: BcBody::ModernMsg(ModernMsg { - xml: Some(xml), - binary: None, + xml: Some(BcXmls::BcXml(xml)), + payload: None, }), } } @@ -86,8 +87,18 @@ impl Bc { Bc { meta, body: BcBody::ModernMsg(ModernMsg { - xml: Some(TopBcXmls::Extension(xml)), - binary: None, + xml: Some(BcXmls::Extension(xml)), + payload: None, + }), + } + } + + pub fn new_from_meta(meta: BcMeta) -> Bc { + Bc { + meta, + body: BcBody::ModernMsg(ModernMsg { + xml: None, + payload: None, }), } } diff --git a/src/bc/ser.rs b/src/bc/ser.rs index f8a9fa5..fb4f711 100644 --- a/src/bc/ser.rs +++ b/src/bc/ser.rs @@ -1,5 +1,5 @@ use super::model::*; -use super::xml::BcXml; +use super::xml::{BcXmls, BcPayloads}; use super::xml_crypto; use cookie_factory::bytes::*; use cookie_factory::sequence::tuple; @@ -24,7 +24,7 @@ impl Bc { body_buf = buf; bin_offset = if has_bin_offset(self.meta.class) { // If we're required to put binary length, put 0 if we have no binary - Some(if modern.binary.is_some() { + Some(if modern.payload.is_some() { xml_len as u32 } else { 0 @@ -47,24 +47,38 @@ impl Bc { // Put the binary part of the body, TODO this is poorly written if let BcBody::ModernMsg(ModernMsg { - binary: Some(ref binary), + payload: Some(ref payload), .. }) = self.body { - let (buf2, _) = gen(slice(binary), buf)?; - buf = buf2 + let (buf2, _) = gen(bc_payload(header.enc_offset, payload), buf)?; + buf = buf2; } Ok(buf) } } -fn bc_xml(enc_offset: u32, xml: &BcXml) -> impl SerializeFn { - let xml_bytes = xml.serialize(vec![]).unwrap(); +fn bc_xml(enc_offset: u32, xml: &BcXmls) -> impl SerializeFn { + let xml_bytes = match xml { + BcXmls::BcXml(x) => x.serialize(vec![]).unwrap(), + BcXmls::Extension(x) => x.serialize(vec![]).unwrap(), + }; let enc_bytes = xml_crypto::crypt(enc_offset, &xml_bytes); slice(enc_bytes) } +fn bc_payload(enc_offset: u32, payload: &BcPayloads) -> impl SerializeFn { + let payload_bytes = match payload { + BcPayloads::BcXml(x) => { + let xml_bytes = x.serialize(vec![]).unwrap(); + xml_crypto::crypt(enc_offset, &xml_bytes) + }, + BcPayloads::Binary(x) => x.to_owned(), + }; + slice(payload_bytes) +} + fn bc_header(header: &BcHeader) -> impl SerializeFn { // TODO this is actually a u16 "response code" in modern messages let (signaled_encryption, spare) = if header.class == 0x0000 { diff --git a/src/bc/xml.rs b/src/bc/xml.rs index 4c33d05..0e3a45f 100644 --- a/src/bc/xml.rs +++ b/src/bc/xml.rs @@ -11,16 +11,32 @@ use indoc::indoc; #[derive(PartialEq, Eq, Debug, YaDeserialize)] #[yaserde(flatten)] -pub(super) enum AllTopXmls { +pub enum BcXmls { #[yaserde(rename = "body")] BcXml(BcXml), Extension(Extension), } // Required for YaDeserialize -impl Default for AllTopXmls { +impl Default for BcXmls { fn default() -> Self { - AllTopXmls::BcXml(Default::default()) + BcXmls::BcXml(Default::default()) + } +} + +#[derive(PartialEq, Eq, Debug, YaDeserialize)] +#[yaserde(flatten)] +pub enum BcPayloads { + #[yaserde(rename = "body")] + BcXml(BcXml), + #[yaserde(flatten)] + Binary(Vec), +} + +// Required for YaDeserialize +impl Default for BcPayloads { + fn default() -> Self { + BcPayloads::Binary(Default::default()) } } @@ -43,7 +59,7 @@ pub struct BcXml { pub norm: Option, } -impl AllTopXmls { +impl BcXmls { pub fn try_parse(s: impl Read) -> Result { yaserde::de::from_reader(s) } @@ -185,9 +201,9 @@ fn test_encryption_deser() { assert_eq!(enc.nonce, "9E6D1FCB9E69846D"); assert_eq!(enc.type_, "md5"); - let t = AllTopXmls::try_parse(sample.as_bytes()).unwrap(); + let t = BcXmls::try_parse(sample.as_bytes()).unwrap(); match t { - AllTopXmls::BcXml(top_b) if top_b == b => assert!(true), + BcXmls::BcXml(top_b) if top_b == b => assert!(true), _ => assert!(false), } } @@ -322,9 +338,9 @@ fn test_binary_deser() { "# ); - let b = AllTopXmls::try_parse(sample.as_bytes()).unwrap(); + let b = BcXmls::try_parse(sample.as_bytes()).unwrap(); match b { - AllTopXmls::Extension(Extension { binary_data: 1 }) => assert!(true), + BcXmls::Extension(Extension { binary_data: 1 }) => assert!(true), _ => assert!(false), } } diff --git a/src/bc_protocol.rs b/src/bc_protocol.rs index 640f24b..7404d7d 100644 --- a/src/bc_protocol.rs +++ b/src/bc_protocol.rs @@ -24,9 +24,10 @@ use crate::Never; type Result = std::result::Result; -const RX_TIMEOUT: Duration = Duration::from_secs(5); +const RX_TIMEOUT: Duration = Duration::from_secs(500); #[derive(Debug, Error)] +#[allow(clippy::large_enum_variant)] pub enum Error { #[error(display = "Communication error")] CommunicationError(#[error(source)] std::io::Error), @@ -49,8 +50,13 @@ pub enum Error { #[error(display = "Timeout")] Timeout(#[error(source)] std::sync::mpsc::RecvTimeoutError), - #[error(display = "Media")] - MediaPacket(#[error(source)] self::media_packet::Error), + // We map std::sync::mpsc::RecvTimeoutError onto one of these based on + // the errors enum + #[error(display = "Dropped connection")] + TimeoutDropped, + + #[error(display = "Timeout")] + TimeoutTimeout, #[error(display = "Credential error")] AuthFailed, @@ -127,12 +133,18 @@ impl BcCamera { sub_login.send(legacy_login)?; - let legacy_reply = sub_login.rx.recv_timeout(RX_TIMEOUT)?; + let legacy_reply = sub_login.rx.recv_timeout(RX_TIMEOUT).map_err(|e| { + match e { + std::sync::mpsc::RecvTimeoutError::Timeout => {Error::TimeoutTimeout} + std::sync::mpsc::RecvTimeoutError::Disconnected => {Error::TimeoutDropped} + } + })?; + let nonce; match legacy_reply.body { BcBody::ModernMsg(ModernMsg { xml: - Some(BcXml { + Some(BcXmls::BcXml(BcXml { encryption: Some(encryption), .. }), @@ -181,13 +193,18 @@ impl BcCamera { ); sub_login.send(modern_login)?; - let modern_reply = sub_login.rx.recv_timeout(RX_TIMEOUT)?; + let modern_reply = sub_login.rx.recv_timeout(RX_TIMEOUT).map_err(|e| { + match e { + std::sync::mpsc::RecvTimeoutError::Timeout => {Error::TimeoutTimeout} + std::sync::mpsc::RecvTimeoutError::Disconnected => {Error::TimeoutDropped} + } + })?; let device_info; match modern_reply.body { BcBody::ModernMsg(ModernMsg { - xml: - Some(BcXml { + payload: + Some(BcPayloads::BcXml(BcXml { device_info: Some(info), .. }), @@ -199,7 +216,7 @@ impl BcCamera { } BcBody::ModernMsg(ModernMsg { xml: None, - binary: None, + payload: None, }) => return Err(Error::AuthFailed), _ => { return Err(Error::UnintelligibleReply { @@ -214,7 +231,7 @@ impl BcCamera { pub fn logout(&mut self) -> Result<()> { if self.logged_in { - // TODO + // TODO: Send message ID 2 } self.logged_in = false; Ok(()) @@ -238,7 +255,12 @@ impl BcCamera { sub_ping.send(ping)?; - sub_ping.rx.recv_timeout(RX_TIMEOUT)?; + sub_ping.rx.recv_timeout(RX_TIMEOUT).map_err(|e| { + match e { + std::sync::mpsc::RecvTimeoutError::Timeout => {Error::TimeoutTimeout} + std::sync::mpsc::RecvTimeoutError::Disconnected => {Error::TimeoutDropped} + } + })?; Ok(()) } diff --git a/src/bc_protocol/media_packet.rs b/src/bc_protocol/media_packet.rs index 3d4689b..f2e3cce 100644 --- a/src/bc_protocol/media_packet.rs +++ b/src/bc_protocol/media_packet.rs @@ -1,6 +1,6 @@ use crate::bc::model::*; use crate::bc_protocol::connection::BcSubscription; -use err_derive::Error; +use super::Error; use log::trace; use log::*; use std::collections::VecDeque; @@ -17,12 +17,6 @@ const PAD_SIZE: usize = 8; type Result = std::result::Result; -#[derive(Debug, Error)] -pub enum Error { - #[error(display = "Timeout")] - Timeout(#[error(source)] std::sync::mpsc::RecvTimeoutError), -} - #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] pub enum MediaDataKind { VideoDataIframe, @@ -156,9 +150,14 @@ impl<'a> MediaDataSubscriber<'a> { fn fill_binary_buffer(&mut self, rx_timeout: Duration) -> Result<()> { // Loop messages until we get binary add that data and return loop { - let msg = self.bc_sub.rx.recv_timeout(rx_timeout)?; + let msg = self.bc_sub.rx.recv_timeout(rx_timeout).map_err(|e| { + match e { + std::sync::mpsc::RecvTimeoutError::Timeout => {Error::TimeoutTimeout} + std::sync::mpsc::RecvTimeoutError::Disconnected => {Error::TimeoutDropped} + } + })?; if let BcBody::ModernMsg(ModernMsg { - binary: Some(binary), + payload: Some(BcPayloads::Binary(binary)), .. }) = msg.body { diff --git a/src/bc_protocol/time.rs b/src/bc_protocol/time.rs index 8777f34..f4f43c2 100644 --- a/src/bc_protocol/time.rs +++ b/src/bc_protocol/time.rs @@ -20,11 +20,16 @@ impl BcCamera { }; sub_get_general.send(get)?; - let msg = sub_get_general.rx.recv_timeout(RX_TIMEOUT)?; + let msg = sub_get_general.rx.recv_timeout(RX_TIMEOUT).map_err(|e| { + match e { + std::sync::mpsc::RecvTimeoutError::Timeout => {Error::TimeoutTimeout} + std::sync::mpsc::RecvTimeoutError::Disconnected => {Error::TimeoutDropped} + } + })?; if let BcBody::ModernMsg(ModernMsg { - xml: - Some(BcXml { + payload: + Some(BcPayloads::BcXml(BcXml { system_general: Some(SystemGeneral { time_zone: Some(time_zone), @@ -106,7 +111,12 @@ impl BcCamera { ); sub_set_general.send(set)?; - let msg = sub_set_general.rx.recv_timeout(RX_TIMEOUT)?; + let msg = sub_set_general.rx.recv_timeout(RX_TIMEOUT).map_err(|e| { + match e { + std::sync::mpsc::RecvTimeoutError::Timeout => {Error::TimeoutTimeout} + std::sync::mpsc::RecvTimeoutError::Disconnected => {Error::TimeoutDropped} + } + })?; Ok(()) } diff --git a/src/main.rs b/src/main.rs index 0660aa3..ba790a2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -20,6 +20,7 @@ use cmdline::Opt; use config::{CameraConfig, Config, UserConfig}; #[derive(Debug, Error)] +#[allow(clippy::large_enum_variant)] pub enum Error { #[error(display = "Configuration parsing error")] ConfigError(#[error(source)] toml::de::Error),