use tracing::{debug, info};
use crate::error::{Aria2Error, Result};
use crate::http::header_processor::HttpResponseHead;
use crate::http::metalink_http::MetalinkHttpParser;
use crate::http::request_response::HttpMethod;
use crate::http::skip_response::{HttpSkipResponseHandler, MAX_REDIRECT_COUNT, SkipResponseResult};
use super::connection::{should_inflate_content_encoding, supports_persistent_connection};
use super::conversion;
use super::filename::determine_filename;
use super::range;
use super::types::{ResponseProcessResult, ResponseProcessorConfig};
use super::validate::{ValidateRequestContext, validate_response};
pub struct HttpResponseProcessor {
config: ResponseProcessorConfig,
}
impl HttpResponseProcessor {
pub fn new(config: ResponseProcessorConfig) -> Self {
Self { config }
}
pub fn with_defaults() -> Self {
Self::new(ResponseProcessorConfig::default())
}
#[allow(clippy::too_many_arguments)]
pub fn process(
&self,
response_head: &HttpResponseHead,
request_method: HttpMethod,
request_url: &str,
requested_range: Option<(u64, u64)>,
piece_storage_initialized: bool,
is_unique_protocol: bool,
accept_metalink: bool,
conditional_request: bool,
) -> Result<ResponseProcessResult> {
let validate_ctx = ValidateRequestContext {
conditional_request,
requested_range,
expected_entity_length: self.config.expected_entity_length,
};
validate_response(response_head, &validate_ctx)?;
let status_code = response_head.status_code;
let supports_persistent = supports_persistent_connection(response_head);
if status_code == 304 {
return self.handle_not_modified(response_head);
}
let mut metalink_uris = Vec::new();
let mut digests = Vec::new();
if !piece_storage_initialized {
if accept_metalink && response_head.header("link").is_some() {
let metalink_result = MetalinkHttpParser::parse_response(
response_head,
&self.config.metalink_location,
);
for link in &metalink_result.links {
metalink_uris.push(link.uri.clone());
debug!(uri = %link.uri, "Adding Metalink/HTTP URI");
}
digests = metalink_result.digests;
}
if response_head.header("digest").is_some() && digests.is_empty() {
for dv in response_head.header_all("digest") {
digests.extend(MetalinkHttpParser::parse_digest_header(dv));
}
}
}
if status_code >= 300 {
return self.handle_non_success(
response_head,
request_method,
request_url,
status_code,
);
}
let entity_length = range::compute_entity_length(response_head);
let filename = determine_filename(
response_head,
request_url,
self.config.content_disposition_default_utf8,
);
let content_type = response_head.header("content-type").map(|s| s.to_string());
let content_range = range::parse_content_range(response_head);
let chunked = range::is_chunked_transfer_encoding(response_head);
let inflate_required =
should_inflate_content_encoding(response_head, self.config.accept_gzip);
let switch_head_to_get = request_method == HttpMethod::Head;
let last_modified = response_head.header("last-modified").map(|s| s.to_string());
let knows_total_length = if entity_length == 0 || inflate_required {
if request_method == HttpMethod::Get
&& (entity_length != 0 || response_head.header("content-length").is_none())
{
false
} else {
entity_length == 0 && response_head.header("content-length").is_some()
}
} else {
true
};
info!(
status = status_code,
entity_length,
filename = %filename,
inflate = inflate_required,
chunked,
persistent = supports_persistent,
"HTTP 2xx response processed"
);
Ok(ResponseProcessResult::DownloadReady {
filename,
entity_length,
content_type,
inflate_required,
chunked,
knows_total_length,
supports_persistent_connection: supports_persistent,
switch_head_to_get,
metalink_uris,
digests,
content_range,
last_modified,
is_unique_protocol,
})
}
fn handle_not_modified(
&self,
response_head: &HttpResponseHead,
) -> Result<ResponseProcessResult> {
let entity_length = range::compute_entity_length(response_head);
info!(entity_length, "304 Not Modified: file already current");
Ok(ResponseProcessResult::NotModified { entity_length })
}
fn handle_non_success(
&self,
response_head: &HttpResponseHead,
request_method: HttpMethod,
request_url: &str,
status_code: u16,
) -> Result<ResponseProcessResult> {
let handler = HttpSkipResponseHandler::new(MAX_REDIRECT_COUNT)
.with_http_auth_challenge(true)
.with_max_file_not_found(self.config.max_file_not_found)
.with_retry_wait(5);
let http_response = conversion::response_head_to_http_response(response_head);
let current_url = url::Url::parse(request_url).map_err(|e| {
Aria2Error::Parse(format!("Invalid request URL '{}': {}", request_url, e))
})?;
let skip_result = handler.handle(&http_response, request_method, ¤t_url, 0)?;
match skip_result {
SkipResponseResult::Redirect(info) => Ok(ResponseProcessResult::Redirect(info)),
SkipResponseResult::AuthChallenge(challenge) => {
Ok(ResponseProcessResult::AuthChallenge(challenge))
}
SkipResponseResult::RetryableError {
status_code,
message,
} => Ok(ResponseProcessResult::Error {
status_code,
message,
}),
SkipResponseResult::FatalError {
status_code,
message,
} => Ok(ResponseProcessResult::Error {
status_code,
message,
}),
SkipResponseResult::Consumed => Ok(ResponseProcessResult::Error {
status_code,
message: format!("HTTP error: {}", status_code),
}),
}
}
}