use std::net::SocketAddr;
pub fn is_private_ip(ip: &str) -> bool {
if let Ok(addr) = ip.parse::<std::net::IpAddr>() {
match addr {
std::net::IpAddr::V4(ipv4) => {
ipv4.is_private()
|| ipv4.is_loopback()
|| ipv4.is_link_local()
|| ipv4.is_unspecified()
|| ipv4.is_multicast()
}
std::net::IpAddr::V6(ipv6) => {
ipv6.is_loopback()
|| ipv6.is_unspecified()
|| ipv6.is_unicast_link_local()
|| ipv6.is_unique_local()
|| ipv6.is_multicast()
}
}
} else {
false
}
}
pub fn extract_client_ip(_headers: &http::HeaderMap, connect_info: &SocketAddr) -> String {
connect_info.ip().to_string()
}
pub struct TrustedProxies {
nets: Vec<(std::net::IpAddr, u32)>,
}
impl TrustedProxies {
pub fn new(specs: &[String]) -> Self {
let mut nets = Vec::with_capacity(specs.len());
for s in specs {
let trimmed = s.trim();
if trimmed.is_empty() {
continue;
}
let (ip_str, bits) = match trimmed.split_once('/') {
Some((ip_s, pre_s)) => {
match (
ip_s.trim().parse::<std::net::IpAddr>(),
pre_s.trim().parse::<u32>(),
) {
(Ok(ip), Ok(b)) => (ip, b),
_ => continue,
}
}
None => match trimmed.parse::<std::net::IpAddr>() {
Ok(ip) => (ip, if ip.is_ipv4() { 32 } else { 128 }),
_ => continue,
},
};
nets.push((ip_str, bits));
}
TrustedProxies { nets }
}
pub fn is_empty(&self) -> bool {
self.nets.is_empty()
}
pub fn contains(&self, ip: &std::net::IpAddr) -> bool {
self.nets
.iter()
.any(|(net, bits)| ip_in_net(ip, net, *bits))
}
}
fn ip_in_net(ip: &std::net::IpAddr, net: &std::net::IpAddr, bits: u32) -> bool {
match (ip, net) {
(std::net::IpAddr::V4(a), std::net::IpAddr::V4(b)) => {
let bits = bits.min(32);
if bits == 0 {
return true;
}
let mask = if bits >= 32 {
u32::MAX
} else {
!(u32::MAX >> bits)
};
(u32::from(*a) & mask) == (u32::from(*b) & mask)
}
(std::net::IpAddr::V6(a), std::net::IpAddr::V6(b)) => {
let bits = bits.min(128);
if bits == 0 {
return true;
}
let ma = a.segments();
let mb = b.segments();
let mut done = 0u32;
for i in 0..8 {
if done >= bits {
return true;
}
let remain = bits - done;
let m: u16 = if remain >= 16 {
0xFFFF
} else {
!(0xFFFFu16 >> remain)
};
if (ma[i] & m) != (mb[i] & m) {
return false;
}
done += 16;
}
true
}
_ => false,
}
}
pub fn extract_client_ip_trusted(
headers: &http::HeaderMap,
connect_info: &SocketAddr,
trusted: &TrustedProxies,
) -> String {
let peer = connect_info.ip();
if !trusted.contains(&peer) {
return peer.to_string();
}
if let Some(v) = headers
.get("CF-Connecting-IP")
.and_then(|h| h.to_str().ok())
{
if let Ok(ip) = v.trim().parse::<std::net::IpAddr>() {
if !trusted.contains(&ip) {
return ip.to_string();
}
}
}
if let Some(v) = headers.get("X-Forwarded-For").and_then(|h| h.to_str().ok()) {
let mut ips: Vec<std::net::IpAddr> = v
.split(',')
.filter_map(|p| p.trim().parse::<std::net::IpAddr>().ok())
.collect();
ips.reverse();
for ip in ips {
if trusted.contains(&ip) || is_internal_ip(&ip) {
continue;
}
return ip.to_string();
}
}
peer.to_string()
}
fn is_internal_ip(ip: &std::net::IpAddr) -> bool {
match ip {
std::net::IpAddr::V4(a) => a.is_private() || a.is_loopback() || a.is_unspecified(),
std::net::IpAddr::V6(a) => a.is_loopback() || a.is_unspecified() || a.is_unique_local(),
}
}
pub struct WebExt;
impl WebExt {
fn split_authority(url_str: &str) -> Option<(&str, Option<&str>)> {
let rest = url_str.split_once("://")?.1;
let (authority, path_part) = match rest.find(['/', '?', '#']) {
Some(i) => (&rest[..i], Some(&rest[i..])),
None => (rest, None),
};
let host_port = authority
.rsplit_once('@')
.map(|(_, h)| h)
.unwrap_or(authority);
Some((host_port, path_part))
}
pub fn domain(url_str: &str) -> Option<String> {
let (host_port, _) = Self::split_authority(url_str)?;
if host_port.is_empty() {
return None;
}
if let Some(ipv6) = host_port.strip_prefix('[') {
return ipv6.find(']').map(|end| ipv6[..end].to_string());
}
host_port.split(':').next().map(|h| h.to_string())
}
pub fn path(url_str: &str) -> Option<String> {
let (_, path_part) = Self::split_authority(url_str)?;
match path_part {
None => Some("/".to_string()),
Some(p) => {
if p.starts_with('?') || p.starts_with('#') {
return Some("/".to_string());
}
let end = p.find(['?', '#']).unwrap_or(p.len());
Some(p[..end].to_string())
}
}
}
pub fn real_ip(headers: &[(String, String)], remote_addr: &str) -> String {
for (key, val) in headers {
if key.eq_ignore_ascii_case("x-forwarded-for") {
if let Some(ip) = val
.split(',')
.filter_map(|p| p.trim().parse::<std::net::IpAddr>().ok())
.next()
{
return ip.to_string();
}
}
if key.eq_ignore_ascii_case("x-real-ip") {
if let Ok(ip) = val.trim().parse::<std::net::IpAddr>() {
return ip.to_string();
}
}
}
remote_addr
.split(':')
.next()
.unwrap_or(remote_addr)
.to_string()
}
pub fn is_private_ip(ip: &str) -> bool {
is_private_ip(ip)
}
pub fn build_query(params: &[(&str, &str)]) -> String {
if params.is_empty() {
return String::new();
}
let parts: Vec<String> = params
.iter()
.map(|(k, v)| format!("{}={}", urlencoding(k), urlencoding(v)))
.collect();
format!("?{}", parts.join("&"))
}
}
fn urlencoding(s: &str) -> String {
let mut result = String::with_capacity(s.len() * 3);
for byte in s.bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
result.push(byte as char);
}
_ => {
result.push_str(&format!("%{:02X}", byte));
}
}
}
result
}