Compare commits

..
10 Commits
26 changed files with 1087 additions and 485 deletions

No files matched your search

Generated
+239 -14
View File
@@ -139,9 +139,9 @@ checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd"
[[package]]
name = "bitflags"
version = "1.2.1"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bitvec"
@@ -240,7 +240,7 @@ dependencies = [
"atty",
"bitflags",
"strsim",
"textwrap",
"textwrap 0.11.0",
"unicode-width",
"vec_map",
]
@@ -349,6 +349,31 @@ dependencies = [
"lazy_static",
]
[[package]]
name = "crossterm"
version = "0.25.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e64e6c0fbe2c17357405f7c758c1ef960fce08bdfb2c03d88d2a18d7e09c4b67"
dependencies = [
"bitflags",
"crossterm_winapi",
"libc",
"mio",
"parking_lot",
"signal-hook",
"signal-hook-mio",
"winapi 0.3.9",
]
[[package]]
name = "crossterm_winapi"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ae1b35a484aa10e07fe0638d02301c5ad24de82d310ccbd2f3693da5f09bf1c"
dependencies = [
"winapi 0.3.9",
]
[[package]]
name = "delegate"
version = "0.9.0"
@@ -399,12 +424,42 @@ dependencies = [
"synstructure",
]
[[package]]
name = "errno"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f639046355ee4f37944e44f60642c6f3a7efa3cf6b78c78a0d989a8ce6c396a1"
dependencies = [
"errno-dragonfly",
"libc",
"winapi 0.3.9",
]
[[package]]
name = "errno-dragonfly"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf"
dependencies = [
"cc",
"libc",
]
[[package]]
name = "event-listener"
version = "2.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7531096570974c3a9dcf9e4b8e1cede1ec26cf5046219fb3b9d897503b9be59"
[[package]]
name = "fastrand"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be"
dependencies = [
"instant",
]
[[package]]
name = "fnv"
version = "1.0.7"
@@ -904,6 +959,12 @@ dependencies = [
"libc",
]
[[package]]
name = "hex-string"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "848ec2dd093df965a34b434580d94852197fc83feac5b2c1962399bbf2cb4f0b"
[[package]]
name = "http"
version = "0.2.6"
@@ -961,6 +1022,25 @@ dependencies = [
"unindent",
]
[[package]]
name = "instant"
version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c"
dependencies = [
"cfg-if",
]
[[package]]
name = "io-lifetimes"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1abeb7a0dd0f8181267ff8adc397075586500b81b28a73e8a0208b00fc170fb3"
dependencies = [
"libc",
"windows-sys 0.45.0",
]
[[package]]
name = "itertools"
version = "0.9.0"
@@ -1016,6 +1096,12 @@ version = "0.2.139"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "201de327520df007757c1f0adce6e827fe8562fbc28bfd9c15571c66ca1f5f79"
[[package]]
name = "linux-raw-sys"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f051f77a7c8e6957c0696eac88f26b0117e54f52d3fc682ab19397a8812846a4"
[[package]]
name = "local-ip-address"
version = "0.4.4"
@@ -1090,7 +1176,7 @@ dependencies = [
"libc",
"log",
"wasi 0.11.0+wasi-snapshot-preview1",
"windows-sys",
"windows-sys 0.42.0",
]
[[package]]
@@ -1120,7 +1206,7 @@ dependencies = [
[[package]]
name = "neolink"
version = "0.5.3"
version = "0.5.4"
dependencies = [
"aes",
"anyhow",
@@ -1137,6 +1223,7 @@ dependencies = [
"gstreamer-app",
"gstreamer-rtsp",
"gstreamer-rtsp-server",
"hex-string",
"itertools",
"lazy_static",
"log",
@@ -1144,6 +1231,7 @@ dependencies = [
"neolink_core",
"nom",
"regex",
"requestty",
"rumqttc",
"serde",
"socket2 0.3.19",
@@ -1160,7 +1248,7 @@ dependencies = [
[[package]]
name = "neolink_core"
version = "0.5.3"
version = "0.5.4"
dependencies = [
"aes",
"assert_matches",
@@ -1249,9 +1337,9 @@ dependencies = [
[[package]]
name = "once_cell"
version = "1.8.0"
version = "1.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "692fcb63b64b1758029e0a96ee63e049ce8c5948587f2f7208df04625e5f6b56"
checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3"
[[package]]
name = "opaque-debug"
@@ -1288,7 +1376,7 @@ dependencies = [
"libc",
"redox_syscall",
"smallvec",
"windows-sys",
"windows-sys 0.42.0",
]
[[package]]
@@ -1469,6 +1557,32 @@ version = "0.6.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b"
[[package]]
name = "requestty"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa883a1f3e288e65187f653e6ba2e84fdf810fe02f4c8074f9c723d1aa26e2ae"
dependencies = [
"requestty-ui",
"shell-words",
"smallvec",
"tempfile",
"winsplit",
]
[[package]]
name = "requestty-ui"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7549bab39cf982b629b68e7ec191a5574e85086e95c0ebe514c02d3b42ffe225"
dependencies = [
"bitflags",
"crossterm",
"once_cell",
"textwrap 0.15.2",
"unicode-segmentation",
]
[[package]]
name = "ring"
version = "0.16.20"
@@ -1511,6 +1625,20 @@ dependencies = [
"semver",
]
[[package]]
name = "rustix"
version = "0.36.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f43abb88211988493c1abb44a70efa56ff0ce98f233b7b276146f1f3f7ba9644"
dependencies = [
"bitflags",
"errno",
"io-lifetimes",
"libc",
"linux-raw-sys",
"windows-sys 0.45.0",
]
[[package]]
name = "rustls"
version = "0.19.1"
@@ -1604,6 +1732,33 @@ version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2579985fda508104f7587689507983eadd6a6e84dd35d6d115361f530916fa0d"
[[package]]
name = "shell-words"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24188a676b6ae68c3b2cb3a01be17fbf7240ce009799bb56d5b1409051e78fde"
[[package]]
name = "signal-hook"
version = "0.3.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "732768f1176d21d09e076c23a93123d40bba92d50c4058da34d45c8de8e682b9"
dependencies = [
"libc",
"signal-hook-registry",
]
[[package]]
name = "signal-hook-mio"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29ad2e15f37ec9a6cc544097b78a1ec90001e9f71b81338ca39f430adaca99af"
dependencies = [
"libc",
"mio",
"signal-hook",
]
[[package]]
name = "signal-hook-registry"
version = "1.4.0"
@@ -1628,6 +1783,12 @@ version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0"
[[package]]
name = "smawk"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f67ad224767faa3c7d8b6d91985b78e70a1324408abcb1cfcc2be4c06bc06043"
[[package]]
name = "socket2"
version = "0.3.19"
@@ -1791,6 +1952,19 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
[[package]]
name = "tempfile"
version = "3.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af18f7ae1acd354b992402e9ec5864359d693cd8a79dcbef59f76891701c1e95"
dependencies = [
"cfg-if",
"fastrand",
"redox_syscall",
"rustix",
"windows-sys 0.42.0",
]
[[package]]
name = "termcolor"
version = "1.1.2"
@@ -1809,6 +1983,17 @@ dependencies = [
"unicode-width",
]
[[package]]
name = "textwrap"
version = "0.15.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7b3e525a49ec206798b40326a44121291b530c963cfb01018f63e135bac543d"
dependencies = [
"smawk",
"unicode-linebreak",
"unicode-width",
]
[[package]]
name = "thiserror"
version = "1.0.37"
@@ -1899,7 +2084,7 @@ dependencies = [
"signal-hook-registry",
"socket2 0.4.7",
"tokio-macros",
"windows-sys",
"windows-sys 0.42.0",
]
[[package]]
@@ -2004,6 +2189,16 @@ version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84a22b9f218b40614adcb3f4ff08b703773ad44fa9423e4e0d346d5db86e4ebc"
[[package]]
name = "unicode-linebreak"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5faade31a542b8b35855fff6e8def199853b2da8da256da52f52f1316ee3137"
dependencies = [
"hashbrown",
"regex",
]
[[package]]
name = "unicode-normalization"
version = "0.1.19"
@@ -2015,15 +2210,15 @@ dependencies = [
[[package]]
name = "unicode-segmentation"
version = "1.8.0"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8895849a949e7845e06bd6dc1aa51731a103c42707010a5b591c0038fb73385b"
checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36"
[[package]]
name = "unicode-width"
version = "0.1.8"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3"
checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b"
[[package]]
name = "unicode-xid"
@@ -2252,6 +2447,30 @@ dependencies = [
"windows_x86_64_msvc",
]
[[package]]
name = "windows-sys"
version = "0.45.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.42.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e2522491fbfcd58cc84d47aeb2958948c4b8982e9a2d8a2a35bbaed431390e7"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.42.1"
@@ -2310,6 +2529,12 @@ version = "0.42.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "447660ad36a13288b1db4d4248e857b510e8c3a225c822ba4fb748c0aafecffd"
[[package]]
name = "winsplit"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ab703352da6a72f35c39a533526393725640575bb211f61987a2748323ad956"
[[package]]
name = "wyz"
version = "0.2.0"
+9 -2
View File
@@ -1,7 +1,7 @@
[package]
name = "neolink"
description = "A standards-compliant bridge to Reolink IP cameras"
version = "0.5.3"
version = "0.5.4"
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
edition = "2018"
@@ -10,8 +10,13 @@ members = [
"crates/*",
]
[[bin]]
name = "decoder"
test = false
bench = false
[dependencies]
neolink_core = { path = "crates/core", version = "0.5.3" }
neolink_core = { path = "crates/core", version = "0.5.4" }
aes = "0.6"
cfb-mode = "0.6"
cookie-factory = "0.3"
@@ -45,3 +50,5 @@ tokio = { version = "1.0", features = ["rt", "macros", "io-util"] }
anyhow = "1.0.42"
async-trait = "0.1.64"
futures = "0.3.26"
hex-string = "0.1.0"
requestty = "0.5.0"
+1
View File
@@ -33,6 +33,7 @@ with additional features not yet in upstream master.
- Improved error messages when your missing gstreamer plugins
- Protocol more closely follows offical reolink format
- Possibly can handle more simulatenous connections
- More ways to connect to the camera. Including Relaying through reolink servers
## Installation
+1 -1
View File
@@ -1,7 +1,7 @@
[package]
name = "neolink_core"
description = "Core services and structure for Reolink IP cameras"
version = "0.5.3"
version = "0.5.4"
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
edition = "2018"
+32 -26
View File
@@ -1,4 +1,4 @@
use crate::{bc, Credentials};
use crate::bc;
use futures::stream::StreamExt;
use log::*;
use std::net::ToSocketAddrs;
@@ -7,6 +7,7 @@ use std::sync::atomic::{AtomicBool, AtomicU16, Ordering};
use Md5Trunc::*;
mod connection;
mod credentials;
mod errors;
mod keepalive;
mod ledstate;
@@ -24,6 +25,7 @@ mod time;
mod version;
pub(crate) use connection::*;
pub(crate) use credentials::*;
pub use errors::Error;
pub use ledstate::LightState;
pub use login::MaxEncryption;
@@ -36,15 +38,6 @@ pub use stream::{StreamData, StreamKind};
pub(crate) type Result<T> = std::result::Result<T, Error>;
impl From<crossbeam_channel::RecvTimeoutError> for Error {
fn from(k: crossbeam_channel::RecvTimeoutError) -> Self {
match k {
crossbeam_channel::RecvTimeoutError::Timeout => Error::Timeout,
crossbeam_channel::RecvTimeoutError::Disconnected => Error::TimeoutDisconnected,
}
}
}
///
/// This is the primary struct of this library when interacting with the camera
///
@@ -96,7 +89,7 @@ impl BcCamera {
}
}
Err(Error::Timeout)
Err(Error::CannotInitCamera)
}
///
@@ -166,7 +159,7 @@ impl BcCamera {
}
}
Err(Error::Timeout)
Err(Error::CannotInitCamera)
}
///
@@ -197,20 +190,22 @@ impl BcCamera {
let (sink, source): (BcConnSink, BcConnSource) = match addr {
SocketAddrOrUid::SocketAddr(addr) => {
debug!("Trying address {}", addr);
trace!("Trying address {}", addr);
let (x, r) = TcpSource::new(addr, &username, passwd.as_ref())
.await?
.split();
(Box::new(x), Box::new(r))
}
SocketAddrOrUid::Uid(uid, method) => {
debug!("Trying uid {}", uid);
trace!("Trying uid {}", uid);
// TODO Make configurable
let (allow_local, allow_remote, allow_relay) = match method {
DiscoveryMethods::None => (false, false, false),
DiscoveryMethods::Local => (true, false, false),
DiscoveryMethods::Remote => (true, true, false),
DiscoveryMethods::Relay => (true, true, true),
let (allow_local, allow_remote, allow_map, allow_relay) = match method {
DiscoveryMethods::None => (false, false, false, false),
DiscoveryMethods::Local => (true, false, false, false),
DiscoveryMethods::Remote => (true, true, false, false),
DiscoveryMethods::Map => (true, true, true, false),
DiscoveryMethods::Relay => (true, true, true, true),
DiscoveryMethods::Debug => (false, false, false, true),
};
let discovery = {
@@ -218,10 +213,10 @@ impl BcCamera {
if allow_local {
let uid_local = uid.clone();
set.spawn(async move {
debug!("Starting Local discovery");
trace!("Starting Local discovery");
let result = Discovery::local(&uid_local).await;
if let Ok(disc) = &result {
debug!(
info!(
"Local discovery success {} at {}",
uid_local,
disc.get_addr()
@@ -233,10 +228,10 @@ impl BcCamera {
if allow_remote {
let uid_remote = uid.clone();
set.spawn(async move {
debug!("Starting Remote discovery");
trace!("Starting Remote discovery");
let result = Discovery::remote(&uid_remote).await;
if let Ok(disc) = &result {
debug!(
info!(
"Remote discovery success {} at {}",
uid_remote,
disc.get_addr()
@@ -245,13 +240,24 @@ impl BcCamera {
result
});
}
if allow_map {
let uid_relay = uid.clone();
set.spawn(async move {
trace!("Starting Map");
let result = Discovery::map(&uid_relay).await;
if let Ok(disc) = &result {
info!("Map success {} at {}", uid_relay, disc.get_addr());
}
result
});
}
if allow_relay {
let uid_relay = uid.clone();
set.spawn(async move {
debug!("Starting Relay");
trace!("Starting Relay");
let result = Discovery::relay(&uid_relay).await;
if let Ok(disc) = &result {
debug!("Relay success {} at {}", uid_relay, disc.get_addr());
info!("Relay success {} at {}", uid_relay, disc.get_addr());
}
result
});
@@ -291,7 +297,7 @@ impl BcCamera {
let conn = BcConnection::new(sink, source).await?;
debug!("Success");
trace!("Success");
let me = Self {
connection: Arc::new(conn),
message_num: AtomicU16::new(0),
@@ -1,5 +1,5 @@
use super::BcSubscription;
use crate::{bc::model::*, Error, Result};
use crate::{bc::model::*, timeout, Error, Result};
use futures::sink::{Sink, SinkExt};
use futures::stream::{Stream, StreamExt};
use log::*;
@@ -15,7 +15,7 @@ type MsgHandler = Box<dyn Fn(&Bc) -> Option<Bc> + Send + Sync>;
#[derive(Default)]
struct Subscriber {
/// Subscribers based on their Num
num: RwLock<BTreeMap<u16, Sender<Bc>>>,
num: RwLock<BTreeMap<u16, Sender<Result<Bc>>>>,
/// Subscribers based on their ID
id: RwLock<BTreeMap<u32, MsgHandler>>,
}
@@ -48,11 +48,7 @@ impl BcConnection {
loop {
let packet = source.next().await;
let bc = match packet {
Some(Ok(bc)) => bc,
Some(Err(e)) => {
error!("Deserialization error: {:?}", e);
break;
}
Some(res) => res,
None => continue,
};
@@ -72,7 +68,7 @@ impl BcConnection {
pub(super) async fn send(&self, bc: Bc) -> crate::Result<()> {
trace!("send Wait: {:?}", bc);
self.sink.lock().await.send(bc).await?;
timeout(self.sink.lock().await.send(bc)).await??;
trace!("send Complete");
Ok(())
}
@@ -119,39 +115,70 @@ impl BcConnection {
Ok(())
}
async fn poll(response: Bc, subscribers: &Subscriber, sink: &Mutex<BcConnSink>) -> Result<()> {
// Don't hold the lock during deserialization so we don't poison the subscribers mutex if
// something goes wrong
let msg_num = response.meta.msg_num;
let msg_id = response.meta.msg_id;
async fn poll(
response: Result<Bc>,
subscribers: &Subscriber,
sink: &Mutex<BcConnSink>,
) -> Result<()> {
match response {
Ok(response) => {
let msg_num = response.meta.msg_num;
let msg_id = response.meta.msg_id;
let mut remove_it_num = false;
match (
subscribers.id.read().await.get(&msg_id),
subscribers.num.read().await.get(&msg_num),
) {
(Some(occ), _) => {
if let Some(reply) = occ(&response) {
assert!(reply.meta.msg_num == response.meta.msg_num);
sink.lock().await.send(reply).await?;
let mut remove_it_num = false;
match (
subscribers.id.read().await.get(&msg_id),
subscribers.num.read().await.get(&msg_num),
) {
(Some(occ), _) => {
if let Some(reply) = occ(&response) {
assert!(reply.meta.msg_num == response.meta.msg_num);
sink.lock().await.send(reply).await?;
}
}
(None, Some(occ)) => {
if occ.capacity() == 0 {
warn!("Reaching limit of channel");
warn!(
"Remaining: {} of {} message space for {} (ID: {})",
occ.capacity(),
occ.max_capacity(),
&msg_num,
&msg_id
);
} else {
trace!(
"Remaining: {} of {} message space for {} (ID: {})",
occ.capacity(),
occ.max_capacity(),
&msg_num,
&msg_id
);
}
if occ.send(Ok(response)).await.is_err() {
remove_it_num = true;
}
}
(None, None) => {
debug!(
"Ignoring uninteresting message id {} (number: {})",
msg_id, msg_num
);
trace!("Contents: {:?}", response);
}
}
if remove_it_num {
subscribers.num.write().await.remove(&msg_num);
}
}
(None, Some(occ)) => {
trace!("occ.full: {}/{}", occ.capacity(), occ.max_capacity());
if occ.send(response).await.is_err() {
remove_it_num = true;
Err(e) => {
for sub in subscribers.num.read().await.values() {
let _ = sub.send(Err(e.clone())).await;
}
subscribers.num.write().await.clear();
subscribers.id.write().await.clear();
return Err(e);
}
(None, None) => {
debug!(
"Ignoring uninteresting message id {} (number: {})",
msg_id, msg_num
);
trace!("Contents: {:?}", response);
}
}
if remove_it_num {
subscribers.num.write().await.remove(&msg_num);
}
Ok(())
+31 -23
View File
@@ -1,8 +1,8 @@
use super::BcConnection;
use crate::bcmedia::codex::BcMediaCodex;
use crate::{bc::model::*, Error, Result};
use crate::{bc::model::*, timeout, Error, Result};
use futures::stream::{IntoAsyncRead, Stream, StreamExt, TryStreamExt};
use std::io::Result as IoResult;
use std::io::{Error as IoError, ErrorKind, Result as IoResult};
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::sync::mpsc::Receiver;
@@ -11,21 +11,21 @@ use tokio_util::codec::FramedRead;
use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt};
pub struct BcSubscription<'a> {
rx: ReceiverStream<Bc>,
rx: ReceiverStream<Result<Bc>>,
msg_num: u32,
conn: &'a BcConnection,
}
pub struct BcStream<'a> {
rx: &'a mut ReceiverStream<Bc>,
rx: &'a mut ReceiverStream<Result<Bc>>,
}
impl<'a> Unpin for BcStream<'a> {}
impl<'a> Stream for BcStream<'a> {
type Item = Bc;
type Item = Result<Bc>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Bc>> {
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Result<Bc>>> {
let mut this = self.as_mut();
match Pin::new(&mut this.rx).poll_next(cx) {
Poll::Ready(Some(bc)) => Poll::Ready(Some(bc)),
@@ -36,7 +36,7 @@ impl<'a> Stream for BcStream<'a> {
}
pub struct BcPayloadStream<'a> {
rx: &'a mut ReceiverStream<Bc>,
rx: &'a mut ReceiverStream<Result<Bc>>,
}
impl<'a> Unpin for BcPayloadStream<'a> {}
@@ -48,9 +48,9 @@ impl<'a> Stream for BcPayloadStream<'a> {
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<IoResult<Vec<u8>>>> {
match Pin::new(&mut self.rx).poll_next(cx) {
Poll::Ready(Some(bc)) => {
match bc {
loop {
match Pin::new(&mut self.rx).poll_next(cx) {
Poll::Ready(Some(Ok(bc))) => match bc {
Bc {
body:
BcBody::ModernMsg(ModernMsg {
@@ -58,15 +58,15 @@ impl<'a> Stream for BcPayloadStream<'a> {
..
}),
..
} => Poll::Ready(Some(Ok(data))),
_ => {
cx.waker().wake_by_ref(); // Make it wake in next frame for another attempt at rx.poll_next(cx)
Poll::Pending
}
} => return Poll::Ready(Some(Ok(data))),
_ => continue,
},
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(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
}
}
@@ -74,7 +74,11 @@ impl<'a> Stream for BcPayloadStream<'a> {
pub type BcMediaStream<'b> = FramedRead<Compat<IntoAsyncRead<BcPayloadStream<'b>>>, BcMediaCodex>;
impl<'a> BcSubscription<'a> {
pub fn new(rx: Receiver<Bc>, msg_num: u32, conn: &'a BcConnection) -> BcSubscription<'a> {
pub fn new(
rx: Receiver<Result<Bc>>,
msg_num: u32,
conn: &'a BcConnection,
) -> BcSubscription<'a> {
BcSubscription {
rx: ReceiverStream::new(rx),
msg_num,
@@ -89,9 +93,13 @@ impl<'a> BcSubscription<'a> {
}
pub async fn recv(&mut self) -> Result<Bc> {
let bc = self.rx.next().await.ok_or(Error::DroppedSubscriber)?;
assert!(bc.meta.msg_num as u32 == self.msg_num);
Ok(bc)
let bc = timeout(self.rx.next())
.await?
.ok_or(Error::DroppedSubscriber)?;
if let Ok(bc) = &bc {
assert!(bc.meta.msg_num as u32 == self.msg_num);
}
bc
}
#[allow(unused)]
@@ -105,10 +113,10 @@ impl<'a> BcSubscription<'a> {
}
#[allow(unused)]
pub fn bcmedia_stream(&'_ mut self) -> BcMediaStream<'_> {
pub fn bcmedia_stream(&'_ mut self, strict: bool) -> BcMediaStream<'_> {
let async_read = BcPayloadStream { rx: &mut self.rx }
.into_async_read()
.compat();
FramedRead::new(async_read, BcMediaCodex::new())
FramedRead::new(async_read, BcMediaCodex::new(strict))
}
}
@@ -33,8 +33,9 @@ use tokio_util::udp::UdpFramed;
#[derive(Debug, Clone)]
struct RegisterResult {
reg: SocketAddr,
dmap: Option<SocketAddr>,
dev: Option<SocketAddr>,
dev: SocketAddr,
dmap: SocketAddr,
relay: SocketAddr,
client_id: i32,
sid: u32,
}
@@ -53,12 +54,6 @@ struct UidLookupResults {
relay: SocketAddr,
}
#[derive(Debug, Clone, Copy)]
enum ConnectionKind {
Local,
Relay,
}
pub(crate) struct Discovery {}
const MTU: u32 = 1030;
@@ -275,12 +270,30 @@ impl Discoverer {
result
}
// This function will contact the p2p relay servers
//
// It will ask each of the servers for details on a specific UID
//
// On success it returns the M2cQr that the p2p relay
// server has about the UID
async fn send_and_forget(&self, mut disc: UdpDiscovery, dest: SocketAddr) -> Result<()> {
if disc.tid == 0 {
// If 0 make a random one
let target_tid = generate_tid();
disc.tid = target_tid;
}
let mut inter = interval(Duration::from_millis(50));
let msg = BcUdp::Discovery(disc);
for _i in 0..5 {
inter.tick().await;
self.send(msg.clone(), dest).await?;
}
Ok(())
}
/// This function will contact the p2p relay servers
///
/// It will ask each of the servers for details on a specific UID
///
/// On success it returns the M2cQr that the p2p relay
/// server has about the UID
async fn uid_loopup(&self, uid: &str) -> Result<UidLookupResults> {
let mut addrs = vec![];
for p2p_relay in P2P_RELAY_HOSTNAMES.iter() {
@@ -321,185 +334,6 @@ impl Discoverer {
})
}
async fn send_and_forget(&self, mut disc: UdpDiscovery, dest: SocketAddr) -> Result<()> {
if disc.tid == 0 {
// If 0 make a random one
let target_tid = generate_tid();
disc.tid = target_tid;
}
let mut inter = interval(Duration::from_millis(50));
let msg = BcUdp::Discovery(disc);
for _i in 0..5 {
inter.tick().await;
self.send(msg.clone(), dest).await?;
}
Ok(())
}
async fn device_initiated_connect(
&self,
client_id: i32,
register_result: &RegisterResult,
) -> Result<ConnectResult> {
let (addr, local_tid, local_did, conn_kind) = self
.handle_incoming(|bc, addr| {
trace!("bc: {:?}", bc);
match (bc, register_result) {
(
UdpDiscovery {
tid,
payload:
UdpXml {
d2c_t: Some(D2cT { sid, cid, did, .. }),
..
},
},
RegisterResult {
dmap: Some(register_dmap),
sid: register_sid,
..
},
) if cid == client_id && &sid == register_sid && &addr == register_dmap => {
Some((addr, tid, did, ConnectionKind::Relay))
}
(
UdpDiscovery {
tid,
payload:
UdpXml {
d2c_t: Some(D2cT { sid, cid, did, .. }),
..
},
},
RegisterResult {
dev: Some(register_dev),
sid: register_sid,
..
},
) if cid == client_id && &sid == register_sid && &addr == register_dev => {
Some((addr, tid, did, ConnectionKind::Local))
}
_ => None,
}
})
.await?;
let conn = match conn_kind {
ConnectionKind::Local => "local",
ConnectionKind::Relay => "map",
}
.to_string();
let msg = UdpDiscovery {
tid: local_tid,
payload: UdpXml {
c2d_a: Some(C2dA {
sid: register_result.sid,
conn,
cid: client_id,
did: local_did,
mtu: MTU,
}),
..Default::default()
},
};
// Send and await confirm
self.retry_send(msg, addr, |bc, _| {
trace!("msg: {:?}", &bc);
match bc {
UdpDiscovery {
tid: _,
payload:
UdpXml {
d2c_cfm: Some(D2cCfm { sid, cid, did, .. }),
..
},
} if sid == register_result.sid && did == local_did && cid == client_id => Some(()),
_ => None,
}
})
.await?;
let result = ConnectResult {
addr,
client_id,
sid: register_result.sid,
camera_id: local_did,
};
match conn_kind {
ConnectionKind::Local => {
self.confirm_map(&result, register_result.reg, result.addr)
.await?;
}
ConnectionKind::Relay => {
self.confirm_relay(&result, register_result.reg).await?;
}
}
Ok(result)
}
async fn client_initiated_connect(
&self,
register_result: &RegisterResult,
) -> Result<ConnectResult> {
let tid = generate_tid();
if let RegisterResult {
dev: Some(dev_addr),
..
} = &register_result
{
let msg = UdpDiscovery {
tid,
payload: UdpXml {
c2d_t: Some(C2dT {
sid: register_result.sid,
cid: register_result.client_id,
mtu: MTU,
conn: "local".to_string(),
}),
..Default::default()
},
};
let (final_addr, local_did) = self
.retry_send(msg, *dev_addr, |bc, addr| match bc {
UdpDiscovery {
tid: _,
payload:
UdpXml {
d2c_cfm: Some(D2cCfm { cid, did, sid, .. }),
..
},
} if cid == register_result.client_id && sid == register_result.sid => {
Some((addr, did))
}
_ => None,
})
.await?;
let result = ConnectResult {
addr: final_addr,
client_id: register_result.client_id,
sid: register_result.sid,
camera_id: local_did,
};
self.confirm_map(&result, register_result.reg, *dev_addr)
.await?;
Ok(result)
} else {
Err(Error::NoDev)
}
}
/// Register our local ip address with the reolink servers
/// This will be used for the device to contact us
async fn register_address(
@@ -538,79 +372,34 @@ impl Discoverer {
};
// Send and await acceptance
let (sid, dmap, dev) = self
let (sid, dev, dmap, relay) = self
.retry_send(msg, lookup.reg, |bc, _| match bc {
UdpDiscovery {
tid: _,
payload:
UdpXml {
r2c_t:
Some(R2cT {
dmap: Some(dmap),
r2c_c_r:
Some(R2cCr {
dmap,
dev,
relay,
sid,
cid,
dev: Some(dev),
rsp,
..
}),
..
},
} if !dmap.ip.is_empty()
&& dmap.port > 0
&& !dev.ip.is_empty()
&& dev.port > 0
&& cid == client_id =>
{
Some(Ok((sid, Some(dmap), Some(dev))))
} if !dev.ip.is_empty() && dev.port > 0 && rsp != -1 => {
Some(Ok((sid, dev, dmap, relay)))
}
UdpDiscovery {
tid: _,
payload:
UdpXml {
r2c_t:
Some(R2cT {
dmap: Some(dmap),
sid,
cid,
dev: None,
}),
r2c_c_r: Some(R2cCr { dev, rsp, .. }),
..
},
} if !dmap.ip.is_empty() && dmap.port > 0 && cid == client_id => {
Some(Ok((sid, Some(dmap), None)))
}
UdpDiscovery {
tid: _,
payload:
UdpXml {
r2c_t:
Some(R2cT {
dmap: None,
sid,
cid,
dev: Some(dev),
}),
..
},
} if !dev.ip.is_empty() && dev.port > 0 && cid == client_id => {
Some(Ok((sid, None, Some(dev))))
}
UdpDiscovery {
tid: _,
payload:
UdpXml {
r2c_c_r: Some(R2cCr { dmap, sid, rsp, .. }),
..
},
} if !dmap.ip.is_empty() && dmap.port > 0 && rsp != -1 => {
Some(Ok((sid, Some(dmap), None)))
}
UdpDiscovery {
tid: _,
payload:
UdpXml {
r2c_c_r: Some(R2cCr { dmap, rsp, .. }),
..
},
} if !dmap.ip.is_empty() && dmap.port > 0 && rsp == -1 => {
} if !dev.ip.is_empty() && dev.port > 0 && rsp == -1 => {
Some(Err(Error::RegisterError))
}
_ => None,
@@ -621,25 +410,224 @@ impl Discoverer {
reg: lookup.reg,
sid,
client_id,
dmap: dmap.map(|dmap| {
SocketAddr::new(dmap.ip.parse().expect("Could not read ip addr"), dmap.port)
}),
dev: dev.map(|dev| {
SocketAddr::new(dev.ip.parse().expect("Could not read ip addr"), dev.port)
}),
dev: SocketAddr::new(dev.ip.parse()?, dev.port),
dmap: SocketAddr::new(dmap.ip.parse()?, dmap.port),
relay: SocketAddr::new(relay.ip.parse()?, relay.port),
})
}
/// Confirm connection with relay
/// This is sent once all data has been found
async fn confirm_relay(&self, conn_result: &ConnectResult, reg_addr: SocketAddr) -> Result<()> {
async fn device_initiated_dev(
&self,
register_result: &RegisterResult,
) -> Result<ConnectResult> {
let (addr, local_tid, local_did) = self
.handle_incoming(|bc, addr| {
trace!("bc: {:?}", bc);
match (bc, register_result) {
(
UdpDiscovery {
tid,
payload:
UdpXml {
d2c_t:
Some(D2cT {
sid,
cid,
did,
conn,
..
}),
..
},
},
RegisterResult {
dmap: register_dmap,
sid: register_sid,
..
},
) if cid == register_result.client_id
&& &sid == register_sid
&& &addr == register_dmap
&& &conn == "local" =>
{
Some((addr, tid, did))
}
_ => None,
}
})
.await?;
let msg = UdpDiscovery {
tid: local_tid,
payload: UdpXml {
c2d_a: Some(C2dA {
sid: register_result.sid,
conn: "local".to_string(),
cid: register_result.client_id,
did: local_did,
mtu: MTU,
}),
..Default::default()
},
};
// Send and await confirm
self.retry_send(msg, addr, |bc, _| {
trace!("msg: {:?}", &bc);
match bc {
UdpDiscovery {
tid: _,
payload:
UdpXml {
d2c_cfm:
Some(D2cCfm {
sid,
cid,
did,
conn,
..
}),
..
},
} if sid == register_result.sid
&& did == local_did
&& cid == register_result.client_id
&& &conn == "local" =>
{
Some(())
}
_ => None,
}
})
.await?;
let result = ConnectResult {
addr,
client_id: register_result.client_id,
sid: register_result.sid,
camera_id: local_did,
};
// Confirm local to register
let msg = UdpDiscovery {
tid: 0,
payload: UdpXml {
c2r_cfm: Some(C2rCfm {
sid: conn_result.sid,
cid: conn_result.client_id,
did: conn_result.camera_id,
sid: result.sid,
cid: result.client_id,
did: result.camera_id,
rsp: 0,
conn: "local".to_string(),
}),
..Default::default()
},
};
self.send_and_forget(msg, register_result.reg).await?;
Ok(result)
}
async fn device_initiated_map(
&self,
register_result: &RegisterResult,
) -> Result<ConnectResult> {
let (addr, local_tid, local_did) = self
.handle_incoming(|bc, addr| {
trace!("bc: {:?}", bc);
match (bc, register_result) {
(
UdpDiscovery {
tid,
payload:
UdpXml {
d2c_t:
Some(D2cT {
sid,
cid,
did,
conn,
..
}),
..
},
},
RegisterResult {
dmap: register_dmap,
sid: register_sid,
..
},
) if cid == register_result.client_id
&& &sid == register_sid
&& &addr == register_dmap
&& &conn == "map" =>
{
Some((addr, tid, did))
}
_ => None,
}
})
.await?;
let msg = UdpDiscovery {
tid: local_tid,
payload: UdpXml {
c2d_a: Some(C2dA {
sid: register_result.sid,
conn: "map".to_string(),
cid: register_result.client_id,
did: local_did,
mtu: MTU,
}),
..Default::default()
},
};
// Send and await confirm
self.retry_send(msg, addr, |bc, _| {
trace!("msg: {:?}", &bc);
match bc {
UdpDiscovery {
tid: _,
payload:
UdpXml {
d2c_cfm:
Some(D2cCfm {
sid,
cid,
did,
conn,
..
}),
..
},
} if sid == register_result.sid
&& did == local_did
&& cid == register_result.client_id
&& &conn == "map" =>
{
Some(())
}
_ => None,
}
})
.await?;
let result = ConnectResult {
addr,
client_id: register_result.client_id,
sid: register_result.sid,
camera_id: local_did,
};
// Confirm map to register
let msg = UdpDiscovery {
tid: 0,
payload: UdpXml {
c2r_cfm: Some(C2rCfm {
sid: result.sid,
cid: result.client_id,
did: result.camera_id,
rsp: 0,
conn: "map".to_string(),
}),
@@ -647,27 +635,62 @@ impl Discoverer {
},
};
self.send_and_forget(msg, reg_addr).await?;
self.send_and_forget(msg, register_result.reg).await?;
Ok(())
Ok(result)
}
/// Confirm Map. This is sent if we learned the IP via the relay
/// then connected locally. We tell the relay they we are establishing
/// a local then tell the camera to connect to us via map
async fn confirm_map(
async fn client_initiated_dev(
&self,
conn_result: &ConnectResult,
reg_addr: SocketAddr,
dev_addr: SocketAddr,
) -> Result<()> {
register_result: &RegisterResult,
) -> Result<ConnectResult> {
let tid = generate_tid();
let dev_addr = register_result.dev;
let msg = UdpDiscovery {
tid,
payload: UdpXml {
c2d_t: Some(C2dT {
sid: register_result.sid,
cid: register_result.client_id,
mtu: MTU,
conn: "local".to_string(),
}),
..Default::default()
},
};
let (final_addr, local_did) = self
.retry_send(msg, dev_addr, |bc, addr| match bc {
UdpDiscovery {
tid: _,
payload:
UdpXml {
d2c_cfm: Some(D2cCfm { cid, did, sid, .. }),
..
},
} if cid == register_result.client_id && sid == register_result.sid => {
Some((addr, did))
}
_ => None,
})
.await?;
let result = ConnectResult {
addr: final_addr,
client_id: register_result.client_id,
sid: register_result.sid,
camera_id: local_did,
};
// Confirm local to register
let msg = UdpDiscovery {
tid: 0,
payload: UdpXml {
c2r_cfm: Some(C2rCfm {
sid: conn_result.sid,
cid: conn_result.client_id,
did: conn_result.camera_id,
sid: result.sid,
cid: result.client_id,
did: result.camera_id,
conn: "local".to_string(),
rsp: 0,
}),
@@ -675,28 +698,69 @@ impl Discoverer {
},
};
self.send_and_forget(msg, reg_addr).await?;
self.send_and_forget(msg, register_result.reg).await?;
Ok(result)
}
async fn client_initiated_relay(
&self,
register_result: &RegisterResult,
) -> Result<ConnectResult> {
let tid = generate_tid();
let msg = UdpDiscovery {
tid: 0,
tid,
payload: UdpXml {
c2d_t: Some(C2dT {
sid: conn_result.sid,
cid: conn_result.client_id,
sid: register_result.sid,
cid: register_result.client_id,
mtu: MTU,
conn: "map".to_string(),
conn: "relay".to_string(),
}),
..Default::default()
},
};
self.send_and_forget(msg, dev_addr).await?;
let (final_addr, local_did) = self
.retry_send(msg, register_result.relay, |bc, addr| match bc {
UdpDiscovery {
tid: _,
payload:
UdpXml {
d2c_cfm:
Some(D2cCfm {
cid,
did,
sid,
conn,
..
}),
..
},
} if cid == register_result.client_id
&& sid == register_result.sid
&& &conn == "relay" =>
{
Some((addr, did))
}
_ => None,
})
.await?;
Ok(())
let result = ConnectResult {
addr: final_addr,
client_id: register_result.client_id,
sid: register_result.sid,
camera_id: local_did,
};
Ok(result)
}
}
impl Discovery {
// Perform UDP broadcast lookup and connection
pub(crate) async fn local(uid: &str) -> Result<DiscoveryResult> {
let discoverer = Discoverer::new().await?;
@@ -745,14 +809,14 @@ impl Discovery {
// This will start remote discovery against the reolink p2p servers
//
// It has the following stages
// - Contact the p2p register: This will get the register, relay and log server ip addresses
// - Register the client ip address to the register (This can probably be used for NAT holepunching if the camera
// tries to connect to us using this data)
// - The register will return the camera ip/port and SID
// - Connect to the camera using register's provided ip/port and negotiate a cid and did
// - Send a message to the reolink log server that we will connect locally
// - Send a message to the camera that we could connect remotely
// This works by registering our ip and intent to connect with the reolink
// servers
//
// We will then try to connect to the camera local ip address while the camera
// will also attempt to connec to ours
//
// This method is best when broadcasts are not possible but we can contact the camera
// directly
#[allow(unused)]
pub(crate) async fn remote(uid: &str) -> Result<DiscoveryResult> {
let mut discoverer = Discoverer::new().await?;
@@ -764,9 +828,11 @@ impl Discovery {
let relay_addr = lookup.relay;
let reg_result = discoverer.register_address(uid, client_id, &lookup).await?;
let dev_addr = reg_result.dev.ok_or(Error::NoDev)?;
let connect_result = discoverer.client_initiated_connect(&reg_result).await?;
let connect_result = tokio::select! {
v = discoverer.client_initiated_dev(&reg_result) => {v},
v = discoverer.device_initiated_dev(&reg_result) => {v},
}?;
Ok(DiscoveryResult {
socket: discoverer.into_socket().await,
@@ -776,34 +842,55 @@ impl Discovery {
})
}
// This is similar to remote, except that a relay (map) will be established.
// This is similar to remote, except that it allows the camera to connect to us
// over it's dmap (public) ip address that it has registered with reolink servers.
//
// All future connections will go VIA the relink servers, this is for
// cellular cameras that do not support local connections
// This works by registering our ip address and the desire to connect with the
// reolink servers. Data however should go to the camera's public ip address
//
// It is possible that this will also establish a local if the camera attempts that
//
#[allow(unused)]
pub(crate) async fn relay(uid: &str) -> Result<DiscoveryResult> {
let mut discoverer = Discoverer::new().await?;
let client_id = generate_cid();
// This method should be used when the camera is behind a NAT or firewall but we are
// reachable
pub(crate) async fn map(uid: &str) -> Result<DiscoveryResult> {
let discoverer = Discoverer::new().await?;
let client_id = generate_cid();
trace!("client_id: {}", client_id);
let lookup = discoverer.uid_loopup(uid).await?;
trace!("lookup: {:?}", lookup);
let reg_addr = lookup.reg;
let relay_addr = lookup.relay;
let reg_result = discoverer.register_address(uid, client_id, &lookup).await?;
trace!("reg_result: {:?}", reg_result);
let dmap_addr = reg_result.dmap.ok_or(Error::NoDmap)?;
let connect_result = discoverer.device_initiated_map(&reg_result).await?;
trace!("connect_result: {:?}", connect_result);
let connect_result = discoverer
.device_initiated_connect(client_id, &reg_result)
.await?;
Ok(DiscoveryResult {
socket: discoverer.into_socket().await,
addr: connect_result.addr,
client_id,
camera_id: connect_result.camera_id,
})
}
// This will forward all connections via the reolinks servers
//
// This method should work if all else fails but it will require
// us to trust reolink with our data once more...
//
pub(crate) async fn relay(uid: &str) -> Result<DiscoveryResult> {
let discoverer = Discoverer::new().await?;
let client_id = generate_cid();
trace!("client_id: {}", client_id);
let lookup = discoverer.uid_loopup(uid).await?;
trace!("lookup: {:?}", lookup);
let reg_result = discoverer.register_address(uid, client_id, &lookup).await?;
trace!("reg_result: {:?}", reg_result);
let connect_result = discoverer.client_initiated_relay(&reg_result).await?;
trace!("connect_result: {:?}", connect_result);
Ok(DiscoveryResult {
@@ -1109,4 +1196,32 @@ async fn connect() -> Result<UdpSocket> {
</P2P>
```
# Thread 4: Observed when behind a NAT on both ends of the connection
- C->R
```
<P2P>
<C2D_T>
<sid>526020041</sid>
<conn>relay</conn>
<cid>38000</cid>
<mtu>1350</mtu>
</C2D_T>
</P2P>
```
- R->C
```xml
<P2P>
<D2C_CFM>
<sid>526020041</sid>
<conn>relay</conn>
<rsp>0</rsp>
<cid>38000</cid>
<did>32</did>
<time_r>0</time_r>
</D2C_CFM>
</P2P>
```
*/
@@ -159,7 +159,8 @@ impl BcUdpSource {
recieved: Default::default(),
state: State::Normal,
send_buffer: Default::default(),
interval: interval(Duration::from_millis(10)), // Offical Client does ack every 10ms
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
}
}
}
@@ -211,8 +212,11 @@ pub(crate) struct UdpPayloadSource {
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 `intveral` controls how ofen we do this
interval: Interval,
/// This `ack_interval` controls how ofen we do this
ack_interval: Interval,
/// Offical Client does resend every 500ms
/// This `resend_interval` controls how ofen we do this
resend_interval: Interval,
}
impl UdpPayloadSource {
@@ -261,12 +265,13 @@ impl UdpPayloadSource {
fn maintanence(&mut self, cx: &mut Context<'_>) {
// Check for periodic resends
if self.interval.poll_tick(cx).is_ready() {
if self.resend_interval.poll_tick(cx).is_ready() {
trace!("UDPSource.RecievedPacket: Resend");
for (_, resend) in self.sent.iter() {
self.send_buffer.push_back(BcUdp::Data(resend.clone()));
}
}
if self.ack_interval.poll_tick(cx).is_ready() {
let ack = BcUdp::Ack(self.build_send_ack());
trace!("UDPSource.RecievedPacket: QueueingAck");
self.send_buffer.push_back(ack);
@@ -0,0 +1,52 @@
//! Handles credentials for camera including default reolink password
use std::convert::TryInto;
/// Used for caching the credentials
#[derive(Clone)]
pub(crate) struct Credentials {
pub(crate) username: String,
pub(crate) password: Option<String>,
}
impl Default for Credentials {
/// Default credentials for some reolink cameras
fn default() -> Self {
Self {
username: "admin".to_string(),
password: Some("123456".to_string()),
}
}
}
impl std::fmt::Debug for Credentials {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_map()
.entry(&"username", &self.username)
.entry(&"password", &"******")
.finish()
}
}
impl Credentials {
pub(crate) fn new<T: Into<String>, U: Into<String>>(username: T, password: Option<U>) -> Self {
Self {
username: username.into(),
password: password.map(|t| t.into()),
}
}
/// This is a convience function to make an AES key from the login password and the NONCE
/// negotiated during login
pub(crate) fn make_aeskey<T: AsRef<str>>(&self, nonce: T) -> [u8; 16] {
let key_phrase = format!(
"{}-{}",
nonce.as_ref(),
self.password.clone().unwrap_or_default()
);
let key_phrase_hash = format!("{:X}\0", md5::compute(key_phrase))
.to_uppercase()
.into_bytes();
key_phrase_hash[0..16].try_into().unwrap()
}
}
+16 -2
View File
@@ -35,14 +35,22 @@ pub enum Error {
#[error(display = "Dropped connection")]
BroadcastDroppedConnectionTry(#[error(source)] tokio::sync::broadcast::error::TryRecvError),
/// Raised when the RX_TIMEOUT is reach
/// Raised when the TIMEOUT is reach
#[error(display = "Timeout")]
Timeout,
Timeout(#[error(source)] std::sync::Arc<tokio::time::error::Elapsed>),
/// Raised when a timeout fails in a non standard way such as timeout during shutdown
#[error(display = "TimeoutError")]
TimeoutError(#[error(source)] tokio::time::error::Error),
/// Raised when connection is dropped because the timeout is reach
#[error(display = "Dropped connection")]
TimeoutDisconnected,
/// Raised when a camera cannot be connected to ay any of the given addresses
#[error(display = "Cannot contact camera at given address")]
CannotInitCamera,
/// Raised when failed to login to the camera
#[error(display = "Credential error")]
AuthFailed,
@@ -162,6 +170,12 @@ impl From<local_ip_address::Error> for Error {
}
}
impl From<tokio::time::error::Elapsed> for Error {
fn from(k: tokio::time::error::Elapsed) -> Self {
Error::Timeout(std::sync::Arc::new(k))
}
}
impl<'a> From<nom::Err<NomErrorType<'a>>> for Error {
fn from(k: nom::Err<NomErrorType<'a>>) -> Self {
match k {
+10 -2
View File
@@ -22,11 +22,19 @@ pub enum DiscoveryMethods {
///
/// **This also enabled `Local` discovery**
Remote,
/// Allow contact with the reolink servers to learn the ip address and relay the connection
/// through those servers.
/// Allow contact with the reolink servers to learn the ip address and map the connection
/// from dev to client through those servers.
///
/// **This also enabled `Local` and `Remote` discovery**
Map,
/// Allow contact with the reolink servers to learn the ip address and relay the connection
/// client to dev through those servers.
///
/// **This also enabled `Local`, `Map` and `Remote` discovery**
Relay,
#[doc(hidden)]
/// Used for debugging it is set to whatever the dev is currently testing
Debug,
}
/// Used to return either the SocketAddr or the UID
+4 -1
View File
@@ -66,10 +66,13 @@ impl BcCamera {
/// The buffer_size represents number of compete messages so 1 would be one complete message
/// which may be a single audio frame or a whole video key frame. If 0 a default of 100 is used
///
/// A value of scrict=true will mean that the stream will error if the underlying stream is not
/// as expected
pub async fn start_video(
&self,
stream: StreamKind,
mut buffer_size: usize,
strict: bool,
) -> Result<StreamData> {
let connection = self.get_connection();
let msg_num = self.new_message_num();
@@ -157,7 +160,7 @@ impl BcCamera {
}
{
let mut media_sub = sub_video.bcmedia_stream();
let mut media_sub = sub_video.bcmedia_stream(strict);
while !abort_handle_thread.load(Ordering::Relaxed) {
if let Some(bc_media) = media_sub.next().await {
+36 -8
View File
@@ -4,14 +4,19 @@
//!
use crate::bcmedia::model::*;
use crate::{Error, Result};
use bytes::BytesMut;
use bytes::{Buf, BytesMut};
use log::*;
use tokio_util::codec::{Decoder, Encoder};
pub struct BcMediaCodex {}
pub struct BcMediaCodex {
/// If true we will not search for the start of the next packet
/// in the event that the stream appears to be corrupted
strict: bool,
}
impl BcMediaCodex {
pub(crate) fn new() -> Self {
Self {}
pub(crate) fn new(strict: bool) -> Self {
Self { strict }
}
}
@@ -32,10 +37,33 @@ impl Decoder for BcMediaCodex {
type Error = Error;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>> {
match { BcMedia::deserialize(src) } {
Ok(bc) => Ok(Some(bc)),
Err(Error::NomIncomplete(_)) => Ok(None),
Err(e) => Err(e),
let mut amount_skipped: usize = 0;
loop {
match { BcMedia::deserialize(src) } {
Ok(bc) => {
if amount_skipped > 0 {
trace!("Amount skipped to restore stream: {}", amount_skipped);
}
return Ok(Some(bc));
}
Err(Error::NomIncomplete(_)) => {
if amount_skipped > 0 {
trace!("Amount skipped to restore stream: {}", amount_skipped);
}
return Ok(None);
}
Err(e) => {
if self.strict {
return Err(e);
} else if src.is_empty() {
return Ok(None);
} else {
src.advance(1);
amount_skipped += 1;
continue;
}
}
}
}
}
}
+47 -8
View File
@@ -1,5 +1,5 @@
/// Video streams encapsulate a stream of BcMedia
#[derive(Debug)]
#[derive(Debug, Clone)]
pub enum BcMedia {
/// Holds info on the stream
InfoV1(BcMediaInfoV1),
@@ -19,7 +19,7 @@ pub(super) const MAGIC_HEADER_BCMEDIA_INFO_V1: u32 = 0x31303031;
/// The start of a BcMedia stream contains this message
/// which describes the data to follow
#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct BcMediaInfoV1 {
// This is the size of the header so it's actually a fixed value
// The other messages have body size here so maybe that's why
@@ -63,7 +63,7 @@ pub(super) const MAGIC_HEADER_BCMEDIA_INFO_V2: u32 = 0x32303031;
/// The start of a BcMedia stream contains this message
/// which describes the data to follow
#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct BcMediaInfoV2 {
// This is the size of the header so it's actually a fixed value
// The other messages have body size here so maybe that's why
@@ -108,7 +108,7 @@ pub(super) const MAGIC_HEADER_BCMEDIA_IFRAME: u32 = 0x63643030;
pub(super) const MAGIC_HEADER_BCMEDIA_IFRAME_LAST: u32 = 0x63643039;
/// Video Types for I/PFrame
#[derive(Debug)]
#[derive(Debug, Clone)]
pub enum VideoType {
/// H264 video data
H264,
@@ -117,7 +117,7 @@ pub enum VideoType {
}
/// This is a BcMedia video IFrame.
#[derive(Debug)]
#[derive(Clone)]
pub struct BcMediaIframe {
/// "H264", or "H265"
pub video_type: VideoType,
@@ -134,12 +134,32 @@ pub struct BcMediaIframe {
pub data: Vec<u8>,
}
impl std::fmt::Debug for BcMediaIframe {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_map()
.entry(&"video_type", &self.video_type)
// .entry(&"payload_size", &self.payload_size)
.entry(&"microseconds", &self.microseconds)
.entry(&"time", &self.time)
.entry(
&"data[0..10]",
&self.data[0..std::cmp::min(20, self.data.len())].to_vec(),
)
.entry(
&"data[-10..-1]",
&self.data[std::cmp::max(0, self.data.len() - 20)..self.data.len()].to_vec(),
)
.entry(&"data.len()", &self.data.len())
.finish()
}
}
// PFrame magics include the channel number in them
pub(super) const MAGIC_HEADER_BCMEDIA_PFRAME: u32 = 0x63643130;
pub(super) const MAGIC_HEADER_BCMEDIA_PFRAME_LAST: u32 = 0x63643139;
/// This is a BcMedia video PFrame.
#[derive(Debug)]
#[derive(Clone)]
pub struct BcMediaPframe {
/// "H264", or "H265"
pub video_type: VideoType,
@@ -153,10 +173,29 @@ pub struct BcMediaPframe {
pub data: Vec<u8>,
}
impl std::fmt::Debug for BcMediaPframe {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_map()
.entry(&"video_type", &self.video_type)
// .entry(&"payload_size", &self.payload_size)
.entry(&"microseconds", &self.microseconds)
.entry(
&"data[0..20]",
&self.data[0..std::cmp::min(20, self.data.len())].to_vec(),
)
.entry(
&"data[-20..-1]",
&self.data[std::cmp::max(0, self.data.len() - 20)..self.data.len()].to_vec(),
)
.entry(&"data.len()", &self.data.len())
.finish()
}
}
pub(super) const MAGIC_HEADER_BCMEDIA_AAC: u32 = 0x62773530;
/// This contains BcMedia audio data in AAC format
#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct BcMediaAac {
// Size of payload after header in bytes
// pub payload_size: u16,
@@ -171,7 +210,7 @@ pub(super) const MAGIC_HEADER_BCMEDIA_ADPCM: u32 = 0x62773130;
pub(super) const MAGIC_HEADER_BCMEDIA_ADPCM_DATA: u16 = 0x0100;
/// This contains BcMedia audio data in ADPCM format
#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct BcMediaAdpcm {
// Size of payload after header in bytes
// pub payload_size: u16,
+2
View File
@@ -283,6 +283,8 @@ pub struct R2cT {
///
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
pub struct R2cCr {
/// Dev camera location (actual local ip)
pub dev: IpPort,
/// Dmap camera location
pub dmap: IpPort,
/// The location of the relay
+14 -47
View File
@@ -38,56 +38,23 @@ pub mod bcudp;
/// Most commands will either return their `Ok(result)` or this `Err(Error)`
pub use bc_protocol::Error;
pub(crate) use bc_protocol::Result;
pub(crate) use bc_protocol::{Credentials, Result};
pub(crate) type NomErrorType<'a> = nom::error::VerboseError<&'a [u8]>;
// Used for caching the credentials
#[derive(Clone)]
pub(crate) struct Credentials {
username: String,
password: Option<String>,
lazy_static::lazy_static! {
/// This is a high level tiemout for the app as a whole. Not the lowlevel io ones
///
/// This is used to timeout when the primary send and receive channels of Bc packets
/// is full for too long. This can happen if messages are not pulled from the endpoints
/// fast enough or if there is an unexpected bug
pub(crate) static ref TIMEOUT: tokio::time::Duration = tokio::time::Duration::from_secs(60);
}
impl Default for Credentials {
/// Default credentials for some reolink cameras
fn default() -> Self {
Self {
username: "admin".to_string(),
password: Some("123456".to_string()),
}
}
}
impl std::fmt::Debug for Credentials {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_map()
.entry(&"username", &self.username)
.entry(&"password", &"******")
.finish()
}
}
use std::convert::TryInto;
impl Credentials {
pub(crate) fn new<T: Into<String>, U: Into<String>>(username: T, password: Option<U>) -> Self {
Self {
username: username.into(),
password: password.map(|t| t.into()),
}
}
/// This is a convience function to make an AES key from the login password and the NONCE
/// negotiated during login
pub(crate) fn make_aeskey<T: AsRef<str>>(&self, nonce: T) -> [u8; 16] {
let key_phrase = format!(
"{}-{}",
nonce.as_ref(),
self.password.clone().unwrap_or_default()
);
let key_phrase_hash = format!("{:X}\0", md5::compute(key_phrase))
.to_uppercase()
.into_bytes();
key_phrase_hash[0..16].try_into().unwrap()
}
/// A convience future to timeout with the default timeout specified in [`TIMEOUT`]
pub(crate) fn timeout<F>(future: F) -> tokio::time::Timeout<F>
where
F: std::future::Future,
{
tokio::time::timeout(*TIMEOUT, future)
}
+4
View File
@@ -151,6 +151,7 @@ local message_types = {
[209]="<LedState> (write)",
[210]="<PTOP>",
[211]="<PTOP> (write)",
[212]="<rfAlarmCfg>",
[216]="<EmailTask> (write)",
[217]="<EmailTask>",
[218]="<PushTask> (write)",
@@ -158,6 +159,9 @@ local message_types = {
[228]="<Crop>",
[229]="<Crop> (write)",
[230]="<cropSnap>",
[234]="UDP Keep Alive",
[252]="<BatteryInfoList>",
[253]="<BatteryInfo>",
[272]="<findAlarmVideo>",
[273]="<alarmVideoInfo>",
[274]="<findAlarmVideo>",
+12
View File
@@ -51,6 +51,18 @@ address = "192.168.1.187:9000"
# If your device has user connection limits try a single stream instead.
# stream = "mainStream"
# By default neolink will use any means to connect to the camera
# from a UID
# This include relaying via reolink servers
# This variable `discovery` controls the method of UID discovery
# - Possible values
# "relay" # Any means including connecting and transmitting through reolink
# "map" # Register our local ip address with reolink and ask the camera to connect to us but don't relay data through reolink
# "remote" # Register our local ip address with reolink but only permit same network connections (useful if broadcast is not possible)
# "local" # Do not contact reolink servers at all. Rely soley on local UDP broadcast based discovery
#
# discovery = "relay"
[[cameras]]
name = "storage shed"
+63
View File
@@ -0,0 +1,63 @@
//! Use to decode AES packet data
use hex_string::HexString;
use requestty::Question;
use std::convert::TryInto;
use aes::Aes128;
use cfb_mode::cipher::{NewStreamCipher, StreamCipher};
use cfb_mode::Cfb;
const IV: &[u8] = b"0123456789abcdef";
fn decrypt(buf: &[u8], aeskey: &[u8; 16]) -> Vec<u8> {
let mut decrypted = buf.to_vec();
Cfb::<Aes128>::new(aeskey.into(), IV.into()).decrypt(&mut decrypted);
decrypted
}
fn make_aeskey<T: AsRef<str>>(password: T, nonce: T) -> [u8; 16] {
let key_phrase = format!("{}-{}", nonce.as_ref(), password.as_ref(),);
let key_phrase_hash = format!("{:X}\0", md5::compute(key_phrase))
.to_uppercase()
.into_bytes();
key_phrase_hash[0..16].try_into().unwrap()
}
fn main() -> Result<(), anyhow::Error> {
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
let question = Question::input("hex")
.message("Enter the hex string to decode")
.build();
let source_str: String = requestty::prompt_one(question)?
.as_string()
.ok_or_else(|| anyhow::anyhow!("Did not get reply"))?
.to_string();
let question = Question::password("password")
.message("Enter Camera Password")
.mask('*')
.build();
let pass = requestty::prompt_one(question)?
.as_string()
.ok_or_else(|| anyhow::anyhow!("Did not get reply"))?
.to_string();
let question = Question::password("nonce")
.message("Enter Login Nonce")
.mask('*')
.build();
let nonce = requestty::prompt_one(question)?
.as_string()
.ok_or_else(|| anyhow::anyhow!("Did not get reply"))?
.to_string();
let source_hex = HexString::from_string(&source_str).unwrap();
let decrypted = decrypt(&source_hex.as_bytes(), &make_aeskey(&pass, &nonce));
log::info!("Bytes: {:X?}", decrypted);
log::info!("Text: {}", String::from_utf8(decrypted)?);
Ok(())
}
+10 -1
View File
@@ -10,7 +10,8 @@ lazy_static! {
Regex::new(r"^(mainStream|subStream|externStream|both|all)$").unwrap();
static ref RE_TLS_CLIENT_AUTH: Regex = Regex::new(r"^(none|request|require)$").unwrap();
static ref RE_PAUSE_MODE: Regex = Regex::new(r"^(black|still|test|none)$").unwrap();
static ref RE_DISC_SRC: Regex = Regex::new(r"^([nN]one|[lL]ocal|[rR]emote|[rR]elay)$").unwrap();
static ref RE_DISC_SRC: Regex =
Regex::new(r"^([nN]one|[lL]ocal|[rR]emote|[Mm]ap|[rR]elay|[Dd]ebug)$").unwrap();
static ref RE_MAXENC_SRC: Regex =
Regex::new(r"^([nN]one|[Aa][Ee][Ss]|[Bb][Cc][Ee][Nn][Cc][Rr][Yy][Pp][Tt])$").unwrap();
}
@@ -94,6 +95,10 @@ pub(crate) struct CameraConfig {
code = "max_encryption"
))]
pub(crate) max_encryption: String,
#[serde(default = "default_strict")]
/// If strict then the media stream will error in the event that the media packets are not as expected
pub(crate) strict: bool,
}
#[derive(Debug, Deserialize, Validate, Clone)]
@@ -206,6 +211,10 @@ fn default_pause_mode() -> String {
"none".to_string()
}
fn default_strict() -> bool {
false
}
fn default_pause() -> PauseConfig {
PauseConfig {
on_motion: default_on_motion(),
+1 -1
View File
@@ -33,7 +33,7 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
.await
.context("Failed to connect to the camera, check credentials and network")?;
let mut stream_data = camera
.start_video(StreamKind::Main, 0)
.start_video(StreamKind::Main, 0, camera_config.strict)
.await
.context("Failed to start video")?;
+1
View File
@@ -129,6 +129,7 @@ impl RtspCamera {
rtsp,
permitted_users,
max_encryption,
strict: config.strict,
};
let mut state: Connected = Default::default();
+1
View File
@@ -26,6 +26,7 @@ pub(crate) struct Shared {
pub(super) permitted_users: HashSet<String>,
pub(super) pause: PauseConfig,
pub(super) max_encryption: MaxEncryption,
pub(super) strict: bool,
}
impl Shared {
+4 -1
View File
@@ -93,8 +93,11 @@ impl CameraState for Streaming {
let output_thread = output.clone();
let stream_thead = *stream;
let strict_thread = shared.strict;
let handle = task::spawn(async move {
let mut stream_data = arc_camera.start_video(stream_thead, 0).await?;
let mut stream_data = arc_camera
.start_video(stream_thead, 0, strict_thread)
.await?;
while arc_abort_handle.is_live() {
let data = stream_data.get_data().await?;
let mut locked_output = output_thread.lock().await;
+2
View File
@@ -37,7 +37,9 @@ impl AddressOrUid {
"none" => DiscoveryMethods::None,
"local" => DiscoveryMethods::Local,
"remote" => DiscoveryMethods::Remote,
"map" => DiscoveryMethods::Map,
"relay" => DiscoveryMethods::Relay,
"debug" => DiscoveryMethods::Debug,
n => {
warn!("Unrecognised discovery method: {}. Using Local", n);
DiscoveryMethods::Local