Files
proxy-scraper-checker/src/proxy.rs
T

158 lines
4.7 KiB
Rust
Raw Normal View History

2025-05-05 11:02:09 +03:00
use std::{fmt, fmt::Write as _, sync::Arc};
2025-04-10 06:55:12 +00:00
2025-04-24 08:57:50 +03:00
use color_eyre::eyre::{OptionExt as _, WrapErr as _, eyre};
2025-04-10 06:55:12 +00:00
use crate::{
2025-04-24 13:44:02 +03:00
config::{CheckWebsiteType, Config, HttpbinResponse, USER_AGENT},
2025-04-10 06:55:12 +00:00
parsers::parse_ipv4,
};
#[derive(serde::Serialize, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
2025-04-24 08:57:50 +03:00
pub enum ProxyType {
2025-04-10 06:55:12 +00:00
#[serde(rename = "http")]
Http,
#[serde(rename = "socks4")]
Socks4,
#[serde(rename = "socks5")]
Socks5,
}
impl TryFrom<&str> for ProxyType {
type Error = color_eyre::Report;
fn try_from(string: &str) -> color_eyre::Result<Self> {
2025-05-05 11:02:09 +03:00
match string.to_ascii_lowercase().as_str() {
2025-04-24 08:57:50 +03:00
"http" | "https" => Ok(Self::Http),
"socks4" => Ok(Self::Socks4),
"socks5" => Ok(Self::Socks5),
2025-04-10 06:55:12 +00:00
_ => Err(eyre!("Failed to convert {string} to ProxyType")),
}
}
}
2025-04-24 13:44:02 +03:00
impl fmt::Display for ProxyType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2025-04-10 06:55:12 +00:00
write!(
f,
"{}",
match self {
Self::Http => "http",
Self::Socks4 => "socks4",
Self::Socks5 => "socks5",
}
)
}
}
2025-04-24 13:44:02 +03:00
#[derive(derivative::Derivative, Eq)]
2025-04-10 06:55:12 +00:00
#[derivative(Hash, PartialEq)]
2025-04-24 08:57:50 +03:00
pub struct Proxy {
pub protocol: ProxyType,
pub host: String,
pub port: u16,
pub username: Option<String>,
pub password: Option<String>,
2025-04-10 06:55:12 +00:00
#[derivative(Hash = "ignore")]
#[derivative(PartialEq = "ignore")]
2025-04-24 08:57:50 +03:00
pub timeout: Option<tokio::time::Duration>,
2025-04-10 06:55:12 +00:00
#[derivative(Hash = "ignore")]
#[derivative(PartialEq = "ignore")]
2025-04-24 08:57:50 +03:00
pub exit_ip: Option<String>,
2025-04-10 06:55:12 +00:00
}
2025-05-05 11:02:09 +03:00
impl TryFrom<&mut Proxy> for reqwest::Proxy {
type Error = color_eyre::Report;
fn try_from(value: &mut Proxy) -> Result<Self, Self::Error> {
let proxy = Self::all(format!(
2025-04-10 06:55:12 +00:00
"{}://{}:{}",
2025-05-05 11:02:09 +03:00
value.protocol, value.host, value.port
2025-04-10 06:55:12 +00:00
))
.wrap_err("failed to create reqwest::Proxy")?;
2025-05-05 11:02:09 +03:00
2025-04-10 06:55:12 +00:00
if let (Some(username), Some(password)) =
2025-05-05 11:02:09 +03:00
(value.username.as_ref(), value.password.as_ref())
2025-04-10 06:55:12 +00:00
{
2025-05-05 11:02:09 +03:00
Ok(proxy.basic_auth(username, password))
} else {
Ok(proxy)
2025-04-10 06:55:12 +00:00
}
2025-05-05 11:02:09 +03:00
}
}
impl Proxy {
pub async fn check(
&mut self,
config: Arc<Config>,
) -> color_eyre::Result<()> {
2025-04-10 06:55:12 +00:00
let client = reqwest::Client::builder()
.user_agent(USER_AGENT)
2025-05-05 11:02:09 +03:00
.proxy(self.try_into()?)
2025-04-10 06:55:12 +00:00
.timeout(config.timeout)
.pool_max_idle_per_host(0)
.tcp_keepalive(None)
.use_rustls_tls()
.build()
.wrap_err("failed to create reqwest::Client")?;
let start = tokio::time::Instant::now();
let response = client
.get(&config.check_website)
.send()
.await
.wrap_err_with(|| {
format!(
"failed to send HTTP request to {}",
config.check_website
)
})?
.error_for_status()
.wrap_err("Got error HTTP status code when checking proxy")?;
2025-04-29 11:49:26 +03:00
drop(client);
2025-04-10 06:55:12 +00:00
self.timeout = Some(start.elapsed());
2025-04-29 13:06:18 +03:00
self.exit_ip = match config.check_website_type {
CheckWebsiteType::HttpbinIp => {
let httpbin = response
.json::<HttpbinResponse>()
.await
.wrap_err("failed to parse response as HttpBin")?;
Some(
parse_ipv4(&httpbin.origin)
.wrap_err("failed to parse ipv4 from httpbin response")?
.ok_or_eyre(
"failed to parse ipv4 from httpbin response",
)?,
)
}
CheckWebsiteType::PlainIp => {
let text = response
.text()
.await
.wrap_err("failed to decode response text")?;
Some(
parse_ipv4(&text)
.wrap_err("failed to parse ipv4 from response text")?
.ok_or_eyre(
"failed to parse ipv4 from response text",
)?,
)
}
CheckWebsiteType::Unknown => None,
};
2025-04-10 06:55:12 +00:00
Ok(())
}
2025-04-24 08:57:50 +03:00
pub fn as_str(&self, include_protocol: bool) -> String {
2025-04-10 06:55:12 +00:00
let mut s = String::new();
if include_protocol {
2025-05-05 11:02:09 +03:00
write!(&mut s, "{}://", self.protocol).unwrap();
2025-04-10 06:55:12 +00:00
}
if let (Some(username), Some(password)) =
(self.username.as_ref(), self.password.as_ref())
{
2025-05-05 11:02:09 +03:00
write!(&mut s, "{username}:{password}@").unwrap();
2025-04-10 06:55:12 +00:00
}
2025-05-05 11:02:09 +03:00
write!(&mut s, "{}:{}", self.host, self.port).unwrap();
2025-04-10 06:55:12 +00:00
s
}
}