From d90e22cf8e00058fd95a21e232485bebf19149e2 Mon Sep 17 00:00:00 2001 From: George Hilliard Date: Fri, 5 Jun 2020 17:35:20 -0500 Subject: [PATCH] Execute the Great Autoformatting of 2020 --- build.rs | 3 +- src/bc/de.rs | 132 ++++++++++++++++++++-------------- src/bc/model.rs | 20 +++--- src/bc/ser.rs | 61 +++++++++------- src/bc/xml.rs | 88 +++++++++++++---------- src/bc/xml_crypto.rs | 6 +- src/bc_protocol.rs | 111 +++++++++++++++++----------- src/bc_protocol/connection.rs | 50 +++++++------ src/config.rs | 4 +- src/gst.rs | 43 ++++++----- src/main.rs | 70 ++++++++++++------ 11 files changed, 360 insertions(+), 228 deletions(-) diff --git a/build.rs b/build.rs index 5186107..b9498f5 100644 --- a/build.rs +++ b/build.rs @@ -10,5 +10,4 @@ fn main() { } #[cfg(not(windows))] -fn main() { -} +fn main() {} diff --git a/src/bc/de.rs b/src/bc/de.rs index 85a6474..d377157 100644 --- a/src/bc/de.rs +++ b/src/bc/de.rs @@ -1,17 +1,17 @@ +use super::model::*; +use super::xml::{AllTopXmls, Extension}; +use super::xml_crypto; use err_derive::Error; use log::*; use nom::IResult; -use nom::{bytes::streaming::take, number::streaming::*, combinator::*, sequence::*}; +use nom::{bytes::streaming::take, combinator::*, number::streaming::*, sequence::*}; use std::io::Read; -use super::model::*; -use super::xml::{Extension, AllTopXmls}; -use super::xml_crypto; #[derive(Debug, Error)] pub enum Error { - #[error(display="Parsing error")] + #[error(display = "Parsing error")] NomError(&'static str), - #[error(display="I/O error")] + #[error(display = "I/O error")] IoError(#[error(source)] std::io::Error), } @@ -36,9 +36,10 @@ impl Bc { } fn read_from_reader(mut parser: P, mut rdr: R) -> Result - where R: Read, - E: for<'a> From>> + From, - P: FnMut(&[u8]) -> nom::IResult<&[u8], O>, +where + R: Read, + E: for<'a> From>> + From, + P: FnMut(&[u8]) -> nom::IResult<&[u8], O>, { let mut input: Vec = Vec::new(); loop { @@ -46,16 +47,19 @@ fn read_from_reader(mut parser: P, mut rdr: R) -> Result Ok((_, parsed)) => return Ok(parsed), Err(nom::Err::Incomplete(needed)) => { match needed { - nom::Needed::Unknown => 1, // read one byte + nom::Needed::Unknown => 1, // read one byte nom::Needed::Size(len) => len, } - }, + } Err(e) => return Err(e.into()), }; if 0 == (&mut rdr).take(to_read as u64).read_to_end(&mut input)? { - return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, - "Read returned 0 bytes").into()); + return Err(std::io::Error::new( + std::io::ErrorKind::UnexpectedEof, + "Read returned 0 bytes", + ) + .into()); } } } @@ -72,9 +76,11 @@ fn bc_msg<'a, 'b>(context: &'a mut BcContext, buf: &'b [u8]) -> IResult<&'b [u8] Ok((buf, bc)) } -fn bc_body<'a, 'b, 'c>(context: &'c mut BcContext, header: &'a BcHeader, buf: &'b [u8]) - -> IResult<&'b [u8], BcBody> -{ +fn bc_body<'a, 'b, 'c>( + context: &'c mut BcContext, + header: &'a BcHeader, + buf: &'b [u8], +) -> IResult<&'b [u8], BcBody> { if header.is_modern() { let (buf, body) = bc_modern_msg(context, header, buf)?; Ok((buf, BcBody::ModernMsg(body))) @@ -88,41 +94,47 @@ fn bc_body<'a, 'b, 'c>(context: &'c mut BcContext, header: &'a BcHeader, buf: &' } fn hex32<'a>() -> impl Fn(&'a [u8]) -> IResult<&'a [u8], String> { - map_res(take(32usize), |slice: &'a [u8]| String::from_utf8(slice.to_vec())) + map_res(take(32usize), |slice: &'a [u8]| { + String::from_utf8(slice.to_vec()) + }) } -fn bc_legacy_login_msg<'a, 'b>(buf: &'b [u8]) - -> IResult<&'b [u8], LegacyMsg> -{ +fn bc_legacy_login_msg<'a, 'b>(buf: &'b [u8]) -> IResult<&'b [u8], LegacyMsg> { let (buf, username) = hex32()(buf)?; let (buf, password) = hex32()(buf)?; - Ok((buf, LegacyMsg::LoginMsg { - username, - password, - })) + Ok((buf, LegacyMsg::LoginMsg { username, password })) } -fn bc_modern_msg<'a, 'b, 'c>(context: &mut BcContext, header: &'a BcHeader, buf: &'b [u8]) - -> IResult<&'b [u8], ModernMsg> -{ - use nom::{Err, error::{make_error, ErrorKind}}; +fn bc_modern_msg<'a, 'b, 'c>( + context: &mut BcContext, + header: &'a BcHeader, + buf: &'b [u8], +) -> IResult<&'b [u8], ModernMsg> { + use nom::{ + error::{make_error, ErrorKind}, + 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 { + let end_of_xml = if in_bin_mode { + 0 + } else { match header.bin_offset { Some(off) if off > 0 => off, - _ => header.body_len + _ => header.body_len, } }; let (mut buf, body_buf) = take(end_of_xml)(buf)?; let decrypted; - let processed_body_buf = if !header.is_encrypted() { buf } else { + let processed_body_buf = if !header.is_encrypted() { + buf + } else { decrypted = xml_crypto::crypt(header.enc_offset, body_buf); &decrypted }; @@ -140,7 +152,9 @@ fn bc_modern_msg<'a, 'b, 'c>(context: &mut BcContext, header: &'a BcHeader, buf: // 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::BcXml(x) => { + xml = Some(x); + } AllTopXmls::Extension(Extension { binary_data: _ }) => { in_bin_mode = true; } @@ -151,8 +165,8 @@ fn bc_modern_msg<'a, 'b, 'c>(context: &mut BcContext, header: &'a BcHeader, buf: 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)?; + 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 @@ -186,14 +200,17 @@ fn bc_header(buf: &[u8]) -> IResult<&[u8], BcHeader> { let (buf, bin_offset) = cond(has_bin_offset(class), le_u32)(buf)?; - Ok((buf, BcHeader { - msg_id, - body_len, - enc_offset, - encrypted, - class, - bin_offset, - })) + Ok(( + buf, + BcHeader { + msg_id, + body_len, + enc_offset, + encrypted, + class, + bin_offset, + }, + )) } #[test] @@ -210,9 +227,10 @@ fn test_bc_modern_login() { assert_eq!(header.encrypted, true); assert_eq!(header.class, 0x6614); match body { - BcBody::ModernMsg(ModernMsg{ xml: Some(ref xml), binary: None }) => { - assert_eq!(xml.encryption.as_ref().unwrap().nonce, "9E6D1FCB9E69846D") - } + BcBody::ModernMsg(ModernMsg { + xml: Some(ref xml), + binary: None, + }) => assert_eq!(xml.encryption.as_ref().unwrap().nonce, "9E6D1FCB9E69846D"), _ => assert!(false), } } @@ -231,9 +249,7 @@ fn test_bc_legacy_login() { assert_eq!(header.encrypted, true); assert_eq!(header.class, 0x6514); match body { - BcBody::LegacyMsg(LegacyMsg::LoginMsg { - username, password - }) => { + BcBody::LegacyMsg(LegacyMsg::LoginMsg { username, password }) => { assert_eq!(username, "21232F297A57A5A743894A0E4A801FC\0"); assert_eq!(password, EMPTY_LEGACY_PASSWORD); } @@ -255,7 +271,10 @@ fn test_bc_modern_login_failed() { assert_eq!(header.encrypted, true); assert_eq!(header.class, 0x0000); match body { - BcBody::ModernMsg(ModernMsg{ xml: None, binary: None }) => { + BcBody::ModernMsg(ModernMsg { + xml: None, + binary: None, + }) => { assert!(true); } _ => assert!(false), @@ -279,7 +298,10 @@ fn test_bc_modern_login_success() { // Previously, we were not handling bin_offset == 0 (no bin offset) correctly. // Test that we decoded XML and no binary. match body { - BcBody::ModernMsg(ModernMsg{ xml: Some(_), binary: None }) => assert!(true), + BcBody::ModernMsg(ModernMsg { + xml: Some(_), + binary: None, + }) => assert!(true), _ => assert!(false), } } @@ -294,13 +316,19 @@ fn test_bc_binary_mode() { let msg1 = Bc::deserialize(&mut context, &sample1[..]).unwrap(); let msg2 = Bc::deserialize(&mut context, &sample2[..]).unwrap(); match msg1.body { - BcBody::ModernMsg(ModernMsg{ xml: None, binary: Some(bin) }) => { + BcBody::ModernMsg(ModernMsg { + xml: None, + binary: Some(bin), + }) => { assert_eq!(bin.len(), 32); } _ => assert!(false), } match msg2.body { - BcBody::ModernMsg(ModernMsg{ xml: None, binary: Some(bin) }) => { + BcBody::ModernMsg(ModernMsg { + xml: None, + binary: Some(bin), + }) => { assert_eq!(bin.len(), 30344); } _ => assert!(false), diff --git a/src/bc/model.rs b/src/bc/model.rs index 827226b..e6c3115 100644 --- a/src/bc/model.rs +++ b/src/bc/model.rs @@ -1,5 +1,5 @@ -use std::collections::HashSet; use super::xml::BcXml; +use std::collections::HashSet; pub(super) const MAGIC_HEADER: u32 = 0xabcdef0; @@ -7,7 +7,8 @@ pub const MSG_ID_LOGIN: u32 = 1; pub const MSG_ID_VIDEO: u32 = 3; pub const MSG_ID_PING: u32 = 93; -pub const EMPTY_LEGACY_PASSWORD: &str = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; +pub const EMPTY_LEGACY_PASSWORD: &str = + "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; #[derive(Debug, PartialEq, Eq)] pub struct Bc { @@ -29,10 +30,7 @@ pub struct ModernMsg { #[derive(Debug, PartialEq, Eq)] pub enum LegacyMsg { - LoginMsg { - username: String, - password: String, - }, + LoginMsg { username: String, password: String }, UnknownMsg, } @@ -73,14 +71,20 @@ impl Bc { /// Convenience function that constructs a modern Bc message from the given meta and XML, with /// no binary payload. pub fn new_from_xml(meta: BcMeta, xml: BcXml) -> Bc { - Bc { meta, body: BcBody::ModernMsg(ModernMsg { xml: Some(xml), binary: None }) } + Bc { + meta, + body: BcBody::ModernMsg(ModernMsg { + xml: Some(xml), + binary: None, + }), + } } } impl BcContext { pub fn new() -> BcContext { BcContext { - in_bin_mode: HashSet::new() + in_bin_mode: HashSet::new(), } } } diff --git a/src/bc/ser.rs b/src/bc/ser.rs index 794b08e..f8a9fa5 100644 --- a/src/bc/ser.rs +++ b/src/bc/ser.rs @@ -1,11 +1,11 @@ -use cookie_factory::bytes::*; -use cookie_factory::{gen, combinator::*}; -use cookie_factory::sequence::tuple; -use cookie_factory::{GenError, SerializeFn, WriteContext}; -use std::io::Write; use super::model::*; use super::xml::BcXml; use super::xml_crypto; +use cookie_factory::bytes::*; +use cookie_factory::sequence::tuple; +use cookie_factory::{combinator::*, gen}; +use cookie_factory::{GenError, SerializeFn, WriteContext}; +use std::io::Write; pub type Error = GenError; @@ -17,15 +17,24 @@ impl Bc { let bin_offset; match &self.body { BcBody::ModernMsg(ref modern) => { - let (buf, xml_len) = gen(opt_ref(&modern.xml, |xml| bc_xml(self.meta.client_idx, xml)), vec!())?; + let (buf, xml_len) = gen( + opt_ref(&modern.xml, |xml| bc_xml(self.meta.client_idx, xml)), + vec![], + )?; 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() { xml_len as u32 } else { 0 }) - } else { None }; + Some(if modern.binary.is_some() { + xml_len as u32 + } else { + 0 + }) + } else { + None + }; } BcBody::LegacyMsg(ref legacy) => { - let (buf, _) = gen(bc_legacy(legacy), vec!())?; + let (buf, _) = gen(bc_legacy(legacy), vec![])?; body_buf = buf; bin_offset = None; } @@ -34,14 +43,14 @@ impl Bc { // Now have enough info to create the header let header = BcHeader::from_meta(&self.meta, body_buf.len() as u32, bin_offset); - let (mut buf, _n) = gen( - tuple(( - bc_header(&header), - slice(body_buf), - )), buf)?; + let (mut buf, _n) = gen(tuple((bc_header(&header), slice(body_buf))), buf)?; // Put the binary part of the body, TODO this is poorly written - if let BcBody::ModernMsg(ModernMsg { binary: Some(ref binary), .. }) = self.body { + if let BcBody::ModernMsg(ModernMsg { + binary: Some(ref binary), + .. + }) = self.body + { let (buf2, _) = gen(slice(binary), buf)?; buf = buf2 } @@ -50,9 +59,8 @@ impl Bc { } } -fn bc_xml(enc_offset: u32, xml: &BcXml) -> impl SerializeFn -{ - let xml_bytes = xml.serialize(vec!()).unwrap(); +fn bc_xml(enc_offset: u32, xml: &BcXml) -> impl SerializeFn { + let xml_bytes = xml.serialize(vec![]).unwrap(); let enc_bytes = xml_crypto::crypt(enc_offset, &xml_bytes); slice(enc_bytes) } @@ -90,7 +98,7 @@ fn bc_legacy<'a, W: Write>(legacy: &'a LegacyMsg) -> impl SerializeFn + 'a { slice(password), // Login messages are 1836 bytes total, username/password // take up 32 chars each, 1772 zeros follow - slice(&[0u8; 1772][..]) + slice(&[0u8; 1772][..]), ))(out) } UnknownMsg => { @@ -102,7 +110,10 @@ fn bc_legacy<'a, W: Write>(legacy: &'a LegacyMsg) -> impl SerializeFn + 'a { /// Applies the supplied serializer with the Option's interior data if present fn opt(opt: Option, ser: impl Fn(T) -> F) -> impl SerializeFn - where F: SerializeFn, T: Copy, W: Write +where + F: SerializeFn, + T: Copy, + W: Write, { move |buf: WriteContext| { if let Some(val) = opt { @@ -114,7 +125,10 @@ fn opt(opt: Option, ser: impl Fn(T) -> F) -> impl SerializeFn } fn opt_ref<'a, W, T, F, S>(opt: &'a Option, ser: S) -> impl SerializeFn + 'a - where F: SerializeFn, W: Write, S: Fn(&'a T) -> F + 'a +where + F: SerializeFn, + W: Write, + S: Fn(&'a T) -> F + 'a, { move |buf: WriteContext| { if let Some(ref val) = opt { @@ -130,7 +144,6 @@ fn do_nothing() -> impl SerializeFn { move |out: WriteContext| Ok(out) } - #[test] fn test_legacy_login_roundtrip() { let mut context = BcContext::new(); @@ -139,7 +152,7 @@ fn test_legacy_login_roundtrip() { let sample = include_bytes!("samples/model_sample_legacy_login.bin"); let msg = Bc::deserialize::<&[u8]>(&mut context, &sample[..]).unwrap(); - let ser_buf = msg.serialize(vec!()).unwrap(); + let ser_buf = msg.serialize(vec![]).unwrap(); let msg2 = Bc::deserialize::<&[u8]>(&mut context, ser_buf.as_ref()).unwrap(); assert_eq!(msg, msg2); assert_eq!(&sample[..], ser_buf.as_slice()); @@ -154,7 +167,7 @@ fn test_modern_login_roundtrip() { let msg = Bc::deserialize::<&[u8]>(&mut context, &sample[..]).unwrap(); - let ser_buf = msg.serialize(vec!()).unwrap(); + let ser_buf = msg.serialize(vec![]).unwrap(); let msg2 = Bc::deserialize::<&[u8]>(&mut context, ser_buf.as_ref()).unwrap(); assert_eq!(msg, msg2); } diff --git a/src/bc/xml.rs b/src/bc/xml.rs index 60bb958..d1fc015 100644 --- a/src/bc/xml.rs +++ b/src/bc/xml.rs @@ -3,8 +3,8 @@ use std::io::{Read, Write}; // YaSerde is currently naming the traits and the derive macros identically -use yaserde_derive::{YaDeserialize, YaSerialize}; use yaserde::{ser::Config, YaDeserialize, YaSerialize}; +use yaserde_derive::{YaDeserialize, YaSerialize}; #[cfg(test)] use indoc::indoc; @@ -12,7 +12,7 @@ use indoc::indoc; #[derive(PartialEq, Eq, Debug, YaDeserialize)] #[yaserde(flatten)] pub(super) enum AllTopXmls { - #[yaserde(rename="body")] + #[yaserde(rename = "body")] BcXml(BcXml), Extension(Extension), } @@ -25,17 +25,17 @@ impl Default for AllTopXmls { } #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] -#[yaserde(rename="body")] +#[yaserde(rename = "body")] pub struct BcXml { - #[yaserde(rename="Encryption")] + #[yaserde(rename = "Encryption")] pub encryption: Option, - #[yaserde(rename="LoginUser")] + #[yaserde(rename = "LoginUser")] pub login_user: Option, - #[yaserde(rename="LoginNet")] + #[yaserde(rename = "LoginNet")] pub login_net: Option, - #[yaserde(rename="DeviceInfo")] + #[yaserde(rename = "DeviceInfo")] pub device_info: Option, - #[yaserde(rename="Preview")] + #[yaserde(rename = "Preview")] pub preview: Option, } @@ -58,7 +58,7 @@ impl BcXml { pub struct Encryption { #[yaserde(attribute)] pub version: String, - #[yaserde(rename="type")] + #[yaserde(rename = "type")] pub type_: String, pub nonce: String, } @@ -67,10 +67,10 @@ pub struct Encryption { pub struct LoginUser { #[yaserde(attribute)] pub version: String, - #[yaserde(rename="userName")] + #[yaserde(rename = "userName")] pub user_name: String, pub password: String, - #[yaserde(rename="userVer")] + #[yaserde(rename = "userVer")] pub user_ver: u32, } @@ -78,9 +78,9 @@ pub struct LoginUser { pub struct LoginNet { #[yaserde(attribute)] pub version: String, - #[yaserde(rename="type")] + #[yaserde(rename = "type")] pub type_: String, - #[yaserde(rename="udpPort")] + #[yaserde(rename = "udpPort")] pub udp_port: u16, } @@ -101,7 +101,7 @@ pub struct DeviceInfo { #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] pub struct Resolution { - #[yaserde(rename="resolutionName")] + #[yaserde(rename = "resolutionName")] pub name: String, pub width: u32, pub height: u32, @@ -112,16 +112,16 @@ pub struct Preview { #[yaserde(attribute)] pub version: String, - #[yaserde(rename="channelId")] + #[yaserde(rename = "channelId")] pub channel_id: u32, pub handle: u32, - #[yaserde(rename="streamType")] + #[yaserde(rename = "streamType")] pub stream_type: String, } #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] pub struct Extension { - #[yaserde(rename="binaryData")] + #[yaserde(rename = "binaryData")] pub binary_data: u32, } @@ -131,14 +131,16 @@ pub fn xml_ver() -> String { #[test] fn test_encryption_deser() { - let sample = indoc!(r#" + let sample = indoc!( + r#" md5 9E6D1FCB9E69846D - "#); + "# + ); let b: BcXml = yaserde::de::from_str(sample).unwrap(); let enc = b.encryption.as_ref().unwrap(); @@ -149,13 +151,14 @@ fn test_encryption_deser() { let t = AllTopXmls::try_parse(sample.as_bytes()).unwrap(); match t { AllTopXmls::BcXml(top_b) if top_b == b => assert!(true), - _ => assert!(false) + _ => assert!(false), } } #[test] fn test_login_deser() { - let sample = indoc!(r#" + let sample = indoc!( + r#" @@ -167,7 +170,8 @@ fn test_login_deser() { LAN 0 - "#); + "# + ); let b: BcXml = yaserde::de::from_str(sample).unwrap(); let login_user = b.login_user.unwrap(); let login_net = b.login_net.unwrap(); @@ -184,7 +188,8 @@ fn test_login_deser() { #[test] fn test_login_ser() { - let sample = indoc!(r#" + let sample = indoc!( + r#" @@ -196,7 +201,8 @@ fn test_login_ser() { LAN 0 - "#); + "# + ); let b = BcXml { login_user: Some(LoginUser { @@ -214,7 +220,7 @@ fn test_login_ser() { }; let b2 = BcXml::try_parse(sample.as_bytes()).unwrap(); - let b3 = BcXml::try_parse(b.serialize(vec!()).unwrap().as_slice()).unwrap(); + let b3 = BcXml::try_parse(b.serialize(vec![]).unwrap().as_slice()).unwrap(); assert_eq!(b, b2); assert_eq!(b, b3); @@ -223,7 +229,8 @@ fn test_login_ser() { #[test] fn test_deviceinfo_partial_deser() { - let sample = indoc!(r#" + let sample = indoc!( + r#" @@ -243,21 +250,26 @@ fn test_deviceinfo_partial_deser() { 0 1 - "#); + "# + ); // Needs to ignore all the other crap that we don't care about let b = BcXml::try_parse(sample.as_bytes()).unwrap(); match b { BcXml { - device_info: Some(DeviceInfo { - resolution: Resolution { - width: 3840, - height: 2160, + device_info: + Some(DeviceInfo { + resolution: + Resolution { + width: 3840, + height: 2160, + .. + }, .. - }, .. - }), .. + }), + .. } => assert!(true), - _ => assert!(false) + _ => assert!(false), } } @@ -265,15 +277,17 @@ fn test_deviceinfo_partial_deser() { fn test_binary_deser() { let _ = env_logger::builder().is_test(true).try_init(); - let sample = indoc!(r#" + let sample = indoc!( + r#" 1 - "#); + "# + ); let b = AllTopXmls::try_parse(sample.as_bytes()).unwrap(); match b { AllTopXmls::Extension(Extension { binary_data: 1 }) => assert!(true), - _ => assert!(false) + _ => assert!(false), } } diff --git a/src/bc/xml_crypto.rs b/src/bc/xml_crypto.rs index 5e7f7b5..edfcfe0 100644 --- a/src/bc/xml_crypto.rs +++ b/src/bc/xml_crypto.rs @@ -2,7 +2,10 @@ const XML_KEY: [u8; 8] = [0x1F, 0x2D, 0x3C, 0x4B, 0x5A, 0x69, 0x78, 0xFF]; pub fn crypt(offset: u32, buf: &[u8]) -> Vec { let key_iter = XML_KEY.iter().cycle().skip(offset as usize % 8); - key_iter.zip(buf).map(|(key, i)| *i ^ key ^ (offset as u8)).collect() + key_iter + .zip(buf) + .map(|(key, i)| *i ^ key ^ (offset as u8)) + .collect() } #[test] @@ -22,4 +25,3 @@ fn test_xml_crypto_roundtrip() { let encrypted = crypt(0, &decrypted[..]); assert_eq!(encrypted, &zeros[..]); } - diff --git a/src/bc_protocol.rs b/src/bc_protocol.rs index 2a58eba..fbc9111 100644 --- a/src/bc_protocol.rs +++ b/src/bc_protocol.rs @@ -1,9 +1,9 @@ +use self::connection::BcConnection; use crate::bc; use crate::bc::{model::*, xml::*}; use err_derive::Error; use log::*; use md5; -use self::connection::BcConnection; use std::io::Write; use std::net::{SocketAddr, ToSocketAddrs}; use std::time::Duration; @@ -23,34 +23,31 @@ type Result = std::result::Result; #[derive(Debug, Error)] pub enum Error { - #[error(display="Communication error")] + #[error(display = "Communication error")] CommunicationError(#[error(source)] std::io::Error), - #[error(display="Deserialization error")] + #[error(display = "Deserialization error")] DeserializationError(#[error(source)] bc::de::Error), - #[error(display="Serialization error")] + #[error(display = "Serialization error")] SerializationError(#[error(source)] bc::ser::Error), - #[error(display="Connection error")] + #[error(display = "Connection error")] ConnectionError(#[error(source)] self::connection::Error), - #[error(display="Communication error")] - UnintelligibleReply { - reply: Bc, - why: &'static str, - }, + #[error(display = "Communication error")] + UnintelligibleReply { reply: Bc, why: &'static str }, - #[error(display="Dropped connection")] + #[error(display = "Dropped connection")] DroppedConnection(#[error(source)] std::sync::mpsc::RecvError), - #[error(display="Timeout")] + #[error(display = "Timeout")] Timeout(#[error(source)] std::sync::mpsc::RecvTimeoutError), - #[error(display="Credential error")] + #[error(display = "Credential error")] AuthFailed, - #[error(display="Other error")] + #[error(display = "Other error")] Other(&'static str), } @@ -62,7 +59,9 @@ impl Drop for BcCamera { impl BcCamera { pub fn new_with_addr(hostname: T) -> Result { - let address = hostname.to_socket_addrs()?.next() + let address = hostname + .to_socket_addrs()? + .next() .ok_or(Error::Other("Address resolution failed"))?; Ok(Self { @@ -90,7 +89,10 @@ impl BcCamera { } pub fn login(&mut self, username: &str, password: Option<&str>) -> Result { - let connection = self.connection.as_ref().expect("Must be connected to log in"); + let connection = self + .connection + .as_ref() + .expect("Must be connected to log in"); let sub_login = connection.subscribe(MSG_ID_LOGIN)?; // Login flow is: Send legacy login message, expect back a modern message with Encryption @@ -103,7 +105,9 @@ impl BcCamera { // Baichuan library, these strings are capped at 32 bytes with a null terminator. This // could also be a mistake in the library, the effect being it only compares 31 chars, not 32. let md5_username = md5_string(username, ZeroLast); - let md5_password = password.map(|p| md5_string(p, ZeroLast)).unwrap_or(EMPTY_LEGACY_PASSWORD.to_owned()); + let md5_password = password + .map(|p| md5_string(p, ZeroLast)) + .unwrap_or(EMPTY_LEGACY_PASSWORD.to_owned()); let legacy_login = Bc { meta: BcMeta { @@ -115,7 +119,7 @@ impl BcCamera { body: BcBody::LegacyMsg(LegacyMsg::LoginMsg { username: md5_username, password: md5_password, - }) + }), }; sub_login.send(legacy_login)?; @@ -124,14 +128,21 @@ impl BcCamera { let nonce; match legacy_reply.body { BcBody::ModernMsg(ModernMsg { - xml: Some(BcXml { encryption: Some(encryption), .. }), .. + xml: + Some(BcXml { + encryption: Some(encryption), + .. + }), + .. }) => { nonce = encryption.nonce; } - _ => return Err(Error::UnintelligibleReply { - reply: legacy_reply, - why: "Expected an Encryption message back" - }) + _ => { + return Err(Error::UnintelligibleReply { + reply: legacy_reply, + why: "Expected an Encryption message back", + }) + } } // In the modern login flow, the username/password are concat'd with the server's nonce @@ -163,7 +174,8 @@ impl BcCamera { }), login_net: Some(LoginNet::default()), ..Default::default() - }); + }, + ); sub_login.send(modern_login)?; let modern_reply = sub_login.rx.recv_timeout(self.rx_timeout)?; @@ -171,21 +183,27 @@ impl BcCamera { let device_info; match modern_reply.body { BcBody::ModernMsg(ModernMsg { - xml: Some(BcXml { device_info: Some(info), .. }), .. + xml: + Some(BcXml { + device_info: Some(info), + .. + }), + .. }) => { // Login succeeded! self.logged_in = true; device_info = info; } BcBody::ModernMsg(ModernMsg { - xml: None, binary: None, - }) => { - return Err(Error::AuthFailed) + xml: None, + binary: None, + }) => return Err(Error::AuthFailed), + _ => { + return Err(Error::UnintelligibleReply { + reply: modern_reply, + why: "Expected a DeviceInfo message back from login", + }) } - _ => return Err(Error::UnintelligibleReply { - reply: modern_reply, - why: "Expected a DeviceInfo message back from login" - }) } Ok(device_info) @@ -223,7 +241,10 @@ impl BcCamera { } pub fn start_video(&self, data_out: &mut dyn Write) -> Result<()> { - let connection = self.connection.as_ref().expect("Must be connected to start video"); + let connection = self + .connection + .as_ref() + .expect("Must be connected to start video"); let sub_video = connection.subscribe(MSG_ID_VIDEO)?; let start_video = Bc::new_from_xml( @@ -241,18 +262,22 @@ impl BcCamera { stream_type: "mainStream".to_string(), }), ..Default::default() - }); + }, + ); sub_video.send(start_video)?; loop { trace!("Getting video message..."); let msg = sub_video.rx.recv_timeout(self.rx_timeout)?; - if let BcBody::ModernMsg(ModernMsg { binary: Some(binary), .. }) = msg.body { + if let BcBody::ModernMsg(ModernMsg { + binary: Some(binary), + .. + }) = msg.body + { trace!("Got {} bytes of video data", binary.len()); data_out.write_all(binary.as_slice())?; - } - else { + } else { warn!("Ignoring weird video message"); debug!("Contents: {:?}", msg); } @@ -271,7 +296,7 @@ impl BcCamera { #[derive(PartialEq, Eq)] enum Md5Trunc { ZeroLast, - Truncate + Truncate, } fn md5_string(input: &str, trunc: Md5Trunc) -> String { @@ -283,6 +308,12 @@ fn md5_string(input: &str, trunc: Md5Trunc) -> String { #[test] fn test_md5_string() { // Note that these literals are only 31 characters long - see explanation above. - assert_eq!(md5_string("admin", Truncate), "21232F297A57A5A743894A0E4A801FC"); - assert_eq!(md5_string("admin", ZeroLast), "21232F297A57A5A743894A0E4A801FC\0"); + assert_eq!( + md5_string("admin", Truncate), + "21232F297A57A5A743894A0E4A801FC" + ); + assert_eq!( + md5_string("admin", ZeroLast), + "21232F297A57A5A743894A0E4A801FC\0" + ); } diff --git a/src/bc_protocol/connection.rs b/src/bc_protocol/connection.rs index 2fade7d..122e8c4 100644 --- a/src/bc_protocol/connection.rs +++ b/src/bc_protocol/connection.rs @@ -2,14 +2,14 @@ use crate::bc; use crate::bc::model::*; use err_derive::Error; use log::*; -use socket2::{Socket, Domain, Type}; -use std::collections::BTreeMap; +use socket2::{Domain, Socket, Type}; use std::collections::btree_map::Entry; -use std::net::{TcpStream, Shutdown, SocketAddr}; +use std::collections::BTreeMap; +use std::net::{Shutdown, SocketAddr, TcpStream}; +use std::sync::mpsc::{channel, Receiver, Sender}; +use std::sync::{Arc, Mutex}; use std::thread::JoinHandle; use std::time::Duration; -use std::sync::{Arc, Mutex}; -use std::sync::mpsc::{channel, Sender, Receiver}; /// A shareable connection to a camera. Handles serialization of messages. To send/receive, call /// .subscribe() with a message ID. You can use the BcSubscription to send or receive only @@ -32,16 +32,16 @@ type Result = std::result::Result; #[derive(Debug, Error)] pub enum Error { - #[error(display="Communication error")] + #[error(display = "Communication error")] CommunicationError(#[error(source)] std::io::Error), - #[error(display="Deserialization error")] + #[error(display = "Deserialization error")] DeserializationError(#[error(source)] bc::de::Error), - #[error(display="Serialization error")] + #[error(display = "Serialization error")] SerializationError(#[error(source)] bc::ser::Error), - #[error(display="Simultaneous subscription")] + #[error(display = "Simultaneous subscription")] SimultaneousSubscription { msg_id: u32 }, } @@ -71,23 +71,26 @@ impl BcConnection { Entry::Vacant(vac_entry) => vac_entry.insert(tx), Entry::Occupied(_) => return Err(Error::SimultaneousSubscription { msg_id }), }; - Ok(BcSubscription { rx, conn: self, msg_id }) + Ok(BcSubscription { + rx, + conn: self, + msg_id, + }) } fn poll( context: &mut BcContext, connection: &TcpStream, - subscribers: &mut Arc>>> + subscribers: &mut Arc>>>, ) -> Result<()> { // Don't hold the lock during deserialization so we don't poison the subscribers mutex if // something goes wrong - let response = Bc::deserialize(context, connection) - .map_err(|err| { - // If the connection hangs up, hang up on all subscribers - subscribers.lock().unwrap().clear(); - err - })?; + let response = Bc::deserialize(context, connection).map_err(|err| { + // If the connection hangs up, hang up on all subscribers + subscribers.lock().unwrap().clear(); + err + })?; let msg_id = response.meta.msg_id; let mut locked_subs = subscribers.lock().unwrap(); @@ -113,10 +116,15 @@ impl Drop for BcConnection { fn drop(&mut self) { debug!("Shutting down BcConnection..."); let _ = self.connection.lock().unwrap().shutdown(Shutdown::Both); - match self.rx_thread.take().expect("rx_thread join handle should always exist").join() { + match self + .rx_thread + .take() + .expect("rx_thread join handle should always exist") + .join() + { Ok(_) => { debug!("Shutdown finished OK"); - }, + } Err(e) => { error!("Receiving thread panicked: {:?}", e); } @@ -143,9 +151,7 @@ impl<'a> Drop for BcSubscription<'a> { /// Helper to create a TcpStream with a connect timeout fn connect_to(addr: SocketAddr, timeout: Duration) -> Result { let socket = match addr { - SocketAddr::V4(_) => { - Socket::new(Domain::ipv4(), Type::stream(), None)? - } + SocketAddr::V4(_) => Socket::new(Domain::ipv4(), Type::stream(), None)?, SocketAddr::V6(_) => { let s = Socket::new(Domain::ipv6(), Type::stream(), None)?; s.set_only_v6(false)?; diff --git a/src/config.rs b/src/config.rs index f792cad..4173765 100644 --- a/src/config.rs +++ b/src/config.rs @@ -6,7 +6,7 @@ use std::time::Duration; pub struct Config { pub cameras: Vec, - #[serde(rename="bind", default="default_bind_addr")] + #[serde(rename = "bind", default = "default_bind_addr")] pub bind_addr: String, } @@ -14,7 +14,7 @@ pub struct Config { pub struct CameraConfig { pub name: String, - #[serde(rename="address")] + #[serde(rename = "address")] pub camera_addr: SocketAddr, pub username: String, diff --git a/src/gst.rs b/src/gst.rs index d2f0724..68d3b84 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -2,12 +2,12 @@ //! data using an ordinary std::io::Write interface. pub use self::maybe_app_src::MaybeAppSrc; -use gstreamer::Bin; use gstreamer::prelude::Cast; +use gstreamer::Bin; use gstreamer_app::AppSrc; //use gstreamer_rtsp::RTSPLowerTrans; -use gstreamer_rtsp_server::{RTSPServer as GstRTSPServer, RTSPAuth, RTSPMediaFactory}; use gstreamer_rtsp_server::prelude::*; +use gstreamer_rtsp_server::{RTSPAuth, RTSPMediaFactory, RTSPServer as GstRTSPServer}; use log::debug; use std::io; use std::io::Write; @@ -27,15 +27,20 @@ impl RtspServer { } pub fn add_stream(&self, name: &str) -> Result { - let mounts = self.server.get_mount_points().expect("The server should have mountpoints"); + let mounts = self + .server + .get_mount_points() + .expect("The server should have mountpoints"); let factory = RTSPMediaFactory::new(); //factory.set_protocols(RTSPLowerTrans::TCP); - factory.set_launch(concat!("( ", - "appsrc name=writesrc is-live=true block=true emit-signals=false max-bytes=0", - " ! h265parse", - " ! rtph265pay name=pay0", - " )")); + factory.set_launch(concat!( + "( ", + "appsrc name=writesrc is-live=true block=true emit-signals=false max-bytes=0", + " ! h265parse", + " ! rtph265pay name=pay0", + " )" + )); factory.set_shared(true); // TODO maybe set video format via @@ -48,14 +53,16 @@ impl RtspServer { let (maybe_app_src, tx) = MaybeAppSrc::new_with_tx(); factory.connect_media_configure(move |_factory, media| { debug!("RTSP: media was configured"); - let bin = media.get_element() - .expect("Media should have an element") - .dynamic_cast::() - .expect("Media source's element should be a bin"); - let app_src = bin.get_by_name_recurse_up("writesrc") - .expect("write_src must be present in created bin") - .dynamic_cast::() - .expect("Source element is expected to be an appsrc!"); + let bin = media + .get_element() + .expect("Media should have an element") + .dynamic_cast::() + .expect("Media source's element should be a bin"); + let app_src = bin + .get_by_name_recurse_up("writesrc") + .expect("write_src must be present in created bin") + .dynamic_cast::() + .expect("Source element is expected to be an appsrc!"); let _ = tx.send(app_src); // Receiver may be dropped, don't panic if so }); @@ -95,8 +102,8 @@ impl RtspServer { } mod maybe_app_src { - use std::sync::mpsc::{sync_channel, Receiver, SyncSender}; use super::*; + use std::sync::mpsc::{sync_channel, Receiver, SyncSender}; /// A Write implementation around AppSrc that also allows delaying the creation of the AppSrc /// until later, discarding written data until the AppSrc is provided. @@ -111,7 +118,7 @@ mod maybe_app_src { /// into the AppSrc when write() is called. pub fn new_with_tx() -> (Self, SyncSender) { let (tx, rx) = sync_channel(3); // The sender should not send very often - (MaybeAppSrc { rx, app_src: None, }, tx) + (MaybeAppSrc { rx, app_src: None }, tx) } /// Attempts to retrieve the AppSrc that should be passed in by the caller of new_with_tx diff --git a/src/main.rs b/src/main.rs index cf8aa4c..7889100 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,25 +1,25 @@ -use neolink::bc_protocol::BcCamera; -use neolink::gst::RtspServer; use err_derive::Error; use log::*; +use neolink::bc_protocol::BcCamera; +use neolink::gst::RtspServer; use std::fs; -use std::time::Duration; use std::io::Write; +use std::time::Duration; use structopt::StructOpt; mod cmdline; mod config; -use config::{Config, CameraConfig}; use cmdline::Opt; +use config::{CameraConfig, Config}; #[derive(Debug, Error)] pub enum Error { - #[error(display="Configuration parsing error")] + #[error(display = "Configuration parsing error")] ConfigError(#[error(source)] toml::de::Error), - #[error(display="Communication error")] + #[error(display = "Communication error")] ProtocolError(#[error(source)] neolink::Error), - #[error(display="I/O error")] + #[error(display = "I/O error")] IoError(#[error(source)] std::io::Error), } @@ -40,7 +40,8 @@ fn main() -> Result<(), Error> { } rtsp.run(&config.bind_addr); - }).unwrap(); + }) + .unwrap(); Ok(()) } @@ -53,41 +54,62 @@ fn camera_loop(camera_config: &CameraConfig, output: &mut dyn Write) -> Result<( loop { match camera_main(camera_config, output) { // Authentication failures are permanent; we retry everything else - Ok(_) => error!("Camera {} stream stopped unexpectedly, will retry in {}s", - camera_config.name, current_backoff.as_secs()), + Ok(_) => error!( + "Camera {} stream stopped unexpectedly, will retry in {}s", + camera_config.name, + current_backoff.as_secs() + ), Err(cam_err) => { if cam_err.connected { current_backoff = min_backoff; } match cam_err.err { neolink::Error::AuthFailed => { - error!("Authentication failed to camera {}, not retrying", camera_config.name); + error!( + "Authentication failed to camera {}, not retrying", + camera_config.name + ); return Err(cam_err.err.into()); } - _ => error!("Error streaming from camera {}, will retry in {}s: {}", - camera_config.name, current_backoff.as_secs(), cam_err.err), + _ => error!( + "Error streaming from camera {}, will retry in {}s: {}", + camera_config.name, + current_backoff.as_secs(), + cam_err.err + ), } } } std::thread::sleep(current_backoff); current_backoff = std::cmp::min(max_backoff, current_backoff * 2); - } + } } fn camera_main(camera_config: &CameraConfig, output: &mut dyn Write) -> Result<(), CameraErr> { - let mut camera = BcCamera::new_with_addr(camera_config.camera_addr).map_err(CameraErr::before_connect)?; + let mut camera = + BcCamera::new_with_addr(camera_config.camera_addr).map_err(CameraErr::before_connect)?; if let Some(timeout) = camera_config.timeout { camera.set_rx_timeout(timeout); } - println!("{}: Connecting to camera at {}", camera_config.name, camera_config.camera_addr); + println!( + "{}: Connecting to camera at {}", + camera_config.name, camera_config.camera_addr + ); camera.connect().map_err(CameraErr::before_connect)?; - camera.login(&camera_config.username, camera_config.password.as_deref()).map_err(CameraErr::after_connect)?; + camera + .login(&camera_config.username, camera_config.password.as_deref()) + .map_err(CameraErr::after_connect)?; - println!("{}: Connected to camera, starting video stream", camera_config.name); - camera.start_video(output).map_err(CameraErr::after_connect)?; + println!( + "{}: Connected to camera, starting video stream", + camera_config.name + ); + camera + .start_video(output) + .map_err(CameraErr::after_connect)?; unreachable!() } @@ -99,9 +121,15 @@ struct CameraErr { impl CameraErr { fn before_connect>(e: E) -> Self { - CameraErr { connected: false, err: e.into() } + CameraErr { + connected: false, + err: e.into(), + } } fn after_connect>(e: E) -> Self { - CameraErr { connected: true, err: e.into() } + CameraErr { + connected: true, + err: e.into(), + } } }