1use std::future::IntoFuture as _;
44use std::io;
45use std::net::{Ipv4Addr, SocketAddr};
46use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
47use std::time::Duration;
48
49use axum::Router;
50use axum::extract::State;
51use axum::http::header::{AUTHORIZATION, CONTENT_TYPE, WWW_AUTHENTICATE};
52use axum::http::{HeaderMap, Method, StatusCode, Uri};
53use axum::response::{IntoResponse, Response};
54use tokio::task::JoinHandle;
55use tr064::{ClientBuilder, Fingerprint, SecretString, Service, Url};
56
57mod auth;
58mod device;
59mod fixture;
60mod soap;
61mod tls;
62mod web;
63
64use device::{Device, Fault, Hooks, short_id};
65pub use fixture::{Answer, Error, Fixture};
66use tls::TlsListener;
67use web::Web;
68
69pub const USERNAME: &str = "fritz-sim";
71pub const PASSWORD: &str = "fritz-sim-password";
73
74const XML: &str = r#"text/xml; charset="utf-8""#;
75
76#[derive(Debug, Clone)]
78pub struct Options {
79 pub address: SocketAddr,
81 pub username: String,
82 pub password: String,
83 pub https: bool,
86}
87
88impl Default for Options {
89 fn default() -> Self {
92 Self {
93 address: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
94 username: USERNAME.to_owned(),
95 password: PASSWORD.to_owned(),
96 https: false,
97 }
98 }
99}
100
101#[derive(Debug, Clone, PartialEq, Eq)]
104#[non_exhaustive]
105pub enum Injection {
106 Fault {
110 service: String,
111 action: String,
112 code: u16,
113 },
114 Delay(Duration),
116 DiscardWrites,
118 LockLogin,
121}
122
123impl Injection {
124 pub fn fault(service: impl Into<String>, action: impl Into<String>, code: u16) -> Self {
126 Self::Fault {
127 service: service.into(),
128 action: action.into(),
129 code,
130 }
131 }
132}
133
134#[derive(Debug, Clone, PartialEq, Eq)]
136pub struct Request {
137 pub method: String,
138 pub path: String,
139 pub action: Option<String>,
141 pub arguments: Vec<(String, String)>,
143 pub authorized: bool,
145}
146
147#[derive(Debug)]
149pub struct Sim {
150 url: Url,
151 fingerprint: Option<Fingerprint>,
152 shared: Arc<Shared>,
153 server: JoinHandle<io::Result<()>>,
154}
155
156impl Sim {
157 pub async fn start(fixture: Fixture) -> io::Result<Self> {
164 Self::start_with(fixture, Options::default()).await
165 }
166
167 pub async fn start_with(fixture: Fixture, options: Options) -> io::Result<Self> {
173 let listener = tokio::net::TcpListener::bind(options.address).await?;
174 let scheme = if options.https { "https" } else { "http" };
175 let url = Url::parse(&format!("{scheme}://{}", listener.local_addr()?))
176 .map_err(io::Error::other)?;
177 let https = options.https;
178 let shared = Arc::new(Shared {
179 options,
180 inner: Mutex::new(Inner {
181 device: Device::new(fixture),
182 web: Web::default(),
183 injections: Vec::new(),
184 requests: Vec::new(),
185 }),
186 });
187 let app = Router::new()
188 .fallback(handle)
189 .with_state(Arc::clone(&shared));
190 let (server, fingerprint) = if https {
191 let (listener, fingerprint) = TlsListener::new(listener);
192 let server = tokio::spawn(axum::serve(listener, app).into_future());
193 (server, Some(fingerprint))
194 } else {
195 (tokio::spawn(axum::serve(listener, app).into_future()), None)
196 };
197 Ok(Self {
198 url,
199 fingerprint,
200 shared,
201 server,
202 })
203 }
204
205 pub fn url(&self) -> &Url {
207 &self.url
208 }
209
210 pub fn fingerprint(&self) -> Option<Fingerprint> {
212 self.fingerprint
213 }
214
215 pub fn client(&self) -> ClientBuilder {
218 let options = &self.shared.options;
219 let builder = tr064::Client::builder(self.url.clone()).credentials(
220 options.username.clone(),
221 SecretString::from(options.password.clone()),
222 );
223 match self.fingerprint {
224 Some(fingerprint) => builder.pin(fingerprint),
225 None => builder,
226 }
227 }
228
229 pub fn inject(&self, injection: Injection) {
231 self.shared.lock().injections.push(injection);
232 }
233
234 pub fn clear_injections(&self) {
236 self.shared.lock().injections.clear();
237 }
238
239 pub fn requests(&self) -> Vec<Request> {
241 self.shared.lock().requests.clone()
242 }
243
244 pub fn state(&self, service: &str, variable: &str) -> Option<String> {
248 let inner = self.shared.lock();
249 let service = inner.device.fixture.description.service(service).ok()?;
250 inner
251 .device
252 .state(short_id(service), variable)
253 .map(str::to_owned)
254 }
255}
256
257impl Drop for Sim {
258 fn drop(&mut self) {
259 self.server.abort();
260 }
261}
262
263#[derive(Debug)]
264struct Shared {
265 options: Options,
266 inner: Mutex<Inner>,
267}
268
269#[derive(Debug)]
270struct Inner {
271 device: Device,
272 web: Web,
273 injections: Vec<Injection>,
274 requests: Vec<Request>,
275}
276
277impl Shared {
278 fn lock(&self) -> MutexGuard<'_, Inner> {
279 self.inner.lock().unwrap_or_else(PoisonError::into_inner)
280 }
281
282 fn respond(
284 &self,
285 method: &Method,
286 uri: &Uri,
287 headers: &HeaderMap,
288 body: &str,
289 ) -> (Response, Duration) {
290 let mut inner = self.lock();
291 let path = uri.path();
292 let call = (method == Method::POST)
293 .then(|| soap::parse(body))
294 .flatten();
295 let locked = inner.injections.contains(&Injection::LockLogin);
296 let authorized = !locked
297 && auth::verify(
298 headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok()),
299 &auth::Expected {
300 username: &self.options.username,
301 password: &self.options.password,
302 nonce: NONCE,
303 method: method.as_str(),
304 uri: uri.path_and_query().map_or(path, |p| p.as_str()),
305 },
306 );
307 inner.requests.push(Request {
308 method: method.to_string(),
309 path: path.to_owned(),
310 action: call.as_ref().map(|c| c.action.clone()),
311 arguments: call.as_ref().map_or_default(|c| c.arguments.clone()),
312 authorized,
313 });
314 let delay = inner
315 .injections
316 .iter()
317 .map(|i| match i {
318 Injection::Delay(delay) => *delay,
319 _ => Duration::ZERO,
320 })
321 .sum();
322 let response = match *method {
323 _ if path == web::LOGIN => inner.web.login(method, body, &self.options, locked),
324 _ if path.starts_with(web::API) => {
325 let Inner { web, device, .. } = &*inner;
326 web.api(&device.fixture.api, method, path, headers)
327 }
328 Method::GET => inner.document(path, uri.query()),
329 Method::POST if !authorized => (
330 StatusCode::UNAUTHORIZED,
331 [(WWW_AUTHENTICATE, auth::challenge(NONCE))],
332 )
333 .into_response(),
334 Method::POST => inner.control(path, headers, call),
335 _ => StatusCode::METHOD_NOT_ALLOWED.into_response(),
336 };
337 (response, delay)
338 }
339}
340
341const NONCE: &str = "F1A2B3C4D5E6F708";
344
345const SESSION: &str = "5e55104d0c0ffee5";
348
349impl Inner {
350 fn document(&self, path: &str, query: Option<&str>) -> Response {
353 let fixture = &self.device.fixture;
354 let name = path.trim_start_matches('/');
355 if let Some(list) = name
356 .strip_suffix(".lua")
357 .and_then(|stem| fixture.lists.get(stem))
358 {
359 let session = query
360 .into_iter()
361 .flat_map(|q| q.split('&'))
362 .any(|p| p == format!("sid={SESSION}"));
363 return if session {
364 list.clone().into_response()
365 } else {
366 StatusCode::FORBIDDEN.into_response()
367 };
368 }
369 let xml = match name {
370 "tr64desc.xml" => Some(&fixture.description_xml),
371 name => fixture.scpds.get(name).map(|(xml, _)| xml),
372 };
373 match xml {
374 Some(xml) => ([(CONTENT_TYPE, XML)], xml.clone()).into_response(),
375 None => StatusCode::NOT_FOUND.into_response(),
376 }
377 }
378
379 fn control(&mut self, path: &str, headers: &HeaderMap, call: Option<soap::Call>) -> Response {
381 let service = self
382 .device
383 .fixture
384 .description
385 .services()
386 .find(|s| s.control_url == path)
387 .cloned();
388 let Some(service) = service else {
389 return StatusCode::NOT_FOUND.into_response();
390 };
391 let Some(call) = call else {
392 return StatusCode::BAD_REQUEST.into_response();
393 };
394 let soap_action = headers
395 .get("SOAPAction")
396 .and_then(|v| v.to_str().ok())
397 .unwrap_or_default()
398 .trim_matches('"');
399 let expected = format!("{}#{}", service.service_type, call.action);
400 let result = if soap_action == expected && call.service_type == service.service_type {
401 let hooks = self.hooks(&service, &call.action);
402 self.device
403 .call(&service, &call.action, &call.arguments, &hooks)
404 } else {
405 Err(Fault::new(401))
406 };
407 match result {
408 Ok(mut out) => {
409 for (_, value) in &mut out {
410 *value = value.replace("sid=***", &format!("sid={SESSION}"));
411 }
412 let xml = soap::response(&service.service_type, &call.action, &out);
413 ([(CONTENT_TYPE, XML)], xml).into_response()
414 }
415 Err(fault) => (
416 StatusCode::INTERNAL_SERVER_ERROR,
417 [(CONTENT_TYPE, XML)],
418 soap::fault(&fault),
419 )
420 .into_response(),
421 }
422 }
423
424 fn hooks(&self, service: &Service, action: &str) -> Hooks {
425 let fault = self.injections.iter().find_map(|i| match i {
426 Injection::Fault {
427 service: reference,
428 action: name,
429 code,
430 } if name == action && service.matches(reference) => Some(Fault::new(*code)),
431 _ => None,
432 });
433 Hooks {
434 fault,
435 discard_writes: self.injections.contains(&Injection::DiscardWrites),
436 }
437 }
438}
439
440async fn handle(
441 State(shared): State<Arc<Shared>>,
442 method: Method,
443 uri: Uri,
444 headers: HeaderMap,
445 body: String,
446) -> Response {
447 let (response, delay) = shared.respond(&method, &uri, &headers, &body);
448 tokio::time::sleep(delay).await;
449 response
450}
451
452#[cfg(test)]
453mod tests {
454 use super::*;
455
456 const FIXTURE: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/fixtures/fritzbox-7690/8.25");
457 const WLAN: &str = "urn:dslforum-org:service:WLANConfiguration:1";
458 const CONTROL: &str = "/upnp/control/wlanconfig1";
459
460 fn inner() -> Inner {
461 Inner {
462 device: Device::new(Fixture::load(FIXTURE).unwrap()),
463 web: Web::default(),
464 injections: Vec::new(),
465 requests: Vec::new(),
466 }
467 }
468
469 fn call(service_type: &str) -> soap::Call {
471 soap::Call {
472 service_type: service_type.to_owned(),
473 action: "GetInfo".to_owned(),
474 arguments: Vec::new(),
475 }
476 }
477
478 fn soap_action(value: &str) -> HeaderMap {
479 let mut headers = HeaderMap::new();
480 headers.insert("SOAPAction", value.parse().unwrap());
481 headers
482 }
483
484 #[test]
485 fn answers_calls_that_match_the_service() {
486 let headers = soap_action(&format!("\"{WLAN}#GetInfo\""));
487 let response = inner().control(CONTROL, &headers, Some(call(WLAN)));
488 assert_eq!(response.status(), StatusCode::OK);
489 }
490
491 #[test]
492 fn rejects_calls_that_do_not_match_the_service() {
493 let mut inner = inner();
494 let right = soap_action(&format!("{WLAN}#GetInfo"));
495 let wrong = soap_action(&format!("{WLAN}#SetEnable"));
496 for (headers, service_type) in [
497 (&wrong, WLAN),
498 (&HeaderMap::new(), WLAN),
499 (&right, "urn:other"),
500 ] {
501 let response = inner.control(CONTROL, headers, Some(call(service_type)));
502 assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
503 }
504 let response = inner.control("/upnp/control/missing", &right, Some(call(WLAN)));
505 assert_eq!(response.status(), StatusCode::NOT_FOUND);
506 let response = inner.control(CONTROL, &right, None);
507 assert_eq!(response.status(), StatusCode::BAD_REQUEST);
508 }
509
510 #[test]
511 fn allows_only_get_and_post() {
512 let shared = Shared {
513 options: Options::default(),
514 inner: Mutex::new(inner()),
515 };
516 let uri = Uri::from_static("/tr64desc.xml");
517 let (response, delay) = shared.respond(&Method::PUT, &uri, &HeaderMap::new(), "");
518 assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED);
519 assert_eq!(delay, Duration::ZERO);
520 assert_eq!(shared.lock().requests[0].method, "PUT");
521 }
522}