-
Notifications
You must be signed in to change notification settings - Fork 342
/
mod.rs
73 lines (66 loc) · 2.17 KB
/
mod.rs
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
use std::collections::HashSet;
use anyhow::Context;
use http_types::{Method, Request, Url};
use once_cell::sync::Lazy;
use std::net::{IpAddr, Ipv4Addr};
use treebitmap::IpLookupTable;
/// List of all Chinese domains.
static DOMAINS: Lazy<HashSet<String>> = Lazy::new(|| {
let ss = include_str!("china-domains.txt");
ss.split_ascii_whitespace()
.filter(|v| v.len() > 1)
.map(|v| v.to_string())
.collect()
});
static IPLOOKUP: Lazy<IpLookupTable<Ipv4Addr, ()>> = Lazy::new(|| {
let ss = include_str!("china-ips.txt");
let mut toret = IpLookupTable::new();
for line in ss.split_ascii_whitespace() {
let vv: Vec<_> = line.split('/').collect();
let ip: Ipv4Addr = vv[0].parse().unwrap();
let plen: u32 = vv[1].parse().unwrap();
toret.insert(ip, plen, ());
}
toret
});
/// Returns true if the given IP is Chinese
pub fn is_chinese_ip(ip: Ipv4Addr) -> bool {
IPLOOKUP.longest_match(ip).is_some()
}
/// Returns true if the given host is Chinese
pub fn is_chinese_host(host: &str) -> bool {
// explode by dots
let exploded: Vec<_> = host.split('.').collect();
// join & lookup in loop
for i in 0..exploded.len() {
let candidate = (exploded[i..]).join(".");
if DOMAINS.contains(&candidate) {
return true;
}
}
false
}
/// Returns whether or not we're in China.
#[cached::proc_macro::cached(result = true)]
pub async fn test_china() -> http_types::Result<bool> {
let req = Request::new(
Method::Get,
Url::parse("http://checkip.amazonaws.com").unwrap(),
);
let connect_to = geph4_aioutils::resolve("checkip.amazonaws.com:80").await?;
let response = {
let connection =
smol::net::TcpStream::connect(connect_to.first().context("no addrs for checkip")?)
.await?;
async_h1::connect(connection, req)
.await?
.body_string()
.await?
};
let response = response.trim();
let parsed: IpAddr = response.parse()?;
match parsed {
IpAddr::V4(inner) => Ok(is_chinese_ip(inner)),
IpAddr::V6(_) => Err(anyhow::anyhow!("cannot tell for ipv6").into()),
}
}