use std::time::Instant;
use url::Url;
use super::Request;
use crate::download::request::PeerStat;
pub const METHOD_GET: &str = "GET";
pub const METHOD_HEAD: &str = "HEAD";
pub const MAX_REDIRECT: u32 = 20;
pub const DEFAULT_FILE: &str = "index.html";
pub fn remove_fragment(uri: &str) -> &str {
match uri.find('#') {
Some(pos) => &uri[..pos],
None => uri,
}
}
pub fn is_absolute_uri(uri: &str) -> bool {
match uri.find("://") {
Some(scheme_end) if scheme_end > 0 => uri[..scheme_end].chars().all(|c| {
c.is_ascii_alphabetic() || c.is_ascii_digit() || c == '+' || c == '-' || c == '.'
}),
_ => false,
}
}
impl Request {
pub fn new(uri: &str) -> Option<Self> {
let mut req = Self::default_inner();
req.set_uri(uri).then_some(req)
}
pub fn set_uri(&mut self, uri: &str) -> bool {
self.supports_persistent_connection = true;
self.uri = uri.to_owned();
self.parse_uri(uri)
}
pub fn redirect_uri(&mut self, uri: &str) -> bool {
self.supports_persistent_connection = true;
self.redirect_count = self.redirect_count.saturating_add(1);
if uri.is_empty() {
return false;
}
let redirected = if uri.starts_with("//") {
format!("{}:{}", self.protocol(), uri)
} else if is_absolute_uri(uri) {
uri.to_owned()
} else {
match Url::parse(&self.current_uri) {
Ok(base) => base
.join(uri)
.map(|u| u.to_string())
.unwrap_or_else(|_| uri.to_owned()),
Err(_) => uri.to_owned(),
}
};
self.parse_uri(&redirected)
}
pub fn reset_uri(&mut self) -> bool {
self.supports_persistent_connection = true;
self.connected_hostname.clear();
self.connected_addr.clear();
self.connected_port = 0;
let uri = self.uri.clone();
self.parse_uri(&uri)
}
fn parse_uri(&mut self, src_uri: &str) -> bool {
let without_fragment = remove_fragment(src_uri);
match Url::parse(without_fragment) {
Ok(url) => {
let ipv6_literal = matches!(url.host(), Some(url::Host::Ipv6(_)));
let host = match url.host_str() {
Some(h) if ipv6_literal => {
h.strip_prefix('[')
.and_then(|s| s.strip_suffix(']'))
.unwrap_or(h)
.to_owned()
}
Some(h) => h.to_owned(),
None => String::new(),
};
let protocol = url.scheme().to_owned();
let port = url.port_or_known_default().unwrap_or(0);
self.current_uri = without_fragment.to_owned();
self.parsed_url = url;
self.host = host;
self.protocol = protocol;
self.port = port;
self.ipv6_literal_address = ipv6_literal;
true
}
Err(e) => {
tracing::warn!("Failed to parse URI '{}': {}", without_fragment, e);
false
}
}
}
pub fn reset_try_count(&mut self) {
self.try_count = 0;
}
pub fn add_try_count(&mut self) {
self.try_count = self.try_count.saturating_add(1);
}
pub fn try_count(&self) -> u32 {
self.try_count
}
pub fn reset_redirect_count(&mut self) {
self.redirect_count = 0;
}
pub fn redirect_count(&self) -> u32 {
self.redirect_count
}
pub fn uri(&self) -> &str {
&self.uri
}
pub fn current_uri(&self) -> &str {
&self.current_uri
}
pub fn referer(&self) -> &str {
&self.referer
}
pub fn set_referer(&mut self, uri: &str) {
self.referer = remove_fragment(uri).to_owned();
}
pub fn protocol(&self) -> &str {
&self.protocol
}
pub fn host(&self) -> &str {
&self.host
}
pub fn uri_host(&self) -> String {
if self.ipv6_literal_address {
format!("[{}]", self.host)
} else {
self.host.clone()
}
}
pub fn port(&self) -> u16 {
self.port
}
pub fn dir(&self) -> &str {
let path = self.parsed_url.path();
match path.rfind('/') {
Some(pos) => &path[..=pos],
None => "/",
}
}
pub fn file(&self) -> &str {
let path = self.parsed_url.path();
match path.rfind('/') {
Some(pos) if pos + 1 < path.len() => &path[pos + 1..],
_ => DEFAULT_FILE,
}
}
pub fn query(&self) -> &str {
self.parsed_url.query().unwrap_or("")
}
pub fn username(&self) -> &str {
self.parsed_url.username()
}
pub fn password(&self) -> Option<&str> {
self.parsed_url.password()
}
pub fn has_password(&self) -> bool {
self.parsed_url.password().is_some()
}
pub fn is_ipv6_literal_address(&self) -> bool {
self.ipv6_literal_address
}
pub fn set_method(&mut self, method: &str) {
self.method = method.to_owned();
}
pub fn method(&self) -> &str {
&self.method
}
pub fn set_supports_persistent_connection(&mut self, f: bool) {
self.supports_persistent_connection = f;
}
pub fn supports_persistent_connection(&self) -> bool {
self.supports_persistent_connection
}
pub fn is_keep_alive_enabled(&self) -> bool {
self.supports_persistent_connection && self.keep_alive_hint
}
pub fn set_keep_alive_hint(&mut self, hint: bool) {
self.keep_alive_hint = hint;
}
pub fn is_pipelining_enabled(&self) -> bool {
self.supports_persistent_connection && self.pipelining_hint
}
pub fn set_pipelining_hint(&mut self, hint: bool) {
self.pipelining_hint = hint;
}
pub fn is_pipelining_hint(&self) -> bool {
self.pipelining_hint
}
pub fn set_max_pipelined_request(&mut self, num: u32) {
self.max_pipelined_request = num;
}
pub fn max_pipelined_request(&self) -> u32 {
self.max_pipelined_request
}
pub fn peer_stat(&self) -> Option<&PeerStat> {
self.peer_stat.as_ref()
}
pub fn init_peer_stat(&mut self) -> &PeerStat {
let (host, protocol) = match Url::parse(remove_fragment(&self.uri)) {
Ok(url) => (
url.host_str().unwrap_or("").to_owned(),
url.scheme().to_owned(),
),
Err(_) => (String::new(), String::new()),
};
self.peer_stat = Some(PeerStat::new(0, host, protocol));
self.peer_stat.as_ref().unwrap()
}
pub fn request_removal(&mut self) {
self.removal_requested = true;
}
pub fn removal_requested(&self) -> bool {
self.removal_requested
}
pub fn set_connected_addr_info(&mut self, hostname: &str, addr: &str, port: u16) {
self.connected_hostname = hostname.to_owned();
self.connected_addr = addr.to_owned();
self.connected_port = port;
}
pub fn connected_hostname(&self) -> &str {
&self.connected_hostname
}
pub fn connected_addr(&self) -> &str {
&self.connected_addr
}
pub fn connected_port(&self) -> u16 {
self.connected_port
}
pub fn set_wake_time(&mut self, time: Instant) {
self.wake_time = time;
}
pub fn wake_time(&self) -> Instant {
self.wake_time
}
pub fn is_wake_time_reached(&self) -> bool {
Instant::now() >= self.wake_time
}
pub fn set_reset_try_count_after_wake(&mut self, f: bool) {
self.reset_try_count_after_wake = f;
}
pub fn reset_try_count_after_wake(&self) -> bool {
self.reset_try_count_after_wake
}
fn default_inner() -> Self {
Self {
parsed_url: Url::parse("http://localhost/").unwrap(),
host: String::new(),
protocol: String::new(),
port: 0,
ipv6_literal_address: false,
uri: String::new(),
current_uri: String::new(),
referer: String::new(),
method: METHOD_GET.to_owned(),
connected_hostname: String::new(),
connected_addr: String::new(),
connected_port: 0,
try_count: 0,
redirect_count: 0,
supports_persistent_connection: true,
keep_alive_hint: false,
pipelining_hint: false,
max_pipelined_request: 1,
peer_stat: None,
removal_requested: false,
wake_time: Instant::now(),
reset_try_count_after_wake: false,
}
}
}
impl Default for Request {
fn default() -> Self {
Self::default_inner()
}
}