Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e08bb66891 | ||
|
|
173c994530 | ||
|
|
95ce97c85e | ||
|
|
9087169873 | ||
|
|
d08a5fe4aa | ||
|
|
6a4468c8f6 | ||
|
|
d084a13eb0 | ||
|
|
1cde5ec3e5 | ||
|
|
97703bdb38 | ||
|
|
d0c85419eb | ||
|
|
a8a306301b | ||
|
|
f23f28c12e | ||
|
|
623fcb3fd1 | ||
|
|
e093151db6 |
No files matched your search
@@ -62,4 +62,4 @@ jobs:
|
||||
uses: nebularg/actions-luacheck@v1
|
||||
with:
|
||||
files: 'dissector/baichuan.lua'
|
||||
args: --globals Dissector Proto ProtoField base ByteArray DESEGMENT_ONE_MORE_SEGMENT DissectorTable
|
||||
args: --globals Dissector Proto ProtoField base ByteArray DESEGMENT_ONE_MORE_SEGMENT DissectorTable Pref
|
||||
Generated
+2
-2
@@ -1425,7 +1425,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "neolink"
|
||||
version = "0.5.17"
|
||||
version = "0.5.18"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.21.2",
|
||||
@@ -1460,7 +1460,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "neolink_core"
|
||||
version = "0.5.17"
|
||||
version = "0.5.18"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"assert_matches",
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "neolink"
|
||||
description = "A standards-compliant bridge to Reolink IP cameras"
|
||||
version = "0.5.17"
|
||||
version = "0.5.18"
|
||||
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0-or-later"
|
||||
@@ -29,7 +29,7 @@ is_sorted = "0.1.1"
|
||||
itertools = "0.11.0"
|
||||
lazy_static = "1.4.0"
|
||||
log = { version = "0.4.17", features = [ "release_max_level_debug" ] }
|
||||
neolink_core = { path = "crates/core", version = "0.5.17" }
|
||||
neolink_core = { path = "crates/core", version = "0.5.18" }
|
||||
regex = "1.7.3"
|
||||
rumqttc = "0.22.0"
|
||||
serde = { version = "1.0.160", features = ["derive"] }
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "neolink_core"
|
||||
description = "Core services and structure for Reolink IP cameras"
|
||||
version = "0.5.17"
|
||||
version = "0.5.18"
|
||||
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0-or-later"
|
||||
|
||||
@@ -15,6 +15,12 @@ pub(crate) struct BcCodex {
|
||||
}
|
||||
|
||||
impl BcCodex {
|
||||
pub(crate) fn new_with_debug(credentials: Credentials) -> Self {
|
||||
let mut context = BcContext::new(credentials);
|
||||
|
||||
context.debug_on();
|
||||
Self { context }
|
||||
}
|
||||
pub(crate) fn new(credentials: Credentials) -> Self {
|
||||
Self {
|
||||
context: BcContext::new(credentials),
|
||||
|
||||
+16
-10
@@ -116,10 +116,12 @@ fn bc_modern_msg<'a>(
|
||||
let mut encrypted_len = None;
|
||||
// Now we'll take the buffer that Nom gave a ref to and parse it.
|
||||
let extension = if ext_len > 0 {
|
||||
log::trace!(
|
||||
"Extension Txt: {:?}",
|
||||
String::from_utf8(processed_ext_buf.to_vec()).unwrap_or("Not Text".to_string())
|
||||
);
|
||||
if context.debug {
|
||||
println!(
|
||||
"Extension Txt: {:?}",
|
||||
String::from_utf8(processed_ext_buf.to_vec()).unwrap_or("Not Text".to_string())
|
||||
);
|
||||
}
|
||||
// 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 = Extension::try_parse(processed_ext_buf).map_err(|_| {
|
||||
@@ -182,8 +184,9 @@ fn bc_modern_msg<'a>(
|
||||
if context.in_bin_mode.contains(&(header.msg_num)) || in_binary {
|
||||
payload = match (context.get_encrypted(), encrypted_len) {
|
||||
(EncryptionProtocol::FullAes(_), Some(encrypted_len)) => {
|
||||
log::trace!("Binary: {:X?}", &processed_payload_buf[0..30]);
|
||||
|
||||
// if if context.debug {
|
||||
// log::trace!("Binary: {:X?}", &processed_payload_buf[0..30]);
|
||||
// }
|
||||
Some(BcPayloads::Binary(
|
||||
processed_payload_buf[0..(encrypted_len as usize)].to_vec(),
|
||||
))
|
||||
@@ -191,10 +194,13 @@ fn bc_modern_msg<'a>(
|
||||
_ => Some(BcPayloads::Binary(payload_buf.to_vec())),
|
||||
};
|
||||
} else {
|
||||
log::trace!(
|
||||
"Payload Txt: {:?}",
|
||||
String::from_utf8(processed_payload_buf.to_vec()).unwrap_or("Not Text".to_string())
|
||||
);
|
||||
if context.debug {
|
||||
println!(
|
||||
"Payload Txt: {:?}",
|
||||
String::from_utf8(processed_payload_buf.to_vec())
|
||||
.unwrap_or("Not Text".to_string())
|
||||
);
|
||||
}
|
||||
let xml = BcXml::try_parse(processed_payload_buf.as_slice()).map_err(|_| {
|
||||
error!("header.msg_id: {}", header.msg_id);
|
||||
error!(
|
||||
|
||||
@@ -210,6 +210,7 @@ pub(crate) struct BcContext {
|
||||
pub(crate) credentials: Credentials,
|
||||
pub(crate) in_bin_mode: HashSet<u16>,
|
||||
pub(crate) encryption_protocol: EncryptionProtocol,
|
||||
pub(crate) debug: bool,
|
||||
}
|
||||
|
||||
impl Bc {
|
||||
@@ -251,6 +252,7 @@ impl BcContext {
|
||||
credentials,
|
||||
in_bin_mode: HashSet::new(),
|
||||
encryption_protocol: EncryptionProtocol::Unencrypted,
|
||||
debug: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -260,6 +262,7 @@ impl BcContext {
|
||||
credentials: Default::default(),
|
||||
in_bin_mode: HashSet::new(),
|
||||
encryption_protocol,
|
||||
debug: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -279,6 +282,10 @@ impl BcContext {
|
||||
pub(crate) fn binary_off(&mut self, msg_id: u16) {
|
||||
self.in_bin_mode.remove(&msg_id);
|
||||
}
|
||||
|
||||
pub(crate) fn debug_on(&mut self) {
|
||||
self.debug = true;
|
||||
}
|
||||
}
|
||||
|
||||
impl BcHeader {
|
||||
|
||||
@@ -87,6 +87,8 @@ pub struct BcCameraOpt {
|
||||
pub discovery: DiscoveryMethods,
|
||||
/// Credentials for login
|
||||
pub credentials: Credentials,
|
||||
/// Toggle debug print of underlying data
|
||||
pub debug: bool,
|
||||
}
|
||||
|
||||
/// Used to choose the print format of various status messages like battery levels
|
||||
@@ -314,16 +316,20 @@ impl BcCamera {
|
||||
let (sink, source): (BcConnSink, BcConnSource) = {
|
||||
match BcCamera::find_camera(options).await? {
|
||||
CameraLocation::Tcp(addr) => {
|
||||
let (x, r) = TcpSource::new(addr, &username, passwd.as_ref())
|
||||
let (x, r) = TcpSource::new(addr, &username, passwd.as_ref(), options.debug)
|
||||
.await?
|
||||
.split();
|
||||
(Box::new(x), Box::new(r))
|
||||
}
|
||||
CameraLocation::Udp(discovery) => {
|
||||
let (x, r) =
|
||||
UdpSource::new_from_discovery(discovery, &username, passwd.as_ref())
|
||||
.await?
|
||||
.split();
|
||||
let (x, r) = UdpSource::new_from_discovery(
|
||||
discovery,
|
||||
&username,
|
||||
passwd.as_ref(),
|
||||
options.debug,
|
||||
)
|
||||
.await?
|
||||
.split();
|
||||
(Box::new(x), Box::new(r))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,9 @@ type MsgHandler = dyn 'static + Send + Sync + for<'a> Fn(&'a Bc) -> BoxFuture<'a
|
||||
#[derive(Default)]
|
||||
struct Subscriber {
|
||||
/// Subscribers based on their ID and their num
|
||||
/// First filtered by ID then number
|
||||
/// If num is None it will be upgraded to a Some based on the number the
|
||||
/// camera assigns
|
||||
num: BTreeMap<u32, BTreeMap<Option<u16>, Sender<Result<Bc>>>>,
|
||||
/// Subscribers based on their ID
|
||||
id: BTreeMap<u32, Arc<MsgHandler>>,
|
||||
@@ -55,10 +58,12 @@ impl BcConnection {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.build()
|
||||
.unwrap();
|
||||
runtime.block_on(
|
||||
let result = runtime.block_on(
|
||||
PollSender::new(thread_poll_commander)
|
||||
.send_all(&mut source.map(|bc| Ok(PollCommand::Bc(Box::new(bc))))),
|
||||
)
|
||||
);
|
||||
log::info!("PollSender Bc {:?}", result);
|
||||
result
|
||||
});
|
||||
rx_thread.spawn(async move {
|
||||
handle.await??;
|
||||
@@ -166,6 +171,18 @@ enum PollCommand {
|
||||
Disconnect,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for PollCommand {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
PollCommand::Bc(_) => f.write_str("PollCommand::Bc"),
|
||||
PollCommand::AddHandler(_, _) => f.write_str("PollCommand::AddHandler"),
|
||||
PollCommand::RemoveHandler(_) => f.write_str("PollCommand::RemoveHandler"),
|
||||
PollCommand::AddSubscriber(_, _, _) => f.write_str("PollCommand::AddSubscriber"),
|
||||
PollCommand::Disconnect => f.write_str("PollCommand::Disconnect"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Poller {
|
||||
subscribers: Subscriber,
|
||||
sink: Sender<Result<Bc>>,
|
||||
@@ -176,16 +193,35 @@ impl Poller {
|
||||
async fn run(&mut self) -> Result<()> {
|
||||
while let Some(command) = self.reciever.next().await {
|
||||
yield_now().await;
|
||||
// Clean Up subscribers
|
||||
self.subscribers
|
||||
.num
|
||||
.iter_mut()
|
||||
.for_each(|(_, channels)| channels.retain(|_, channel| !channel.is_closed()));
|
||||
self.subscribers
|
||||
.num
|
||||
.retain(|_, channels| !channels.is_empty());
|
||||
// Handle the command
|
||||
match command {
|
||||
PollCommand::Bc(boxed_response) => {
|
||||
match *boxed_response {
|
||||
Ok(response) => {
|
||||
let msg_num = response.meta.msg_num;
|
||||
let msg_id = response.meta.msg_id;
|
||||
|
||||
let msg_num = response.meta.msg_num;
|
||||
log::trace!(
|
||||
"Looking for ID: {} with num: {}, in {:?} and {:?}",
|
||||
msg_id,
|
||||
msg_num,
|
||||
self.subscribers.id.keys().to_owned(),
|
||||
self.subscribers
|
||||
.num
|
||||
.iter()
|
||||
.map(|(k, v)| (k, v.keys()))
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
match (
|
||||
self.subscribers.id.get(&msg_id),
|
||||
self.subscribers.num.get_mut(&msg_id),
|
||||
self.subscribers.num.get_mut(&msg_id), // Both filter first on ID
|
||||
) {
|
||||
(Some(occ), _) => {
|
||||
if let Some(reply) = occ(&response).await {
|
||||
|
||||
@@ -1030,8 +1030,11 @@ impl Discovery {
|
||||
pub(crate) async fn check_tcp(&self, addr: SocketAddr, channel_id: u8) -> Result<()> {
|
||||
let username = "admin";
|
||||
let password = Some("123456");
|
||||
let mut tcp_source =
|
||||
timeout(*MAXIMUM_WAIT, TcpSource::new(addr, username, password)).await??;
|
||||
let mut tcp_source = timeout(
|
||||
*MAXIMUM_WAIT,
|
||||
TcpSource::new(addr, username, password, false),
|
||||
)
|
||||
.await??;
|
||||
|
||||
let md5_username = md5_string(username, Md5Trunc::ZeroLast);
|
||||
let md5_password = password
|
||||
|
||||
@@ -18,11 +18,17 @@ impl TcpSource {
|
||||
addr: SocketAddr,
|
||||
username: T,
|
||||
password: Option<U>,
|
||||
debug: bool,
|
||||
) -> Result<TcpSource> {
|
||||
let stream = connect_to(addr).await?;
|
||||
|
||||
let codex = if debug {
|
||||
BcCodex::new_with_debug(Credentials::new(username, password))
|
||||
} else {
|
||||
BcCodex::new(Credentials::new(username, password))
|
||||
};
|
||||
Ok(Self {
|
||||
inner: Framed::new(stream, BcCodex::new(Credentials::new(username, password))),
|
||||
inner: Framed::new(stream, codex),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,20 +9,21 @@ use futures::{
|
||||
sink::{Sink, SinkExt},
|
||||
stream::{IntoAsyncRead, Stream, StreamExt, TryStreamExt},
|
||||
};
|
||||
use log::*;
|
||||
use rand::{seq::SliceRandom, thread_rng};
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::VecDeque;
|
||||
use std::io::{Error as IoError, ErrorKind, Result as IoResult};
|
||||
use std::net::SocketAddr;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::task::{Context, Poll};
|
||||
use tokio::sync::mpsc::channel;
|
||||
use tokio::{
|
||||
net::UdpSocket,
|
||||
time::{interval, Duration, Instant, Interval},
|
||||
time::{interval, sleep, Duration, Instant, Interval, Sleep},
|
||||
};
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt};
|
||||
use tokio_util::sync::PollSender;
|
||||
use tokio_util::{
|
||||
codec::{Decoder, Encoder, Framed},
|
||||
udp::UdpFramed,
|
||||
@@ -43,15 +44,20 @@ impl UdpSource {
|
||||
camera_id: i32,
|
||||
username: T,
|
||||
password: Option<U>,
|
||||
debug: bool,
|
||||
) -> Result<Self> {
|
||||
let stream = Arc::new(connect().await?);
|
||||
|
||||
Self::new_from_socket(stream, addr, client_id, camera_id, username, password).await
|
||||
Self::new_from_socket(
|
||||
stream, addr, client_id, camera_id, username, password, debug,
|
||||
)
|
||||
.await
|
||||
}
|
||||
pub(crate) async fn new_from_discovery<T: Into<String>, U: Into<String>>(
|
||||
discovery: DiscoveryResult,
|
||||
username: T,
|
||||
password: Option<U>,
|
||||
debug: bool,
|
||||
) -> Result<Self> {
|
||||
// Ensure that the discovery keep alive are all stopped here
|
||||
// We now handle all coms in UdpSource
|
||||
@@ -62,6 +68,7 @@ impl UdpSource {
|
||||
discovery.camera_id,
|
||||
username,
|
||||
password,
|
||||
debug,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -73,14 +80,17 @@ impl UdpSource {
|
||||
camera_id: i32,
|
||||
username: T,
|
||||
password: Option<U>,
|
||||
debug: bool,
|
||||
) -> Result<Self> {
|
||||
let bcudp_source = BcUdpSource::new_from_socket(stream, addr).await?;
|
||||
let payload_source = bcudp_source.into_payload_source(client_id, camera_id);
|
||||
let payload_source = bcudp_source.into_payload_source(client_id, camera_id).await;
|
||||
let async_read = payload_source.into_async_read().compat();
|
||||
let framed = Framed::new(
|
||||
async_read,
|
||||
BcCodex::new(Credentials::new(username, password)),
|
||||
);
|
||||
let codex = if debug {
|
||||
BcCodex::new_with_debug(Credentials::new(username, password))
|
||||
} else {
|
||||
BcCodex::new(Credentials::new(username, password))
|
||||
};
|
||||
let framed = Framed::new(async_read, codex);
|
||||
|
||||
Ok(Self { inner: framed })
|
||||
}
|
||||
@@ -151,21 +161,12 @@ impl BcUdpSource {
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn into_payload_source(self, client_id: i32, camera_id: i32) -> UdpPayloadSource {
|
||||
UdpPayloadSource {
|
||||
inner: self,
|
||||
client_id,
|
||||
camera_id,
|
||||
packets_sent: 0,
|
||||
packets_want: 0,
|
||||
sent: Default::default(),
|
||||
recieved: Default::default(),
|
||||
state: State::Normal,
|
||||
send_buffer: Default::default(),
|
||||
ack_interval: interval(Duration::from_millis(10)), // Offical Client does ack every 10ms
|
||||
resend_interval: interval(Duration::from_millis(500)), // Offical Client does resend every 500ms
|
||||
ack_latency: Default::default(),
|
||||
}
|
||||
pub(crate) async fn into_payload_source(
|
||||
self,
|
||||
client_id: i32,
|
||||
camera_id: i32,
|
||||
) -> UdpPayloadSource {
|
||||
UdpPayloadSource::new(self, client_id, camera_id).await
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,6 +200,7 @@ impl Sink<(BcUdp, SocketAddr)> for BcUdpSource {
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug)]
|
||||
enum State {
|
||||
Normal, // Normal recieve
|
||||
Flushing, // Used to send ack packets and things in the buffer
|
||||
@@ -258,15 +260,20 @@ impl AckLatency {
|
||||
}
|
||||
|
||||
pub(crate) struct UdpPayloadSource {
|
||||
inner_stream: ReceiverStream<IoResult<Vec<u8>>>,
|
||||
inner_sink: PollSender<Vec<u8>>,
|
||||
}
|
||||
|
||||
struct UdpPayloadInner {
|
||||
inner: BcUdpSource,
|
||||
thread_stream: PollSender<IoResult<Vec<u8>>>,
|
||||
thread_sink: ReceiverStream<Vec<u8>>,
|
||||
client_id: i32,
|
||||
camera_id: i32,
|
||||
packets_sent: u32,
|
||||
packets_want: u32,
|
||||
sent: BTreeMap<u32, UdpData>,
|
||||
recieved: BTreeMap<u32, Vec<u8>>,
|
||||
state: State,
|
||||
send_buffer: VecDeque<BcUdp>,
|
||||
/// Offical Client does ack every 10ms if we don't also do this the camera
|
||||
/// seems to think we have a poor connection and will abort
|
||||
/// This `ack_interval` controls how ofen we do this
|
||||
@@ -275,9 +282,104 @@ pub(crate) struct UdpPayloadSource {
|
||||
/// This `resend_interval` controls how ofen we do this
|
||||
resend_interval: Interval,
|
||||
ack_latency: AckLatency,
|
||||
// Tracks the timeout of recieving ANY packet
|
||||
recv_timeout: Pin<Box<Sleep>>,
|
||||
}
|
||||
impl UdpPayloadInner {
|
||||
fn new(
|
||||
inner: BcUdpSource,
|
||||
thread_stream: PollSender<IoResult<Vec<u8>>>,
|
||||
thread_sink: ReceiverStream<Vec<u8>>,
|
||||
client_id: i32,
|
||||
camera_id: i32,
|
||||
) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
thread_stream,
|
||||
thread_sink,
|
||||
client_id,
|
||||
camera_id,
|
||||
packets_sent: 0,
|
||||
packets_want: 0,
|
||||
sent: Default::default(),
|
||||
recieved: Default::default(),
|
||||
ack_interval: interval(Duration::from_millis(10)), // Offical Client does ack every 10ms
|
||||
resend_interval: interval(Duration::from_millis(500)), // Offical Client does resend every 500ms
|
||||
ack_latency: Default::default(),
|
||||
// A packet of ANY kind must be recieved in the last second
|
||||
// since there are 10 acks a second 3s should be fine
|
||||
recv_timeout: Box::pin(sleep(Duration::from_secs(3))),
|
||||
}
|
||||
}
|
||||
async fn run(&mut self) -> Result<()> {
|
||||
let camera_addr = self.inner.addr;
|
||||
tokio::select! {
|
||||
_ = self.ack_interval.tick() => {
|
||||
let ack = BcUdp::Ack(self.build_send_ack());
|
||||
self.inner.feed((ack, camera_addr)).await?;
|
||||
Result::Ok(())
|
||||
},
|
||||
_ = self.resend_interval.tick() => {
|
||||
for (_, resend) in self.sent.iter() {
|
||||
self.inner.feed((BcUdp::Data(resend.clone()), camera_addr)).await?;
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
v = self.thread_sink.next() => {
|
||||
// Incomming from application
|
||||
// Outgoing on socket
|
||||
let item = v.ok_or(Error::DroppedConnection)?;
|
||||
|
||||
for chunk in item.chunks(MTU - UDPDATA_HEADER_SIZE) {
|
||||
let udp_data = UdpData {
|
||||
connection_id: self.camera_id,
|
||||
packet_id: self.packets_sent,
|
||||
payload: chunk.to_vec(),
|
||||
};
|
||||
self.packets_sent += 1;
|
||||
self.sent.insert(udp_data.packet_id, udp_data.clone());
|
||||
self.inner.feed((BcUdp::Data(udp_data), camera_addr)).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
v = self.inner.next() => {
|
||||
// Incomming from socket
|
||||
// Outgoing to application
|
||||
let (item, addr) = v.ok_or(Error::DroppedConnection)??;
|
||||
if addr == camera_addr {
|
||||
match item {
|
||||
BcUdp::Discovery(_disc) => {},
|
||||
BcUdp::Ack(ack) => {
|
||||
if ack.connection_id == self.client_id {
|
||||
self.handle_ack(ack);
|
||||
}
|
||||
},
|
||||
BcUdp::Data(data) => {
|
||||
if data.connection_id == self.client_id {
|
||||
let packet_id = data.packet_id;
|
||||
if packet_id >= self.packets_want {
|
||||
// error!("packets_want: {}", this.packets_want);
|
||||
self.recieved.insert(packet_id, data.payload);
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
self.recv_timeout.as_mut().reset(Instant::now() + Duration::from_secs(3));
|
||||
Ok(())
|
||||
},
|
||||
_ = self.recv_timeout.as_mut() => {
|
||||
Err(Error::DroppedConnection)
|
||||
}
|
||||
}?;
|
||||
while let Some(payload) = self.recieved.remove(&self.packets_want) {
|
||||
self.packets_want += 1;
|
||||
self.thread_stream.send(Ok(payload)).await?;
|
||||
}
|
||||
self.inner.flush().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl UdpPayloadSource {
|
||||
fn build_send_ack(&self) -> UdpAck {
|
||||
if self.packets_want > 0 {
|
||||
let mut first_missing: u32 = self.packets_want;
|
||||
@@ -329,20 +431,39 @@ impl UdpPayloadSource {
|
||||
}
|
||||
self.ack_latency.feed_ack();
|
||||
}
|
||||
}
|
||||
impl UdpPayloadSource {
|
||||
async fn new(inner: BcUdpSource, client_id: i32, camera_id: i32) -> Self {
|
||||
let (inner_sink, thread_sink) = channel(100);
|
||||
let (thread_stream, inner_stream) = channel(100);
|
||||
|
||||
fn maintanence(&mut self, cx: &mut Context<'_>) {
|
||||
// Check for periodic resends
|
||||
if self.resend_interval.poll_tick(cx).is_ready() {
|
||||
for (_, resend) in self.sent.iter() {
|
||||
self.send_buffer.push_back(BcUdp::Data(resend.clone()));
|
||||
let mut payload_inner = UdpPayloadInner::new(
|
||||
inner,
|
||||
PollSender::new(thread_stream),
|
||||
ReceiverStream::new(thread_sink),
|
||||
client_id,
|
||||
camera_id,
|
||||
);
|
||||
tokio::task::spawn(async move {
|
||||
loop {
|
||||
match payload_inner.run().await {
|
||||
Ok(()) => {}
|
||||
Err(e) => {
|
||||
// log::error!("payload_inner: {:?}", e);
|
||||
// Pass error up
|
||||
let _ = payload_inner
|
||||
.thread_stream
|
||||
.send(Err(IoError::new(ErrorKind::Other, e.clone())))
|
||||
.await;
|
||||
return Result::<()>::Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.ack_interval.poll_tick(cx).is_ready()
|
||||
// && self.packets_want > 0
|
||||
{
|
||||
let ack = BcUdp::Ack(self.build_send_ack());
|
||||
self.send_buffer.push_back(ack);
|
||||
self.state = State::Flushing;
|
||||
});
|
||||
|
||||
UdpPayloadSource {
|
||||
inner_stream: ReceiverStream::new(inner_stream),
|
||||
inner_sink: PollSender::new(inner_sink),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -350,105 +471,16 @@ impl UdpPayloadSource {
|
||||
impl Stream for UdpPayloadSource {
|
||||
type Item = IoResult<Vec<u8>>;
|
||||
|
||||
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
let camera_addr = self.inner.addr;
|
||||
let this = self.get_mut();
|
||||
match this.state {
|
||||
State::Normal => {
|
||||
// this.state = State::YieldNow;
|
||||
// Handle resend events
|
||||
this.maintanence(cx);
|
||||
// Data ready to go
|
||||
if let Some(payload) = this.recieved.remove(&this.packets_want) {
|
||||
this.packets_want += 1;
|
||||
// error!("packets_want: {}", this.packets_want);
|
||||
return Poll::Ready(Some(Ok(payload)));
|
||||
}
|
||||
// Normal behaviors
|
||||
match this.inner.poll_next_unpin(cx) {
|
||||
Poll::Ready(Some(Ok((
|
||||
BcUdp::Data(UdpData {
|
||||
connection_id,
|
||||
packet_id,
|
||||
payload,
|
||||
}),
|
||||
addr,
|
||||
)))) if connection_id == this.client_id
|
||||
&& addr == camera_addr
|
||||
&& packet_id >= this.packets_want =>
|
||||
{
|
||||
if packet_id == this.packets_want {
|
||||
this.packets_want += 1;
|
||||
// error!("packets_want: {}", this.packets_want);
|
||||
let ack = BcUdp::Ack(this.build_send_ack());
|
||||
this.send_buffer.push_back(ack);
|
||||
return Poll::Ready(Some(Ok(payload)));
|
||||
} else {
|
||||
this.recieved.insert(packet_id, payload);
|
||||
}
|
||||
}
|
||||
Poll::Ready(Some(Ok((
|
||||
BcUdp::Data(UdpData {
|
||||
connection_id,
|
||||
packet_id,
|
||||
..
|
||||
}),
|
||||
addr,
|
||||
)))) if connection_id == this.client_id
|
||||
&& addr == camera_addr
|
||||
&& packet_id < this.packets_want =>
|
||||
{
|
||||
trace!("UdpPayloadSource.RecievedPacket: Old data: {}", packet_id);
|
||||
}
|
||||
Poll::Ready(Some(Ok((
|
||||
BcUdp::Ack(ack @ UdpAck { connection_id, .. }),
|
||||
addr,
|
||||
)))) if connection_id == this.client_id && addr == camera_addr => {
|
||||
this.handle_ack(ack);
|
||||
// Rather then immediatly flush wait for the next call
|
||||
// this.state = State::Flushing;
|
||||
}
|
||||
Poll::Ready(Some(Err(e))) => {
|
||||
return Poll::Ready(Some(Err(IoError::new(ErrorKind::Other, e))));
|
||||
}
|
||||
Poll::Ready(None) => {
|
||||
return Poll::Ready(None);
|
||||
}
|
||||
Poll::Pending => {
|
||||
return Poll::Pending;
|
||||
}
|
||||
Poll::Ready(Some(Ok((bcudp, addr)))) => {
|
||||
trace!(
|
||||
"UdpPayloadSource.RecievedPacker: UnexpectedData {:?} from {}",
|
||||
bcudp,
|
||||
addr
|
||||
);
|
||||
} // _ => {
|
||||
// trace!("UDPSource.RecievedPacker: Other?");
|
||||
// // Repeat/unintersting packet
|
||||
// }
|
||||
}
|
||||
}
|
||||
State::Flushing => match this.poll_flush_unpin(cx) {
|
||||
Poll::Ready(Ok(())) => {
|
||||
this.state = State::Normal;
|
||||
}
|
||||
Poll::Ready(Err(e)) => {
|
||||
return Poll::Ready(Some(Err(e)));
|
||||
}
|
||||
Poll::Pending => {
|
||||
return Poll::Pending;
|
||||
}
|
||||
},
|
||||
State::Closed => {
|
||||
return Poll::Ready(Some(Err(IoError::from(ErrorKind::ConnectionAborted))));
|
||||
}
|
||||
State::YieldNow => {
|
||||
this.state = State::Normal;
|
||||
}
|
||||
delegate! {
|
||||
to Pin::new(&mut self.inner_stream) {
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>;
|
||||
}
|
||||
}
|
||||
|
||||
delegate! {
|
||||
to self.inner_stream {
|
||||
fn size_hint(&self) -> (usize, Option<usize>);
|
||||
}
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
@@ -459,104 +491,35 @@ impl Sink<Vec<u8>> for UdpPayloadSource {
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<std::result::Result<(), Self::Error>> {
|
||||
let this = self.get_mut();
|
||||
match this.state {
|
||||
State::Normal | State::YieldNow => this
|
||||
.inner
|
||||
.poll_ready_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e)),
|
||||
State::Flushing => this
|
||||
.inner
|
||||
.poll_flush_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e)),
|
||||
State::Closed => Poll::Ready(Err(IoError::from(ErrorKind::ConnectionAborted))),
|
||||
}
|
||||
self.get_mut()
|
||||
.inner_sink
|
||||
.poll_ready_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
}
|
||||
fn start_send(self: Pin<&mut Self>, item: Vec<u8>) -> std::result::Result<(), Self::Error> {
|
||||
let this = self.get_mut();
|
||||
for chunk in item.chunks(MTU - UDPDATA_HEADER_SIZE) {
|
||||
let udp_data = UdpData {
|
||||
connection_id: this.camera_id,
|
||||
packet_id: this.packets_sent,
|
||||
payload: chunk.to_vec(),
|
||||
};
|
||||
this.packets_sent += 1;
|
||||
this.send_buffer.push_back(BcUdp::Data(udp_data));
|
||||
}
|
||||
if let Some(first) = this.send_buffer.pop_front() {
|
||||
if let BcUdp::Data(data) = &first {
|
||||
let id = data.packet_id;
|
||||
this.sent.insert(id, data.clone());
|
||||
}
|
||||
let addr = this.inner.addr;
|
||||
Pin::new(&mut this.inner)
|
||||
.start_send((first, addr))
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))?;
|
||||
}
|
||||
Ok(())
|
||||
self.get_mut()
|
||||
.inner_sink
|
||||
.start_send_unpin(item)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
}
|
||||
fn poll_flush(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<std::result::Result<(), Self::Error>> {
|
||||
let this = self.get_mut();
|
||||
match this
|
||||
.inner
|
||||
self.get_mut()
|
||||
.inner_sink
|
||||
.poll_flush_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
{
|
||||
Poll::Ready(Ok(())) => {
|
||||
if let Some(next) = this.send_buffer.pop_front() {
|
||||
match this
|
||||
.inner
|
||||
.poll_ready_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
{
|
||||
Poll::Ready(Ok(())) => {
|
||||
if let BcUdp::Data(data) = &next {
|
||||
let id = data.packet_id;
|
||||
this.sent.insert(id, data.clone());
|
||||
}
|
||||
|
||||
let addr = this.inner.addr;
|
||||
Pin::new(&mut this.inner)
|
||||
.start_send((next, addr))
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))?;
|
||||
}
|
||||
poll => {
|
||||
return poll;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
}
|
||||
poll => {
|
||||
return poll;
|
||||
}
|
||||
}
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
}
|
||||
|
||||
fn poll_close(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<std::result::Result<(), Self::Error>> {
|
||||
let this = self.get_mut();
|
||||
if let State::Closed = this.state {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
|
||||
match this.poll_flush_unpin(cx) {
|
||||
Poll::Ready(Ok(())) => {
|
||||
this.state = State::Closed;
|
||||
this.inner
|
||||
.poll_close_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
}
|
||||
poll => poll,
|
||||
}
|
||||
self.get_mut()
|
||||
.inner_sink
|
||||
.poll_close_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ impl BcCamera {
|
||||
|
||||
sub_ping.recv().await?;
|
||||
|
||||
log::trace!("Ping complete");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,7 @@ impl BcCamera {
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
drop(sub_get); // Ensure that we are NOT listening on that msgnum as the reply can come on ANY msgnum
|
||||
log::trace!("Got snap XML {} with size {}", filename, expected_size);
|
||||
// Messages are now sent on ID 109 but not with the same message ID
|
||||
// preumably because the camera considers it to be a new message rather
|
||||
|
||||
+61
-10
@@ -147,11 +147,14 @@ local message_types = {
|
||||
[106]="<Dst>",
|
||||
[107]="<Dst> (write)",
|
||||
[108]="<ConfigFileInfo> (log)",
|
||||
[109]="<Snap>",
|
||||
[114]="<Uid>",
|
||||
[115]="<WifiSignal>",
|
||||
[116]="<Wifi>",
|
||||
[120]="<OnlineUserList>",
|
||||
[122]="<PerformanceInfo>",
|
||||
[123]="<ReplaySeek>",
|
||||
[124]="<PushInfo>",
|
||||
[132]="<VideoInput>", -- <InputAdvanceCfg>
|
||||
[133]="<RfAlarm>",
|
||||
[141]="<Email> (test)",
|
||||
@@ -161,6 +164,7 @@ local message_types = {
|
||||
[151]="<AbilityInfo>",
|
||||
[190]="PTZ Preset",
|
||||
[194]="<Ftp> (test)",
|
||||
[195]="<AutoUpdate>",
|
||||
[199]="<Support>",
|
||||
[208]="<LedState>",
|
||||
[209]="<LedState> (write)",
|
||||
@@ -175,9 +179,13 @@ local message_types = {
|
||||
[228]="<Crop>",
|
||||
[229]="<Crop> (write)",
|
||||
[230]="<cropSnap>",
|
||||
[232]="<AudioTask>",
|
||||
[234]="UDP Keep Alive",
|
||||
[252]="<BatteryInfoList>",
|
||||
[253]="<BatteryInfo>",
|
||||
[268]="<CloudBindInfo>",
|
||||
[282]="<CloudLoginKey>",
|
||||
[287]="<TimeCfg>",
|
||||
[272]="<findAlarmVideo>",
|
||||
[273]="<alarmVideoInfo>",
|
||||
[274]="<findAlarmVideo>",
|
||||
@@ -189,6 +197,7 @@ local message_classes = {
|
||||
[0x6514]="legacy",
|
||||
[0x6614]="modern",
|
||||
[0x6414]="modern",
|
||||
[0x6482]="modern (file download)",
|
||||
[0x0000]="modern",
|
||||
}
|
||||
|
||||
@@ -196,9 +205,37 @@ local header_lengths = {
|
||||
[0x6514]=20,
|
||||
[0x6614]=20,
|
||||
[0x6414]=24,
|
||||
[0x6482]=24,
|
||||
[0x0000]=24,
|
||||
}
|
||||
|
||||
-----
|
||||
-- Decryption routine.
|
||||
-----
|
||||
-- For other locations, use: LUA_CPATH=.../luagcrypt/?.so
|
||||
bc_protocol.prefs.key = Pref.string("Decryption key", "",
|
||||
"Passphrase used for the camera. Required to decrypt the AES packets")
|
||||
bc_protocol.prefs.nonce = Pref.string("Nonce key", "",
|
||||
"Nonce negotiate during login. You can find this in the msg_id == 1 packets.")
|
||||
local function hexencode(str)
|
||||
return (str:gsub(".", function(char) return string.format("%02X", char:byte()) end))
|
||||
end
|
||||
local gcrypt = require("luagcrypt")
|
||||
local function aes_decrypt(data)
|
||||
local raw_key = bc_protocol.prefs.nonce .. "-" .. bc_protocol.prefs.key
|
||||
local iv = "0123456789abcdef"
|
||||
local hasher = gcrypt.Hash(gcrypt.MD_MD5)
|
||||
hasher:write(raw_key)
|
||||
local key = string.sub(hexencode(hasher:read()),0,16)
|
||||
local ciphertext = data
|
||||
local cipher = gcrypt.Cipher(gcrypt.CIPHER_AES256, gcrypt.CIPHER_MODE_CFB)
|
||||
cipher:setkey(key)
|
||||
cipher:setiv(iv)
|
||||
local decrypted = cipher:decrypt(ciphertext)
|
||||
local result = ByteArray.new(decrypted, true)
|
||||
return result
|
||||
end
|
||||
|
||||
local function xml_decrypt(ba, offset)
|
||||
local key = "\031\045\060\075\090\105\120\255" -- 1f, 2d, 3c, 4b, 5a, 69, 78 ,ff
|
||||
local e = ByteArray.new()
|
||||
@@ -216,12 +253,14 @@ local function get_header_len(buffer)
|
||||
return -1 -- No header found
|
||||
end
|
||||
local header_len = header_lengths[buffer(18, 2):le_uint()]
|
||||
if (not header_len) then
|
||||
return 20
|
||||
end
|
||||
return header_len
|
||||
end
|
||||
|
||||
local function get_header(buffer)
|
||||
-- bin_offset is either nil (no binary data) or nonzero
|
||||
-- TODO: bin_offset is actually stateful!
|
||||
local bin_offset = nil
|
||||
local return_code = nil
|
||||
local encr_xml = nil
|
||||
@@ -246,12 +285,11 @@ local function get_header(buffer)
|
||||
channel_id = buffer(12, 1):le_uint(),
|
||||
enc_offset = buffer(12, 1):le_uint(),
|
||||
stream_type = stream_text,
|
||||
unknown = buffer(14, 1):le_uint(),
|
||||
msg_handle = buffer(15, 1):le_uint(),
|
||||
msg_handle = buffer(14, 2):le_uint(),
|
||||
msg_cls = buffer(18, 2):le_uint(),
|
||||
status_code = return_code,
|
||||
class = message_classes[buffer(18, 2):le_uint()],
|
||||
header_len = header_lengths[buffer(18, 2):le_uint()],
|
||||
class = message_classes[buffer(18, 2):le_uint()] or "unknown",
|
||||
header_len = get_header_len(buffer(0, nil)),
|
||||
bin_offset = bin_offset,
|
||||
}
|
||||
end
|
||||
@@ -275,8 +313,7 @@ local function process_header(buffer, headers_tree)
|
||||
header:add_le(channel_id, buffer(12, 1))
|
||||
header:add_le(stream_id, buffer(13, 1))
|
||||
:append_text(stream_text)
|
||||
header:add_le(unknown, buffer(14, 1))
|
||||
header:add_le(msg_handle, buffer(15, 1))
|
||||
header:add_le(msg_handle, buffer(14, 2))
|
||||
|
||||
header:add_le(message_class, buffer(18, 2)):append_text(" (" .. header_data.class .. ")")
|
||||
|
||||
@@ -312,7 +349,14 @@ local function process_body(header, body_buffer, bc_subtree, pinfo)
|
||||
local body_tvb = xml_buffer:tvb("Meta Payload")
|
||||
body:add(body_tvb(), "Meta Payload")
|
||||
if xml_len >= 4 then
|
||||
if xml_decrypt(xml_buffer(0,5):bytes(), header.enc_offset):raw() == "<?xml" then -- Encrypted xml found
|
||||
if aes_decrypt(xml_buffer:raw(0,5)):raw() == "<?xml" then -- AES encrypted
|
||||
local ba = xml_buffer:bytes()
|
||||
local decrypted = aes_decrypt(ba:raw())
|
||||
body_tvb = decrypted:tvb("Decrypted XML (in Meta Payload)")
|
||||
-- Create a tree item that, when clicked, automatically shows the tab we just created
|
||||
body:add(body_tvb(), "Decrypted XML (in Meta Payload)")
|
||||
Dissector.get("xml"):call(body_tvb, pinfo, body)
|
||||
elseif xml_decrypt(xml_buffer(0,5):bytes(), header.enc_offset):raw() == "<?xml" then -- Encrypted xml found
|
||||
local ba = xml_buffer:bytes()
|
||||
local decrypted = xml_decrypt(ba, header.enc_offset)
|
||||
body_tvb = decrypted:tvb("Decrypted XML (in Meta Payload)")
|
||||
@@ -335,7 +379,14 @@ local function process_body(header, body_buffer, bc_subtree, pinfo)
|
||||
local body_tvb = binary_buffer:tvb("Main Payload");
|
||||
body:add(body_tvb(), "Main Payload")
|
||||
if bin_len > 4 then
|
||||
if xml_decrypt(binary_buffer(0,5):bytes(), header.enc_offset):raw() == "<?xml" then -- Encrypted xml found
|
||||
if aes_decrypt(binary_buffer:raw(0,5)):raw() == "<?xml" then -- AES encrypted
|
||||
local ba = binary_buffer:bytes()
|
||||
local decrypted = aes_decrypt(ba:raw())
|
||||
body_tvb = decrypted:tvb("Decrypted XML (in Binary Payload)")
|
||||
-- Create a tree item that, when clicked, automatically shows the tab we just created
|
||||
body:add(body_tvb(), "Decrypted XML (in Binary Payload)")
|
||||
Dissector.get("xml"):call(body_tvb, pinfo, body)
|
||||
elseif xml_decrypt(binary_buffer(0,5):bytes(), header.enc_offset):raw() == "<?xml" then -- Encrypted xml found
|
||||
local decrypted = xml_decrypt(binary_buffer:bytes(), header.enc_offset)
|
||||
body_tvb = decrypted:tvb("Decrypted XML (in Main Payload)")
|
||||
-- Create a tree item that, when clicked, automatically shows the tab we just created
|
||||
@@ -643,7 +694,7 @@ local function udp_reassemple(udp_header, subbuffer, more, pinfo, tree)
|
||||
local needed = start_fragment.result
|
||||
if needed == "DONE" then
|
||||
if start_fragment.message_id == udp_header.packet_count then
|
||||
process_bc_message(start_fragment.buffer:tvb(), pinfo, tree)
|
||||
process_bc_message(start_fragment.buffer:tvb("UDP Reassemble"), pinfo, tree)
|
||||
end
|
||||
elseif needed == "+1" then
|
||||
-- Cannot handle in UDP...
|
||||
|
||||
@@ -126,6 +126,9 @@ pub(crate) struct CameraConfig {
|
||||
|
||||
#[serde(default = "default_true", alias = "enable")]
|
||||
pub(crate) enabled: bool,
|
||||
|
||||
#[serde(default = "default_false", alias = "verbose")]
|
||||
pub(crate) debug: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
@@ -191,6 +194,10 @@ const fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
const fn default_false() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn default_mqtt() -> Option<MqttConfig> {
|
||||
None
|
||||
}
|
||||
|
||||
+2
-1
@@ -17,7 +17,7 @@ pub(crate) fn timeout<F>(future: F) -> tokio::time::Timeout<F>
|
||||
where
|
||||
F: std::future::Future,
|
||||
{
|
||||
tokio::time::timeout(tokio::time::Duration::from_secs(5), future)
|
||||
tokio::time::timeout(tokio::time::Duration::from_secs(15), future)
|
||||
}
|
||||
|
||||
pub(crate) enum AddressOrUid {
|
||||
@@ -97,6 +97,7 @@ impl AddressOrUid {
|
||||
username: camera_config.username.clone(),
|
||||
password: camera_config.password.clone(),
|
||||
},
|
||||
debug: camera_config.debug,
|
||||
};
|
||||
|
||||
trace!("Camera Info: {:?}", options);
|
||||
|
||||
Reference in new issue
Block a user