diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index db68f96..5583ebd 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -2,7 +2,7 @@ use crate::bc; use futures::stream::StreamExt; use log::*; use serde::{Deserialize, Serialize}; -use std::net::ToSocketAddrs; +use std::net::{IpAddr, SocketAddr}; use std::{ collections::HashMap, sync::atomic::{AtomicBool, AtomicU16, Ordering}, @@ -32,7 +32,7 @@ mod time; mod version; pub(crate) use connection::*; -pub(crate) use credentials::*; +pub use credentials::*; pub use errors::Error; pub use ledstate::LightState; pub use login::MaxEncryption; @@ -65,7 +65,31 @@ pub struct BcCamera { abilities: RwLock>, } -/// Used to choode the print format of various status messages like battery levels +/// Options used to construct a camera +#[derive(Debug)] +pub struct BcCameraOpt { + /// Name, mostly used for message logs + pub name: String, + /// Channel the camera is on 0 unless using a NVR + pub channel_id: u8, + /// IPs of the camera + pub addrs: Vec, + /// The UID of the camera + pub uid: Option, + /// Port to try optional. When not given all known BC ports will be tried + /// When given all known bc port AND the given port will be tried + pub port: Option, + /// Protocol decides if UDP/TCP are used for the camera + pub protocol: ConnectionProtocol, + /// Discovery method to allow + pub discovery: DiscoveryMethods, + /// Printing format for auxilaary data such as battery levels + pub aux_printing: PrintFormat, + /// Credentials for login + pub credentials: Credentials, +} + +/// Used to choose the print format of various status messages like battery levels /// /// Currently this is just the format of battery levels but if we ever got more status /// messages then they will also use this information @@ -79,303 +103,236 @@ pub enum PrintFormat { Xml, } +/// Type of connection to try +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +pub enum ConnectionProtocol { + /// TCP and UDP + TcpUdp, + /// TCP only + Tcp, + /// Udp only + Udp, +} + +impl Default for ConnectionProtocol { + fn default() -> Self { + ConnectionProtocol::TcpUdp + } +} + +enum CameraLocation { + Tcp(SocketAddr), + Udp(DiscoveryResult), +} + impl BcCamera { - /// - /// Create a new camera interface with this address and channel ID - /// - /// # Parameters - /// - /// * `host` - The address of the camera either ip address or hostname string - /// - /// * `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_addr, W: Into>( - host: U, - channel_id: u8, - username: V, - passwd: Option, - aux_info_format: PrintFormat, - ) -> Result { - let username: String = username.into(); - let passwd: Option = passwd.map(|t| t.into()); - let addr_iter = match host.to_socket_addrs() { - Ok(iter) => iter, - Err(_) => return Err(Error::AddrResolutionError), - }; - for addr in addr_iter { - if let Ok(cam) = Self::new( - SocketAddrOrUid::SocketAddr(addr), - channel_id, - &username, - passwd.as_ref(), - aux_info_format, - ) - .await - { - return Ok(cam); + /// 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 mut tcp_set = tokio::task::JoinSet::new(); + let mut local_set = tokio::task::JoinSet::new(); + let mut remote_set = tokio::task::JoinSet::new(); + let mut map_set = tokio::task::JoinSet::new(); + let mut relay_set = tokio::task::JoinSet::new(); + + if let ConnectionProtocol::Tcp | ConnectionProtocol::TcpUdp = options.protocol { + let mut sockets = vec![]; + match options.port { + Some(9000) | None => { + for addr in options.addrs.iter() { + sockets.push(SocketAddr::new(*addr, 9000)); + } + } + Some(n) => { + for addr in options.addrs.iter() { + sockets.push(SocketAddr::new(*addr, n)); + sockets.push(SocketAddr::new(*addr, 9000)); + } + } + } + for socket in sockets.drain(..) { + let channel_id: u8 = options.channel_id; + let name: String = options.name.clone(); + tcp_set.spawn(async move { + Discovery::check_tcp(socket, channel_id).await.map(|_| { + info!("{}: TCP Discovery success at {:?}", name, &socket); + socket + }) + }); } } + if let (Some(uid), ConnectionProtocol::Udp | ConnectionProtocol::TcpUdp) = + (options.uid.as_ref(), options.protocol) + { + let mut sockets = vec![]; + match options.port { + None => { + for addr in options.addrs.iter() { + sockets.push(SocketAddr::new(*addr, 2018)); + sockets.push(SocketAddr::new(*addr, 2015)); + } + } + Some(2015) => { + for addr in options.addrs.iter() { + sockets.push(SocketAddr::new(*addr, 2018)); + } + } + Some(2018) => { + for addr in options.addrs.iter() { + sockets.push(SocketAddr::new(*addr, 2015)); + } + } + Some(n) => { + for addr in options.addrs.iter() { + sockets.push(SocketAddr::new(*addr, n)); + sockets.push(SocketAddr::new(*addr, 2015)); + sockets.push(SocketAddr::new(*addr, 2018)); + } + } + } + let (allow_local, allow_remote, allow_map, allow_relay) = match options.discovery { + 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), + }; + + if allow_local { + let uid_local = uid.clone(); + let name: String = options.name.clone(); + local_set.spawn(async move { + trace!("{}: Starting Local discovery", name); + let result = Discovery::local(&uid_local, Some(sockets)).await; + if let Ok(disc) = &result { + info!( + "{}: Local discovery success {} at {}", + name, + uid_local, + disc.get_addr() + ); + } + result + }); + } + if allow_remote { + let uid_remote = uid.clone(); + let name: String = options.name.clone(); + remote_set.spawn(async move { + trace!("Starting Remote discovery"); + let result = Discovery::remote(&uid_remote).await; + if let Ok(disc) = &result { + info!( + "{}: Remote discovery success {} at {}", + name, + uid_remote, + disc.get_addr() + ); + } + result + }); + } + if allow_map { + let uid_map = uid.clone(); + let name: String = options.name.clone(); + map_set.spawn(async move { + trace!("Starting Map"); + let result = Discovery::map(&uid_map).await; + if let Ok(disc) = &result { + info!("{}: Map success {} at {}", name, uid_map, disc.get_addr()); + } + result + }); + } + if allow_relay { + let uid_relay = uid.clone(); + let name: String = options.name.clone(); + relay_set.spawn(async move { + trace!("Starting Relay"); + let result = Discovery::relay(&uid_relay).await; + if let Ok(disc) = &result { + info!( + "{}: Relay success {} at {}", + name, + uid_relay, + disc.get_addr() + ); + } + result + }); + } + } + + // Wait for all TCP to finish + while let Some(result) = tcp_set.join_next().await { + if let Ok(Ok(addr)) = result { + return Ok(CameraLocation::Tcp(addr)); + } + } + // Tcp failed see if Local faired any better + // Wait for all local to finish + while let Some(result) = local_set.join_next().await { + if let Ok(Ok(discovery)) = result { + return Ok(CameraLocation::Udp(discovery)); + } + } + // Local failed see if Remote faired any better + // Wait for all remote to finish + while let Some(result) = remote_set.join_next().await { + if let Ok(Ok(discovery)) = result { + return Ok(CameraLocation::Udp(discovery)); + } + } + // Remote failed see if Map faired any better + // Wait for all Map to finish + while let Some(result) = map_set.join_next().await { + if let Ok(Ok(discovery)) = result { + return Ok(CameraLocation::Udp(discovery)); + } + } + // Map failed see if Relay faired any better + // Wait for all Relay to finish + while let Some(result) = relay_set.join_next().await { + if let Ok(Ok(discovery)) = result { + return Ok(CameraLocation::Udp(discovery)); + } + } + // Nothing works Err(Error::CannotInitCamera) } /// - /// Create a new camera interface with this uid and channel ID + /// Create a new camera interface /// /// # Parameters /// - /// * `uid` - The uid of the camera - /// - /// * `channel_id` - The channel ID this is usually zero unless using a NVR + /// * `options` - Camera information see [`BcCameraOpt] /// /// # Returns /// /// returns either an error or the camera /// - pub async fn new_with_uid, V: Into>( - uid: &str, - channel_id: u8, - username: U, - passwd: Option, - discovery_method: DiscoveryMethods, - aux_info_format: PrintFormat, - ) -> Result { - Self::new( - SocketAddrOrUid::Uid(uid.to_string(), None, discovery_method), - channel_id, - username, - passwd, - aux_info_format, - ) - .await - } + pub async fn new(options: BcCameraOpt) -> Result { + let username: String = options.credentials.username.clone(); + let passwd: Option = options.credentials.password.clone(); - /// - /// 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, - aux_info_format, - ) - .await - } - - /// - /// Create a new camera interface with this address/uid and channel ID - /// - /// This method will first perform hostname resolution on the address - /// then fallback to uid if that resolution fails. - /// - /// Be aware that it is possible (although unlikely) that there is - /// a dns entry with the same address as the uid. If uncertain use - /// one of the other methods. - /// - /// # Parameters - /// - /// * `host` - The address of the camera either ip address, hostname string, or uid - /// - /// * `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_addr_or_uid, W: Into>( - host: U, - channel_id: u8, - username: V, - passwd: Option, - aux_info_format: PrintFormat, - ) -> Result { - let addr_iter = match host.to_socket_addrs_or_uid() { - Ok(iter) => iter, - Err(_) => return Err(Error::AddrResolutionError), - }; - let username: String = username.into(); - let passwd: Option = passwd.map(|t| t.into()); - for addr_or_uid in addr_iter { - if let Ok(cam) = Self::new( - addr_or_uid, - channel_id, - &username, - passwd.as_ref(), - aux_info_format, - ) - .await - { - return Ok(cam); - } - } - - Err(Error::CannotInitCamera) - } - - /// - /// Create a new camera interface with this address/uid and channel ID - /// - /// # Parameters - /// - /// * `addr` - An enum of [`SocketAddrOrUid`] that contains the address - /// - /// * `channel_id` - The channel ID this is usually zero unless using a NVR - /// - /// * `username` - The username to login with - /// - /// * `passed` - The password to login with required for AES encrypted camera - /// - /// # Returns - /// - /// returns either an error or the camera - /// - pub async fn new, V: Into>( - addr: SocketAddrOrUid, - channel_id: u8, - username: U, - passwd: Option, - aux_info_format: PrintFormat, - ) -> Result { - let username: String = username.into(); - let passwd: Option = passwd.map(|t| t.into()); - - let (sink, source): (BcConnSink, BcConnSource) = match addr { - SocketAddrOrUid::SocketAddr(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, optional_addrs, method) => { - trace!("Trying uid {}", uid); - // TODO Make configurable - 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 = { - let mut set = tokio::task::JoinSet::new(); - if allow_local { - let uid_local = uid.clone(); - set.spawn(async move { - trace!("Starting Local discovery"); - let result = Discovery::local(&uid_local, optional_addrs).await; - if let Ok(disc) = &result { - info!( - "Local discovery success {} at {}", - uid_local, - disc.get_addr() - ); - } - result - }); - } - if allow_remote { - let uid_remote = uid.clone(); - set.spawn(async move { - trace!("Starting Remote discovery"); - let result = Discovery::remote(&uid_remote).await; - if let Ok(disc) = &result { - info!( - "Remote discovery success {} at {}", - uid_remote, - disc.get_addr() - ); - } - 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 { - trace!("Starting Relay"); - let result = Discovery::relay(&uid_relay).await; - if let Ok(disc) = &result { - info!("Relay success {} at {}", uid_relay, disc.get_addr()); - } - result - }); - } - - let last_result; - loop { - match set.join_next().await { - Some(Ok(Ok(disc))) => { - last_result = Ok(disc); - break; - } - Some(Ok(Err(e))) => { - debug!("Discovery Error: {:?}", e); - } - Some(Err(join_error)) => { - last_result = Err(Error::OtherString(format!( - "Panic while joining Discovery threads: {:?}", - join_error - ))); - break; - } - None => { - last_result = Err(Error::DiscoveryTimeout); - break; - } - } - } - last_result - }?; - let (x, r) = UdpSource::new_from_discovery(discovery, &username, passwd.as_ref()) - .await? - .split(); - (Box::new(x), Box::new(r)) + let (sink, source): (BcConnSink, BcConnSource) = { + match BcCamera::find_camera(&options).await? { + CameraLocation::Tcp(addr) => { + let (x, r) = TcpSource::new(addr, &username, passwd.as_ref()) + .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(); + (Box::new(x), Box::new(r)) + } } }; @@ -385,7 +342,7 @@ impl BcCamera { let me = Self { connection: Arc::new(conn), message_num: AtomicU16::new(0), - channel_id, + channel_id: options.channel_id, logged_in: AtomicBool::new(false), credentials: Credentials::new(username, passwd), abilities: Default::default(), diff --git a/crates/core/src/bc_protocol/connection/discovery.rs b/crates/core/src/bc_protocol/connection/discovery.rs index 7f733f8..d7a67cd 100644 --- a/crates/core/src/bc_protocol/connection/discovery.rs +++ b/crates/core/src/bc_protocol/connection/discovery.rs @@ -3,6 +3,8 @@ //! Given a UID find the associated IP //! use super::DiscoveryResult; +use crate::bc::model::*; +use crate::bc_protocol::{md5_string, Md5Trunc, TcpSource}; use crate::bcudp::codex::BcUdpCodex; use crate::bcudp::model::*; use crate::bcudp::xml::*; @@ -70,6 +72,10 @@ lazy_static! { "p2p14.reolink.com", "p2p15.reolink.com", ]; + /// Maximum wait for a reply + static ref MAXIMUM_WAIT: Duration = Duration::from_secs(5); + /// How long to wait before resending + static ref RESEND_WAIT: Duration = Duration::from_millis(500); } type Subscriber = Arc>>>>; @@ -234,9 +240,8 @@ impl Discoverer { let mut reply = ReceiverStream::new(self.subscribe(target_tid).await?); let msg = BcUdp::Discovery(disc); - let maximum_wait = Duration::from_secs(60); - let resend_wait = Duration::from_millis(500); - let mut inter = interval(resend_wait); + + let mut inter = interval(*RESEND_WAIT); let result = tokio::select! { v = async { @@ -261,7 +266,7 @@ impl Discoverer { } => {Err::(v)}, _ = { // Sleep then emit Timeout - tokio::time::sleep(maximum_wait) + tokio::time::sleep(*MAXIMUM_WAIT) } => { Err::(Error::DiscoveryTimeout) } @@ -760,6 +765,42 @@ impl Discoverer { } impl Discovery { + // 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<()> { + let username = "admin"; + let password = Some("123456"); + let mut tcp_source = TcpSource::new(addr, username, password).await?; + + let md5_username = md5_string(username, Md5Trunc::ZeroLast); + let md5_password = password + .map(|p| md5_string(p, Md5Trunc::ZeroLast)) + .unwrap_or_else(|| EMPTY_LEGACY_PASSWORD.to_owned()); + + tcp_source + .send(Bc { + meta: BcMeta { + msg_id: MSG_ID_LOGIN, + channel_id, + msg_num: 0, + stream_type: 0, + response_code: 0x00, + class: 0x6514, + }, + body: BcBody::LegacyMsg(LegacyMsg::LoginMsg { + username: md5_username, + password: md5_password, + }), + }) + .await?; + + let _bc: Bc = tokio::time::timeout(Duration::from_secs(10), tcp_source.next()) + .await? + .ok_or(Error::CannotInitCamera)??; // Successful recv should mean a Bc packet if not then deser will fail + Ok(()) + } + // Perform UDP broadcast lookup and connection pub(crate) async fn local( uid: &str, @@ -789,6 +830,7 @@ impl Discovery { 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 (camera_address, camera_id) = discoverer diff --git a/crates/core/src/bc_protocol/credentials.rs b/crates/core/src/bc_protocol/credentials.rs index 6a0c1e8..ccff7e2 100644 --- a/crates/core/src/bc_protocol/credentials.rs +++ b/crates/core/src/bc_protocol/credentials.rs @@ -2,11 +2,13 @@ use std::convert::TryInto; -/// Used for caching the credentials +/// Used for caching and supplying the credentials #[derive(Clone)] -pub(crate) struct Credentials { - pub(crate) username: String, - pub(crate) password: Option, +pub struct Credentials { + /// The username to login to the camera with + pub username: String, + /// The password to use for login. Some camera allow this to be ommited + pub password: Option, } impl Default for Credentials { diff --git a/src/mqtt/event_cam.rs b/src/mqtt/event_cam.rs index c2fa812..5ce2cc6 100644 --- a/src/mqtt/event_cam.rs +++ b/src/mqtt/event_cam.rs @@ -158,12 +158,7 @@ impl EventCam { camera_config.name, camera_addr ); let camera = camera_addr - .connect_camera( - camera_config.channel_id, - &camera_config.username, - camera_config.password.as_ref(), - camera_config.print_format, - ) + .connect_camera(camera_config) .await .with_context(|| { format!( diff --git a/src/rtsp/states/mod.rs b/src/rtsp/states/mod.rs index 3cfe7c0..6f3daa7 100644 --- a/src/rtsp/states/mod.rs +++ b/src/rtsp/states/mod.rs @@ -62,20 +62,12 @@ impl RtspCamera { })?; info!("{}: Connecting to camera at {}", config.name, camera_addr); - let camera = camera_addr - .connect_camera( - config.channel_id, - &config.username, - config.password.as_ref(), - config.print_format, + let camera = camera_addr.connect_camera(config).await.with_context(|| { + format!( + "Failed to connect to camera {} at {} on channel {}", + config.name, camera_addr, config.channel_id ) - .await - .with_context(|| { - format!( - "Failed to connect to camera {} at {} on channel {}", - config.name, camera_addr, config.channel_id - ) - })?; + })?; let mut streams: HashSet = Default::default(); if ["all", "both", "mainStream", "mainstream"] diff --git a/src/utils.rs b/src/utils.rs index eff7bfc..c870648 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -4,8 +4,14 @@ use log::*; use super::config::{CameraConfig, Config}; use anyhow::{anyhow, Context, Error, Result}; -use neolink_core::bc_protocol::{BcCamera, DiscoveryMethods, MaxEncryption, PrintFormat}; -use std::fmt::{Display, Error as FmtError, Formatter}; +use neolink_core::bc_protocol::{ + BcCamera, BcCameraOpt, ConnectionProtocol, DiscoveryMethods, MaxEncryption, Credentials, +}; +use std::{ + fmt::{Display, Error as FmtError, Formatter}, + net::{IpAddr, ToSocketAddrs}, + str::FromStr, +}; pub(crate) enum AddressOrUid { Address(String), @@ -45,40 +51,51 @@ impl AddressOrUid { } // Convience method to get the BcCamera with the appropiate method - pub(crate) async fn connect_camera, U: Into>( + // from a camera_config + pub(crate) async fn connect_camera( &self, - channel_id: u8, - username: T, - passwd: Option, - aux_print_format: PrintFormat, + camera_config: &CameraConfig, ) -> 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) - .await?, - ) + let (port, addrs) = { + if let Some(addr_str) = camera_config.camera_addr.as_ref() { + match addr_str.to_socket_addrs() { + Ok(addr_iter) => { + let mut port = None; + let mut ipaddrs = vec![]; + for addr in addr_iter { + port = Some(addr.port()); + ipaddrs.push(addr.ip()); + } + Ok((port, ipaddrs)) + } + Err(_) => match IpAddr::from_str(addr_str) { + Ok(ip) => Ok((None, vec![ip])), + Err(_) => Err(anyhow!("Could not parse address in config")), + }, + } + } else { + Ok((None, vec![])) } - AddressOrUid::Uid(host, method) => Ok(BcCamera::new_with_uid( - host, - channel_id, - username, - passwd, - *method, - aux_print_format, - ) - .await?), - } + }?; + + let options = BcCameraOpt { + name: camera_config.name.clone(), + channel_id: camera_config.channel_id, + addrs, + port, + uid: camera_config.camera_uid.clone(), + protocol: ConnectionProtocol::TcpUdp, + discovery: camera_config.discovery, + aux_printing: camera_config.print_format, + credentials: Credentials { + username: camera_config.username.clone(), + password: camera_config.password.clone(), + }, + }; + + trace!("Camera Info: {:?}", options); + + Ok(BcCamera::new(options).await?) } } @@ -100,12 +117,7 @@ pub(crate) async fn connect_and_login(camera_config: &CameraConfig) -> Result