1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
use crate::fetchers::config::FetcherConfig;
use crate::fetchers::proxy::ProxyRotator;
use crate::fetchers::response::Response;
use std::collections::HashMap;
use std::time::Duration;
pub struct Fetcher {
config: FetcherConfig,
/// One client per rotating proxy when rotation is enabled, otherwise a
/// single client. Indexed by `rotator` when present.
clients: Vec<reqwest::Client>,
rotator: Option<ProxyRotator>,
}
#[derive(Debug, thiserror::Error)]
pub enum FetcherError {
#[error("Request failed after retries: {0}")]
RequestFailed(String),
#[error("HTTP error: {0}")]
Http(#[from] reqwest::Error),
}
impl Fetcher {
/// Build a fetcher from config.
///
/// Returns [`FetcherError::Http`] if the underlying reqwest client cannot
/// be built (e.g. the TLS backend fails to initialize on a misconfigured
/// system) rather than panicking, so callers can handle it.
pub fn new(config: FetcherConfig) -> Result<Self, FetcherError> {
if !config.verify_ssl {
log::warn!(
"SSL certificate verification is DISABLED. This is insecure \
and must not be used in production."
);
}
let (clients, rotator) = if config.proxy_list.is_empty() {
// No rotation: a single client honouring `proxy` and the
// per-protocol `proxies` map.
(vec![Self::build_client(&config, None)?], None)
} else {
// Rotation: one client bound to each proxy, selected round-robin.
let clients = config
.proxy_list
.iter()
.map(|p| Self::build_client(&config, Some(p)))
.collect::<Result<Vec<_>, _>>()?;
let rotator = ProxyRotator::new(config.proxy_list.clone());
(clients, rotator)
};
Ok(Self {
config,
clients,
rotator,
})
}
/// Build a single reqwest client. When `proxy_override` is `Some`, that
/// proxy is applied for all protocols; otherwise the config's `proxy` and
/// per-protocol `proxies` map are applied.
fn build_client(
config: &FetcherConfig,
proxy_override: Option<&str>,
) -> Result<reqwest::Client, FetcherError> {
let mut builder = reqwest::Client::builder()
.timeout(Duration::from_secs(config.timeout_secs))
.danger_accept_invalid_certs(!config.verify_ssl);
// Configure redirects
if config.follow_redirects {
builder = builder.redirect(reqwest::redirect::Policy::limited(
config.max_redirects as usize,
));
} else {
builder = builder.redirect(reqwest::redirect::Policy::none());
}
// Configure proxy
if let Some(proxy_url) = proxy_override {
if let Ok(proxy) = reqwest::Proxy::all(proxy_url) {
builder = builder.proxy(proxy);
}
} else {
// Apply scheme-specific proxies before any wildcard so the specific
// ones win (reqwest uses the first matching proxy). `proxies` is a
// HashMap, so iterate in a deterministic order.
if let Some(proxy_url) = config.proxies.get("http") {
if let Ok(proxy) = reqwest::Proxy::http(proxy_url) {
builder = builder.proxy(proxy);
}
}
if let Some(proxy_url) = config.proxies.get("https") {
if let Ok(proxy) = reqwest::Proxy::https(proxy_url) {
builder = builder.proxy(proxy);
}
}
let mut wildcard_keys: Vec<&String> = config
.proxies
.keys()
.filter(|k| k.as_str() != "http" && k.as_str() != "https")
.collect();
wildcard_keys.sort();
for key in wildcard_keys {
if let Ok(proxy) = reqwest::Proxy::all(&config.proxies[key]) {
builder = builder.proxy(proxy);
}
}
// Single wildcard proxy applied last as a general fallback.
if let Some(ref proxy_url) = config.proxy {
if let Ok(proxy) = reqwest::Proxy::all(proxy_url) {
builder = builder.proxy(proxy);
}
}
}
Ok(builder.build()?)
}
/// Select the client to use for the next request attempt. With rotation
/// enabled this advances the round-robin cursor so a failing proxy is
/// swapped on retry.
fn next_client(&self) -> &reqwest::Client {
match &self.rotator {
Some(rotator) => &self.clients[rotator.next_index()],
None => &self.clients[0],
}
}
pub async fn get(&self, url: &str) -> Result<Response, FetcherError> {
self.request(reqwest::Method::GET, url, None, None).await
}
pub async fn post(
&self,
url: &str,
body: Option<&str>,
json: Option<&serde_json::Value>,
) -> Result<Response, FetcherError> {
self.request(reqwest::Method::POST, url, body, json).await
}
pub async fn put(
&self,
url: &str,
body: Option<&str>,
json: Option<&serde_json::Value>,
) -> Result<Response, FetcherError> {
self.request(reqwest::Method::PUT, url, body, json).await
}
pub async fn delete(&self, url: &str) -> Result<Response, FetcherError> {
self.request(reqwest::Method::DELETE, url, None, None).await
}
/// Internal request method with retry loop.
async fn request(
&self,
method: reqwest::Method,
url: &str,
body: Option<&str>,
json: Option<&serde_json::Value>,
) -> Result<Response, FetcherError> {
let headers = self.config.build_headers(url, self.config.stealthy_headers);
let mut last_error = String::new();
for attempt in 0..=self.config.retries {
let mut req = self.next_client().request(method.clone(), url);
// Set headers
for (key, value) in &headers {
req = req.header(key.as_str(), value.as_str());
}
// Set body or json
if let Some(json_val) = json {
req = req.json(json_val);
} else if let Some(text_body) = body {
req = req.body(text_body.to_string());
}
match req.send().await {
Ok(mut resp) => {
let status_code = resp.status().as_u16();
let final_url = resp.url().to_string();
// Extract headers
let mut resp_headers: HashMap<String, String> = HashMap::new();
for (key, value) in resp.headers() {
if let Ok(v) = value.to_str() {
resp_headers.insert(key.to_string(), v.to_string());
}
}
// Extract content-type before consuming response
let content_type = resp_headers
.get("content-type")
.cloned()
.unwrap_or_default();
// Reject obviously-too-large bodies up front when the
// server advertised a Content-Length. Use try_from so the
// u64 -> usize cast cannot truncate on 32-bit targets.
let max_body = self.config.max_body_bytes;
if let Some(len) = resp.content_length() {
let too_large = match usize::try_from(len) {
Ok(n) => n > max_body,
Err(_) => true,
};
if too_large {
return Err(FetcherError::RequestFailed(format!(
"response body too large: {} bytes (max {})",
len, max_body
)));
}
}
// Stream the body and cap the accumulated size so a
// server that lies about (or omits) Content-Length still
// cannot exhaust memory. Chunk read errors surface as a
// request failure rather than a truncated success.
let mut bytes: Vec<u8> = Vec::new();
loop {
match resp.chunk().await {
Ok(Some(chunk)) => {
let new_len = bytes.len().checked_add(chunk.len());
if new_len.map(|n| n > max_body).unwrap_or(true) {
return Err(FetcherError::RequestFailed(format!(
"response body exceeded {} bytes",
max_body
)));
}
bytes.extend_from_slice(&chunk);
}
Ok(None) => break,
Err(e) => {
return Err(FetcherError::RequestFailed(format!(
"chunk read error: {}",
e
)));
}
}
}
let body_text = crate::fetchers::encoding::decode_body(&bytes, &content_type);
return Ok(Response::new(
status_code,
content_type,
body_text,
final_url,
resp_headers,
));
}
Err(e) => {
last_error = e.to_string();
if attempt < self.config.retries {
tokio::time::sleep(Duration::from_secs(self.config.retry_delay_secs)).await;
}
}
}
}
Err(FetcherError::RequestFailed(last_error))
}
}