Skip to main content

dahua_camera_discovery/
lib.rs

1//! Finding cameras on the LAN: WS-Discovery, Dahua discovery, IP-range scan.
2//!
3//! Three mechanisms, because no single one finds everything:
4//!
5//! | Mechanism | Finds | Misses |
6//! |---|---|---|
7//! | [`ws_discovery`] | Anything speaking ONVIF | Cameras with ONVIF disabled; anything across a router |
8//! | [`dahua`] | Dahua devices, including ONVIF-disabled ones | Other vendors; anything across a router |
9//! | [`scan`] | Anything with an open port, across subnets | Nothing — but it is slow and noisy |
10//!
11//! Both multicast mechanisms are **link-local**: they do not cross a router,
12//! which on a vehicle LAN is usually fine and occasionally the whole problem.
13//! The range scan is the fallback for when it is not.
14//!
15//! # Discovery finds addresses, not access
16//!
17//! A discovered camera is a *candidate*. Nothing here authenticates, and
18//! nothing here fills in a working [`CameraConfig`](dahua_camera_core::CameraConfig)
19//! — credentials come from the environment or the keyring, never from the
20//! network. A [`Discovered`] is something to show an operator, who then says
21//! which of them to configure.
22
23#![warn(missing_docs)]
24#![forbid(unsafe_code)]
25
26pub mod dahua;
27pub mod scan;
28pub mod ws_discovery;
29
30use serde::{Deserialize, Serialize};
31use std::net::IpAddr;
32use std::time::Duration;
33
34/// How long to listen for replies before giving up.
35///
36/// Multicast discovery has no "done" — devices answer whenever they feel like
37/// it, and a busy camera can take a second or more. Three seconds catches
38/// essentially everything without making an operator wait.
39pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(3);
40
41/// How a device was found.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
43#[serde(rename_all = "snake_case")]
44pub enum DiscoveryMethod {
45    /// WS-Discovery multicast probe (ONVIF).
46    WsDiscovery,
47    /// Dahua's own UDP discovery broadcast.
48    Dahua,
49    /// A port scan across a configured address range.
50    Scan,
51}
52
53/// A candidate camera found on the network.
54///
55/// Deliberately thin. Discovery reports what a device *volunteered*; anything
56/// more requires credentials, which discovery does not have.
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
58pub struct Discovered {
59    /// Where it answered from.
60    pub address: IpAddr,
61    /// How it was found.
62    pub method: DiscoveryMethod,
63    /// Manufacturer, if it said.
64    #[serde(skip_serializing_if = "Option::is_none", default)]
65    pub manufacturer: Option<String>,
66    /// Model, if it said.
67    #[serde(skip_serializing_if = "Option::is_none", default)]
68    pub model: Option<String>,
69    /// Serial number, if it said.
70    #[serde(skip_serializing_if = "Option::is_none", default)]
71    pub serial: Option<String>,
72    /// ONVIF service URLs it advertised.
73    #[serde(default, skip_serializing_if = "Vec::is_empty")]
74    pub service_urls: Vec<String>,
75}
76
77impl Discovered {
78    /// A bare result with only an address and a method.
79    pub fn at(address: IpAddr, method: DiscoveryMethod) -> Self {
80        Self {
81            address,
82            method,
83            manufacturer: None,
84            model: None,
85            serial: None,
86            service_urls: Vec::new(),
87        }
88    }
89
90    /// A stable identifier suggestion, derived from what the device reported.
91    ///
92    /// Only a *suggestion*: ids appear in URLs and log fields, and the operator
93    /// naming a camera "front" is more useful than `dahua-7a03c41pag00123`.
94    pub fn suggested_id(&self) -> String {
95        let base = self
96            .serial
97            .as_deref()
98            .or(self.model.as_deref())
99            .map(|s| s.to_ascii_lowercase())
100            .unwrap_or_else(|| self.address.to_string());
101
102        base.chars()
103            .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
104            .collect::<String>()
105            .trim_matches('-')
106            .to_owned()
107    }
108}
109
110/// Merge results from several mechanisms, preferring the richest entry per
111/// address.
112///
113/// A camera commonly answers both WS-Discovery and Dahua discovery, and one
114/// reply usually carries more detail than the other. Reporting it twice would
115/// make an operator wonder whether there are two cameras.
116pub fn merge(results: impl IntoIterator<Item = Discovered>) -> Vec<Discovered> {
117    let mut by_address: std::collections::BTreeMap<IpAddr, Discovered> =
118        std::collections::BTreeMap::new();
119
120    for found in results {
121        by_address
122            .entry(found.address)
123            .and_modify(|existing| {
124                if detail_score(&found) > detail_score(existing) {
125                    *existing = found.clone();
126                }
127            })
128            .or_insert(found);
129    }
130
131    by_address.into_values().collect()
132}
133
134/// A value unlikely to repeat within a device's replay window.
135#[cfg(feature = "net")]
136fn fresh_id() -> u128 {
137    std::time::SystemTime::now()
138        .duration_since(std::time::UNIX_EPOCH)
139        .unwrap_or_default()
140        .as_nanos()
141}
142
143/// How much a result actually tells us.
144fn detail_score(found: &Discovered) -> usize {
145    found.manufacturer.is_some() as usize
146        + found.model.is_some() as usize
147        + found.serial.is_some() as usize
148        + !found.service_urls.is_empty() as usize
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154    use std::net::Ipv4Addr;
155
156    fn ip(last: u8) -> IpAddr {
157        IpAddr::V4(Ipv4Addr::new(192, 168, 50, last))
158    }
159
160    #[test]
161    fn a_bare_result_carries_only_what_was_observed() {
162        let found = Discovered::at(ip(101), DiscoveryMethod::Dahua);
163        assert_eq!(found.manufacturer, None);
164        assert!(found.service_urls.is_empty());
165    }
166
167    #[test]
168    fn merging_collapses_one_camera_answering_two_probes() {
169        let sparse = Discovered::at(ip(101), DiscoveryMethod::WsDiscovery);
170        let rich = Discovered {
171            manufacturer: Some("Dahua".into()),
172            model: Some("IPC-HDW1230T".into()),
173            serial: Some("7A03C41PAG00123".into()),
174            ..Discovered::at(ip(101), DiscoveryMethod::Dahua)
175        };
176
177        let merged = merge([sparse, rich]);
178        assert_eq!(merged.len(), 1, "one camera, one entry");
179        assert_eq!(merged[0].model.as_deref(), Some("IPC-HDW1230T"), "the richer reply wins");
180    }
181
182    #[test]
183    fn merging_keeps_distinct_addresses_apart() {
184        let merged = merge([
185            Discovered::at(ip(101), DiscoveryMethod::Dahua),
186            Discovered::at(ip(102), DiscoveryMethod::Dahua),
187        ]);
188        assert_eq!(merged.len(), 2);
189    }
190
191    #[test]
192    fn merged_results_are_ordered_by_address_so_listings_are_stable() {
193        let merged = merge([
194            Discovered::at(ip(103), DiscoveryMethod::Scan),
195            Discovered::at(ip(101), DiscoveryMethod::Scan),
196            Discovered::at(ip(102), DiscoveryMethod::Scan),
197        ]);
198        let addresses: Vec<_> = merged.iter().map(|d| d.address).collect();
199        assert_eq!(addresses, [ip(101), ip(102), ip(103)]);
200    }
201
202    #[test]
203    fn a_richer_reply_does_not_lose_to_a_later_sparse_one() {
204        let rich = Discovered {
205            serial: Some("ABC".into()),
206            ..Discovered::at(ip(101), DiscoveryMethod::Dahua)
207        };
208        let merged = merge([rich, Discovered::at(ip(101), DiscoveryMethod::WsDiscovery)]);
209        assert_eq!(merged[0].serial.as_deref(), Some("ABC"));
210    }
211
212    #[test]
213    fn suggested_ids_are_url_safe() {
214        let found = Discovered {
215            serial: Some("7A03/C41 PAG:00123".into()),
216            ..Discovered::at(ip(101), DiscoveryMethod::Dahua)
217        };
218        let id = found.suggested_id();
219        assert!(id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'), "{id}");
220        assert!(!id.starts_with('-') && !id.ends_with('-'), "{id}");
221    }
222
223    #[test]
224    fn a_device_that_said_nothing_falls_back_to_its_address() {
225        assert_eq!(Discovered::at(ip(101), DiscoveryMethod::Scan).suggested_id(), "192-168-50-101");
226    }
227
228    #[test]
229    fn a_result_round_trips_through_json() {
230        let found = Discovered {
231            manufacturer: Some("Dahua".into()),
232            service_urls: vec!["http://192.168.50.101/onvif/device_service".into()],
233            ..Discovered::at(ip(101), DiscoveryMethod::WsDiscovery)
234        };
235        let json = serde_json::to_string(&found).expect("serialises");
236        let back: Discovered = serde_json::from_str(&json).expect("deserialises");
237        assert_eq!(found, back);
238    }
239
240    #[test]
241    fn absent_fields_are_omitted_rather_than_serialised_as_null() {
242        let json = serde_json::to_value(Discovered::at(ip(101), DiscoveryMethod::Scan))
243            .expect("serialises");
244        assert!(json.get("manufacturer").is_none(), "{json}");
245        assert!(json.get("service_urls").is_none(), "{json}");
246    }
247}
248
249/// Every usable local IPv4 address, one per interface.
250///
251/// # Why this exists
252///
253/// A socket bound to `0.0.0.0` sends a broadcast or multicast datagram out
254/// **one** interface — whichever the routing table calls default. On a host
255/// with more than one network that is very often the wrong one, and the
256/// symptom is total silence from cameras that are demonstrably reachable.
257///
258/// This is the normal case, not an edge case: a panel PC has the camera LAN
259/// plus Wi-Fi, a VPN, and whatever virtual adapters Docker or WSL installed.
260/// So discovery probes from **every** interface and merges the answers.
261///
262/// Loopback and link-local (`169.254.x.x`) addresses are skipped: nothing
263/// answers on the first, and the second means DHCP failed on that adapter.
264#[cfg(feature = "net")]
265pub fn local_ipv4_interfaces() -> Vec<std::net::Ipv4Addr> {
266    let Ok(interfaces) = if_addrs::get_if_addrs() else { return Vec::new() };
267
268    let mut addresses: Vec<std::net::Ipv4Addr> = interfaces
269        .into_iter()
270        .filter(|interface| !interface.is_loopback())
271        .filter_map(|interface| match interface.addr.ip() {
272            IpAddr::V4(v4) if !v4.is_link_local() && !v4.is_unspecified() => Some(v4),
273            _ => None,
274        })
275        .collect();
276
277    addresses.sort();
278    addresses.dedup();
279    addresses
280}
281
282/// The subnet-directed broadcast address for an interface.
283///
284/// Windows will sometimes drop `255.255.255.255` on a non-default interface
285/// while happily delivering `192.168.50.255`, so both are used.
286#[cfg(feature = "net")]
287pub fn subnet_broadcast(address: std::net::Ipv4Addr, prefix_len: u8) -> std::net::Ipv4Addr {
288    let bits = u32::from(address);
289    let host_mask = if prefix_len >= 32 { 0 } else { u32::MAX >> prefix_len };
290    std::net::Ipv4Addr::from(bits | host_mask)
291}
292
293#[cfg(all(test, feature = "net"))]
294mod interface_tests {
295    use super::*;
296    use std::net::Ipv4Addr;
297
298    #[test]
299    fn a_slash_24_broadcast_is_the_last_address() {
300        assert_eq!(
301            subnet_broadcast(Ipv4Addr::new(192, 168, 50, 23), 24),
302            Ipv4Addr::new(192, 168, 50, 255)
303        );
304    }
305
306    #[test]
307    fn a_slash_16_broadcast_covers_both_host_octets() {
308        assert_eq!(
309            subnet_broadcast(Ipv4Addr::new(172, 24, 128, 1), 16),
310            Ipv4Addr::new(172, 24, 255, 255)
311        );
312    }
313
314    #[test]
315    fn a_slash_32_has_no_host_bits_to_set() {
316        let single = Ipv4Addr::new(10, 0, 0, 5);
317        assert_eq!(subnet_broadcast(single, 32), single);
318    }
319
320    /// Loopback answers nothing, and 169.254.x.x means DHCP failed on that
321    /// adapter — probing either is pure delay.
322    #[test]
323    fn enumeration_skips_loopback_and_link_local() {
324        for address in local_ipv4_interfaces() {
325            assert!(!address.is_loopback(), "{address}");
326            assert!(!address.is_link_local(), "{address}");
327        }
328    }
329}