use dahua_camera_core::{CameraError, Result};
use std::time::Duration;
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Clone)]
pub struct CameraHttpClient {
client: reqwest::Client,
camera_id: String,
username: String,
password: String,
}
impl std::fmt::Debug for CameraHttpClient {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CameraHttpClient")
.field("camera_id", &self.camera_id)
.field("username", &self.username)
.field("password", &"<redacted>")
.finish_non_exhaustive()
}
}
impl CameraHttpClient {
pub fn new(camera_id: &str, username: &str, password: &str) -> Self {
let client = reqwest::Client::builder()
.timeout(REQUEST_TIMEOUT)
.build()
.unwrap_or_default();
Self {
client,
camera_id: camera_id.to_owned(),
username: username.to_owned(),
password: password.to_owned(),
}
}
pub async fn get(&self, url: &str, stream: bool) -> Result<reqwest::Response> {
let first = self.send(url, None, stream).await?;
if first.status() != reqwest::StatusCode::UNAUTHORIZED {
return self.check_status(first, url);
}
let challenge = first
.headers()
.get(reqwest::header::WWW_AUTHENTICATE)
.and_then(|v| v.to_str().ok())
.map(str::to_owned)
.ok_or_else(|| self.error("401 with no WWW-Authenticate challenge"))?;
let authorization = self.answer_challenge(&challenge, url)?;
let second = self.send(url, Some(&authorization), stream).await?;
self.check_status(second, url)
}
pub async fn get_text(&self, url: &str) -> Result<String> {
self.get(url, false)
.await?
.text()
.await
.map_err(|e| self.error(&format!("reading body: {e}")))
}
pub async fn get_bytes(&self, url: &str) -> Result<bytes::Bytes> {
self.get(url, false)
.await?
.bytes()
.await
.map_err(|e| self.error(&format!("reading body: {e}")))
}
pub async fn post_xml(&self, url: &str, body: String) -> Result<String> {
let first = self.send_xml(url, body.clone(), None).await?;
let response = if first.status() == reqwest::StatusCode::UNAUTHORIZED {
let challenge = first
.headers()
.get(reqwest::header::WWW_AUTHENTICATE)
.and_then(|v| v.to_str().ok())
.map(str::to_owned)
.ok_or_else(|| self.error("401 with no WWW-Authenticate challenge"))?;
let authorization = self.answer_challenge_for(&challenge, url, "POST")?;
self.send_xml(url, body, Some(&authorization)).await?
} else {
first
};
response.text().await.map_err(|e| self.error(&format!("reading body: {e}")))
}
async fn send_xml(
&self,
url: &str,
body: String,
authorization: Option<&str>,
) -> Result<reqwest::Response> {
let mut request = self
.client
.post(url)
.header(reqwest::header::CONTENT_TYPE, "application/soap+xml; charset=utf-8")
.body(body);
if let Some(value) = authorization {
request = request.header(reqwest::header::AUTHORIZATION, value);
}
request.send().await.map_err(|e| self.error(&e.to_string()))
}
async fn send(
&self,
url: &str,
authorization: Option<&str>,
stream: bool,
) -> Result<reqwest::Response> {
let mut request = self.client.get(url);
if stream {
request = request.timeout(Duration::MAX);
}
if let Some(value) = authorization {
request = request.header(reqwest::header::AUTHORIZATION, value);
}
request.send().await.map_err(|e| self.error(&e.to_string()))
}
fn answer_challenge(&self, challenge: &str, url: &str) -> Result<String> {
self.answer_challenge_for(challenge, url, "GET")
}
fn answer_challenge_for(&self, challenge: &str, url: &str, method: &str) -> Result<String> {
let mut prompt = digest_auth::parse(challenge)
.map_err(|e| self.error(&format!("unparseable auth challenge: {e}")))?;
let parsed = url::Url::parse(url).map_err(|e| self.error(&format!("bad url: {e}")))?;
let path = match parsed.query() {
Some(query) => format!("{}?{}", parsed.path(), query),
None => parsed.path().to_owned(),
};
let mut context = digest_auth::AuthContext::new(&self.username, &self.password, &path);
context.method = digest_auth::HttpMethod::from(method);
prompt
.respond(&context)
.map(|answer| answer.to_header_string())
.map_err(|e| self.error(&format!("computing digest response: {e}")))
}
fn check_status(&self, response: reqwest::Response, url: &str) -> Result<reqwest::Response> {
let status = response.status();
if status == reqwest::StatusCode::UNAUTHORIZED {
return Err(CameraError::Unauthorized {
camera_id: self.camera_id.clone(),
detail: format!("{status} for {}", redact(url)),
});
}
if !status.is_success() {
return Err(self.error(&format!("{status} for {}", redact(url))));
}
Ok(response)
}
fn error(&self, detail: &str) -> CameraError {
CameraError::Cgi { camera_id: self.camera_id.clone(), detail: detail.to_owned() }
}
}
fn redact(url: &str) -> String {
match url::Url::parse(url) {
Ok(mut parsed) if !parsed.username().is_empty() || parsed.password().is_some() => {
let _ = parsed.set_username("");
let _ = parsed.set_password(None);
parsed.to_string()
}
_ => url.to_owned(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn client() -> CameraHttpClient {
CameraHttpClient::new("front", "admin", "hunter2")
}
#[test]
fn digest_response_covers_path_and_query_not_the_whole_url() {
let challenge = r#"Digest realm="DHAC", qop="auth", nonce="abc123", opaque="xyz""#;
let header = client()
.answer_challenge(challenge, "http://10.0.0.5/cgi-bin/ptz.cgi?action=start&code=Up")
.expect("challenge is answerable");
assert!(header.starts_with("Digest "), "{header}");
assert!(header.contains(r#"username="admin""#), "{header}");
assert!(
header.contains(r#"uri="/cgi-bin/ptz.cgi?action=start&code=Up""#),
"digest must sign path+query: {header}"
);
assert!(!header.contains("hunter2"), "password must never appear: {header}");
}
#[test]
fn digest_response_handles_a_url_with_no_query() {
let challenge = r#"Digest realm="DHAC", qop="auth", nonce="abc123""#;
let header = client()
.answer_challenge(challenge, "http://10.0.0.5/cgi-bin/magicBox.cgi")
.expect("challenge is answerable");
assert!(header.contains(r#"uri="/cgi-bin/magicBox.cgi""#), "{header}");
}
#[test]
fn a_malformed_challenge_is_an_error_not_a_panic() {
let err = client().answer_challenge("Basic realm=\"x\"", "http://10.0.0.5/a").unwrap_err();
assert!(matches!(err, CameraError::Cgi { .. }), "{err}");
}
#[test]
fn redaction_removes_embedded_credentials() {
assert_eq!(
redact("http://admin:hunter2@10.0.0.5/cgi-bin/snapshot.cgi"),
"http://10.0.0.5/cgi-bin/snapshot.cgi"
);
}
#[test]
fn debug_never_prints_the_password() {
let rendered = format!("{:?}", client());
assert!(!rendered.contains("hunter2"), "password leaked into Debug: {rendered}");
assert!(rendered.contains("<redacted>"), "{rendered}");
assert!(rendered.contains("front") && rendered.contains("admin"), "{rendered}");
}
#[test]
fn redaction_leaves_ordinary_urls_alone() {
let url = "http://10.0.0.5/cgi-bin/snapshot.cgi?channel=1";
assert_eq!(redact(url), url);
}
}