diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index f838bfc..bc2536e 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -126,6 +126,7 @@ impl BcCamera { /// Try to connect to the camera via appropaite methods and return /// the location that should be used async fn find_camera(options: &BcCameraOpt) -> Result { + let discovery = Discovery::new().await?; if let ConnectionProtocol::Tcp | ConnectionProtocol::TcpUdp = options.protocol { let mut sockets = vec![]; match options.port { @@ -145,7 +146,7 @@ impl BcCamera { info!("{}: Trying TCP discovery", options.name); for socket in sockets.drain(..) { let channel_id: u8 = options.channel_id; - if let Ok(addr) = Discovery::check_tcp(socket, channel_id).await.map(|_| { + if let Ok(addr) = discovery.check_tcp(socket, channel_id).await.map(|_| { info!("{}: TCP Discovery success at {:?}", options.name, &socket); socket }) { @@ -184,10 +185,16 @@ impl BcCamera { DiscoveryMethods::Debug => (false, false, false, true), }; + let reg_result = if allow_remote || allow_map || allow_relay { + Some(discovery.get_registration(uid).await?) + } else { + None + }; + if allow_local { let uid_local = uid.clone(); info!("{}: Trying local discovery", options.name); - let result = Discovery::local(&uid_local, Some(sockets)).await; + let result = discovery.local(&uid_local, Some(sockets)).await; if let Ok(disc) = result { info!( "{}: Local discovery success {} at {}", @@ -201,7 +208,9 @@ impl BcCamera { if allow_remote { let uid_remote = uid.clone(); info!("{}: Trying remote discovery", options.name); - let result = Discovery::remote(&uid_remote).await; + let result = discovery + .remote(&uid_remote, reg_result.as_ref().unwrap()) + .await; if let Ok(disc) = result { info!( "{}: Remote discovery success {} at {}", @@ -215,7 +224,7 @@ impl BcCamera { if allow_map { let uid_map = uid.clone(); info!("{}: Trying map discovery", options.name); - let result = Discovery::map(&uid_map).await; + let result = discovery.map(reg_result.as_ref().unwrap()).await; if let Ok(disc) = result { info!( "{}: Map success {} at {}", @@ -229,7 +238,7 @@ impl BcCamera { if allow_relay { let uid_relay = uid.clone(); info!("{}: Trying relay discovery", options.name); - let result = Discovery::relay(&uid_relay).await; + let result = discovery.relay(reg_result.as_ref().unwrap()).await; if let Ok(disc) = result { info!( "{}: Relay success {} at {}", diff --git a/crates/core/src/bc_protocol/connection/discovery.rs b/crates/core/src/bc_protocol/connection/discovery.rs index 0c6433c..e0f1c59 100644 --- a/crates/core/src/bc_protocol/connection/discovery.rs +++ b/crates/core/src/bc_protocol/connection/discovery.rs @@ -11,7 +11,7 @@ use crate::bcudp::xml::*; use crate::{Error, Result}; use futures::{ sink::SinkExt, - stream::{FuturesUnordered, StreamExt}, + stream::{FuturesUnordered, Stream, StreamExt}, }; use lazy_static::lazy_static; use local_ip_address::local_ip; @@ -34,7 +34,7 @@ use tokio_stream::wrappers::ReceiverStream; use tokio_util::udp::UdpFramed; #[derive(Debug, Clone)] -struct RegisterResult { +pub(crate) struct RegisterResult { reg: SocketAddr, dev: Option, dmap: Option, @@ -57,8 +57,6 @@ struct UidLookupResults { relay: SocketAddr, } -pub(crate) struct Discovery {} - const MTU: u32 = 1350; lazy_static! { static ref P2P_RELAY_HOSTNAMES: [&'static str; 10] = [ @@ -154,10 +152,8 @@ impl Discoverer { }) } - async fn into_socket(self) -> (Arc, JoinSet<()>) { - let socket = self.socket.clone(); - let handle = self.handle.into_inner(); - (socket, handle) + async fn get_socket(&self) -> Arc { + self.socket.clone() } async fn subscribe(&self, tid: u32) -> Result>> { @@ -214,32 +210,6 @@ impl Discoverer { &self.local_addr } - async fn retry_send_multi( - &self, - mut disc: UdpDiscovery, - dests: &[SocketAddr], - map: F, - ) -> Result - where - F: Fn(UdpDiscovery, SocketAddr) -> Option, - { - trace!("Retrying send"); - disc.tid = 0; // Must be random to avoid simulatenous subscription errors - let mut set = FuturesUnordered::new(); - for dest in dests.iter() { - set.push(self.retry_send(disc.clone(), *dest, &map)); - } - - // Get what ever completes first - while let Some(result) = set.next().await { - trace!("Result: {}", result.is_ok()); - if let Ok(ret) = result { - return Ok(ret); - } - } - Err(Error::DiscoveryTimeout) - } - async fn retry_send(&self, mut disc: UdpDiscovery, dest: SocketAddr, map: F) -> Result where F: Fn(UdpDiscovery, SocketAddr) -> Option, @@ -357,13 +327,10 @@ impl Discoverer { Ok(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 uid_loopup(&self, uid: &str) -> Result { + async fn uid_lookup_all<'a>( + &'a self, + uid: &'a str, + ) -> Result + 'a> { let task = tokio::task::spawn_blocking(move || { let mut addrs = vec![]; for p2p_relay in P2P_RELAY_HOSTNAMES.iter() { @@ -376,8 +343,22 @@ impl Discoverer { } addrs }); - let addrs = timeout(*MAXIMUM_WAIT, task).await??; + let mut addrs = timeout(*MAXIMUM_WAIT, task).await??; trace!("Uid lookup to: {:?}", addrs); + + Ok(addrs + .drain(..) + .map(|addr| self.uid_lookup(uid, addr)) + .collect::>() + .filter_map(|f| async { f.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 will returns an async iter that yields the M2cQr that the p2p relay + /// server has about the UID + async fn uid_lookup(&self, uid: &str, addr: SocketAddr) -> Result { let msg = UdpDiscovery { tid: 0, payload: UdpXml { @@ -390,7 +371,7 @@ impl Discoverer { }; trace!("Sending look up {:?}", msg); let (packet, _) = self - .retry_send_multi(msg, addrs.as_slice(), |bc, addr| match bc { + .retry_send(msg, addr, |bc, addr| match bc { UdpDiscovery { tid: _, payload: @@ -939,11 +920,49 @@ impl Discoverer { } } +pub(crate) struct Discovery { + discoverer: Discoverer, + client_id: i32, +} + impl Discovery { + pub(crate) async fn new() -> Result { + Ok(Self { + discoverer: Discoverer::new().await?, + client_id: generate_cid(), + }) + } + + pub(crate) async fn get_registration(&self, uid: &str) -> Result { + let lookups = self.discoverer.uid_lookup_all(uid).await?; + + let reg_result = Box::pin( + lookups + .then(|lookup| { + let discoverer = &self.discoverer; + let client_id = self.client_id; + async move { + trace!("lookup: {:?}", lookup); + let reg_result = discoverer.register_address(uid, client_id, &lookup).await; + trace!("reg_result: {:?}", reg_result); + reg_result + } + }) + .filter_map(|f| async { f.ok() }), + ) + .next() + .await + .ok_or(Error::Other( + "No reolink registers returned valid device data.", + ))?; + + Ok(reg_result) + } + // Check if TCP is possible // // To do this we send a dummy login and see if it replies with any BC packet - pub(crate) async fn check_tcp(addr: SocketAddr, channel_id: u8) -> Result<()> { + pub(crate) async fn check_tcp(&self, addr: SocketAddr, channel_id: u8) -> Result<()> { let username = "admin"; let password = Some("123456"); let mut tcp_source = @@ -979,18 +998,17 @@ impl Discovery { // Perform UDP broadcast lookup and connection pub(crate) async fn local( + &self, uid: &str, mut optional_addrs: Option>, ) -> Result { - let discoverer = Discoverer::new().await?; - - let client_id = generate_cid(); let mut dests = get_broadcasts(&[2015, 2018])?; if let Some(mut optional_addrs) = optional_addrs.take() { trace!("Also sending to {:?}", optional_addrs); dests.append(&mut optional_addrs); } - let discoverer_ref = &discoverer; + let discoverer_ref = &self.discoverer; + let client_id = self.client_id; let mut futures = FuturesUnordered::new(); for addr in dests.iter().copied() { futures.push(async move { @@ -1018,10 +1036,9 @@ impl Discovery { drop(futures); // drop(discoverer_ref); - let (socket, keep_alive_tasks) = discoverer.into_socket().await; + let socket = self.discoverer.get_socket().await; Ok(DiscoveryResult { socket, - keep_alive_tasks, addr: connect_result.addr, camera_id: connect_result.camera_id, client_id: connect_result.client_id, @@ -1039,33 +1056,22 @@ impl Discovery { // 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 { + pub(crate) async fn remote( + &self, + uid: &str, + reg_result: &RegisterResult, + ) -> Result { trace!("Start remote"); - let mut 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 connect_result = tokio::select! { - v = discoverer.client_initiated_dev(®_result) => {v}, - v = discoverer.device_initiated_dev(®_result) => {v}, + v = self.discoverer.client_initiated_dev(reg_result) => {v}, + v = self.discoverer.device_initiated_dev(reg_result) => {v}, }?; trace!("connect_result: {:?}", connect_result); - - let (socket, keep_alive_tasks) = discoverer.into_socket().await; + let socket = self.discoverer.get_socket().await; Ok(DiscoveryResult { socket, - keep_alive_tasks, addr: connect_result.addr, - client_id, + client_id: self.client_id, camera_id: connect_result.camera_id, }) } @@ -1078,27 +1084,15 @@ impl Discovery { // // 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 { - 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.device_initiated_map(®_result).await?; + pub(crate) async fn map(&self, reg_result: &RegisterResult) -> Result { + let connect_result = self.discoverer.device_initiated_map(reg_result).await?; trace!("connect_result: {:?}", connect_result); - let (socket, keep_alive_tasks) = discoverer.into_socket().await; + let socket = self.discoverer.get_socket().await; Ok(DiscoveryResult { socket, - keep_alive_tasks, addr: connect_result.addr, - client_id, + client_id: self.client_id, camera_id: connect_result.camera_id, }) } @@ -1108,27 +1102,15 @@ impl Discovery { // 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 { - 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(®_result).await?; + pub(crate) async fn relay(&self, reg_result: &RegisterResult) -> Result { + let connect_result = self.discoverer.client_initiated_relay(reg_result).await?; trace!("connect_result: {:?}", connect_result); - let (socket, keep_alive_tasks) = discoverer.into_socket().await; + let socket = self.discoverer.get_socket().await; Ok(DiscoveryResult { socket, - keep_alive_tasks, addr: connect_result.addr, - client_id, + client_id: self.client_id, camera_id: connect_result.camera_id, }) } diff --git a/crates/core/src/bc_protocol/connection/mod.rs b/crates/core/src/bc_protocol/connection/mod.rs index ff44166..44ac1be 100644 --- a/crates/core/src/bc_protocol/connection/mod.rs +++ b/crates/core/src/bc_protocol/connection/mod.rs @@ -6,7 +6,7 @@ //! use std::net::SocketAddr; use std::sync::Arc; -use tokio::{net::UdpSocket, task::JoinSet}; +use tokio::net::UdpSocket; mod bcconn; mod bcsub; @@ -22,16 +22,11 @@ pub(crate) use self::{ pub(crate) struct DiscoveryResult { socket: Arc, addr: SocketAddr, - keep_alive_tasks: JoinSet<()>, client_id: i32, camera_id: i32, } impl DiscoveryResult { - /// Stop all keep alive and any remaining tasks that the discover is managing - pub(crate) async fn shutdown(&mut self) { - self.keep_alive_tasks.shutdown().await; - } /// Get the address discovered pub(crate) fn get_addr(&self) -> &SocketAddr { &self.addr diff --git a/crates/core/src/bc_protocol/connection/udpsource.rs b/crates/core/src/bc_protocol/connection/udpsource.rs index bebd910..1c9d030 100644 --- a/crates/core/src/bc_protocol/connection/udpsource.rs +++ b/crates/core/src/bc_protocol/connection/udpsource.rs @@ -49,13 +49,12 @@ impl UdpSource { Self::new_from_socket(stream, addr, client_id, camera_id, username, password).await } pub(crate) async fn new_from_discovery, U: Into>( - mut discovery: DiscoveryResult, + discovery: DiscoveryResult, username: T, password: Option, ) -> Result { // Ensure that the discovery keep alive are all stopped here // We now handle all coms in UdpSource - discovery.shutdown().await; Self::new_from_socket( discovery.socket, discovery.addr,