1use std::net::IpAddr;
8
9use serde::Serialize;
10
11use crate::status::Right;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
15#[serde(rename_all = "lowercase")]
16pub enum Status {
17 Ok,
18 Warn,
20 Fail,
21 Skip,
23}
24
25impl Status {
26 pub fn name(self) -> &'static str {
28 match self {
29 Self::Ok => "ok",
30 Self::Warn => "warn",
31 Self::Fail => "fail",
32 Self::Skip => "skip",
33 }
34 }
35}
36
37#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
40pub struct Check {
41 pub check: &'static str,
43 pub status: Status,
44 pub detail: String,
45 #[serde(skip_serializing_if = "Option::is_none")]
46 pub hint: Option<String>,
47}
48
49impl Check {
50 pub fn ok(check: &'static str, detail: impl Into<String>) -> Self {
51 Self::new(check, Status::Ok, detail.into(), None)
52 }
53
54 pub fn skip(check: &'static str, detail: impl Into<String>) -> Self {
55 Self::new(check, Status::Skip, detail.into(), None)
56 }
57
58 pub fn warn(check: &'static str, detail: impl Into<String>, hint: impl Into<String>) -> Self {
59 Self::new(check, Status::Warn, detail.into(), Some(hint.into()))
60 }
61
62 pub fn fail(check: &'static str, detail: impl Into<String>, hint: impl Into<String>) -> Self {
63 Self::new(check, Status::Fail, detail.into(), Some(hint.into()))
64 }
65
66 fn new(check: &'static str, status: Status, detail: String, hint: Option<String>) -> Self {
67 Self {
68 check,
69 status,
70 detail,
71 hint,
72 }
73 }
74
75 pub fn failed(&self) -> bool {
77 self.status == Status::Fail
78 }
79}
80
81pub fn is_local(ip: IpAddr) -> bool {
84 match ip {
85 IpAddr::V4(ip) => ip.is_loopback() || ip.is_private() || ip.is_link_local(),
86 IpAddr::V6(ip) => match ip.to_ipv4_mapped() {
87 Some(ip) => is_local(IpAddr::V4(ip)),
88 None => ip.is_loopback() || ip.is_unique_local() || ip.is_unicast_link_local(),
89 },
90 }
91}
92
93pub fn host(name: &'static str, host: &str, addresses: &[IpAddr]) -> Check {
97 let local: Vec<String> = addresses
98 .iter()
99 .filter(|ip| is_local(**ip))
100 .map(ToString::to_string)
101 .collect();
102 let public = addresses.len() - local.len();
103 let hint = "set --host to the local address of the device, like 192.168.178.1";
104 if addresses.is_empty() {
105 return Check::fail(name, format!("{host} does not resolve"), hint);
106 }
107 if local.is_empty() {
108 let detail = format!("{host} resolves only to public addresses");
109 return Check::fail(name, detail, hint);
110 }
111 let also = match public {
112 0 => String::new(),
113 n => format!(" and {n} public"),
114 };
115 Check::ok(name, format!("{host} is {}{also}", local.join(", ")))
116}
117
118const NEEDS: [(&str, &str, Status); 3] = [
121 (
122 "BoxAdmin",
123 "most commands, like overview, hosts, wlan and internet",
124 Status::Fail,
125 ),
126 ("Phone", "telephony, calls and phonebook", Status::Warn),
127 ("HomeAuto", "smarthome", Status::Warn),
128];
129
130pub fn rights(name: &'static str, rights: &[Right]) -> Check {
133 if rights.is_empty() {
134 return Check::skip(name, "the device reports no rights for the user");
135 }
136 let has = |area: &str| {
137 rights
138 .iter()
139 .any(|r| r.area == area && !r.access.is_empty() && r.access != "none")
140 };
141 let covered = |area: &str| has(area) || (area == "Phone" && has("BoxAdmin"));
142 let missing: Vec<_> = NEEDS.iter().filter(|(area, ..)| !covered(area)).collect();
143 let all: Vec<String> = rights
144 .iter()
145 .map(|r| format!("{}: {}", r.area, r.access))
146 .collect();
147 if missing.is_empty() {
148 return Check::ok(name, all.join(", "));
149 }
150 let detail = missing
151 .iter()
152 .map(|(area, commands, _)| format!("{area} missing, needed by {commands}"))
153 .collect::<Vec<_>>()
154 .join("; ");
155 let hint = "give the user these rights in System > FRITZ!Box Users, see docs/box-setup.md";
156 if missing.iter().any(|(.., status)| *status == Status::Fail) {
157 Check::fail(name, detail, hint)
158 } else {
159 Check::warn(name, detail, hint)
160 }
161}
162
163pub fn two_factor(name: &'static str, enabled: Option<bool>, changes: bool) -> Check {
166 match (enabled, changes) {
167 (None, _) => Check::skip(name, "the device does not report it"),
168 (Some(false), _) => Check::ok(name, "off: changes need no confirmation on the device"),
169 (Some(true), false) => Check::ok(
170 name,
171 "on: some changes need a confirmation on the device; reads are not affected",
172 ),
173 (Some(true), true) => Check::warn(
174 name,
175 "on: some changes need a confirmation on the device, which fritz never gives",
176 "such changes fail with confirmation_required; make them in the web interface",
177 ),
178 }
179}
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184
185 fn right(area: &str, access: &str) -> Right {
186 Right {
187 area: area.to_owned(),
188 access: access.to_owned(),
189 }
190 }
191
192 #[test]
193 fn tells_local_from_public_addresses() {
194 for ip in [
195 "127.0.0.1",
196 "192.168.178.1",
197 "10.0.0.1",
198 "169.254.1.1",
199 "::1",
200 "fd00::1",
201 "fe80::1",
202 "::ffff:192.168.178.1",
203 ] {
204 assert!(is_local(ip.parse().unwrap()), "{ip}");
205 }
206 for ip in ["8.8.8.8", "2001:db8::1", "::ffff:8.8.8.8"] {
207 assert!(!is_local(ip.parse().unwrap()), "{ip}");
208 }
209 }
210
211 #[test]
212 fn checks_the_host() {
213 let local = "192.168.178.1".parse().unwrap();
214 let public = "203.0.113.1".parse().unwrap();
215 let check = host("Host", "fritz.box", &[local, public]);
216 assert_eq!(check.status, Status::Ok);
217 assert_eq!(check.detail, "fritz.box is 192.168.178.1 and 1 public");
218 assert_eq!(host("Host", "box", &[local]).detail, "box is 192.168.178.1");
219 let check = host("Host", "box.example", &[public]);
220 assert!(check.failed());
221 assert!(!check.detail.contains("203.0.113.1"), "{}", check.detail);
222 let check = host("Host", "box.example", &[]);
223 assert_eq!(check.detail, "box.example does not resolve");
224 assert!(check.hint.unwrap().contains("--host"));
225 }
226
227 #[test]
228 fn checks_the_rights() {
229 let all = [right("BoxAdmin", "readwrite"), right("HomeAuto", "read")];
230 let check = rights("Rights", &all);
231 assert_eq!(check.status, Status::Ok);
232 assert_eq!(check.detail, "BoxAdmin: readwrite, HomeAuto: read");
233
234 let check = rights("Rights", &[right("BoxAdmin", "readwrite")]);
235 assert_eq!(check.status, Status::Warn);
236 assert_eq!(check.detail, "HomeAuto missing, needed by smarthome");
237
238 let check = rights("Rights", &[right("HomeAuto", "readwrite")]);
239 assert!(check.failed());
240 assert_eq!(
241 check.detail,
242 "BoxAdmin missing, needed by most commands, like overview, hosts, wlan and \
243 internet; Phone missing, needed by telephony, calls and phonebook"
244 );
245 let check = rights("Rights", &[right("BoxAdmin", "none")]);
246 assert!(check.failed());
247 assert_eq!(rights("Rights", &[]).status, Status::Skip);
248 }
249
250 #[test]
251 fn checks_the_second_factor() {
252 assert_eq!(two_factor("2FA", None, true).status, Status::Skip);
253 assert_eq!(two_factor("2FA", Some(false), true).status, Status::Ok);
254 assert_eq!(two_factor("2FA", Some(true), false).status, Status::Ok);
255 let check = two_factor("2FA", Some(true), true);
256 assert_eq!(check.status, Status::Warn);
257 assert!(check.hint.is_some());
258 }
259
260 #[test]
261 fn names_the_statuses() {
262 let names: Vec<_> = [Status::Ok, Status::Warn, Status::Fail, Status::Skip]
263 .iter()
264 .map(|s| s.name())
265 .collect();
266 assert_eq!(names, ["ok", "warn", "fail", "skip"]);
267 let json = serde_json::to_value(Check::warn("Host", "detail", "hint")).unwrap();
268 assert_eq!(
269 json,
270 serde_json::json!({"check": "Host", "status": "warn", "detail": "detail", "hint": "hint"})
271 );
272 }
273}