1use std::future::IntoFuture as _;
54use std::io;
55use std::net::{Ipv4Addr, SocketAddr};
56use std::pin::Pin;
57use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
58use std::task::{Context, Poll};
59use std::time::Duration;
60
61use axum::Router;
62use axum::body::{Body, Bytes, HttpBody};
63use axum::extract::State;
64use axum::http::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, WWW_AUTHENTICATE};
65use axum::http::{HeaderMap, Method, StatusCode, Uri};
66use axum::response::{IntoResponse, Response};
67use tokio::task::JoinHandle;
68use tr064::{ClientBuilder, Fingerprint, SecretString, Service, Url};
69
70mod auth;
71mod callmonitor;
72mod device;
73pub mod dns;
74mod fixture;
75mod soap;
76mod tls;
77mod web;
78
79pub use callmonitor::CallMonitor;
80use device::{Device, Fault, Hooks, short_id};
81pub use fixture::{Answer, Error, Fixture};
82use tls::TlsListener;
83use web::Web;
84
85pub const USERNAME: &str = "fritz-sim";
87pub const PASSWORD: &str = "fritz-sim-password";
89
90const XML: &str = r#"text/xml; charset="utf-8""#;
91
92#[derive(Debug, Clone)]
94pub struct Options {
95 pub address: SocketAddr,
97 pub username: String,
98 pub password: String,
99 pub https: bool,
102}
103
104impl Default for Options {
105 fn default() -> Self {
108 Self {
109 address: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
110 username: USERNAME.to_owned(),
111 password: PASSWORD.to_owned(),
112 https: false,
113 }
114 }
115}
116
117#[derive(Debug, Clone, PartialEq, Eq)]
120#[non_exhaustive]
121pub enum Injection {
122 Fault {
126 service: String,
127 action: String,
128 code: u16,
129 },
130 Delay(Duration),
132 DiscardWrites,
134 SideEffect {
138 service: String,
139 action: String,
140 variable: String,
141 value: String,
142 },
143 LockLogin,
146 Counter {
150 service: String,
151 variable: String,
152 step: u64,
153 wrap: Option<u64>,
154 },
155 Disconnect { service: String, action: String },
158 Truncate { service: String, action: String },
162 Reboot { down: u32, serial: Option<String> },
168 FailPage {
172 page: String,
173 field: String,
174 value: String,
175 },
176}
177
178impl Injection {
179 pub fn disconnect(service: impl Into<String>, action: impl Into<String>) -> Self {
181 Self::Disconnect {
182 service: service.into(),
183 action: action.into(),
184 }
185 }
186
187 pub fn truncate(service: impl Into<String>, action: impl Into<String>) -> Self {
189 Self::Truncate {
190 service: service.into(),
191 action: action.into(),
192 }
193 }
194
195 pub fn reboot(down: u32) -> Self {
198 Self::Reboot { down, serial: None }
199 }
200
201 pub fn fail_page(
203 page: impl Into<String>,
204 field: impl Into<String>,
205 value: impl Into<String>,
206 ) -> Self {
207 Self::FailPage {
208 page: page.into(),
209 field: field.into(),
210 value: value.into(),
211 }
212 }
213
214 pub fn fault(service: impl Into<String>, action: impl Into<String>, code: u16) -> Self {
216 Self::Fault {
217 service: service.into(),
218 action: action.into(),
219 code,
220 }
221 }
222
223 pub fn side_effect(
226 service: impl Into<String>,
227 action: impl Into<String>,
228 variable: impl Into<String>,
229 value: impl Into<String>,
230 ) -> Self {
231 Self::SideEffect {
232 service: service.into(),
233 action: action.into(),
234 variable: variable.into(),
235 value: value.into(),
236 }
237 }
238
239 pub fn counter(
242 service: impl Into<String>,
243 variable: impl Into<String>,
244 step: u64,
245 wrap: Option<u64>,
246 ) -> Self {
247 Self::Counter {
248 service: service.into(),
249 variable: variable.into(),
250 step,
251 wrap,
252 }
253 }
254}
255
256#[derive(Debug, Clone, PartialEq, Eq)]
258pub struct Request {
259 pub method: String,
260 pub path: String,
261 pub action: Option<String>,
263 pub arguments: Vec<(String, String)>,
265 pub authorized: bool,
267}
268
269#[derive(Debug)]
271pub struct Sim {
272 url: Url,
273 fingerprint: Option<Fingerprint>,
274 shared: Arc<Shared>,
275 server: JoinHandle<io::Result<()>>,
276}
277
278impl Sim {
279 pub async fn start(fixture: Fixture) -> io::Result<Self> {
286 Self::start_with(fixture, Options::default()).await
287 }
288
289 pub async fn start_with(fixture: Fixture, options: Options) -> io::Result<Self> {
295 let listener = tokio::net::TcpListener::bind(options.address).await?;
296 let scheme = if options.https { "https" } else { "http" };
297 let url = Url::parse(&format!("{scheme}://{}", listener.local_addr()?))
298 .map_err(io::Error::other)?;
299 let https = options.https;
300 let shared = Arc::new(Shared {
301 options,
302 inner: Mutex::new(Inner {
303 web: Web::new(&fixture.pages),
304 device: Device::new(fixture),
305 injections: Vec::new(),
306 requests: Vec::new(),
307 down: 0,
308 }),
309 });
310 let app = Router::new()
311 .fallback(handle)
312 .with_state(Arc::clone(&shared));
313 let (server, fingerprint) = if https {
314 let (listener, fingerprint) = TlsListener::new(listener);
315 let server = tokio::spawn(axum::serve(listener, app).into_future());
316 (server, Some(fingerprint))
317 } else {
318 (tokio::spawn(axum::serve(listener, app).into_future()), None)
319 };
320 Ok(Self {
321 url,
322 fingerprint,
323 shared,
324 server,
325 })
326 }
327
328 pub fn url(&self) -> &Url {
330 &self.url
331 }
332
333 pub fn fingerprint(&self) -> Option<Fingerprint> {
335 self.fingerprint
336 }
337
338 pub fn client(&self) -> ClientBuilder {
341 let options = &self.shared.options;
342 let builder = tr064::Client::builder(self.url.clone()).credentials(
343 options.username.clone(),
344 SecretString::from(options.password.clone()),
345 );
346 match self.fingerprint {
347 Some(fingerprint) => builder.pin(fingerprint),
348 None => builder,
349 }
350 }
351
352 pub fn inject(&self, injection: Injection) {
354 self.shared.lock().injections.push(injection);
355 }
356
357 pub fn clear_injections(&self) {
359 self.shared.lock().injections.clear();
360 }
361
362 pub fn requests(&self) -> Vec<Request> {
364 self.shared.lock().requests.clone()
365 }
366
367 pub fn log_filter(&self) -> Option<String> {
371 self.shared.lock().web.log_filter().map(str::to_owned)
372 }
373
374 pub fn state(&self, service: &str, variable: &str) -> Option<String> {
378 let inner = self.shared.lock();
379 let service = inner.device.fixture.description.service(service).ok()?;
380 inner
381 .device
382 .state(short_id(service), variable)
383 .map(str::to_owned)
384 }
385}
386
387impl Drop for Sim {
388 fn drop(&mut self) {
389 self.server.abort();
390 }
391}
392
393#[derive(Debug)]
394struct Shared {
395 options: Options,
396 inner: Mutex<Inner>,
397}
398
399#[derive(Debug)]
400struct Inner {
401 device: Device,
402 web: Web,
403 injections: Vec<Injection>,
404 requests: Vec<Request>,
405 down: u32,
407}
408
409impl Shared {
410 fn lock(&self) -> MutexGuard<'_, Inner> {
411 self.inner.lock().unwrap_or_else(PoisonError::into_inner)
412 }
413
414 fn respond(
416 &self,
417 method: &Method,
418 uri: &Uri,
419 headers: &HeaderMap,
420 body: &str,
421 ) -> (Response, Duration) {
422 let mut inner = self.lock();
423 let path = uri.path();
424 let call = (method == Method::POST)
425 .then(|| soap::parse(body))
426 .flatten();
427 let locked = inner.injections.contains(&Injection::LockLogin);
428 let authorized = !locked
429 && auth::verify(
430 headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok()),
431 &auth::Expected {
432 username: &self.options.username,
433 password: &self.options.password,
434 nonce: NONCE,
435 method: method.as_str(),
436 uri: uri.path_and_query().map_or(path, |p| p.as_str()),
437 },
438 );
439 inner.requests.push(Request {
440 method: method.to_string(),
441 path: path.to_owned(),
442 action: call.as_ref().map(|c| c.action.clone()),
443 arguments: call.as_ref().map_or_default(|c| c.arguments.clone()),
444 authorized,
445 });
446 let delay = inner
447 .injections
448 .iter()
449 .map(|i| match i {
450 Injection::Delay(delay) => *delay,
451 _ => Duration::ZERO,
452 })
453 .sum();
454 let response = match *method {
455 _ if inner.down > 0 => {
456 inner.down -= 1;
457 broken()
458 }
459 _ if path == web::LOGIN => inner.web.login(method, body, &self.options, locked),
460 _ if path.starts_with(web::API) => {
461 let Inner { web, device, .. } = &*inner;
462 web.api(&device.fixture.api, method, path, headers)
463 }
464 _ if path == web::DATA => {
465 let Inner {
466 web,
467 device,
468 injections,
469 ..
470 } = &mut *inner;
471 web.page(&device.fixture.pages, injections, method, body)
472 }
473 _ if path == web::HOMEAUTO => {
474 inner.web.stats(&inner.device.fixture.stats, method, body)
475 }
476 Method::GET => inner.document(path, uri.query()),
477 Method::POST if !authorized => (
478 StatusCode::UNAUTHORIZED,
479 [(WWW_AUTHENTICATE, auth::challenge(NONCE))],
480 )
481 .into_response(),
482 Method::POST => inner.control(path, headers, call),
483 _ => StatusCode::METHOD_NOT_ALLOWED.into_response(),
484 };
485 (response, delay)
486 }
487}
488
489const NONCE: &str = "F1A2B3C4D5E6F708";
492
493const SESSION: &str = "5e55104d0c0ffee5";
496
497impl Inner {
498 fn document(&self, path: &str, query: Option<&str>) -> Response {
501 let fixture = &self.device.fixture;
502 let name = path.trim_start_matches('/');
503 if let Some(list) = name
504 .strip_suffix(".lua")
505 .and_then(|stem| fixture.lists.get(stem))
506 {
507 let session = query
508 .into_iter()
509 .flat_map(|q| q.split('&'))
510 .any(|p| p == format!("sid={SESSION}"));
511 return if session {
512 list.clone().into_response()
513 } else {
514 StatusCode::FORBIDDEN.into_response()
515 };
516 }
517 let xml = match name {
518 "tr64desc.xml" => Some(&fixture.description_xml),
519 name => fixture.scpds.get(name).map(|(xml, _)| xml),
520 };
521 match xml {
522 Some(xml) => ([(CONTENT_TYPE, XML)], xml.clone()).into_response(),
523 None => StatusCode::NOT_FOUND.into_response(),
524 }
525 }
526
527 fn control(&mut self, path: &str, headers: &HeaderMap, call: Option<soap::Call>) -> Response {
529 let service = self
530 .device
531 .fixture
532 .description
533 .services()
534 .find(|s| s.control_url == path)
535 .cloned();
536 let Some(service) = service else {
537 return StatusCode::NOT_FOUND.into_response();
538 };
539 let Some(call) = call else {
540 return StatusCode::BAD_REQUEST.into_response();
541 };
542 let soap_action = headers
543 .get("SOAPAction")
544 .and_then(|v| v.to_str().ok())
545 .unwrap_or_default()
546 .trim_matches('"');
547 let expected = format!("{}#{}", service.service_type, call.action);
548 let result = if soap_action == expected && call.service_type == service.service_type {
549 if let Some(response) = self.breaks(&service, &call.action) {
550 return response;
551 }
552 let hooks = self.hooks(&service, &call.action);
553 let result = self
554 .device
555 .call(&service, &call.action, &call.arguments, &hooks);
556 if result.is_ok() {
557 self.reboot(&service, &call.action);
558 }
559 result
560 } else {
561 Err(Fault::new(401))
562 };
563 match result {
564 Ok(mut out) => {
565 for (_, value) in &mut out {
566 *value = value.replace("sid=***", &format!("sid={SESSION}"));
567 }
568 let xml = soap::response(&service.service_type, &call.action, &out);
569 ([(CONTENT_TYPE, XML)], xml).into_response()
570 }
571 Err(fault) => (
572 StatusCode::INTERNAL_SERVER_ERROR,
573 [(CONTENT_TYPE, XML)],
574 soap::fault(&fault),
575 )
576 .into_response(),
577 }
578 }
579
580 fn breaks(&self, service: &Service, action: &str) -> Option<Response> {
582 self.injections.iter().find_map(|i| match i {
583 Injection::Disconnect {
584 service: reference,
585 action: name,
586 } if name == action && service.matches(reference) => Some(broken()),
587 Injection::Truncate {
588 service: reference,
589 action: name,
590 } if name == action && service.matches(reference) => Some(truncated()),
591 _ => None,
592 })
593 }
594
595 fn reboot(&mut self, service: &Service, action: &str) -> Option<()> {
598 (action == "Reboot" && service.matches("DeviceConfig1")).then_some(())?;
599 let reboot = self
600 .injections
601 .iter()
602 .find(|i| matches!(i, Injection::Reboot { .. }));
603 let Some(Injection::Reboot { down, serial }) = reboot.cloned() else {
604 return None;
605 };
606 self.down = down;
607 let device = &mut self.device;
608 device.set_output("DeviceInfo1", "GetInfo", "NewUpTime", "0")?;
609 device.set_output("DeviceInfo1", "GetInfo", "NewSerialNumber", &serial?)
610 }
611
612 fn hooks(&self, service: &Service, action: &str) -> Hooks {
613 let fault = self.injections.iter().find_map(|i| match i {
614 Injection::Fault {
615 service: reference,
616 action: name,
617 code,
618 } if name == action && service.matches(reference) => Some(Fault::new(*code)),
619 _ => None,
620 });
621 let side_effects = self
622 .injections
623 .iter()
624 .filter_map(|i| match i {
625 Injection::SideEffect {
626 service: reference,
627 action: name,
628 variable,
629 value,
630 } if name == action && service.matches(reference) => {
631 Some((variable.clone(), value.clone()))
632 }
633 _ => None,
634 })
635 .collect();
636 let counters = self
637 .injections
638 .iter()
639 .filter_map(|i| match i {
640 Injection::Counter {
641 service: reference,
642 variable,
643 step,
644 wrap,
645 } if service.matches(reference) => Some((variable.clone(), *step, *wrap)),
646 _ => None,
647 })
648 .collect();
649 Hooks {
650 fault,
651 discard_writes: self.injections.contains(&Injection::DiscardWrites),
652 side_effects,
653 counters,
654 }
655 }
656}
657
658fn broken() -> Response {
661 (StatusCode::OK, [(CONTENT_LENGTH, "1")], Body::new(Broken)).into_response()
662}
663
664fn truncated() -> Response {
666 (StatusCode::OK, "<?xml version=\"1.0\"?><s:Envelope").into_response()
667}
668
669struct Broken;
671
672impl HttpBody for Broken {
673 type Data = Bytes;
674 type Error = io::Error;
675
676 fn poll_frame(
677 self: Pin<&mut Self>,
678 _: &mut Context<'_>,
679 ) -> Poll<Option<Result<http_body::Frame<Bytes>, io::Error>>> {
680 Poll::Ready(Some(Err(io::ErrorKind::ConnectionReset.into())))
681 }
682}
683
684async fn handle(
685 State(shared): State<Arc<Shared>>,
686 method: Method,
687 uri: Uri,
688 headers: HeaderMap,
689 body: String,
690) -> Response {
691 let (response, delay) = shared.respond(&method, &uri, &headers, &body);
692 tokio::time::sleep(delay).await;
693 response
694}
695
696#[cfg(test)]
697mod tests {
698 use super::*;
699
700 const FIXTURE: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/fixtures/fritzbox-7690/8.25");
701 const WLAN: &str = "urn:dslforum-org:service:WLANConfiguration:1";
702 const CONTROL: &str = "/upnp/control/wlanconfig1";
703
704 fn inner() -> Inner {
705 Inner {
706 device: Device::new(Fixture::load(FIXTURE).unwrap()),
707 web: Web::default(),
708 injections: Vec::new(),
709 requests: Vec::new(),
710 down: 0,
711 }
712 }
713
714 fn call(service_type: &str) -> soap::Call {
716 soap::Call {
717 service_type: service_type.to_owned(),
718 action: "GetInfo".to_owned(),
719 arguments: Vec::new(),
720 }
721 }
722
723 fn soap_action(value: &str) -> HeaderMap {
724 let mut headers = HeaderMap::new();
725 headers.insert("SOAPAction", value.parse().unwrap());
726 headers
727 }
728
729 #[test]
730 fn answers_calls_that_match_the_service() {
731 let headers = soap_action(&format!("\"{WLAN}#GetInfo\""));
732 let response = inner().control(CONTROL, &headers, Some(call(WLAN)));
733 assert_eq!(response.status(), StatusCode::OK);
734 }
735
736 #[test]
737 fn rejects_calls_that_do_not_match_the_service() {
738 let mut inner = inner();
739 let right = soap_action(&format!("{WLAN}#GetInfo"));
740 let wrong = soap_action(&format!("{WLAN}#SetEnable"));
741 for (headers, service_type) in [
742 (&wrong, WLAN),
743 (&HeaderMap::new(), WLAN),
744 (&right, "urn:other"),
745 ] {
746 let response = inner.control(CONTROL, headers, Some(call(service_type)));
747 assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
748 }
749 let response = inner.control("/upnp/control/missing", &right, Some(call(WLAN)));
750 assert_eq!(response.status(), StatusCode::NOT_FOUND);
751 let response = inner.control(CONTROL, &right, None);
752 assert_eq!(response.status(), StatusCode::BAD_REQUEST);
753 }
754
755 #[test]
756 fn allows_only_get_and_post() {
757 let shared = Shared {
758 options: Options::default(),
759 inner: Mutex::new(inner()),
760 };
761 let uri = Uri::from_static("/tr64desc.xml");
762 let (response, delay) = shared.respond(&Method::PUT, &uri, &HeaderMap::new(), "");
763 assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED);
764 assert_eq!(delay, Duration::ZERO);
765 assert_eq!(shared.lock().requests[0].method, "PUT");
766 }
767}