Restuructured bc_protocol to increase modulaitry

This commit is contained in:
QuantumEntangledAndy committed 2021-08-01 07:53:21 +07:00
1 parent 9efedd660a
commit 1c07973c37
7 files changed
+415 -384

No files matched your search

+8 -384
View File
@@ -1,8 +1,5 @@
use self::connection::BcConnection;
use self::media_packet::{MediaDataKind, MediaDataSubscriber};
use crate::bc;
use crate::bc::{model::*, xml::*};
use err_derive::Error;
use log::*;
use std::convert::TryInto;
use std::net::ToSocketAddrs;
@@ -12,74 +9,22 @@ use std::time::Duration;
use Md5Trunc::*;
mod connection;
mod errors;
mod login;
mod logout;
mod media_packet;
mod ping;
mod stream;
mod time;
mod version;
use crate::Never;
pub use errors::Error;
pub use stream::{StreamFormat, StreamOutput, StreamOutputError};
type Result<T> = std::result::Result<T, Error>;
const RX_TIMEOUT: Duration = Duration::from_secs(5);
/// This is the primary error type of the library
#[derive(Debug, Error)]
#[allow(clippy::large_enum_variant)]
pub enum Error {
/// Error raised when IO fails such as when the connection is lost
#[error(display = "Communication error")]
Communication(#[error(source)] std::io::Error),
/// Errors raised during deserlization
#[error(display = "Deserialization error")]
Deserialization(#[error(source)] bc::de::Error),
/// Errors raised during serlization
#[error(display = "Serialization error")]
Serialization(#[error(source)] bc::ser::Error),
/// A connection error such as Simultaneous subscription
#[error(display = "Connection error")]
ConnectionError(#[error(source)] self::connection::Error),
/// Raised when a Bc reply was not understood
#[error(display = "Communication error")]
UnintelligibleReply {
/// The Bc packet that was not understood
reply: Bc,
/// The message attached to the error
why: &'static str,
},
/// Raised when a connection is dropped. This can be for many reasons
/// and is usually not helpful
#[error(display = "Dropped connection")]
DroppedConnection(#[error(source)] std::sync::mpsc::RecvError),
/// Raised when the RX_TIMEOUT is reach
#[error(display = "Timeout")]
Timeout,
/// Raised when connection is dropped because the RX_TIMEOUT is reach
#[error(display = "Dropped connection")]
TimeoutDisconnected,
/// Raised when failed to login to the camera
#[error(display = "Credential error")]
AuthFailed,
/// Raised when the given camera url could not be resolved
#[error(display = "Failed to translate camera address")]
AddrResolutionError,
/// A generic catch all error
#[error(display = "Other error")]
Other(&'static str),
/// A generic catch all error
#[error(display = "Other error")]
OtherString(String),
}
impl<'a> From<std::sync::mpsc::RecvTimeoutError> for Error {
fn from(k: std::sync::mpsc::RecvTimeoutError) -> Self {
match k {
@@ -99,31 +44,6 @@ pub struct BcCamera {
message_num: AtomicU16,
}
/// The stream from the camera will be using one of these formats
#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
pub enum StreamFormat {
/// H264 (AVC) video format
H264,
/// H265 (HEVC) video format
H265,
/// AAC audio
AAC,
/// ADPCM in DVI-4 format
ADPCM,
}
/// Convience type for the error raised by the StreamOutput trait
pub type StreamOutputError = Result<()>;
/// The method `start_stream` requires a structure with this trait to pass the
/// audio and video data back to
pub trait StreamOutput {
/// This is the callback raised when audio data is received
fn write_audio(&mut self, data: &[u8], format: StreamFormat) -> StreamOutputError;
/// This is the callback raised when video data is received
fn write_video(&mut self, data: &[u8], format: StreamFormat) -> StreamOutputError;
}
impl Drop for BcCamera {
fn drop(&mut self) {
self.disconnect();
@@ -189,302 +109,6 @@ impl BcCamera {
}
self.connection = None;
}
/// Will try to login to the camera.
///
/// This should be called before most other commands
pub fn login(&mut self, username: &str, password: Option<&str>) -> Result<DeviceInfo> {
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
// details. Then, re-send the login as a modern login message. Expect back a device info
// congratulating us on logging in.
// In the legacy scheme, username/password are MD5'd if they are encrypted (which they need
// to be to "upgrade" to the modern login flow), then the hex of the MD5 is sent.
// Note: I suspect there may be a buffer overflow opportunity in the firmware since in the
// 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_else(|| EMPTY_LEGACY_PASSWORD.to_owned());
let legacy_login = Bc {
meta: BcMeta {
msg_id: MSG_ID_LOGIN,
channel_id: self.channel_id,
msg_num: self.new_message_num(),
stream_type: 0,
response_code: 0xdc03,
class: 0x6514,
},
body: BcBody::LegacyMsg(LegacyMsg::LoginMsg {
username: md5_username,
password: md5_password,
}),
};
sub_login.send(legacy_login)?;
let legacy_reply = sub_login.rx.recv_timeout(RX_TIMEOUT)?;
let nonce;
match legacy_reply.body {
BcBody::ModernMsg(ModernMsg {
payload:
Some(BcPayloads::BcXml(BcXml {
encryption: Some(encryption),
..
})),
..
}) => {
nonce = encryption.nonce;
}
_ => {
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
// string, then MD5'd, then the hex of this MD5 is sent as the password. This nonce
// prevents replay attacks if the server were to require modern flow, but not rainbow table
// attacks (since the plain user/password MD5s have already been sent). The upshot is that
// you should use a very strong random password that is not found in a rainbow table and
// not feasibly crackable with John the Ripper.
let modern_password = password.unwrap_or("");
let concat_username = format!("{}{}", username, nonce);
let concat_password = format!("{}{}", modern_password, nonce);
let md5_username = md5_string(&concat_username, Truncate);
let md5_password = md5_string(&concat_password, Truncate);
let modern_login = Bc::new_from_xml(
BcMeta {
msg_id: MSG_ID_LOGIN,
channel_id: self.channel_id,
msg_num: self.new_message_num(),
stream_type: 0,
response_code: 0,
class: 0x6414,
},
BcXml {
login_user: Some(LoginUser {
version: xml_ver(),
user_name: md5_username,
password: md5_password,
user_ver: 1,
}),
login_net: Some(LoginNet::default()),
..Default::default()
},
);
sub_login.send(modern_login)?;
let modern_reply = sub_login.rx.recv_timeout(RX_TIMEOUT)?;
let device_info;
match modern_reply.body {
BcBody::ModernMsg(ModernMsg {
payload:
Some(BcPayloads::BcXml(BcXml {
device_info: Some(info),
..
})),
..
}) => {
// Login succeeded!
self.logged_in = true;
device_info = info;
}
BcBody::ModernMsg(ModernMsg {
extension: None,
payload: None,
}) => return Err(Error::AuthFailed),
_ => {
return Err(Error::UnintelligibleReply {
reply: modern_reply,
why: "Expected a DeviceInfo message back from login",
})
}
}
if let EncryptionProtocol::Aes(_) = connection.get_encrypted() {
// We setup the data for the AES key now
// as all subsequent communications will use it
let passwd = password.unwrap_or("");
let full_key = make_aes_key(&nonce, passwd);
connection.set_encrypted(EncryptionProtocol::Aes(Some(full_key)));
}
Ok(device_info)
}
/// Will logout from the camera
pub fn logout(&mut self) -> Result<()> {
if self.logged_in {
// TODO: Send message ID 2
}
self.logged_in = false;
Ok(())
}
/// Request the VersionInfo xml
pub fn version(&self) -> Result<VersionInfo> {
let connection = self
.connection
.as_ref()
.expect("Must be connected to get version info");
let sub_version = connection.subscribe(MSG_ID_VERSION)?;
let version = Bc {
meta: BcMeta {
msg_id: MSG_ID_VERSION,
channel_id: self.channel_id,
msg_num: self.new_message_num(),
stream_type: 0,
response_code: 0,
class: 0x6414, // IDK why
},
body: BcBody::ModernMsg(ModernMsg {
..Default::default()
}),
};
sub_version.send(version)?;
let modern_reply = sub_version.rx.recv_timeout(RX_TIMEOUT)?;
let version_info;
match modern_reply.body {
BcBody::ModernMsg(ModernMsg {
payload:
Some(BcPayloads::BcXml(BcXml {
version_info: Some(info),
..
})),
..
}) => {
version_info = info;
}
_ => {
return Err(Error::UnintelligibleReply {
reply: modern_reply,
why: "Expected a VersionInfo message",
})
}
}
Ok(version_info)
}
/// Ping the camera will either return Ok(()) which means a sucess reply
/// or error
pub fn ping(&self) -> Result<()> {
let connection = self.connection.as_ref().expect("Must be connected to ping");
let sub_ping = connection.subscribe(MSG_ID_PING)?;
let ping = Bc {
meta: BcMeta {
msg_id: MSG_ID_PING,
channel_id: self.channel_id,
msg_num: self.new_message_num(),
stream_type: 0,
response_code: 0,
class: 0x6414,
},
body: BcBody::ModernMsg(ModernMsg {
..Default::default()
}),
};
sub_ping.send(ping)?;
sub_ping.rx.recv_timeout(RX_TIMEOUT)?;
Ok(())
}
///
/// Starts the video stream
///
/// # Parameters
///
/// * `data_outs` - This should be a struct that implements the `StreamOutput` trait
///
/// * `stream_name` - The name of the stream either `"mainStream"` for HD or `"subStream"` for SD
///
/// # Returns
///
/// This will block forever or return an error when the camera connection is dropped
///
pub fn start_video<Outputs>(&self, data_outs: &mut Outputs, stream_name: &str) -> Result<Never>
where
Outputs: StreamOutput,
{
let connection = self
.connection
.as_ref()
.expect("Must be connected to start video");
let sub_video = connection.subscribe(MSG_ID_VIDEO)?;
let stream_num = match stream_name {
"mainStream" => 0,
"subStream" => 1,
_ => 0,
};
let start_video = Bc::new_from_xml(
BcMeta {
msg_id: MSG_ID_VIDEO,
channel_id: self.channel_id,
msg_num: self.new_message_num(),
stream_type: stream_num,
response_code: 0,
class: 0x6414, // IDK why
},
BcXml {
preview: Some(Preview {
version: xml_ver(),
channel_id: self.channel_id,
handle: 0,
stream_type: stream_name.to_string(),
}),
..Default::default()
},
);
sub_video.send(start_video)?;
let mut media_sub = MediaDataSubscriber::from_bc_sub(&sub_video);
loop {
let binary_data = media_sub.next_media_packet()?;
// We now have a complete interesting packet. Send it to gst.
// Process the packet
match (binary_data.kind(), binary_data.media_format()) {
(
MediaDataKind::VideoDataIframe | MediaDataKind::VideoDataPframe,
Some(media_format),
) => {
data_outs.write_video(binary_data.body(), media_format)?;
}
(MediaDataKind::AudioDataAac, Some(media_format)) => {
data_outs.write_audio(binary_data.body(), media_format)?;
}
(MediaDataKind::AudioDataAdpcm, Some(media_format)) => {
data_outs.write_audio(binary_data.body(), media_format)?;
}
_ => {}
};
}
}
}
/// The Baichuan library has a very peculiar behavior where it always zeros the last byte. I
+61
View File
@@ -0,0 +1,61 @@
use super::bc::model::Bc;
use err_derive::Error;
/// This is the primary error type of the library
#[derive(Debug, Error)]
#[allow(clippy::large_enum_variant)]
pub enum Error {
/// Error raised when IO fails such as when the connection is lost
#[error(display = "Communication error")]
Communication(#[error(source)] std::io::Error),
/// Errors raised during deserlization
#[error(display = "Deserialization error")]
Deserialization(#[error(source)] super::bc::de::Error),
/// Errors raised during serlization
#[error(display = "Serialization error")]
Serialization(#[error(source)] super::bc::ser::Error),
/// A connection error such as Simultaneous subscription
#[error(display = "Connection error")]
ConnectionError(#[error(source)] super::connection::Error),
/// Raised when a Bc reply was not understood
#[error(display = "Communication error")]
UnintelligibleReply {
/// The Bc packet that was not understood
reply: Bc,
/// The message attached to the error
why: &'static str,
},
/// Raised when a connection is dropped. This can be for many reasons
/// and is usually not helpful
#[error(display = "Dropped connection")]
DroppedConnection(#[error(source)] std::sync::mpsc::RecvError),
/// Raised when the RX_TIMEOUT is reach
#[error(display = "Timeout")]
Timeout,
/// Raised when connection is dropped because the RX_TIMEOUT is reach
#[error(display = "Dropped connection")]
TimeoutDisconnected,
/// Raised when failed to login to the camera
#[error(display = "Credential error")]
AuthFailed,
/// Raised when the given camera url could not be resolved
#[error(display = "Failed to translate camera address")]
AddrResolutionError,
/// A generic catch all error
#[error(display = "Other error")]
Other(&'static str),
/// A generic catch all error
#[error(display = "Other error")]
OtherString(String),
}
+141
View File
@@ -0,0 +1,141 @@
use super::{make_aes_key, md5_string, BcCamera, Error, Result, Truncate, ZeroLast, RX_TIMEOUT};
use crate::bc::{model::*, xml::*};
impl BcCamera {
/// Will try to login to the camera.
///
/// This should be called before most other commands
pub fn login(&mut self, username: &str, password: Option<&str>) -> Result<DeviceInfo> {
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
// details. Then, re-send the login as a modern login message. Expect back a device info
// congratulating us on logging in.
// In the legacy scheme, username/password are MD5'd if they are encrypted (which they need
// to be to "upgrade" to the modern login flow), then the hex of the MD5 is sent.
// Note: I suspect there may be a buffer overflow opportunity in the firmware since in the
// 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_else(|| EMPTY_LEGACY_PASSWORD.to_owned());
let legacy_login = Bc {
meta: BcMeta {
msg_id: MSG_ID_LOGIN,
channel_id: self.channel_id,
msg_num: self.new_message_num(),
stream_type: 0,
response_code: 0xdc03,
class: 0x6514,
},
body: BcBody::LegacyMsg(LegacyMsg::LoginMsg {
username: md5_username,
password: md5_password,
}),
};
sub_login.send(legacy_login)?;
let legacy_reply = sub_login.rx.recv_timeout(RX_TIMEOUT)?;
let nonce;
match legacy_reply.body {
BcBody::ModernMsg(ModernMsg {
payload:
Some(BcPayloads::BcXml(BcXml {
encryption: Some(encryption),
..
})),
..
}) => {
nonce = encryption.nonce;
}
_ => {
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
// string, then MD5'd, then the hex of this MD5 is sent as the password. This nonce
// prevents replay attacks if the server were to require modern flow, but not rainbow table
// attacks (since the plain user/password MD5s have already been sent). The upshot is that
// you should use a very strong random password that is not found in a rainbow table and
// not feasibly crackable with John the Ripper.
let modern_password = password.unwrap_or("");
let concat_username = format!("{}{}", username, nonce);
let concat_password = format!("{}{}", modern_password, nonce);
let md5_username = md5_string(&concat_username, Truncate);
let md5_password = md5_string(&concat_password, Truncate);
let modern_login = Bc::new_from_xml(
BcMeta {
msg_id: MSG_ID_LOGIN,
channel_id: self.channel_id,
msg_num: self.new_message_num(),
stream_type: 0,
response_code: 0,
class: 0x6414,
},
BcXml {
login_user: Some(LoginUser {
version: xml_ver(),
user_name: md5_username,
password: md5_password,
user_ver: 1,
}),
login_net: Some(LoginNet::default()),
..Default::default()
},
);
sub_login.send(modern_login)?;
let modern_reply = sub_login.rx.recv_timeout(RX_TIMEOUT)?;
let device_info;
match modern_reply.body {
BcBody::ModernMsg(ModernMsg {
payload:
Some(BcPayloads::BcXml(BcXml {
device_info: Some(info),
..
})),
..
}) => {
// Login succeeded!
self.logged_in = true;
device_info = info;
}
BcBody::ModernMsg(ModernMsg {
extension: None,
payload: None,
}) => return Err(Error::AuthFailed),
_ => {
return Err(Error::UnintelligibleReply {
reply: modern_reply,
why: "Expected a DeviceInfo message back from login",
})
}
}
if let EncryptionProtocol::Aes(_) = connection.get_encrypted() {
// We setup the data for the AES key now
// as all subsequent communications will use it
let passwd = password.unwrap_or("");
let full_key = make_aes_key(&nonce, passwd);
connection.set_encrypted(EncryptionProtocol::Aes(Some(full_key)));
}
Ok(device_info)
}
}
+12
View File
@@ -0,0 +1,12 @@
use super::{BcCamera, Result};
impl BcCamera {
/// Logout from the camera
pub fn logout(&mut self) -> Result<()> {
if self.logged_in {
// TODO: Send message ID 2
}
self.logged_in = false;
Ok(())
}
}
+31
View File
@@ -0,0 +1,31 @@
use super::{BcCamera, Result, RX_TIMEOUT};
use crate::bc::model::*;
impl BcCamera {
/// Ping the camera will either return Ok(()) which means a sucess reply
/// or error
pub fn ping(&self) -> Result<()> {
let connection = self.connection.as_ref().expect("Must be connected to ping");
let sub_ping = connection.subscribe(MSG_ID_PING)?;
let ping = Bc {
meta: BcMeta {
msg_id: MSG_ID_PING,
channel_id: self.channel_id,
msg_num: self.new_message_num(),
stream_type: 0,
response_code: 0,
class: 0x6414,
},
body: BcBody::ModernMsg(ModernMsg {
..Default::default()
}),
};
sub_ping.send(ping)?;
sub_ping.rx.recv_timeout(RX_TIMEOUT)?;
Ok(())
}
}
+110
View File
@@ -0,0 +1,110 @@
use super::{
media_packet::{MediaDataKind, MediaDataSubscriber},
BcCamera, Result,
};
use crate::{
bc::{model::*, xml::*},
Never,
};
/// The stream from the camera will be using one of these formats
#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
pub enum StreamFormat {
/// H264 (AVC) video format
H264,
/// H265 (HEVC) video format
H265,
/// AAC audio
AAC,
/// ADPCM in DVI-4 format
ADPCM,
}
/// Convience type for the error raised by the StreamOutput trait
pub type StreamOutputError = Result<()>;
/// The method `start_stream` requires a structure with this trait to pass the
/// audio and video data back to
pub trait StreamOutput {
/// This is the callback raised when audio data is received
fn write_audio(&mut self, data: &[u8], format: StreamFormat) -> StreamOutputError;
/// This is the callback raised when video data is received
fn write_video(&mut self, data: &[u8], format: StreamFormat) -> StreamOutputError;
}
impl BcCamera {
///
/// Starts the video stream
///
/// # Parameters
///
/// * `data_outs` - This should be a struct that implements the `StreamOutput` trait
///
/// * `stream_name` - The name of the stream either `"mainStream"` for HD or `"subStream"` for SD
///
/// # Returns
///
/// This will block forever or return an error when the camera connection is dropped
///
pub fn start_video<Outputs>(&self, data_outs: &mut Outputs, stream_name: &str) -> Result<Never>
where
Outputs: StreamOutput,
{
let connection = self
.connection
.as_ref()
.expect("Must be connected to start video");
let sub_video = connection.subscribe(MSG_ID_VIDEO)?;
let stream_num = match stream_name {
"mainStream" => 0,
"subStream" => 1,
_ => 0,
};
let start_video = Bc::new_from_xml(
BcMeta {
msg_id: MSG_ID_VIDEO,
channel_id: self.channel_id,
msg_num: self.new_message_num(),
stream_type: stream_num,
response_code: 0,
class: 0x6414, // IDK why
},
BcXml {
preview: Some(Preview {
version: xml_ver(),
channel_id: self.channel_id,
handle: 0,
stream_type: stream_name.to_string(),
}),
..Default::default()
},
);
sub_video.send(start_video)?;
let mut media_sub = MediaDataSubscriber::from_bc_sub(&sub_video);
loop {
let binary_data = media_sub.next_media_packet()?;
// We now have a complete interesting packet. Send it to gst.
// Process the packet
match (binary_data.kind(), binary_data.media_format()) {
(
MediaDataKind::VideoDataIframe | MediaDataKind::VideoDataPframe,
Some(media_format),
) => {
data_outs.write_video(binary_data.body(), media_format)?;
}
(MediaDataKind::AudioDataAac, Some(media_format)) => {
data_outs.write_audio(binary_data.body(), media_format)?;
}
(MediaDataKind::AudioDataAdpcm, Some(media_format)) => {
data_outs.write_audio(binary_data.body(), media_format)?;
}
_ => {}
};
}
}
}
+52
View File
@@ -0,0 +1,52 @@
use super::{BcCamera, Error, Result, RX_TIMEOUT};
use crate::bc::{model::*, xml::*};
impl BcCamera {
/// Request the VersionInfo xml
pub fn version(&self) -> Result<VersionInfo> {
let connection = self
.connection
.as_ref()
.expect("Must be connected to get version info");
let sub_version = connection.subscribe(MSG_ID_VERSION)?;
let version = Bc {
meta: BcMeta {
msg_id: MSG_ID_VERSION,
channel_id: self.channel_id,
msg_num: self.new_message_num(),
stream_type: 0,
response_code: 0,
class: 0x6414, // IDK why
},
body: BcBody::ModernMsg(ModernMsg {
..Default::default()
}),
};
sub_version.send(version)?;
let modern_reply = sub_version.rx.recv_timeout(RX_TIMEOUT)?;
let version_info;
match modern_reply.body {
BcBody::ModernMsg(ModernMsg {
payload:
Some(BcPayloads::BcXml(BcXml {
version_info: Some(info),
..
})),
..
}) => {
version_info = info;
}
_ => {
return Err(Error::UnintelligibleReply {
reply: modern_reply,
why: "Expected a VersionInfo message",
})
}
}
Ok(version_info)
}
}