1use serde_json::{Value, json};
7use std::time::{Duration, Instant};
8use std::{net::ToSocketAddrs, sync::LazyLock};
9
10#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
11pub enum Tier {
12 #[default]
13 Plain,
14 Bd,
15 Oxy,
16 OxyJs,
17 Decodo,
18 DecodoJs,
19}
20
21#[derive(serde::Deserialize)]
22#[serde(deny_unknown_fields)]
23pub struct Spec {
24 pub name: &'static str,
26 pub short: &'static str,
27 pub env: &'static str,
28 pub timeout: Duration,
29 pub price: f64,
31 can: Vec<&'static str>,
35 pub bills_site_5xx: bool,
39 pub buys: &'static str,
41 pub search_s: u64,
43}
44
45#[derive(serde::Deserialize)]
54#[serde(deny_unknown_fields, bound(deserialize = "'de: 'static"))]
55pub struct Providers {
56 pub specs: Vec<Spec>,
57 pub apis: Vec<ApiRow>,
58 pub links: Vec<Links>,
59 pub cctld: std::collections::HashMap<&'static str, &'static str>,
60}
61
62pub static PROVIDERS: LazyLock<Providers> = LazyLock::new(|| crate::settings::table("providers"));
63
64impl Tier {
65 pub const ALL: [Tier; 6] = [Tier::Plain, Tier::Bd, Tier::Oxy, Tier::OxyJs, Tier::Decodo, Tier::DecodoJs];
66
67 pub fn spec(self) -> &'static Spec {
68 &PROVIDERS.specs[self as usize]
69 }
70
71 pub fn parse(s: &str) -> Option<Tier> {
73 Tier::ALL.into_iter().find(|t| t.spec().short == s || t.spec().name == s)
74 }
75
76 pub fn owner(self) -> Tier {
78 Tier::ALL.into_iter().find(|t| t.spec().env == self.spec().env).unwrap_or(self)
79 }
80
81 pub fn renders(self) -> bool {
84 self.owner() != self
85 }
86
87 pub fn can(self, job: &str) -> bool {
89 self.spec().can.contains(&job)
90 }
91
92 pub fn switch(self) -> &'static str {
94 if self == Tier::Plain { "free" } else { self.owner().spec().short }
95 }
96
97 pub fn key(self) -> Option<String> {
100 match self {
101 Tier::Plain => crate::settings::on(self.switch()).then(String::new),
102 Tier::Bd => crate::settings::zone().and_then(|_| self.saved_key()),
103 _ => self.saved_key(),
104 }
105 }
106
107 pub fn saved_key(self) -> Option<String> {
110 crate::settings::on(self.switch()).then(|| crate::settings::key(self.switch())).flatten()
111 }
112}
113
114pub fn short(name: &str) -> &str {
116 PROVIDERS.specs.iter().find(|s| s.name == name).map_or(name, |s| s.short)
117}
118
119#[derive(Clone, Default)]
121pub struct Ask {
122 pub url: String,
123 pub js: bool,
125 pub country: Option<String>,
127 pub timeout: Option<Duration>,
128 pub max_bytes: u64,
130 pub mobile: bool,
132 pub doc: bool,
134 pub html: bool,
137}
138
139pub const MD_ACCEPT: &str = "text/markdown;q=1.0, text/html;q=0.9, application/xhtml+xml;q=0.9, */*;q=0.8";
143
144#[derive(Default)]
146pub struct Raw {
147 pub status: u16,
148 pub final_url: String,
149 pub ctype: String,
150 pub headers: String,
151 pub body: Vec<u8>,
152 pub charset: &'static str,
154 pub limit: Option<Limit>,
156 pub refreshed_from: Option<String>,
159 pub why: String,
161}
162
163#[derive(Clone, Copy, Debug, Default, PartialEq)]
167pub struct Limit {
168 pub limit: u32,
169 pub remaining: u32,
170}
171
172pub const RETRY_AFTER: u64 = 5;
174
175#[derive(Debug, Default, PartialEq)]
179pub struct Fail {
180 pub code: &'static str,
181 pub status: u16,
182 pub body: Vec<u8>,
183 pub why: String,
185 pub limit: Option<Limit>,
186}
187
188impl From<&'static str> for Fail {
189 fn from(code: &'static str) -> Fail {
190 Fail { code, ..Fail::default() }
191 }
192}
193
194pub async fn get(t: Tier, ask: &Ask, key: &str) -> (Result<Raw, Fail>, bool) {
196 let wait = ask.timeout.unwrap_or(t.spec().timeout);
197 let r = match t {
198 Tier::Plain => plain(ask, wait).await,
199 Tier::Bd => brightdata(ask, key, wait).await,
200 Tier::Oxy | Tier::OxyJs => oxylabs(ask, key, wait).await,
201 Tier::Decodo | Tier::DecodoJs => decodo(ask, key, wait).await,
202 };
203 let billed = charged(t, r.as_ref().map(|raw| raw.status));
204 (r.and_then(|raw| if raw.body.len() as u64 > ask.max_bytes { Err("too_big".into()) } else { Ok(raw) }), billed)
205}
206
207pub fn block<F: Future>(f: F) -> Option<F::Output> {
210 Some(tokio::runtime::Builder::new_current_thread().enable_all().build().ok()?.block_on(f))
211}
212
213pub fn all_within<F>(calls: Vec<F>, wait: Duration) -> Vec<Option<F::Output>>
216where
217 F: Future<Output: Send> + Send + 'static,
218{
219 let mut got: Vec<Option<F::Output>> = calls.iter().map(|_| None).collect();
220 block(async {
221 let mut set = tokio::task::JoinSet::new();
222 for (i, call) in calls.into_iter().enumerate() {
223 set.spawn(async move { (i, call.await) });
224 }
225 let end = tokio::time::Instant::now() + wait;
226 while let Ok(Some(Ok((i, answer)))) = tokio::time::timeout_at(end, set.join_next()).await {
227 got[i] = Some(answer);
228 }
229 });
230 got
231}
232
233pub fn late(wait: Duration) -> Fail {
235 Fail { why: format!("wait:{}s", wait.as_secs()), ..Fail::from("provider_timeout") }
236}
237
238pub async fn exists(host: &str) -> Option<bool> {
244 for (ty, code) in [("A", 1), ("AAAA", 28)] {
245 let (body, ..) = api(Api::Doh, "", json!({"name": host, "type": ty}), 64 << 10, DOH_WAIT).await.ok()?;
246 let j = serde_json::from_slice::<Value>(&body).ok()?;
247 let records = j["Answer"].as_array().into_iter().flatten();
248 match j["Status"].as_u64()? {
249 0 if records.into_iter().any(|r| r["type"] == code) => return Some(true),
250 0 => {}
251 3 => return Some(false),
252 _ => return None,
253 }
254 }
255 Some(false)
256}
257
258pub async fn ours(to: Api, req: Value, wait: Duration) -> Result<Vec<u8>, String> {
261 let fail = |f: Fail| if f.status > 0 { f.status.to_string() } else { f.code.to_string() };
262 api(to, "", req, 64 << 10, wait).await.map(|a| a.0).map_err(fail)
263}
264
265pub const DOH_WAIT: Duration = Duration::from_millis(1500);
266
267pub fn host_check(url: &str, wall: Option<Duration>) -> Option<(&'static str, String)> {
280 let url::Host::Domain(host) = url::Url::parse(url).ok()?.host()?.to_owned() else { return None };
281 let (t0, (tx, rx), name) = (Instant::now(), std::sync::mpsc::channel(), host.clone());
282 let ask = crate::lang::askable(&host);
285 ask.then(|| std::thread::spawn(move || tx.send(lookup(&name))));
286 let all = rx
287 .recv_timeout(Duration::from_secs(crate::settings::limit("dns_wait")).min(wall.unwrap_or(Duration::MAX)))
288 .ok();
289 let fast = t0.elapsed() < Duration::from_millis(crate::settings::limit("dns_fast_ms"));
290 let second = || block(exists(&host)).flatten();
294 let got = all.map(|all| match all {
295 Ok(all) if !all.is_empty() => Ok(all_private(&all)),
296 all => Err((second(), all.err())),
297 });
298 let (code, why) = match got {
300 _ if !ask => ("no_host", None),
301 Some(Ok(true)) if !crate::settings::get().allow_private.value => ("private_address", None),
302 Some(Ok(_) | Err((Some(true), _))) => return None,
303 Some(Err((Some(false), _))) => ("no_host", None),
304 Some(Err((None, why))) if fast => ("dns_failed", why),
305 _ => ("dns_timeout", None),
306 };
307 Some((code, why.unwrap_or_default()))
308}
309
310fn all_private(all: &[std::net::SocketAddr]) -> bool {
312 !all.is_empty() && all.iter().all(|a| private_ip(a.ip()))
313}
314
315pub fn lookup(host: &str) -> Result<Vec<std::net::SocketAddr>, String> {
319 if in_process() {
320 std::thread::sleep(Duration::from_secs(if host.starts_with("lag.") { 2 } else { 0 }));
321 let lan = host.starts_with("lan.").then(|| vec![([10, 0, 0, 1], 443).into()]);
322 return lan.ok_or_else(|| said_short("nodename nor servname provided, or not known"));
323 }
324 let said = |e: std::io::Error| said_short(&e.to_string().rsplit(": ").next().unwrap_or_default().to_lowercase());
325 (host, 443).to_socket_addrs().map(Iterator::collect).map_err(said)
326}
327
328pub fn charged(t: Tier, status: Result<u16, &Fail>) -> bool {
337 t != Tier::Plain && status.is_ok_and(|s| s < 500 || t.spec().bills_site_5xx)
338}
339
340pub const OWN_REASON: [&str; 2] = ["provider_error", "provider_refused"];
343
344pub const REFUSED: &[&str] = &[OWN_REASON[0], OWN_REASON[1], "rate_limited"];
348
349pub fn spend(costs: impl IntoIterator<Item = f64>) -> f64 {
351 costs.into_iter().fold(0.0, |total, cost| total + cost)
352}
353
354fn net(e: &wreq::Error) -> Fail {
357 let mut src: Option<&(dyn std::error::Error + 'static)> = Some(e);
358 let mut tls = String::new();
359 while let Some(s) = src {
360 if s.is::<Private>() {
361 return Fail::from("private_address");
362 }
363 if let Some(r) = s.to_string().strip_prefix('[').and_then(|r| r.split(']').next()) {
364 tls = format!("tls:{}", r.to_lowercase().replace('_', "-"));
365 }
366 src = s.source();
367 }
368 let code = match () {
369 _ if e.is_timeout() => "provider_timeout",
370 _ if e.is_connect() || e.is_dns() || e.is_tls() => "connect_failed",
371 _ => "net_error",
372 };
373 Fail { why: said_short(&tls), ..Fail::from(code) }
374}
375
376fn pairs(h: &wreq::header::HeaderMap) -> Vec<(String, String)> {
378 h.iter().map(|(k, v)| (k.as_str().to_string(), String::from_utf8_lossy(v.as_bytes()).into())).collect()
379}
380
381fn header_lines<'a>(h: impl Iterator<Item = (&'a String, &'a str)>) -> String {
385 let safe = |(k, _): &(&String, &str)| !crate::lang::WORDS.secret_headers.contains(&k.to_lowercase().as_str());
386 h.filter(safe).map(|(k, v)| format!("{}: {}\n", k.to_lowercase(), v.to_lowercase())).collect()
387}
388
389pub fn proxy_note() -> Option<&'static str> {
394 let vars = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"].map(|k| [k.to_string(), k.to_lowercase()]);
395 let set = vars.as_flattened().iter().any(|k| crate::settings::env(k).is_some());
396 set.then_some("proxy env ignored on plain (your own connection); paid tiers are the proxies")
397}
398
399async fn plain(ask: &Ask, wait: Duration) -> Result<Raw, Fail> {
400 let client = wreq::Client::builder()
401 .emulation(browser())
402 .no_proxy()
403 .redirect(wreq::redirect::Policy::none())
404 .dns_resolver(Fence)
405 .timeout(wait)
406 .build()
407 .map_err(|_| "net_error")?;
408 let send = |u: String| {
409 let req = client.get(&u);
410 let md = crate::settings::get().accept_md.value && !ask.doc && !ask.html;
411 let req = if md { req.header(wreq::header::ACCEPT, MD_ACCEPT) } else { req };
412 async move {
413 let r = req.send().await.map_err(|e| net(&e))?;
414 let to = r.headers().get("location").map(|v| String::from_utf8_lossy(v.as_bytes()).into_owned());
415 Ok::<_, Fail>((r.status().as_u16(), to, r))
416 }
417 };
418 let read = |at: String| {
419 let send = &send;
420 async move {
421 let (final_url, r) = follow(&at, send).await?;
422 let (status, headers) =
423 (r.status().as_u16(), header_lines(pairs(r.headers()).iter().map(|h| (&h.0, h.1.as_str()))));
424 let ctype = r.headers().get("content-type").map(|v| String::from_utf8_lossy(v.as_bytes()).to_lowercase());
425 let ctype = ctype.unwrap_or_default();
426 let body = capped(r, ask.max_bytes).await?;
427 let declared =
428 ctype.split("charset=").nth(1).map(|c| c.split(';').next().unwrap_or(c).trim_matches(['"', ' ']));
429 let (body, charset) = if ctype.starts_with("image/") { (body, "") } else { decode_body(body, declared) };
431 Ok::<Raw, Fail>(Raw { status, final_url, ctype, headers, body, charset, ..Raw::default() })
432 }
433 };
434 let mut first = read(ask.url.clone()).await;
442 if let Err(f) = &mut first
443 && f.code == "connect_failed"
444 && let Some(r) = ask.url.strip_prefix("https:")
445 {
446 let cause = if f.why.is_empty() { String::new() } else { format!("{}+", f.why) };
447 match read(format!("http:{r}")).await {
448 Ok(raw) if (200..300).contains(&raw.status) => {
449 first = Ok(Raw { why: format!("{cause}http:{}", raw.status), ..raw })
450 }
451 h => {
452 f.why = format!("{cause}http:{}", h.map_or_else(|h| h.code.into(), |r| r.status.to_string()));
453 f.code = if f.why.starts_with("tls:certificate-") { "tls_failed" } else { f.code };
454 }
455 }
456 }
457 let first = first?;
458 let Some(to) = refresh(&first) else { return Ok(first) };
459 match read(to).await {
462 Ok(raw) if (200..300).contains(&raw.status) => Ok(Raw { refreshed_from: Some(first.final_url), ..raw }),
463 _ => Ok(first),
464 }
465}
466
467fn refresh(raw: &Raw) -> Option<String> {
475 let html = raw.status < 300 && crate::clean::kind_of(&raw.ctype, &raw.body) == "html";
476 let marked = html && raw.body.windows(10).any(|w| w.eq_ignore_ascii_case(b"http-equiv"));
477 let tree = crate::html::parse(&String::from_utf8_lossy(marked.then_some(&raw.body[..])?));
478 let tag = |n: &&crate::html::Node| n.attr("http-equiv").is_some_and(|v| v.eq_ignore_ascii_case("refresh"));
479 let (delay, rest) = tree.nodes.iter().find(tag)?.attr("content")?.split_once([';', ','])?;
480 let rest = rest.split_once('=').filter(|(k, _)| k.trim().eq_ignore_ascii_case("url")).map_or(rest, |(_, v)| v);
481 let target = rest.trim().trim_matches(['\x22', '\'']);
483 let at = url::Url::parse(&raw.final_url).ok()?;
484 let delay = delay.trim();
485 let to = at.join(target).ok().filter(|_| !target.is_empty())?;
486 let scheme = at.scheme() == to.scheme() || (at.scheme(), to.scheme()) == ("http", "https");
487 let origin = scheme && (at.host_str(), at.port()) == (to.host_str(), to.port());
488 let alone = !tree.nodes.iter().any(|n| n.tag == "script") && origin;
489 let small = crate::fetch::visible(&tree).0.chars().count() < crate::settings::limit("page_chars");
490 (!delay.is_empty() && delay.bytes().all(|b| b == b'0') && alone && small).then(|| to.into())
491}
492
493pub fn decode_body(body: Vec<u8>, declared: Option<&str>) -> (Vec<u8>, &'static str) {
497 if crate::clean::sniff(&body).is_some() { (body, "") } else { crate::clean::decode(body, declared) }
498}
499
500pub fn private_ip(ip: std::net::IpAddr) -> bool {
505 use std::net::IpAddr::{V4, V6};
506 let bits = |ip| match ip {
507 V4(a) => (u128::from(a.to_bits()), 32),
508 V6(a) => (a.to_bits(), 128),
509 };
510 let block = |(net, n): (&str, &str)| Some((bits(net.parse().ok()?), n.parse::<u32>().ok()?));
511 let (at, width) = bits(ip);
512 let blocks = crate::fetch::SITES.fence.iter().filter_map(|b| block(b.split_once('/')?));
514 let within = || blocks.clone().any(|((net, w), n)| w == width && (at ^ net).checked_shr(w - n.min(w)) == Some(0));
515 let V6(a) = ip else { return within() };
516 let s = a.segments();
517 let v4 = |hi: u16, lo: u16| Some(std::net::Ipv4Addr::from((u32::from(hi) << 16) | u32::from(lo)));
519 let v4 = a.to_ipv4_mapped().or(match s {
520 [0x64, 0xff9b, 0, 0, 0, 0, ..] | [0, 0, 0, 0, 0, 0, ..] => v4(s[6], s[7]),
521 [0x2002, ..] => v4(s[1], s[2]),
522 _ => None,
523 });
524 v4.map_or_else(within, |v4| private_ip(V4(v4)))
525}
526
527pub fn private_host(url: &str) -> bool {
530 !crate::settings::get().allow_private.value && private_name(url)
531}
532
533fn private_name(url: &str) -> bool {
534 match url::Url::parse(url).ok().as_ref().and_then(url::Url::host) {
535 Some(url::Host::Ipv4(a)) => private_ip(a.into()),
536 Some(url::Host::Ipv6(a)) => private_ip(a.into()),
537 Some(url::Host::Domain(d)) => {
538 let d = d.trim_end_matches('.');
539 d == "localhost" || d.ends_with(".localhost")
540 }
541 None => true,
542 }
543}
544
545pub fn pace(url: &str) -> (Option<std::fs::File>, u64) {
553 use std::io::{Seek, Write};
554 let (gap, t0) = (Duration::from_millis(crate::settings::limit("plain_host_pace_ms")), Instant::now());
555 let at = crate::settings::get().cache.value.join("pace").join(crate::clean::host_of(url));
556 let open = || std::fs::OpenOptions::new().create(true).truncate(false).read(true).write(true).open(&at);
557 let file = at.parent().map(std::fs::create_dir_all).and_then(Result::ok).and_then(|()| open().ok());
558 let Some(mut f) = file.filter(|f| !gap.is_zero() && f.lock().is_ok()) else { return (None, 0) };
559 let last = std::io::read_to_string(&f).ok().and_then(|s| s.get(..20)?.parse::<f64>().ok());
564 let since = last.and_then(|t| Duration::try_from_secs_f64((crate::cache::now() - t).max(0.0)).ok());
566 std::thread::sleep(since.and_then(|s| gap.checked_sub(s)).unwrap_or_default());
567 f.rewind().and_then(|()| write!(f, "{:020.6}", crate::cache::now())).ok();
568 (Some(f), t0.elapsed().as_millis() as u64)
569}
570
571struct Fence;
574
575#[derive(Debug)]
576struct Private;
577
578impl std::fmt::Display for Private {
579 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
580 f.write_str("resolves to a private address")
581 }
582}
583
584impl std::error::Error for Private {}
585
586impl wreq::dns::Resolve for Fence {
587 fn resolve(&self, name: wreq::dns::Name) -> wreq::dns::Resolving {
588 Box::pin(async move {
589 let all = tokio::task::spawn_blocking(move || (name.as_str(), 0).to_socket_addrs());
590 let open = crate::settings::get().allow_private.value;
591 let keep: Vec<_> = all.await??.filter(|a| open || !private_ip(a.ip())).collect();
592 if keep.is_empty() {
593 return Err(Box::new(Private) as Box<dyn std::error::Error + Send + Sync>);
594 }
595 Ok(Box::new(keep.into_iter()) as wreq::dns::Addrs)
596 })
597 }
598}
599
600async fn follow<R, E: From<&'static str>, F>(url: &str, send: impl Fn(String) -> F) -> Result<(String, R), E>
606where
607 F: Future<Output = Result<(u16, Option<String>, R), E>>,
608{
609 let mut at = url.to_string();
610 for hop in 0..=10 {
611 if private_host(&at) || hop > 0 && hop_private(&at).await == Some(true) {
612 return Err("private_address".into());
613 }
614 match send(at.clone()).await? {
615 (301 | 302 | 303 | 307 | 308, Some(to), _) => {
616 at = url::Url::parse(&at).and_then(|u| u.join(&to)).map_err(|_| "net_error")?.into();
617 }
618 (_, _, r) => return Ok((at, r)),
619 }
620 }
621 Err("redirect_loop".into())
622}
623
624async fn hop_private(url: &str) -> Option<bool> {
629 let url::Host::Domain(host) = url::Url::parse(url).ok()?.host()?.to_owned() else { return None };
630 let wait = Duration::from_secs(crate::settings::limit("dns_wait"));
631 let all = tokio::time::timeout(wait, tokio::task::spawn_blocking(move || lookup(&host))).await.ok()?.ok()?.ok()?;
632 Some(all_private(&all) && !crate::settings::get().allow_private.value)
633}
634
635async fn capped(mut r: wreq::Response, cap: u64) -> Result<Vec<u8>, Fail> {
638 use http_body::Body;
639 if let Some(n) = r.content_length().filter(|&n| n > cap) {
640 return Err(Fail { why: format!("{}B", crate::lang::ksize(n as usize)), ..Fail::from("too_big") });
641 }
642 let mut v = Vec::new();
643 while let Some(f) = std::future::poll_fn(|cx| std::pin::Pin::new(&mut r).poll_frame(cx)).await {
644 let Ok(d) = f.map_err(|e| net(&e))?.into_data() else { continue };
645 if (v.len() + d.len()) as u64 > cap {
646 return Err("too_big".into());
647 }
648 v.extend_from_slice(&d);
649 }
650 Ok(v)
651}
652
653#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
660pub enum Api {
661 BdRequest,
662 OxyScrape,
663 OxySearch,
664 OxyScrapers,
667 BdBalance,
670 BdZones,
671 BdCosts,
672 BdZoneCost,
673 Doh,
675 GhRepos,
677 GhUser,
678 DecodoScrape,
681 Telemetry,
683 TelemetryL2,
684}
685
686#[derive(serde::Deserialize)]
689#[serde(deny_unknown_fields)]
690pub struct ApiRow {
691 pub api: Api,
692 pub method: &'static str,
693 pub url: &'static str,
694 pub what: &'static str,
695 #[serde(default)]
697 pub accept: &'static str,
698}
699
700impl Api {
701 pub fn row(self) -> &'static ApiRow {
702 &PROVIDERS.apis[self as usize]
703 }
704
705 pub fn url(self, req: &Value) -> String {
707 let get = req.as_object().into_iter().flatten().filter(|_| self.row().method == "GET");
708 let pairs = get.map(|(k, v)| (k, v.as_str().unwrap_or_default()));
709 let q = url::form_urlencoded::Serializer::new(String::new()).extend_pairs(pairs).finish();
710 let url = crate::lang::draw(self.row().url, &[("q", req["q"].as_str().unwrap_or_default())]);
712 if q.is_empty() { url } else { format!("{url}?{q}") }
713 }
714}
715
716#[derive(serde::Deserialize)]
721#[serde(deny_unknown_fields)]
722pub struct Links {
723 pub short: &'static str,
724 pub name: &'static str,
725 pub signup: &'static str,
726 pub mint: &'static str,
727 pub keys: Option<&'static str>,
728 pub billing: Option<&'static str>,
729 pub usage: Option<&'static str>,
730 pub rank: &'static str,
731 pub free: &'static str,
732 pub cost: &'static str,
733 pub step: &'static str,
734}
735
736pub fn links(short: &str) -> Option<&'static Links> {
738 PROVIDERS.links.iter().find(|l| l.short == Tier::parse(short).map_or(short, |t| t.owner().spec().short))
739}
740
741pub fn page(code: &str, short: &str) -> Option<String> {
744 let l = links(short)?;
745 match code {
746 "no_key" => Some(l.signup.into()),
747 "bad_key" => l.keys.map(String::from),
748 "low_balance" => l.billing.map(String::from),
749 _ => None,
750 }
751}
752
753pub fn pages<'a>(code: &str, names: impl IntoIterator<Item = &'a str>) -> String {
755 names.into_iter().filter_map(|n| page(code, n).map(|p| format!(" · {n} {p}"))).collect()
756}
757
758pub struct Reply {
761 pub status: u16,
762 pub headers: Vec<(String, String)>,
763 pub body: Vec<u8>,
764}
765
766impl Reply {
767 fn header(&self, name: &str) -> Option<&str> {
768 self.headers.iter().find(|h| h.0 == name).map(|h| h.1.as_str())
769 }
770
771 fn refused(&self) -> bool {
774 self.header("x-brd-error").or(self.header("x-luminati-error")).is_some()
775 }
776
777 fn retry_in(&self) -> Option<u64> {
782 let num = |name: &str| self.header(name).and_then(|s| s.trim().parse::<u64>().ok());
783 let after = num("retry-after").filter(|s| (1..=3600).contains(s));
784 let titled = serde_json::from_slice::<Value>(&self.body).is_ok_and(|j| j["title"] == "RATE_LIMIT_EXCEEDED");
785 let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
786 let reset = num("x-ratelimit-reset").filter(|_| num("x-ratelimit-remaining") == Some(0));
787 let rate = self.status == 429 && titled;
788 after.or(if rate { Some(RETRY_AFTER) } else { reset.map(|t| t.saturating_sub(now).max(1)) })
789 }
790
791 fn limit(&self) -> Option<Limit> {
793 let num = |end: &str| {
794 let mine = |n: &str| n.starts_with("x-ratelimit-") && !n.contains("system_") && n.ends_with(end);
795 self.headers.iter().find(|h| mine(&h.0)).and_then(|h| h.1.trim().parse().ok())
796 };
797 Some(Limit { limit: num("-limit")?, remaining: num("-remaining")? })
798 }
799}
800
801fn reason(status: u16, body: &[u8], secrets: &[String]) -> String {
810 let j: Value = serde_json::from_slice(body).unwrap_or_default();
811 let text = |v: &Value| crate::lang::redact(v.as_str().unwrap_or_default(), secrets).to_lowercase();
812 let e = &j["errors"][0];
813 let faulted = if j["state"] == "faulted" { "faulted".into() } else { String::new() };
814 let (label, said) = match text(&e["detail"]) {
815 d if !d.is_empty() => (text(&e["pointer"]).rsplit('/').next().unwrap_or_default().to_string(), d),
816 _ => (faulted, text(&j["title"]).replace('_', " ")),
817 };
818 said_short(&format!("{status} {} {said}", if label.is_empty() { label } else { label + ":" }))
819}
820
821fn said_short(words: &str) -> String {
823 let ok = |w: &&str| w.bytes().all(|b| b.is_ascii_alphanumeric() || b".,:/#-".contains(&b));
824 let (mut n, cap) = (0, crate::settings::limit::<usize>("reason_chars") + 1);
825 let fits = words.split_whitespace().filter(ok).take_while(|w| {
826 n += w.len() + 1;
827 n <= cap
828 });
829 let fits: Vec<&str> = fits.collect();
830 fits.join(" ").trim_end_matches(['.', ':']).to_string()
831}
832
833fn token(v: Option<&str>) -> String {
835 let v = v.unwrap_or_default().trim().to_ascii_lowercase();
836 let ok =
837 !v.is_empty() && v.len() <= 32 && v.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_');
838 if ok { v } else { String::new() }
839}
840
841#[cfg(feature = "fake")]
844pub type Fake = fn(Api, &str, &Value) -> Reply;
845#[cfg(feature = "fake")]
846static FAKE: std::sync::OnceLock<Fake> = std::sync::OnceLock::new();
847
848#[cfg(feature = "fake")]
849pub fn fake(f: Fake) {
850 FAKE.set(f).ok(); }
852
853pub fn in_process() -> bool {
856 #[cfg(feature = "fake")]
857 if FAKE.get().is_some() {
858 return true;
859 }
860 cfg!(test)
861}
862
863async fn api(to: Api, key: &str, req: Value, cap: u64, wait: Duration) -> Result<Answer, Fail> {
866 #[cfg(feature = "fake")]
867 if let Some(f) = FAKE.get() {
868 let r = f(to, key, &req);
870 let ms = r.header("x-fake-delay-ms").and_then(|v| v.parse().ok()).unwrap_or(0);
871 tokio::time::sleep(Duration::from_millis(ms).min(wait)).await;
872 return if ms > wait.as_millis() as u64 { Err("provider_timeout".into()) } else { read(to, key, r) };
873 }
874 read(to, key, send(to, key, req, cap, wait).await?)
875}
876
877async fn send(to: Api, key: &str, req: Value, cap: u64, wait: Duration) -> Result<Reply, &'static str> {
880 let client = wreq::Client::builder().timeout(wait).build().map_err(|_| "net_error")?;
881 let r = match to.row().method {
882 "GET" => client.get(to.url(&req)),
883 _ => client.post(to.row().url).header("content-type", "application/json").body(req.to_string()),
884 };
885 let r = r.header("user-agent", concat!("fatsearch/", env!("CARGO_PKG_VERSION")));
886 let r = if to.row().accept.is_empty() { r } else { r.header("accept", to.row().accept) };
887 let r = if key.is_empty() { r } else { r.bearer_auth(key) };
888 let r = r.send().await.map_err(|e| net(&e).code)?;
889 let status = r.status().as_u16();
890 let mut reply = Reply { status, headers: pairs(r.headers()), body: Vec::new() };
891 reply.body = match (reply.refused(), status) {
892 (false, 200) => capped(r, cap).await.map_err(|f| f.code)?,
893 _ => capped(r, crate::settings::limit("err_cap_bytes")).await.unwrap_or_default(),
895 };
896 Ok(reply)
897}
898
899type Answer = (Vec<u8>, Option<Limit>, Option<u16>);
903
904fn read(to: Api, key: &str, r: Reply) -> Result<Answer, Fail> {
913 let limit = r.limit();
914 let cap = limit.map(|l| format!("cap {} on this account · ", l.limit)).filter(|_| !key.is_empty());
917 let target = r.header("x-brd-status-code").and_then(|s| s.trim().parse().ok());
918 let named = |z: &str| match (to, r.status) {
922 (Api::BdZoneCost, 422) => true,
923 (Api::BdRequest | Api::BdZoneCost, 400) => String::from_utf8_lossy(&r.body).contains(&format!("zone \"{z}\"")),
924 _ => false,
925 };
926 let zone = crate::settings::zone().filter(|z| !z.is_empty() && named(z));
927 let (code, why) = match (r.refused(), r.status) {
928 (false, 200) if !r.body.is_empty() => return Ok((r.body, limit, target)),
929 (false, 200) => ("provider_error", "empty".into()),
930 (true, _) => bd_refused(token(r.header("x-brd-error-code")), r.header("x-brd-status-code"), r.retry_in()),
931 (_, 400 | 422) if let Some(z) = zone => ("bad_zone", z.into()),
932 (_, 403 | 429) if let Some(s) = r.retry_in() => {
933 ("rate_limited", format!("{}retry in {s}s", cap.unwrap_or_default()))
934 }
935 (_, 401 | 403) => ("bad_key", String::new()),
936 (_, 408) => ("provider_timeout", String::new()),
937 (_, 429) => ("rate_limited", String::new()),
938 _ => ("provider_error", String::new()),
939 };
940 let mut secrets = crate::settings::secrets();
941 secrets.extend(Some(key.to_string()).filter(|k| !k.is_empty()));
942 let why = if code == "provider_error" && why.is_empty() { reason(r.status, &r.body, &secrets) } else { why };
943 let code = if why.starts_with("400 url:") { "provider_refused" } else { code };
945 let text = serde_json::from_slice::<Value>(&r.body)
947 .map_or_else(|_| String::from_utf8_lossy(&r.body).into(), |j| j.to_string());
948 let body = crate::lang::redact(&text, &secrets).into_bytes();
949 Err(Fail { code, status: r.status, body, why, limit })
950}
951
952fn bd_refused(why: String, site: Option<&str>, retry: Option<u64>) -> (&'static str, String) {
957 const SITE: [&str; 4] = ["blocked_401", "blocked_403", "blocked_429", "blocked_451"];
958 let relayed = site.and_then(|s| SITE.into_iter().find(|c| c[8..] == *s.trim())).filter(|_| why == "http_status");
959 match retry {
960 _ if !why.contains("rate_limit") => (relayed.unwrap_or("provider_refused"), why),
961 Some(s) => ("rate_limited", format!("{why} retry in {s}s")),
962 None => ("rate_limited", why),
963 }
964}
965
966async fn brightdata(ask: &Ask, key: &str, wait: Duration) -> Result<Raw, Fail> {
972 let (body, _, target) = api(Api::BdRequest, key, bd_body(ask), 2 * ask.max_bytes, wait).await?;
973 if ask.doc {
974 let (body, charset) = decode_body(body, None);
977 let status = target.unwrap_or(200);
978 return Ok(Raw { status, final_url: ask.url.clone(), body, charset, ..Raw::default() });
979 }
980 let j: Value = serde_json::from_slice(&body).map_err(|_| "provider_error")?;
981 let inner = |k: &str| j["headers"][k].as_str();
985 if inner("x-brd-error").is_some() && j["status_code"].as_u64().is_some_and(|s| s < 500) {
986 let why = token(inner("x-brd-err-code").or(inner("x-brd-error-code")));
987 let (code, why) = bd_refused(why, inner("x-brd-status-code"), None);
988 return Err(Fail { why, ..Fail::from(code) });
989 }
990 relayed(&j, "body", j["headers"]["x-unblocker-redirected-to"].as_str().unwrap_or(&ask.url))
991}
992
993fn relayed(j: &Value, body: &str, final_url: &str) -> Result<Raw, Fail> {
996 let headers =
997 header_lines(j["headers"].as_object().into_iter().flatten().map(|(k, v)| (k, v.as_str().unwrap_or(""))));
998 let status = j["status_code"].as_u64().map_or(Ok(200), u16::try_from).map_err(|_| "provider_error")?;
999 let body = j[body].as_str().unwrap_or_default().as_bytes().to_vec();
1000 Ok(Raw { status, final_url: final_url.into(), headers, body, ..Raw::default() })
1001}
1002
1003pub fn domain_country(url: &str) -> Option<String> {
1006 let host = crate::clean::host_of(url);
1007 PROVIDERS.cctld.get(host.rsplit('.').next().unwrap_or_default()).map(|c| c[..2].to_uppercase())
1008}
1009
1010pub fn home() -> String {
1012 crate::settings::get().country.value.to_uppercase()
1013}
1014
1015pub fn sent(ask: &Ask, t: Tier) -> Option<String> {
1024 let named = ask.country.as_ref().filter(|c| !c.is_empty()).map(|c| c.to_uppercase());
1025 let home = Some(home()).filter(|h| h != "US" || !t.can("auto_geo"));
1026 (t != Tier::Plain).then(|| named.or_else(|| domain_country(&ask.url)).or(home)).flatten()
1027}
1028
1029fn bd_body(ask: &Ask) -> Value {
1031 let format = if ask.doc { "raw" } else { "json" };
1032 let mut req = json!({"zone": crate::settings::zone(), "url": ask.url, "format": format});
1033 if let Some(c) = sent(ask, Tier::Bd) {
1034 req["country"] = c.to_lowercase().into();
1035 }
1036 req
1037}
1038
1039fn oxy_body(ask: &Ask) -> Value {
1044 let mut req = json!({"url": ask.url, "output": ["html"], "run_js": ask.js, "location": sent(ask, Tier::Oxy)});
1045 if ask.mobile {
1046 req["device"] = "mobile".into();
1047 }
1048 req
1049}
1050
1051async fn oxylabs(ask: &Ask, key: &str, wait: Duration) -> Result<Raw, Fail> {
1054 let (body, limit, _) = api(Api::OxyScrape, key, oxy_body(ask), 5 * ask.max_bytes, wait).await?;
1055 let j: Value = serde_json::from_slice(&body).map_err(|_| "provider_error")?;
1056 let r = &j["results"][0];
1057 let html = r["html"].as_str().ok_or("provider_error")?.as_bytes();
1058 let status = r["metadata"]["statuses"]["http_request"]["code"].as_u64().and_then(|c| u16::try_from(c).ok());
1061 Ok(Raw {
1062 status: status.unwrap_or(200),
1063 final_url: r["metadata"]["url"].as_str().unwrap_or(&ask.url).to_string(),
1064 body: if crate::clean::sniff(html).is_some() { file_bytes(html) } else { html.to_vec() },
1065 limit,
1066 ..Raw::default()
1067 })
1068}
1069
1070fn decodo_body(ask: &Ask) -> Value {
1076 let mut req = json!({"url": ask.url, "target": "universal"});
1077 if let Some(c) = sent(ask, Tier::Decodo) {
1078 req["geo"] = c.to_lowercase().into();
1079 }
1080 if ask.js {
1081 req["headless"] = "html".into();
1082 }
1083 if ask.mobile {
1084 req["device_type"] = "mobile".into();
1085 }
1086 req
1087}
1088
1089async fn decodo(ask: &Ask, key: &str, wait: Duration) -> Result<Raw, Fail> {
1090 let (body, limit, _) = api(Api::DecodoScrape, key, decodo_body(ask), 2 * ask.max_bytes, wait).await?;
1091 let j: Value = serde_json::from_slice(&body).map_err(|_| "provider_error")?;
1092 let r = &j["results"][0];
1093 r["content"].as_str().ok_or("provider_error")?;
1094 Ok(Raw { limit, ..relayed(r, "content", r["url"].as_str().unwrap_or(&ask.url))? })
1095}
1096
1097fn file_bytes(s: &[u8]) -> Vec<u8> {
1105 let hex = |c: u8| (c as char).to_digit(16).filter(|_| !c.is_ascii_uppercase()).map(|d| d as u8);
1106 let (mut out, mut i) = (Vec::with_capacity(s.len()), 0);
1107 while i < s.len() {
1108 match (&s[i..], s.get(i + 2).copied().and_then(hex), s.get(i + 3).copied().and_then(hex)) {
1109 ([b'\\', b'x', ..], Some(h @ 8..), Some(l)) => {
1110 out.push(h << 4 | l);
1111 i += 4;
1112 }
1113 _ => {
1114 out.push(s[i]);
1115 i += 1;
1116 }
1117 }
1118 }
1119 out
1120}
1121
1122#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
1126pub struct Hit {
1127 pub url: String,
1128 pub title: String,
1129 pub snippet: String,
1130}
1131
1132pub const SEARCH_MAX: usize = 20;
1135pub const SEARCH_TIMEOUT: Duration = Duration::from_secs(15);
1136
1137pub fn bill(cost: f64, upto: f64) -> String {
1139 if upto > 0.0 { format!("${cost:.4} + ≤${upto:.4} unverified") } else { format!("${cost:.4}") }
1140}
1141
1142pub fn spent(glue: &str, cost: f64, upto: f64) -> String {
1145 if cost > 0.0 || upto > 0.0 { format!("{glue}spent {}", bill(cost, upto)) } else { String::new() }
1146}
1147
1148fn search_req(t: Tier, q: &str, limit: usize, country: Option<&str>) -> (Api, Value) {
1153 let c = search_country(country);
1154 if t == Tier::Bd {
1155 let p = [("q", q.to_string()), ("brd_json", "1".into()), ("gl", c.to_lowercase())];
1156 let url =
1157 url::Url::parse_with_params("https://www.google.com/search", &p).map(String::from).unwrap_or_default();
1158 let req = json!({"zone": crate::settings::zone(), "url": url, "format": "json", "country": c.to_lowercase()});
1159 return (Api::BdRequest, req);
1160 }
1161 (Api::OxySearch, json!({"query": q, "max_results": limit.min(SEARCH_MAX), "location": c}))
1162}
1163
1164pub fn search_country(country: Option<&str>) -> String {
1166 country.filter(|c| !c.is_empty()).map_or_else(home, str::to_uppercase)
1167}
1168
1169pub fn hits(t: Tier, body: &[u8], limit: usize) -> Result<Vec<Hit>, &'static str> {
1172 let j: Value = serde_json::from_slice(body).map_err(|_| "provider_error")?;
1173 let s = |v: &Value| crate::clean::collapse(v.as_str().unwrap_or_default());
1174 let (list, url, snip) = match t {
1175 Tier::Bd => {
1176 let inner = j["body"].as_str().and_then(|b| serde_json::from_str::<Value>(b).ok()).unwrap_or_default();
1177 let j = if j["organic"].is_array() { &j } else { &inner };
1178 (j["organic"].as_array().cloned().ok_or("provider_error")?, "link", "description")
1179 }
1180 _ => (j["results"].as_array().cloned().ok_or("provider_error")?, "url", "outline"),
1181 };
1182 let hits = list.iter().filter(|r| r[url].is_string()).take(limit);
1183 Ok(hits
1184 .map(|r| Hit {
1185 url: s(&r[url]),
1186 title: s(&r["title"]),
1187 snippet: if r[snip].is_array() { s(&r[snip][0]) } else { s(&r[snip]) },
1188 })
1189 .collect())
1190}
1191
1192pub async fn search(
1194 t: Tier,
1195 q: &str,
1196 limit: usize,
1197 country: Option<&str>,
1198 wait: Duration,
1199) -> (Result<(Vec<Hit>, Option<Limit>), Fail>, bool) {
1200 let key = t.key().unwrap_or_default();
1201 let (to, req) = search_req(t, q, limit, country);
1202 let r = api(to, &key, req, 2 * crate::cli::MAX_BYTES, wait).await;
1203 let r = r.and_then(|(body, lim, _)| hits(t, &body, limit).map(|h| (h, lim)).map_err(Fail::from));
1204 let billed = charged(t, r.as_ref().map(|_| 200));
1206 (r, billed)
1207}
1208
1209pub async fn gh_repos(q: String, limit: usize) -> Result<(Vec<Hit>, Vec<(&'static str, String)>), Fail> {
1221 let (key, per) = (crate::settings::key("gh").unwrap_or_default(), limit.min(crate::settings::limit("gh_max")));
1222 let call = |to: Api, req: Value| api(to, &key, req, 4 << 20, SEARCH_TIMEOUT);
1223 let login = q.len() <= 39 && !q.contains(|c: char| !c.is_ascii_alphanumeric() && c != '-');
1224 let user = login.then_some(async {
1225 let by_stars = json!({"q": format!("user:{q}"), "sort": "stars", "order": "desc", "per_page": "100"});
1226 match call(Api::GhRepos, by_stars).await {
1227 Err(f) if f.status == 422 => call(Api::GhUser, json!({"q": q, "sort": "pushed", "per_page": "100"})).await,
1228 r => r,
1229 }
1230 });
1231 let req = json!({"q": q, "sort": "stars", "order": "desc", "per_page": per.to_string()});
1232 let (found, user) = tokio::join!(call(Api::GhRepos, req), async { Some(user?.await) });
1233 let items =
1234 |r: Result<Answer, Fail>| serde_json::from_slice::<Value>(&r?.0).map_err(|_| Fail::from("provider_error"));
1235 let items = |r| items(r).map(|j| j["items"].as_array().or(j.as_array()).cloned().unwrap_or_default());
1236 let mut repos = items(found)?;
1237 let user = match user.map(items) {
1239 Some(Err(f)) if f.status == 404 => Some(("not_found", format!(" · no user {q}"))),
1240 Some(Err(f)) if repos.is_empty() => return Err(Fail { why: format!("user {q} {}", f.why), ..f }),
1241 Some(Err(f)) => Some((f.code, format!(" · user lookup: {} {}", f.code, f.why).trim_end().into())),
1242 theirs => theirs.map(|r| repos.extend(r.unwrap_or_default())).map(|()| ("ok", String::new())),
1243 };
1244 repos.sort_by_key(|r| std::cmp::Reverse(r["stargazers_count"].as_u64()));
1245 let s = |v: &Value| crate::clean::collapse(v.as_str().unwrap_or_default());
1246 let hit = |r: &Value| {
1247 let stars = crate::lang::ksize(r["stargazers_count"].as_u64().unwrap_or(0) as usize);
1248 let pushed = format!("pushed {}", crate::lang::cut(&s(&r["pushed_at"]), 10));
1249 let about: Vec<String> =
1250 [crate::lang::short(&s(&r["description"]), 80), pushed].into_iter().filter(|x| !x.is_empty()).collect();
1251 Hit { url: s(&r["html_url"]), title: format!("★{stars} {}", s(&r["full_name"])), snippet: about.join(" · ") }
1252 };
1253 let on_github =
1254 |h: &Hit| url::Url::parse(&h.url).is_ok_and(|u| u.scheme() == "https" && u.host_str() == Some("github.com"));
1255 let hits = crate::lang::uniq(repos.iter().map(hit).filter(on_github), |h| h.url.clone());
1256 Ok((hits.into_iter().take(per).collect(), [("ok", String::new())].into_iter().chain(user).collect()))
1257}
1258
1259pub const ACCOUNTS: [Tier; 2] = [Tier::Oxy, Tier::Bd];
1263pub const KEYS: [Tier; 3] = [Tier::Oxy, Tier::Bd, Tier::Decodo];
1265pub const ACCOUNT_TIMEOUT: Duration = Duration::from_secs(10);
1267const ACCOUNT_CAP: u64 = 1 << 20;
1269
1270#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
1272#[serde(default)]
1273pub struct Account {
1274 pub provider: String,
1276 pub code: String,
1278 #[serde(skip_serializing_if = "String::is_empty")]
1279 pub why: String,
1280 pub ms: u64,
1281 pub calls: usize,
1282 pub scrapers: Option<usize>,
1283 pub balance: Option<f64>,
1285 pub spend: Option<f64>,
1287 pub reqs_unblocker: Option<u64>,
1288 pub reqs_serp: Option<u64>,
1289 pub zone_cost: Option<f64>,
1291 pub zones: Vec<String>,
1292 pub denied: Vec<Api>,
1294}
1295
1296pub fn account_calls(t: Tier, month: (&str, &str), zone: Option<&str>) -> Vec<(Api, Value)> {
1300 let (from, to) = month;
1301 match t {
1302 Tier::Bd => {
1303 let mut v = vec![
1304 (Api::BdBalance, json!({})),
1305 (Api::BdZones, json!({})),
1306 (Api::BdCosts, json!({"dimension": "products", "filters": {}, "from": from, "to": to})),
1307 ];
1308 v.extend(zone.map(|z| (Api::BdZoneCost, json!({"from": from, "to": to, "zone": z}))));
1309 v
1310 }
1311 _ => vec![(Api::OxyScrapers, json!({}))],
1312 }
1313}
1314
1315pub fn account_read(a: &mut Account, to: Api, body: &[u8]) {
1319 let j: Value = serde_json::from_slice(body).unwrap_or_default();
1320 match to {
1321 Api::OxyScrapers => a.scrapers = j["scrapers"].as_array().map(Vec::len),
1322 Api::BdBalance => a.balance = j["balance"].as_f64(),
1323 Api::BdZones => {
1324 let z = j.as_array().into_iter().flatten().filter_map(|z| z["type"].as_str().map(String::from));
1325 a.zones = z.collect::<std::collections::BTreeSet<_>>().into_iter().collect();
1326 }
1327 Api::BdCosts => a.spend = j["total"].as_object().map(|t| spend(t.values().filter_map(Value::as_f64))),
1328 Api::BdZoneCost => {
1329 let customers = j.as_object().into_iter().flat_map(|c| c.values());
1330 let plans: Vec<&Value> = customers.filter_map(Value::as_object).flat_map(|p| p.values()).collect();
1331 let sum = |k: &str| plans.iter().map(|p| p[k].as_u64()).sum::<Option<u64>>();
1332 let n = |k: &str| sum(k).filter(|_| !plans.is_empty());
1333 (a.reqs_unblocker, a.reqs_serp) = (n("reqs_unblocker"), n("reqs_serp"));
1334 a.zone_cost = plans.iter().map(|p| p["cost"].as_f64()).sum::<Option<f64>>().filter(|_| !plans.is_empty());
1335 }
1336 _ => {}
1337 }
1338}
1339
1340pub async fn account(t: Tier, key: String, month: (String, String), zone: Option<&str>) -> Account {
1345 let t0 = std::time::Instant::now();
1346 let mut a = Account { provider: t.spec().short.into(), code: "ok".into(), ..Account::default() };
1347 for (to, req) in account_calls(t, (&month.0, &month.1), zone) {
1348 a.calls += 1;
1349 match api(to, &key, req, ACCOUNT_CAP, ACCOUNT_TIMEOUT).await {
1350 Ok((body, ..)) => account_read(&mut a, to, &body),
1351 Err(f) if f.status == 403 && f.code == "bad_key" => {
1352 a.denied.push(to);
1353 }
1354 Err(f) => {
1355 (a.code, a.why) = (f.code.into(), f.why);
1356 break;
1357 }
1358 }
1359 }
1360 if a.denied.len() == a.calls {
1361 a.code = "bad_key".into();
1362 }
1363 a.ms = t0.elapsed().as_millis() as u64;
1364 a
1365}
1366
1367pub const NO_HOST: &str = "https://does-not-exist.decodo.com";
1369
1370pub fn check_call(t: Tier) -> (Api, Value) {
1374 match t.owner() {
1375 Tier::Bd => (Api::BdZones, json!({})),
1376 Tier::Decodo => (Api::DecodoScrape, json!({"url": NO_HOST, "target": "universal"})),
1377 _ => (Api::OxyScrapers, json!({})),
1378 }
1379}
1380
1381pub async fn check_key(t: Tier, key: String) -> Result<(String, Vec<String>), Fail> {
1384 let (to, req) = check_call(t);
1385 let j: Value = match api(to, &key, req, ACCOUNT_CAP, ACCOUNT_TIMEOUT).await {
1386 Err(f) if to == Api::DecodoScrape && f.status == 400 => json!({}),
1387 r => serde_json::from_slice(&r?.0).unwrap_or_default(),
1388 };
1389 let zones = j.as_array().into_iter().flatten().filter(|z| z["type"] == "unblocker");
1390 let what = j["scrapers"].as_array().map_or("key ok".into(), |s| format!("{} scrapers", s.len()));
1391 Ok((what, zones.filter_map(|z| z["name"].as_str().map(String::from)).collect()))
1392}
1393
1394fn browser() -> wreq_util::Emulation {
1397 wreq_util::Emulation::builder().profile(wreq_util::Profile::Safari26).platform(wreq_util::Platform::MacOS).build()
1398}
1399
1400#[cfg(test)]
1401mod tests {
1402 use super::*;
1403
1404 #[test]
1407 fn plain_calls_to_one_host_are_paced() {
1408 let url = format!("https://pace-{}.example/a", std::process::id());
1409 let (first, waited) = pace(&url);
1410 assert!(first.is_some() && waited < 500, "the first call runs at once: {waited} ms");
1411 let second = std::thread::spawn(move || pace(&url).1);
1412 std::thread::sleep(Duration::from_millis(300));
1413 drop(first);
1414 let waited = second.join().expect("second call");
1415 assert!((600..2000).contains(&waited), "the held turn, then 1 s from the first start: {waited} ms");
1416 let other = format!("https://pace-tail-{}.example/", std::process::id());
1418 let at = crate::settings::get().cache.value.join("pace").join(crate::clean::host_of(&other));
1419 std::fs::create_dir_all(at.parent().expect("pace dir")).ok();
1420 std::fs::write(&at, format!("1.0{}", "x".repeat(40))).ok();
1421 drop(pace(&other));
1422 let kept = std::fs::read_to_string(&at).unwrap_or_default();
1423 assert!(kept.get(..20).and_then(|k| k.parse::<f64>().ok()).is_some_and(|t| t > 1e9), "one start: {kept}");
1424 assert_eq!(kept.len(), 43, "written over, never cut or grown");
1425 }
1426
1427 #[test]
1430 fn charged_only_on_a_charged_reply() {
1431 let (late, err) = (Fail::from("provider_timeout"), Fail::from("provider_error"));
1432 for t in [Tier::Oxy, Tier::OxyJs, Tier::Bd] {
1433 let fetch = |s| charged(t, s);
1434 assert!(fetch(Ok(200)) && fetch(Ok(404)), "{t:?}: an answer");
1435 assert_eq!(fetch(Ok(502)), t != Tier::Bd, "{t:?}: a site's 5xx");
1437 assert!(!fetch(Err(&late)) && !fetch(Err(&err)), "{t:?}: a timeout or refusal is free");
1438 }
1439 assert!(!charged(Tier::Plain, Ok(200)), "plain is free");
1440 }
1441
1442 #[test]
1445 fn oxy_request_body() {
1446 let ask = Ask { url: "https://ex.com/a".into(), ..Ask::default() };
1447 let want = json!({"url": "https://ex.com/a", "output": ["html"], "run_js": false, "location": "US"});
1448 assert_eq!(oxy_body(&ask), want);
1449 let ask = Ask { url: "https://ex.com/a".into(), js: true, mobile: true, ..Ask::default() };
1450 assert_eq!(
1451 oxy_body(&ask),
1452 json!({"url": "https://ex.com/a", "output": ["html"], "run_js": true, "location": "US", "device": "mobile"})
1453 );
1454 assert_eq!(oxy_body(&Ask { url: "https://www.lemonde.fr/".into(), ..Ask::default() })["location"], "FR");
1455 }
1456
1457 #[test]
1460 fn oxylabs_file_bytes() {
1461 let file: &[u8] = b"%PDF-1.5 \x9c\xff\\x48 \xc3\xa9 \\x9C \\x9";
1462 let escaped = r"%PDF-1.5 \x9c\xff\x48 é \x9C \x9";
1463 assert_eq!(file_bytes(escaped.as_bytes()), file);
1464 }
1465
1466 #[test]
1472 fn keys_go_only_to_listed_endpoints() {
1473 const HOSTS: &[&str] = &[
1476 "api.brightdata.com", "webapi.oxylabs.io", "1.1.1.1", "api.github.com", "data.decodo.com", "fatsearch.com",
1477 ];
1478 const NEVER: &[&str] = &["password", "/proxy/list", "/billing", "/account", "/users"];
1479 const POST: &[&str] = &["/request", "/scrape", "/search", "/costs/export/json", "/v1/l2"];
1480 for (i, ApiRow { api, method, url, .. }) in PROVIDERS.apis.iter().enumerate() {
1481 assert_eq!(*api as usize, i, "apis is indexed by Api");
1482 let u = url::Url::parse(url).expect("url");
1483 assert_eq!(u.scheme(), "https", "{url}");
1484 assert!(HOSTS.contains(&u.host_str().unwrap_or_default()), "{url}: unlisted host");
1485 let p = u.path();
1486 let public = u.host_str() == Some("api.github.com") && p.ends_with("/repos");
1488 assert!(p != "/zone" && (public || NEVER.iter().all(|n| !p.contains(n))), "{url}: returns secrets");
1489 assert!(*method == "GET" || (*method == "POST" && POST.iter().any(|e| p.ends_with(e))), "{url}");
1490 }
1491 let links: Vec<&str> = PROVIDERS
1492 .links
1493 .iter()
1494 .flat_map(|l| [Some(l.signup), Some(l.mint), l.keys, l.billing, l.usage])
1495 .flatten()
1496 .collect();
1497 assert!(links.iter().all(|l| l.starts_with("https://")));
1498 let src: String = [
1499 include_str!("provider.rs"),
1500 include_str!("fetch.rs"),
1501 include_str!("cli.rs"),
1502 include_str!("stats.rs"),
1503 include_str!("settings.rs"),
1504 include_str!("mcp.rs"),
1505 include_str!("data/providers.json"),
1506 ]
1507 .iter()
1508 .map(|f| f.split("#[cfg(test)]").next().unwrap_or_default())
1509 .collect();
1510 assert_eq!(src.matches("bearer_auth(").count(), 1, "one request carries a key");
1511 assert!(!src.contains("basic_auth(") && !src.to_ascii_lowercase().contains("\"authorization\""));
1512 let listed: Vec<&str> = PROVIDERS.apis.iter().map(|a| a.url).chain(links).collect();
1513 let provider = [
1514 "oxylabs.io", "brightdata.com", "luminati", "webshare.io", "decodo.com", "1.1.1.1", "github.com",
1515 "fatsearch.com",
1516 ];
1517 let lits: Vec<String> =
1518 src.split("\"http").skip(1).filter_map(|r| r.split('"').next()).map(|r| format!("http{r}")).collect();
1519 let found: Vec<&String> =
1521 lits.iter().filter(|l| *l != NO_HOST && provider.iter().any(|h| l.contains(h))).collect();
1522 assert_eq!(found.len(), listed.len(), "each provider URL is written once, in apis or links: {found:?}");
1523 assert!(found.iter().all(|l| listed.contains(&l.as_str())), "provider URL outside apis/links: {found:?}");
1524 }
1525
1526 #[test]
1528 fn replies_become_codes() {
1529 let r = |status, refused: bool, body: &str| {
1530 let h = [
1531 ("x-brd-error", "Access denied: x.gov is classified as Government"),
1532 ("x-brd-error-code", "proxy_error"),
1533 ];
1534 let headers = h.iter().filter(|_| refused).map(|(k, v)| (k.to_string(), v.to_string())).collect();
1535 read(Api::BdRequest, "", Reply { status, headers, body: body.into() })
1536 };
1537 assert_eq!(r(200, false, "{}"), Ok((b"{}".to_vec(), None, None)));
1538 let raw = Reply { status: 200, headers: vec![("x-brd-status-code".into(), "404".into())], body: b"<p>".into() };
1539 assert_eq!(
1540 read(Api::BdRequest, "", raw),
1541 Ok((b"<p>".to_vec(), None, Some(404))),
1542 "Bright Data's target status"
1543 );
1544 let empty = r(200, false, "").expect_err("200 + empty body");
1545 assert_eq!((empty.code, empty.why.as_str()), ("provider_error", "empty"));
1546 let gov = r(200, true, "").expect_err("Bright Data refusal");
1547 assert_eq!(
1548 (gov.code, gov.why.as_str()),
1549 ("provider_refused", "proxy_error"),
1550 "the code header, not the message"
1551 );
1552 let brd = |code: &str, site: &str| {
1554 let h = [("x-brd-error", "rejected"), ("x-brd-error-code", code), ("x-brd-status-code", site)];
1555 let reply = Reply { status: 200, headers: h.map(|(k, v)| (k.into(), v.into())).to_vec(), body: vec![] };
1556 let f = read(Api::BdRequest, "", reply);
1557 f.map_err(|f| (f.code, f.why)).expect_err("refused")
1558 };
1559 assert_eq!(brd("http_status", "403"), ("blocked_403", "http_status".into()), "a relayed site 403");
1560 assert_eq!(brd("http_status", "502").0, "provider_refused", "no site block row");
1561 assert_eq!(brd("bucket_rate_limit", "").0, "rate_limited", "a rate limit");
1562 assert_eq!(bd_refused("bucket_rate_limit".into(), None, Some(30)).1, "bucket_rate_limit retry in 30s");
1563 assert!(!charged(Tier::Bd, Err(&Fail::from("blocked_403"))), "a relayed status is no answer: not billed");
1564 assert_eq!(token(Some("Access denied: x.gov")), "", "free text is never a token");
1565 assert_eq!(token(Some(" Proxy_Error ")), "proxy_error");
1566 let f = r(401, false, "Invalid api key").expect_err("401");
1567 assert_eq!((f.code, f.status, f.body.as_slice()), ("bad_key", 401, &b"Invalid api key"[..]));
1568 assert_eq!(r(403, false, "").map_err(|f| f.code), Err("bad_key"));
1569 assert_eq!(r(408, false, "").map_err(|f| f.code), Err("provider_timeout"));
1570 assert_eq!(r(429, false, "").map_err(|f| (f.code, f.why)), Err(("rate_limited", String::new())), "quota?");
1571 assert_eq!(r(500, false, "<html>oops").map_err(|f| (f.code, f.why)), Err(("provider_error", "500".into())));
1572 }
1573
1574 #[test]
1576 fn a_rate_limit_says_when_and_its_cap() {
1577 let acct = |h: &[(&str, &str)]| Reply {
1578 status: 429,
1579 headers: h.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(),
1580 body: br#"{"status":429,"title":"RATE_LIMIT_EXCEEDED","detail":"Too many requests."}"#.to_vec(),
1581 };
1582 let h = [
1583 ("x-ratelimit-search_total_dynamic_europe-1234567-limit", "10"),
1584 ("x-ratelimit-search_total_dynamic_europe-1234567-remaining", "0"),
1585 ("x-ratelimit-system_search_total_dynamic_europe-remaining", "9999"),
1586 ];
1587 let f = read(Api::OxyScrape, "", acct(&h)).expect_err("429");
1588 assert_eq!(
1589 (f.why.as_str(), f.limit),
1590 ("retry in 5s", Some(Limit { limit: 10, remaining: 0 })),
1591 "no key, no cap"
1592 );
1593 let f = read(Api::OxyScrape, "k3y", acct(&h)).expect_err("429");
1594 assert_eq!(f.why, "cap 10 on this account · retry in 5s", "the account's own cap beside its wait");
1595 let f = read(Api::OxyScrape, "", acct(&[("retry-after", "7")])).expect_err("429");
1596 assert_eq!((f.why.as_str(), f.limit), ("retry in 7s", None), "retry-after wins; no budget sent");
1597 assert_eq!(
1598 read(Api::OxyScrape, "", acct(&[("retry-after", "Wed, 21 Oct 2026 07:28:00 GMT")])).map_err(|f| f.why),
1599 Err("retry in 5s".into())
1600 );
1601 }
1602
1603 #[test]
1605 fn a_refusal_keeps_its_reason() {
1606 let fail = |status, body: &str| {
1607 let r = Reply { status, headers: vec![], body: body.into() };
1608 read(Api::OxyScrape, "", r).map_err(|f| (f.code, f.why)).expect_err("refused")
1609 };
1610 let why = |status, body: &str| fail(status, body).1;
1611 let url =
1612 r##"{"title":"INVALID_BODY_PROPERTY","errors":[{"detail":"Value not supported.","pointer":"#/url"}]}"##;
1613 assert_eq!(fail(400, url), ("provider_refused", "400 url: value not supported".into()), "it refuses the URL");
1614 let zip = r##"{"errors":[{"detail":"Value should be in zip/postal codes.","pointer":"#/location"}]}"##;
1615 assert_eq!(fail(400, zip), ("provider_error", "400 location: value should be in zip/postal codes".into()));
1616 let field = r##"{"errors":[{"detail":"Input should be less than or equal to 20","pointer":"#/max_results"}]}"##;
1617 assert_eq!(fail(400, field).0, "provider_error", "our own field: no refusal of the URL");
1618 let faulted =
1619 r#"{"status":500,"state":"faulted","title":"REQUEST_FAILED_AFTER_TOO_MANY_RETRIES","detail":"x"}"#;
1620 assert_eq!(why(500, faulted), "500 faulted: request failed after too many retries");
1621 let long = r#"{"title":"A_B","errors":[{"detail":"key=*** <b>is</b> wrong and this sentence goes on far too long to fit"}]}"#;
1622 assert_eq!(why(400, long), "400 wrong and this sentence goes on far too long", "masked and markup words drop");
1623 let key = ["Ab3dEf6hIj9kLm2nOp".to_string()];
1625 let escaped: String = key[0].chars().map(|c| format!("\\u{:04x}", c as u32)).collect();
1626 let body = format!(r##"{{"errors":[{{"detail":"key {escaped} refused","pointer":"#/key"}}]}}"##);
1627 assert_eq!(reason(400, body.as_bytes(), &key), "400 key: key refused");
1628 }
1629
1630 #[test]
1632 fn search_requests_and_answers() {
1633 let (u, r) = search_req(Tier::Oxy, "heidelberg university", 50, Some("fr"));
1634 assert_eq!(u.row().url, "https://webapi.oxylabs.io/v1/search");
1635 assert_eq!(r, json!({"query": "heidelberg university", "max_results": 20, "location": "FR"}));
1636 assert_eq!(search_req(Tier::Oxy, "a", 10, None).1, json!({"query": "a", "max_results": 10, "location": "US"}));
1637 let none = search_req(Tier::Bd, "a", 10, None).1;
1638 assert_eq!(
1639 (none["country"].as_str(), none["url"].as_str()),
1640 (Some("us"), Some("https://www.google.com/search?q=a&brd_json=1&gl=us"))
1641 );
1642 let (u, r) = search_req(Tier::Bd, "a b&c", 10, Some("fr"));
1643 assert_eq!(u.row().url, "https://api.brightdata.com/request");
1644 assert_eq!(r["url"], "https://www.google.com/search?q=a+b%26c&brd_json=1&gl=fr");
1645 assert_eq!((r["format"].as_str(), r["country"].as_str()), (Some("json"), Some("fr")));
1646 let oxy = hits(Tier::Oxy, include_bytes!("../tests/fixtures/oxy-search.json"), 10).expect("oxy fixture");
1647 assert_eq!(oxy.len(), 5);
1648 assert_eq!(
1649 (oxy[0].url.as_str(), oxy[0].title.as_str()),
1650 ("https://www.uni-heidelberg.de/en", "Heidelberg University")
1651 );
1652 assert!(oxy[0].snippet.starts_with("Heidelberg University – the oldest in Germany"));
1653 assert_eq!(hits(Tier::Oxy, include_bytes!("../tests/fixtures/oxy-search.json"), 2).map(|h| h.len()), Ok(2));
1654 let bd = hits(Tier::Bd, include_bytes!("../tests/fixtures/bd-serp.json"), 10).expect("bd fixture");
1655 assert_eq!(bd.len(), 3);
1656 assert_eq!(bd[0].url, "https://pizza.example.com/delivery-springfield");
1657 assert!(bd[0].snippet.starts_with("Example Pizzeria offers fast pizza delivery"));
1658 assert_eq!(hits(Tier::Oxy, b"<html>", 10), Err("provider_error"));
1659 assert_eq!(hits(Tier::Oxy, br#"{"state":"done","results":[]}"#, 10), Ok(vec![]));
1660 }
1661
1662 #[test]
1665 fn account_answers() {
1666 let mut a = Account::default();
1667 account_read(&mut a, Api::OxyScrapers, include_bytes!("../tests/fixtures/account-oxy-scrapers.json"));
1668 assert_eq!(a.scrapers, Some(351));
1669 account_read(&mut a, Api::BdBalance, include_bytes!("../tests/fixtures/account-bd-balance.json"));
1670 account_read(&mut a, Api::BdZones, include_bytes!("../tests/fixtures/account-bd-zones.json"));
1671 account_read(&mut a, Api::BdCosts, include_bytes!("../tests/fixtures/account-bd-costs.json"));
1672 account_read(&mut a, Api::BdZoneCost, include_bytes!("../tests/fixtures/account-bd-zone-cost.json"));
1673 assert_eq!((a.balance, format!("{:.2}", a.spend.unwrap_or_default())), (Some(1234.56), "5.50".into()));
1674 assert_eq!((a.reqs_unblocker, a.reqs_serp, a.zone_cost), (Some(1500), Some(700), Some(3.21)));
1675 let all: Value = serde_json::from_slice(include_bytes!("../tests/fixtures/account-bd-costs.json")).unwrap();
1676 let every: f64 = all
1677 .as_object()
1678 .unwrap()
1679 .values()
1680 .flat_map(|d| d.as_object().unwrap().values())
1681 .filter_map(Value::as_f64)
1682 .sum();
1683 assert_eq!(format!("{every:.2}"), "11.00", "the double count the `total` rule avoids");
1684 assert_eq!(a.zones, ["dc", "serp", "unblocker"], "zone types, sorted, each once");
1685 let mut b = Account::default();
1686 account_read(&mut b, Api::BdZoneCost, b"{}");
1687 account_read(&mut b, Api::BdBalance, b"<html>");
1688 assert_eq!((b.reqs_unblocker, b.balance, b.zone_cost), (None, None, None), "no answer = n/a, never 0");
1689 let calls = |z| account_calls(Tier::Bd, ("2026-10-01", "2026-11-01"), z);
1690 assert_eq!(calls(None).len(), 3, "no zone, no zone month");
1691 let all = calls(Some("unblocker"));
1692 assert_eq!(all[3].1, json!({"zone": "unblocker", "from": "2026-10-01", "to": "2026-11-01"}));
1693 assert_eq!(account_calls(Tier::Oxy, ("", ""), None)[0].0.row().url, "https://webapi.oxylabs.io/v1/scrapers");
1694 }
1695
1696 #[test]
1698 fn row_pages() {
1699 assert_eq!(
1700 pages("no_key", ["oxyjs", "bd"]),
1701 " · oxyjs https://dashboard.oxylabs.io/en/registration · bd https://brightdata.com/cp/start"
1702 );
1703 assert_eq!(pages("bad_key", "oxy bd".split(' ')), format!("{K} · bd https://brightdata.com/cp/setting/users"));
1704 const K: &str = " · oxy https://dashboard.oxylabs.io (a Web API instance's key)";
1706 assert_eq!(pages("bad_key", ["oxy"]), K);
1707 assert_eq!(pages("provider_error", ["bd"]), "", "only key and money codes");
1708 assert_eq!(page("low_balance", "bd").as_deref(), Some("https://brightdata.com/cp/billing"));
1709 assert_eq!(page("no_key", "plain"), None);
1710 }
1711
1712 #[test]
1715 fn country_from_tld() {
1716 let at = |url: &str, c: Option<&str>, t: Tier| {
1717 sent(&Ask { url: url.into(), country: c.map(String::from), ..Ask::default() }, t)
1718 };
1719 for (url, want) in [
1720 ("https://www.lemonde.fr/a", Some("FR")),
1721 ("https://www.spiegel.de/", Some("DE")),
1722 ("https://www.bbc.co.uk/news", Some("GB")),
1723 ("https://www.idealo.fr/x", Some("FR")),
1724 ("https://ex.gr/", Some("GR")),
1725 ("https://example.com/", None),
1726 ("https://europa.eu/", None),
1727 ("https://crates.io/", None),
1728 ("https://ex.us/", None),
1729 ] {
1730 assert_eq!(at(url, None, Tier::Bd).as_deref(), want, "{url}");
1731 for t in [Tier::Oxy, Tier::OxyJs] {
1732 assert_eq!(at(url, None, t).as_deref(), want.or(Some("US")), "{url} {t:?}");
1733 }
1734 }
1735 assert_eq!(at("https://www.lemonde.fr/", Some("de"), Tier::Oxy).as_deref(), Some("DE"), "country: wins");
1736 assert_eq!(at("https://ex.com/", Some("pl"), Tier::Bd).as_deref(), Some("PL"));
1737 assert_eq!(at("https://www.lemonde.fr/", Some("de"), Tier::Plain), None);
1738 }
1739
1740 #[test]
1744 fn oxylabs_always_names_a_location_bd_only_a_named_one() {
1745 let ask = |url: &str, c: Option<&str>| Ask { url: url.into(), country: c.map(String::from), ..Ask::default() };
1746 for (url, c, oxy, bd) in [
1747 ("https://example.com/", None, "US", None),
1748 ("https://example.com/", Some(""), "US", None),
1749 ("https://www.lemonde.fr/a", None, "FR", Some("fr")),
1750 ("https://example.com/", Some("de"), "DE", Some("de")),
1751 ] {
1752 let a = ask(url, c);
1753 assert_eq!(oxy_body(&a)["location"].as_str(), Some(oxy), "{url} {c:?}");
1754 assert_eq!(bd_body(&a).get("country").and_then(Value::as_str), bd, "{url} {c:?}");
1755 assert_eq!(decodo_body(&a)["geo"].as_str(), Some(oxy.to_lowercase().as_str()), "Decodo as Oxylabs");
1756 }
1757 let js = Ask { js: true, mobile: true, ..ask("https://ex.com/", None) };
1759 let mut want = json!({"url": "https://ex.com/", "target": "universal", "geo": "us"});
1760 assert_eq!(decodo_body(&ask("https://ex.com/", None)), want);
1761 (want["headless"], want["device_type"]) = ("html".into(), "mobile".into());
1762 assert_eq!(decodo_body(&js), want);
1763 }
1764
1765 #[test]
1767 fn private_addresses() {
1768 for ip in [
1769 "127.0.0.1", "10.1.2.3", "172.16.0.1", "192.168.1.1", "169.254.169.254", "100.64.0.1", "0.0.0.0",
1770 "255.255.255.255", "224.0.0.1", "240.0.0.1", "198.18.0.1", "192.0.0.8", "::1", "::", "fe80::1", "fc00::1",
1771 "fd12::1", "::ffff:127.0.0.1", "::ffff:10.0.0.1", "64:ff9b::a9fe:a9fe", "2001:db8::1", "::7f00:1",
1772 "::a9fe:a9fe", "2002:7f00:1::", "2002:c0a8:101::1", "203.0.113.9", "fec0::1", "ff02::1", "192.0.2.1",
1773 "198.51.100.7",
1774 ] {
1775 assert!(private_ip(ip.parse().unwrap()), "{ip} is private");
1776 }
1777 let block =
1779 |b: &str| b.split_once('/').map(|(ip, n)| (ip.parse::<std::net::IpAddr>().is_ok(), n.parse::<u32>()));
1780 let bad: Vec<&&str> =
1781 crate::fetch::SITES.fence.iter().filter(|b| !matches!(block(b), Some((true, Ok(_))))).collect();
1782 assert!(bad.is_empty(), "{bad:?}");
1783 for ip in [
1784 "8.8.8.8", "172.32.0.1", "100.128.0.1", "198.20.0.1", "2606:4700::1111", "::ffff:8.8.8.8",
1785 "2002:808:808::1",
1786 ] {
1787 assert!(!private_ip(ip.parse().unwrap()), "{ip} is public");
1788 }
1789 for url in [
1790 "http://localhost:8080/",
1791 "http://api.localhost/",
1792 "http://127.0.0.1/",
1793 "http://2130706433/",
1794 "http://0x7f.1/",
1795 "http://[::1]/",
1796 "http://169.254.169.254/latest/meta-data/",
1797 "http://10.0.0.1:9000/x",
1798 "data:text/html,hi",
1799 ] {
1800 assert!(private_host(url), "{url} is refused");
1801 }
1802 assert!(!private_host("https://example.com/") && !private_host("http://8.8.8.8/"));
1803 }
1804
1805 #[test]
1809 fn a_meta_refresh_moves_only_alone() {
1810 let page = |status: u16, head: &str, body: &str| Raw {
1811 status,
1812 ctype: "text/html".into(),
1813 body: format!("<html><head>{head}</head><body>{body}</body></html>").into_bytes(),
1814 final_url: "https://a.example/releases/latest/".into(),
1815 ..Raw::default()
1816 };
1817 let tag = |c: &str| format!("<meta http-equiv=\"Refresh\" content=\"{c}\">");
1818 let to = |status, head: &str, body: &str| refresh(&page(status, head, body));
1819 let at = Some("https://a.example/2026/10/15/one/".to_string());
1820 assert_eq!(to(200, &tag("0; url=/2026/10/15/one/"), ""), at);
1821 assert_eq!(to(200, &tag("0;URL='../../2026/10/15/one/'"), ""), at, "WHATWG: any case, quotes, relative");
1822 assert_eq!(to(200, &tag("0, https://a.example/2026/10/15/one/"), ""), at, "a comma, no url=");
1823 assert_eq!(to(200, &tag("5; url=/2026/10/15/one/"), ""), None, "a delay");
1824 assert_eq!(to(200, &tag("0; url=https://b.example/one/"), ""), None, "another host");
1825 assert_eq!(to(200, &tag("0; url=https://a.example:8443/one/"), ""), None, "another port");
1827 assert_eq!(to(200, &tag("0; url=http://a.example/one/"), ""), None, "https → http");
1828 let up = Raw { final_url: "http://a.example/x".into(), ..page(200, &tag("0; url=https://a.example/one/"), "") };
1829 assert_eq!(refresh(&up).as_deref(), Some("https://a.example/one/"), "http → https");
1830 for c in ["+0; url=/one/", "-0; url=/one/", "0.0; url=/one/", " ; url=/one/", "0; url=", "0; url=''"] {
1832 assert_eq!(to(200, &tag(c), ""), None, "{c}");
1833 }
1834 assert_eq!(to(200, &tag("00 ; url=/one/"), "").as_deref(), Some("https://a.example/one/"));
1835 assert_eq!(to(200, "<meta name=refresh content='0; url=/one/'>", ""), None, "no http-equiv");
1837 assert_eq!(to(200, &tag("0; url=/one/"), "<script src=/app.js></script>"), None, "a script");
1838 assert_eq!(to(200, "", &format!("<noscript>{}</noscript>", tag("360"))), None, "no URL");
1839 assert_eq!(to(404, &tag("0; url=/one/"), ""), None, "no 2xx");
1840 assert_eq!(to(200, &tag("0; url=/one/"), &"<p>A page of its own. </p>".repeat(80)), None, "a page");
1841 }
1842
1843 #[test]
1846 fn redirects_are_fenced() {
1847 let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
1848 let calls = std::cell::RefCell::new(Vec::<String>::new());
1849 let fake = |to: Option<&'static str>| {
1850 let calls = &calls;
1851 move |u: String| {
1852 calls.borrow_mut().push(u);
1853 let reply = match to {
1854 Some(t) => (302, Some(t.to_string()), ()),
1855 None => (200, None, ()),
1856 };
1857 std::future::ready(Ok::<_, &'static str>(reply))
1858 }
1859 };
1860 let r = rt.block_on(follow("https://ex.com/a", fake(Some("http://169.254.169.254/latest/meta-data/"))));
1861 assert_eq!(r.err(), Some("private_address"));
1862 assert_eq!(*calls.borrow(), ["https://ex.com/a"], "the private hop is never requested");
1863 calls.borrow_mut().clear();
1864 let r = rt.block_on(follow("https://ex.com/a", fake(Some("http://lan.ex.com:8765/admin"))));
1866 assert_eq!(r.err(), Some("private_address"));
1867 assert_eq!(*calls.borrow(), ["https://ex.com/a"], "the private hop is never requested");
1868 calls.borrow_mut().clear();
1869 assert_eq!(
1870 rt.block_on(follow("https://ex.com/a", fake(Some("http://[::ffff:7f00:1]/")))).err(),
1871 Some("private_address")
1872 );
1873 calls.borrow_mut().clear();
1874 assert_eq!(rt.block_on(follow("https://ex.com/a", fake(Some("/b")))).err(), Some("redirect_loop"));
1875 assert_eq!(calls.borrow().len(), 11, "the first request + 10 redirects");
1876 assert!(calls.borrow()[1..].iter().all(|u| u == "https://ex.com/b"));
1877 let ok = rt.block_on(follow("https://ex.com/a", fake(None)));
1878 assert_eq!(ok.map(|r| r.0), Ok("https://ex.com/a".to_string()));
1879 }
1880
1881 #[test]
1884 fn resolver_drops_private_answers() {
1885 use wreq::dns::Resolve;
1886 let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
1887 let e = rt.block_on(Fence.resolve("localhost".into())).err().expect("refused");
1888 assert!(e.is::<Private>());
1889 }
1890}