1use std::collections::BTreeSet;
11use std::io;
12use std::net::{IpAddr, Ipv4Addr, SocketAddr};
13
14use serde::Serialize;
15
16use crate::generic::Error;
17use crate::host::{self, Detail, Lookup};
18use crate::read::Reader;
19use crate::status::{self, Host};
20use crate::wlan::{self, Views};
21
22mod network;
23mod router;
24
25pub use network::{Fixed, Network, PROBE_TIMEOUT, Port, RESOLVE_TIMEOUT, System, is_private};
26pub use router::{ROUTER, router};
27
28pub const WEAK_SIGNAL: u8 = 30;
30
31const MAX_CANDIDATES: usize = 10;
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
36#[serde(rename_all = "lowercase")]
37pub enum Status {
38 Pass,
39 Fail,
40 Skip,
43 Unknown,
45}
46
47#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
49pub struct Check {
50 pub name: String,
52 pub status: Status,
53 pub detail: Option<String>,
55 pub hint: Option<String>,
57}
58
59impl Check {
60 pub(crate) fn new(name: impl Into<String>, status: Status, detail: Option<String>) -> Self {
61 Self {
62 name: name.into(),
63 status,
64 detail,
65 hint: None,
66 }
67 }
68
69 pub(crate) fn fail(name: impl Into<String>, detail: Option<String>, hint: String) -> Self {
71 Self {
72 hint: Some(hint),
73 ..Self::new(name, Status::Fail, detail)
74 }
75 }
76}
77
78#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
80pub struct Report {
81 pub target: String,
83 #[serde(skip_serializing_if = "Option::is_none")]
85 pub host: Option<Detail>,
86 pub checks: Vec<Check>,
87}
88
89impl Report {
90 #[must_use]
92 pub fn failures(&self) -> usize {
93 self.checks
94 .iter()
95 .filter(|c| c.status == Status::Fail)
96 .count()
97 }
98}
99
100#[derive(Debug, Clone, Default)]
102pub struct Options {
103 pub ports: Vec<u16>,
105 pub private_only: bool,
107}
108
109enum Found {
111 None,
112 One(Box<Detail>),
113 Many(Vec<Host>),
114}
115
116pub async fn host(
124 reader: &mut Reader,
125 network: &impl Network,
126 query: &str,
127 options: &Options,
128) -> Result<Report, Error> {
129 let mut report = Report {
130 target: query.to_owned(),
131 host: None,
132 checks: Vec::new(),
133 };
134 let detail = match find(reader, query).await? {
135 Found::One(detail) => *detail,
136 Found::None => {
137 let hint = format!(
138 "the device knows no host {query:?}; check the name, or give its MAC or IP address"
139 );
140 report.checks.push(Check::fail(KNOWN, None, hint));
141 return Ok(report);
142 }
143 Found::Many(hosts) => {
144 report.checks.push(ambiguous(&hosts));
145 return Ok(report);
146 }
147 };
148 let signal = signal(reader, &detail).await?;
149 report.checks = checks(&detail, signal, network, options).await;
150 report.host = Some(detail);
151 Ok(report)
152}
153
154const KNOWN: &str = "known to the device";
155const ACTIVE: &str = "active";
156const ADDRESS: &str = "address";
157const LINK: &str = "link";
158const RESOLVES: &str = "name resolves";
159const PORTS: &str = "ports";
160
161async fn find(reader: &mut Reader, query: &str) -> Result<Found, Error> {
163 if let Ok(lookup) = Lookup::mac(query).or_else(|_| Lookup::ip(query)) {
164 let detail = host::lookup(reader, &lookup).await?;
165 return Ok(detail.map_or(Found::None, |d| Found::One(Box::new(d))));
166 }
167 let hosts = status::hosts(reader).await?.hosts;
168 let mut named = host::named(hosts, query);
169 match named.len() {
170 0 => Ok(Found::None),
171 1 => {
172 let found = named.remove(0);
173 Ok(Found::One(Box::new(host::detail(reader, found).await?)))
174 }
175 _ => Ok(Found::Many(named)),
176 }
177}
178
179fn ambiguous(hosts: &[Host]) -> Check {
181 let names: Vec<String> = hosts
182 .iter()
183 .take(MAX_CANDIDATES)
184 .map(|h| {
185 let name = h.name.as_deref().unwrap_or("?");
186 let address = h.ip.as_deref().or(h.mac.as_deref()).unwrap_or("?");
187 format!("{name} ({address})")
188 })
189 .collect();
190 let more = hosts.len().saturating_sub(MAX_CANDIDATES);
191 let more = if more > 0 {
192 format!(" and {more} more")
193 } else {
194 String::new()
195 };
196 Check::fail(
197 KNOWN,
198 Some(format!("{} hosts match", hosts.len())),
199 format!(
200 "give one by its MAC or IP address: {}{more}",
201 names.join(", ")
202 ),
203 )
204}
205
206async fn signal(reader: &mut Reader, detail: &Detail) -> Result<Option<u8>, Error> {
209 let host = &detail.host;
210 let (true, Some(mac)) = (host.active && is_wireless(detail), host.mac.as_deref()) else {
211 return Ok(None);
212 };
213 let views = Views {
214 clients: true,
215 details: false,
216 };
217 let networks = wlan::wlans(reader, views).await?;
218 Ok(networks
219 .iter()
220 .flat_map(|n| n.clients.iter().flatten())
221 .find(|c| {
222 c.mac
223 .as_deref()
224 .is_some_and(|m| m.eq_ignore_ascii_case(mac))
225 })
226 .and_then(|c| c.signal))
227}
228
229fn is_wireless(detail: &Detail) -> bool {
231 link_kind(detail).as_deref() == Some("WLAN")
232}
233
234fn link_kind(detail: &Detail) -> Option<String> {
236 let attached = detail.attached_to.as_ref().and_then(|a| a.kind.clone());
237 attached.or_else(|| {
238 detail
239 .host
240 .interface
241 .as_deref()
242 .map(|interface| match interface {
243 "Ethernet" => "LAN".to_owned(),
244 "802.11" => "WLAN".to_owned(),
245 other => other.to_owned(),
246 })
247 })
248}
249
250async fn checks(
252 detail: &Detail,
253 signal: Option<u8>,
254 network: &impl Network,
255 options: &Options,
256) -> Vec<Check> {
257 let host = &detail.host;
258 let ip = host
259 .ip
260 .as_deref()
261 .and_then(|ip| ip.parse::<Ipv4Addr>().ok());
262 let mut checks = vec![
263 known(host),
264 active(host),
265 address(host, ip),
266 link(detail, signal),
267 ];
268 let name = host.name.as_deref().filter(|n| is_dns_name(n));
269 let resolved = match name {
270 Some(name) => Some(network.resolve(name).await),
271 None => None,
272 };
273 checks.push(resolution(host.name.as_deref(), ip, resolved));
274 checks.extend(ports(network, host.active, ip, options).await);
275 checks
276}
277
278fn known(host: &Host) -> Check {
279 let name = host.name.as_deref().unwrap_or("(no name)");
280 let detail = match &host.address_source {
281 Some(source) => format!("{name} ({source})"),
282 None => name.to_owned(),
283 };
284 Check::new(KNOWN, Status::Pass, Some(detail))
285}
286
287fn active(host: &Host) -> Check {
288 if host.active {
289 return Check::new(ACTIVE, Status::Pass, None);
290 }
291 Check::fail(
292 ACTIVE,
293 Some("not connected".to_owned()),
294 "the device does not see the host connected now: it is off, asleep, out of range or \
295 connected to another network"
296 .to_owned(),
297 )
298}
299
300fn address(host: &Host, ip: Option<Ipv4Addr>) -> Check {
301 let Some(ip) = ip else {
302 return match &host.ip {
303 Some(other) => Check::new(ADDRESS, Status::Unknown, Some(other.clone())),
304 None => Check::fail(
305 ADDRESS,
306 None,
307 "the device knows no IPv4 address of the host; it may not have asked for one by \
308 DHCP"
309 .to_owned(),
310 ),
311 };
312 };
313 let parts = [
314 Some(ip.to_string()),
315 host.address_source.clone(),
316 (!host.active).then(|| "last known".to_owned()),
317 ];
318 let detail = parts.into_iter().flatten().collect::<Vec<_>>().join(", ");
319 Check::new(ADDRESS, Status::Pass, Some(detail))
320}
321
322fn link(detail: &Detail, signal: Option<u8>) -> Check {
323 if !detail.host.active {
324 return Check::new(LINK, Status::Skip, Some("not connected".to_owned()));
325 }
326 let attached = detail.attached_to.as_ref();
327 let band = attached.and_then(|a| a.band.clone());
328 let kind = [link_kind(detail), band]
329 .into_iter()
330 .flatten()
331 .collect::<Vec<_>>()
332 .join(" ");
333 let node = attached.and_then(|a| a.node.as_deref());
334 let parts: Vec<String> = [
335 Some(kind).filter(|k| !k.is_empty()),
336 detail.host.speed.map(|s| format!("{s} Mbit/s")),
337 signal.map(|s| format!("signal {s}%")),
338 node.map(|n| format!("via {n}")),
339 ]
340 .into_iter()
341 .flatten()
342 .collect();
343 if parts.is_empty() {
344 return Check::new(LINK, Status::Unknown, None);
345 }
346 let text = Some(parts.join(", "));
347 match signal.filter(|s| *s < WEAK_SIGNAL) {
348 Some(weak) => Check::fail(
349 LINK,
350 text,
351 format!(
352 "the host is attached to {} with a weak signal of {weak}%; move it closer or add \
353 a repeater",
354 node.unwrap_or("the device")
355 ),
356 ),
357 None => Check::new(LINK, Status::Pass, text),
358 }
359}
360
361fn is_dns_name(name: &str) -> bool {
364 name.len() <= 253
365 && name.trim_end_matches('.').split('.').all(|label| {
366 !label.is_empty()
367 && label.len() <= 63
368 && label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
369 })
370}
371
372fn resolution(
373 name: Option<&str>,
374 ip: Option<Ipv4Addr>,
375 resolved: Option<io::Result<Vec<IpAddr>>>,
376) -> Check {
377 let Some(resolved) = resolved else {
378 let detail = match name {
379 Some(_) => "the name is not a DNS name",
380 None => "the host has no name",
381 };
382 return Check::new(RESOLVES, Status::Skip, Some(detail.to_owned()));
383 };
384 let addresses = resolved.unwrap_or_default();
385 let name = name.unwrap_or_default();
386 if addresses.is_empty() {
387 return Check::fail(
388 RESOLVES,
389 Some("does not resolve".to_owned()),
390 format!(
391 "{name} does not resolve on this machine; use the device as DNS server, or the \
392 address"
393 ),
394 );
395 }
396 let list = addresses
397 .iter()
398 .map(ToString::to_string)
399 .collect::<Vec<_>>()
400 .join(", ");
401 let Some(ip) = ip else {
402 return Check::new(RESOLVES, Status::Unknown, Some(list));
403 };
404 if addresses.contains(&IpAddr::V4(ip)) {
405 return Check::new(RESOLVES, Status::Pass, Some(ip.to_string()));
406 }
407 Check::fail(
408 RESOLVES,
409 Some(format!("{list} (device: {ip})")),
410 format!("DNS returns {list}, the device knows {ip}"),
411 )
412}
413
414async fn ports(
416 network: &impl Network,
417 active: bool,
418 ip: Option<Ipv4Addr>,
419 options: &Options,
420) -> Vec<Check> {
421 let skip = |detail: String| vec![Check::new(PORTS, Status::Skip, Some(detail))];
422 if options.ports.is_empty() {
423 return skip("no port given".to_owned());
424 }
425 if !active {
426 return skip("not connected".to_owned());
427 }
428 let Some(ip) = ip else {
429 return skip("no IPv4 address".to_owned());
430 };
431 if options.private_only && !is_private(IpAddr::V4(ip)) {
432 return skip(format!("{ip} is not a private address"));
433 }
434 let mut checks = Vec::new();
435 for port in options.ports.iter().copied().collect::<BTreeSet<u16>>() {
436 let state = network.connect(SocketAddr::new(IpAddr::V4(ip), port)).await;
437 checks.push(port_check(port, state));
438 }
439 checks
440}
441
442fn port_check(port: u16, state: Port) -> Check {
443 let name = format!("TCP {port}");
444 match state {
445 Port::Open => Check::new(name, Status::Pass, Some("open".to_owned())),
446 Port::Closed => Check::fail(
447 name,
448 Some("closed".to_owned()),
449 format!(
450 "the host refuses port {port}: the service is not running or listens on another port"
451 ),
452 ),
453 Port::Filtered => Check::fail(
454 name,
455 Some("filtered".to_owned()),
456 format!(
457 "no answer on port {port} within {} s: a firewall on the host drops it, or the \
458 host cannot be reached from here",
459 PROBE_TIMEOUT.as_secs()
460 ),
461 ),
462 }
463}
464
465#[cfg(test)]
466mod tests;