use std::sync::{Arc, Mutex};
use std::time::Duration;
use reqwest::header::{AUTHORIZATION, CONTENT_TYPE, HeaderValue, WWW_AUTHENTICATE};
use reqwest::{Method, RequestBuilder, Response, StatusCode, Url, redirect};
use secrecy::{ExposeSecret as _, SecretString};
use crate::digest::{Challenge, DigestAuth};
use crate::tls::PinnedVerifier;
use crate::{Arguments, DeviceDescription, Error, Fingerprint, Scpd, Service, soap};
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Debug)]
pub struct Client {
http: reqwest::Client,
verifier: Arc<PinnedVerifier>,
base: Url,
credentials: Option<(String, SecretString)>,
auth: Mutex<Option<DigestAuth>>,
}
#[derive(Debug)]
pub struct ClientBuilder {
base: Url,
credentials: Option<(String, SecretString)>,
timeout: Duration,
pin: Option<Fingerprint>,
}
impl ClientBuilder {
#[must_use]
pub fn credentials(mut self, username: impl Into<String>, password: SecretString) -> Self {
self.credentials = Some((username.into(), password));
self
}
#[must_use]
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
#[must_use]
pub fn pin(mut self, fingerprint: Fingerprint) -> Self {
self.pin = Some(fingerprint);
self
}
pub fn build(self) -> Result<Client, Error> {
match (self.base.scheme(), self.pin) {
("https", Some(_)) | ("http", None) => {}
("https", None) => {
return Err(Error::InvalidUrl(format!(
"{} needs a pinned certificate",
self.base
)));
}
_ => {
return Err(Error::InvalidUrl(format!(
"{} is neither https with a pinned certificate nor http",
self.base
)));
}
}
let verifier = PinnedVerifier::new(self.pin);
let http = reqwest::Client::builder()
.tls_backend_preconfigured(verifier.config())
.timeout(self.timeout)
.redirect(redirect::Policy::none())
.no_proxy()
.build()?;
Ok(Client {
http,
verifier,
base: self.base,
credentials: self.credentials,
auth: Mutex::new(None),
})
}
}
impl Client {
pub fn builder(base: Url) -> ClientBuilder {
ClientBuilder {
base,
credentials: None,
timeout: DEFAULT_TIMEOUT,
pin: None,
}
}
pub async fn get(&self, path: &str) -> Result<String, Error> {
let url = self.url(path)?;
let response = self
.send(self.http.get(url.clone()), &Method::GET, &url)
.await?;
Ok(response.text().await?)
}
pub async fn description(&self) -> Result<DeviceDescription, Error> {
DeviceDescription::parse(&self.get("/tr64desc.xml").await?)
}
pub async fn scpd(&self, service: &Service) -> Result<Scpd, Error> {
Scpd::parse(&self.get(&service.scpd_url).await?)
}
pub async fn call(
&self,
service: &Service,
action: &str,
arguments: &[(&str, &str)],
) -> Result<Arguments, Error> {
let url = self.url(&service.control_url)?;
let body = soap::envelope(&service.service_type, action, arguments)?;
let soap_action = format!("\"{}#{action}\"", service.service_type);
let request = self
.http
.post(url.clone())
.header("SOAPAction", soap_action)
.header(CONTENT_TYPE, r#"text/xml; charset="utf-8""#)
.body(body);
let response = self.send(request, &Method::POST, &url).await?;
soap::parse_response(&response.text().await?, action)
}
fn url(&self, path: &str) -> Result<Url, Error> {
let url = self
.base
.join(path)
.map_err(|e| Error::InvalidUrl(format!("{path:?}: {e}")))?;
if url.origin() == self.base.origin() {
Ok(url)
} else {
Err(Error::InvalidUrl(format!(
"{url} is not on the device {}",
self.base.origin().ascii_serialization()
)))
}
}
async fn send(
&self,
request: RequestBuilder,
method: &Method,
url: &Url,
) -> Result<Response, Error> {
let uri = match url.query() {
Some(query) => format!("{}?{query}", url.path()),
None => url.path().to_owned(),
};
let cached = self.cached_authorization(method, &uri);
let mut response = self.execute(with_authorization(&request, cached)).await?;
if response.status() == StatusCode::UNAUTHORIZED {
*self.lock() = None;
let (auth, header) = self.answer(&response, method, &uri)?;
response = self
.execute(with_authorization(&request, Some(header)))
.await?;
if response.status() == StatusCode::UNAUTHORIZED {
return Err(Error::AuthenticationFailed);
}
*self.lock() = Some(auth);
}
check_status(response, url).await
}
async fn execute(&self, request: RequestBuilder) -> Result<Response, Error> {
request.send().await.map_err(|e| self.verifier.explain(e))
}
fn answer(
&self,
response: &Response,
method: &Method,
uri: &str,
) -> Result<(DigestAuth, String), Error> {
let (username, password) = self
.credentials
.as_ref()
.ok_or(Error::CredentialsRequired)?;
let mut auth = DigestAuth::new(challenge(response.headers().get_all(WWW_AUTHENTICATE))?);
let header = auth.authorization(username, password.expose_secret(), method.as_str(), uri);
Ok((auth, header))
}
fn cached_authorization(&self, method: &Method, uri: &str) -> Option<String> {
let (username, password) = self.credentials.as_ref()?;
self.lock().as_mut().map(|auth| {
auth.authorization(username, password.expose_secret(), method.as_str(), uri)
})
}
fn lock(&self) -> std::sync::MutexGuard<'_, Option<DigestAuth>> {
self.auth
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
fn with_authorization(request: &RequestBuilder, authorization: Option<String>) -> RequestBuilder {
let request = request
.try_clone()
.expect("request bodies are held in memory");
match authorization {
Some(value) => request.header(AUTHORIZATION, value),
None => request,
}
}
async fn check_status(response: Response, url: &Url) -> Result<Response, Error> {
let status = response.status();
if status.is_success() {
return Ok(response);
}
let text = response.text().await.unwrap_or_default();
if status == StatusCode::INTERNAL_SERVER_ERROR
&& let Some(fault) = soap::parse_fault(&text)
{
return Err(fault);
}
Err(Error::Status {
status: status.as_u16(),
url: url.to_string(),
})
}
fn challenge<'a>(headers: impl IntoIterator<Item = &'a HeaderValue>) -> Result<Challenge, Error> {
let mut first_error = None;
for header in headers {
match Challenge::parse(&String::from_utf8_lossy(header.as_bytes())) {
Ok(challenge) => return Ok(challenge),
Err(e) => {
first_error.get_or_insert(e);
}
}
}
Err(first_error
.unwrap_or_else(|| Error::UnsupportedAuth("no WWW-Authenticate header".to_owned())))
}