From b49ce87f320422d11c254e4e360e0b8ada38b6f4 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Mon, 20 Feb 2023 12:01:35 +0700 Subject: [PATCH] Added config option to control discovery --- crates/core/src/bc_protocol.rs | 14 ++++++--- crates/core/src/bc_protocol/resolution.rs | 37 ++++++++++++++++++++-- src/config.rs | 13 ++++++++ src/mqtt/event_cam.rs | 8 +++-- src/rtsp/states/mod.rs | 7 +++-- src/utils.rs | 38 +++++++++++++++++------ 6 files changed, 95 insertions(+), 22 deletions(-) diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index 623b0f5..b8a5c41 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -115,9 +115,10 @@ impl BcCamera { channel_id: u8, username: U, passwd: Option, + discovery_method: DiscoveryMethods, ) -> Result { Self::new( - SocketAddrOrUid::Uid(uid.to_string()), + SocketAddrOrUid::Uid(uid.to_string(), discovery_method), channel_id, username, passwd, @@ -200,12 +201,15 @@ impl BcCamera { .split(); (Box::new(x), Box::new(r)) } - SocketAddrOrUid::Uid(uid) => { + SocketAddrOrUid::Uid(uid, method) => { debug!("Trying uid {}", uid); // TODO Make configurable - let allow_local = false; - let allow_remote = false; - let allow_relay = true; + 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 discovery = { let mut set = tokio::task::JoinSet::new(); diff --git a/crates/core/src/bc_protocol/resolution.rs b/crates/core/src/bc_protocol/resolution.rs index 9cb3e54..66a02b5 100644 --- a/crates/core/src/bc_protocol/resolution.rs +++ b/crates/core/src/bc_protocol/resolution.rs @@ -6,12 +6,35 @@ use std::{ net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs}, }; +/// Select permitted discovery methods +/// +/// This is used for UID lookup, it is unused with +/// TPC/known ip address cameras +#[derive(Debug, Copy, Clone)] +pub enum DiscoveryMethods { + /// Forbid all discovery methods. Only TCP connections with known addresses will work + None, + /// Allow local discovery on the local network using broadcasts + /// This method does NOT contact reolink servers + Local, + /// Allow contact with the reolink servers to learn the ip address but DO NOT + /// allow the camera/clinet to communicate through the reolink servers. + /// + /// **This also enabled `Local` discovery** + Remote, + /// Allow contact with the reolink servers to learn the ip address and relay the connection + /// through those servers. + /// + /// **This also enabled `Local` and `Remote` discovery** + Relay, +} + /// Used to return either the SocketAddr or the UID pub enum SocketAddrOrUid { /// When the result is a addr it will be this SocketAddr(SocketAddr), /// When the result is a UID - Uid(String), + Uid(String, DiscoveryMethods), } /// An extension of ToSocketAddrs that will also resolve to a camera UID @@ -50,7 +73,11 @@ impl ToSocketAddrsOrUid for str { debug!("Trying as uid"); let re = regex::Regex::new(r"^[0-9A-Za-z]+$").unwrap(); if re.is_match(self) { - Ok(vec![SocketAddrOrUid::Uid(self.to_string())].into_iter()) + Ok(vec![SocketAddrOrUid::Uid( + self.to_string(), + DiscoveryMethods::Local, + )] + .into_iter()) } else { debug!("Regex fails {:?} => {:?} ", re, self); Err(e) @@ -73,7 +100,11 @@ impl ToSocketAddrsOrUid for String { debug!("Trying as uid"); let re = regex::Regex::new(r"^[0-9A-Za-z]+$").unwrap(); if re.is_match(self) { - Ok(vec![SocketAddrOrUid::Uid(self.to_string())].into_iter()) + Ok(vec![SocketAddrOrUid::Uid( + self.to_string(), + DiscoveryMethods::Local, + )] + .into_iter()) } else { debug!("Regex fails {:?} => {:?} ", re, self); Err(e) diff --git a/src/config.rs b/src/config.rs index 10d27fc..cbd5bcd 100644 --- a/src/config.rs +++ b/src/config.rs @@ -10,6 +10,7 @@ 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(); } #[derive(Debug, Deserialize, Validate, Clone)] @@ -75,6 +76,14 @@ pub(crate) struct CameraConfig { #[validate] #[serde(default = "default_pause")] pub(crate) pause: PauseConfig, + + #[serde(default = "default_discovery")] + #[validate(regex( + path = "RE_DISC_SRC", + message = "Invalid discovery method", + code = "discovery" + ))] + pub(crate) discovery: String, } #[derive(Debug, Deserialize, Validate, Clone)] @@ -119,6 +128,10 @@ fn default_mqtt() -> Option { None } +fn default_discovery() -> String { + "Relay".to_string() +} + #[derive(Debug, Deserialize, Validate, Clone)] pub(crate) struct PauseConfig { #[serde(default = "default_on_motion")] diff --git a/src/mqtt/event_cam.rs b/src/mqtt/event_cam.rs index cda7f65..0f06a7d 100644 --- a/src/mqtt/event_cam.rs +++ b/src/mqtt/event_cam.rs @@ -143,8 +143,12 @@ impl EventCam { rx: Arc>>, app: Arc, ) -> Result<()> { - let camera_addr = - AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap(); + let camera_addr = AddressOrUid::new( + &camera_config.camera_addr, + &camera_config.camera_uid, + &camera_config.discovery, + ) + .unwrap(); info!( "{}: Connecting to camera at {}", diff --git a/src/rtsp/states/mod.rs b/src/rtsp/states/mod.rs index f8af0c6..7be6b56 100644 --- a/src/rtsp/states/mod.rs +++ b/src/rtsp/states/mod.rs @@ -53,12 +53,13 @@ impl RtspCamera { rtsp: Arc, ) -> Result { let camera_addr = - AddressOrUid::new(&config.camera_addr, &config.camera_uid).with_context(|| { - format!( + AddressOrUid::new(&config.camera_addr, &config.camera_uid, &config.discovery) + .with_context(|| { + format!( "Could not connect to camera {}. Please check UUID or IP:Port in the config", config.name ) - })?; + })?; info!("{}: Connecting to camera at {}", config.name, camera_addr); let camera = camera_addr diff --git a/src/utils.rs b/src/utils.rs index 2244eab..fc62c0b 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -4,31 +4,47 @@ use log::*; use super::config::{CameraConfig, Config}; use anyhow::{anyhow, Context, Error, Result}; -use neolink_core::bc_protocol::BcCamera; +use neolink_core::bc_protocol::{BcCamera, DiscoveryMethods}; use std::fmt::{Display, Error as FmtError, Formatter}; pub(crate) enum AddressOrUid { Address(String), - Uid(String), + Uid(String, DiscoveryMethods), } impl Display for AddressOrUid { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> { match self { AddressOrUid::Address(host) => write!(f, "Address: {}", host), - AddressOrUid::Uid(host) => write!(f, "UID: {}", host), + AddressOrUid::Uid(host, _) => write!(f, "UID: {}", host), } } } impl AddressOrUid { // Created by translating the config fields directly - pub(crate) fn new(address: &Option, uid: &Option) -> Result { + pub(crate) fn new( + address: &Option, + uid: &Option, + disc_method: &str, + ) -> Result { match (address, uid) { (None, None) => Err(anyhow!("Neither address or uid given")), (Some(_), Some(_)) => Err(anyhow!("Either address or uid should be given not both")), (Some(host), None) => Ok(AddressOrUid::Address(host.clone())), - (None, Some(host)) => Ok(AddressOrUid::Uid(host.clone())), + (None, Some(host)) => { + let method = match disc_method.to_lowercase().as_str() { + "none" => DiscoveryMethods::None, + "local" => DiscoveryMethods::Local, + "remote" => DiscoveryMethods::Remote, + "relay" => DiscoveryMethods::Relay, + n => { + warn!("Unrecognised discovery method: {}. Using Local", n); + DiscoveryMethods::Local + } + }; + Ok(AddressOrUid::Uid(host.clone(), method)) + } } } @@ -43,8 +59,8 @@ impl AddressOrUid { AddressOrUid::Address(host) => { Ok(BcCamera::new_with_addr(host, channel_id, username, passwd).await?) } - AddressOrUid::Uid(host) => { - Ok(BcCamera::new_with_uid(host, channel_id, username, passwd).await?) + AddressOrUid::Uid(host, method) => { + Ok(BcCamera::new_with_uid(host, channel_id, username, passwd, *method).await?) } } } @@ -56,8 +72,12 @@ pub(crate) async fn find_and_connect(config: &Config, name: &str) -> Result Result { - let camera_addr = - AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap(); + let camera_addr = AddressOrUid::new( + &camera_config.camera_addr, + &camera_config.camera_uid, + &camera_config.discovery, + ) + .unwrap(); info!( "{}: Connecting to camera at {}", camera_config.name, camera_addr