From 94805c881e247c0159cc669afd05fda7523a5b46 Mon Sep 17 00:00:00 2001 From: Andrew Date: Fri, 3 Mar 2023 09:28:42 +0700 Subject: [PATCH] Permit connect with UID at an Addr --- crates/core/src/bc_protocol.rs | 47 +++++++++++++++++-- .../src/bc_protocol/connection/discovery.rs | 10 +++- crates/core/src/bc_protocol/resolution.rs | 13 ++++- src/config.rs | 15 ++---- src/utils.rs | 38 ++++++++------- 5 files changed, 88 insertions(+), 35 deletions(-) diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index 3699f7b..db68f96 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -145,7 +145,48 @@ impl BcCamera { aux_info_format: PrintFormat, ) -> Result { Self::new( - SocketAddrOrUid::Uid(uid.to_string(), discovery_method), + SocketAddrOrUid::Uid(uid.to_string(), None, discovery_method), + channel_id, + username, + passwd, + aux_info_format, + ) + .await + } + + /// + /// Create a new camera interface with this uid and channel ID + /// while also including IP address information. This will allow + /// More ways of connecting to a UID camera without contacting + /// reolink + /// + /// # Parameters + /// + /// * `uid` - The uid of the camera + /// + /// * `address` - The address of the camera + /// + /// * `channel_id` - The channel ID this is usually zero unless using a NVR + /// + /// # Returns + /// + /// returns either an error or the camera + /// + pub async fn new_with_uid_and_addr, V: Into, W: ToSocketAddrs>( + uid: &str, + host: W, + channel_id: u8, + username: U, + passwd: Option, + discovery_method: DiscoveryMethods, + aux_info_format: PrintFormat, + ) -> Result { + Self::new( + SocketAddrOrUid::Uid( + uid.to_string(), + Some(host.to_socket_addrs()?.collect()), + discovery_method, + ), channel_id, username, passwd, @@ -239,7 +280,7 @@ impl BcCamera { .split(); (Box::new(x), Box::new(r)) } - SocketAddrOrUid::Uid(uid, method) => { + SocketAddrOrUid::Uid(uid, optional_addrs, method) => { trace!("Trying uid {}", uid); // TODO Make configurable let (allow_local, allow_remote, allow_map, allow_relay) = match method { @@ -257,7 +298,7 @@ impl BcCamera { let uid_local = uid.clone(); set.spawn(async move { trace!("Starting Local discovery"); - let result = Discovery::local(&uid_local).await; + let result = Discovery::local(&uid_local, optional_addrs).await; if let Ok(disc) = &result { info!( "Local discovery success {} at {}", diff --git a/crates/core/src/bc_protocol/connection/discovery.rs b/crates/core/src/bc_protocol/connection/discovery.rs index 25c273a..7f733f8 100644 --- a/crates/core/src/bc_protocol/connection/discovery.rs +++ b/crates/core/src/bc_protocol/connection/discovery.rs @@ -761,7 +761,10 @@ impl Discoverer { impl Discovery { // Perform UDP broadcast lookup and connection - pub(crate) async fn local(uid: &str) -> Result { + pub(crate) async fn local( + uid: &str, + mut optional_addrs: Option>, + ) -> Result { let discoverer = Discoverer::new().await?; let client_id = generate_cid(); @@ -784,7 +787,10 @@ impl Discovery { }, }; - let dests = get_broadcasts(&[2015, 2018])?; + let mut dests = get_broadcasts(&[2015, 2018])?; + if let Some(mut optional_addrs) = optional_addrs.take() { + dests.append(&mut optional_addrs); + } let (camera_address, camera_id) = discoverer .retry_send_multi(msg, &dests, |bc, addr| match bc { UdpDiscovery { diff --git a/crates/core/src/bc_protocol/resolution.rs b/crates/core/src/bc_protocol/resolution.rs index 5c169cc..f442209 100644 --- a/crates/core/src/bc_protocol/resolution.rs +++ b/crates/core/src/bc_protocol/resolution.rs @@ -1,6 +1,7 @@ //! This is a helper module to resolve either to a UID or a SockerAddr use log::*; +use serde::{Deserialize, Serialize}; use std::{ io::Error, net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs}, @@ -10,29 +11,35 @@ use std::{ /// /// This is used for UID lookup, it is unused with /// TPC/known ip address cameras -#[derive(Debug, Copy, Clone)] +#[derive(Debug, Copy, Clone, Serialize, Deserialize)] pub enum DiscoveryMethods { /// Forbid all discovery methods. Only TCP connections with known addresses will work + #[serde(alias = "none")] None, /// Allow local discovery on the local network using broadcasts /// This method does NOT contact reolink servers + #[serde(alias = "local")] 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** + #[serde(alias = "remote")] Remote, /// 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** + #[serde(alias = "map")] 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** + #[serde(alias = "relay")] Relay, #[doc(hidden)] + #[serde(alias = "debug")] /// Used for debugging it is set to whatever the dev is currently testing Debug, } @@ -42,7 +49,7 @@ pub enum SocketAddrOrUid { /// When the result is a addr it will be this SocketAddr(SocketAddr), /// When the result is a UID - Uid(String, DiscoveryMethods), + Uid(String, Option>, DiscoveryMethods), } /// An extension of ToSocketAddrs that will also resolve to a camera UID @@ -83,6 +90,7 @@ impl ToSocketAddrsOrUid for str { if re.is_match(self) { Ok(vec![SocketAddrOrUid::Uid( self.to_string(), + None, DiscoveryMethods::Local, )] .into_iter()) @@ -110,6 +118,7 @@ impl ToSocketAddrsOrUid for String { if re.is_match(self) { Ok(vec![SocketAddrOrUid::Uid( self.to_string(), + None, DiscoveryMethods::Local, )] .into_iter()) diff --git a/src/config.rs b/src/config.rs index a6a8243..49b53b5 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,5 +1,5 @@ use lazy_static::lazy_static; -use neolink_core::bc_protocol::PrintFormat; +use neolink_core::bc_protocol::{DiscoveryMethods, PrintFormat}; use regex::Regex; use serde::Deserialize; use std::clone::Clone; @@ -11,8 +11,6 @@ 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|[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(); } @@ -82,12 +80,7 @@ pub(crate) struct CameraConfig { pub(crate) pause: PauseConfig, #[serde(default = "default_discovery")] - #[validate(regex( - path = "RE_DISC_SRC", - message = "Invalid discovery method", - code = "discovery" - ))] - pub(crate) discovery: String, + pub(crate) discovery: DiscoveryMethods, #[serde(default = "default_maxenc")] #[validate(regex( @@ -151,8 +144,8 @@ fn default_print() -> PrintFormat { PrintFormat::None } -fn default_discovery() -> String { - "Relay".to_string() +fn default_discovery() -> DiscoveryMethods { + DiscoveryMethods::Relay } fn default_maxenc() -> String { diff --git a/src/utils.rs b/src/utils.rs index 58f2a56..eff7bfc 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -10,11 +10,15 @@ use std::fmt::{Display, Error as FmtError, Formatter}; pub(crate) enum AddressOrUid { Address(String), Uid(String, DiscoveryMethods), + AddressWithUid(String, String, DiscoveryMethods), } impl Display for AddressOrUid { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> { match self { + AddressOrUid::AddressWithUid(addr, uid, _) => { + write!(f, "Address: {}, UID: {}", addr, uid) + } AddressOrUid::Address(host) => write!(f, "Address: {}", host), AddressOrUid::Uid(host, _) => write!(f, "UID: {}", host), } @@ -26,27 +30,17 @@ impl AddressOrUid { pub(crate) fn new( address: &Option, uid: &Option, - disc_method: &str, + method: &DiscoveryMethods, ) -> 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), Some(uid)) => Ok(AddressOrUid::AddressWithUid( + host.clone(), + uid.clone(), + *method, + )), (Some(host), None) => Ok(AddressOrUid::Address(host.clone())), - (None, Some(host)) => { - let method = match disc_method.to_lowercase().as_str() { - "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 - } - }; - Ok(AddressOrUid::Uid(host.clone(), method)) - } + (None, Some(host)) => Ok(AddressOrUid::Uid(host.clone(), *method)), } } @@ -59,6 +53,16 @@ impl AddressOrUid { aux_print_format: PrintFormat, ) -> Result { match self { + AddressOrUid::AddressWithUid(addr, uid, method) => Ok(BcCamera::new_with_uid_and_addr( + uid, + addr, + channel_id, + username, + passwd, + *method, + aux_print_format, + ) + .await?), AddressOrUid::Address(host) => { Ok( BcCamera::new_with_addr(host, channel_id, username, passwd, aux_print_format)