1use std::net::SocketAddr;
4
5pub fn is_private_ip(ip: &str) -> bool {
19 if let Ok(addr) = ip.parse::<std::net::IpAddr>() {
20 match addr {
21 std::net::IpAddr::V4(ipv4) => {
22 ipv4.is_private()
23 || ipv4.is_loopback()
24 || ipv4.is_link_local()
25 || ipv4.is_unspecified()
26 || ipv4.is_multicast()
27 }
28 std::net::IpAddr::V6(ipv6) => {
29 let seg0 = ipv6.segments()[0];
30 ipv6.is_loopback()
31 || ipv6.is_unspecified()
32 || (seg0 & 0xffc0) == 0xfe80
34 || (seg0 & 0xfe00) == 0xfc00
36 || ipv6.is_multicast()
37 }
38 }
39 } else {
40 false
41 }
42}
43
44pub fn extract_client_ip(_headers: &http::HeaderMap, connect_info: &SocketAddr) -> String {
51 connect_info.ip().to_string()
52}
53
54pub struct TrustedProxies {
56 nets: Vec<(std::net::IpAddr, u32)>,
57}
58
59impl TrustedProxies {
60 pub fn new(specs: &[String]) -> Self {
63 let mut nets = Vec::with_capacity(specs.len());
64 for s in specs {
65 let trimmed = s.trim();
66 if trimmed.is_empty() {
67 continue;
68 }
69 let (ip_str, bits) = match trimmed.split_once('/') {
70 Some((ip_s, pre_s)) => {
71 match (
72 ip_s.trim().parse::<std::net::IpAddr>(),
73 pre_s.trim().parse::<u32>(),
74 ) {
75 (Ok(ip), Ok(b)) => (ip, b),
76 _ => continue,
77 }
78 }
79 None => match trimmed.parse::<std::net::IpAddr>() {
80 Ok(ip) => (ip, if ip.is_ipv4() { 32 } else { 128 }),
81 _ => continue,
82 },
83 };
84 nets.push((ip_str, bits));
85 }
86 TrustedProxies { nets }
87 }
88
89 pub fn is_empty(&self) -> bool {
91 self.nets.is_empty()
92 }
93
94 pub fn contains(&self, ip: &std::net::IpAddr) -> bool {
96 self.nets
97 .iter()
98 .any(|(net, bits)| ip_in_net(ip, net, *bits))
99 }
100}
101
102fn ip_in_net(ip: &std::net::IpAddr, net: &std::net::IpAddr, bits: u32) -> bool {
104 match (ip, net) {
105 (std::net::IpAddr::V4(a), std::net::IpAddr::V4(b)) => {
106 let bits = bits.min(32);
107 if bits == 0 {
108 return true;
109 }
110 let mask = if bits >= 32 {
111 u32::MAX
112 } else {
113 !(u32::MAX >> bits)
114 };
115 (u32::from(*a) & mask) == (u32::from(*b) & mask)
116 }
117 (std::net::IpAddr::V6(a), std::net::IpAddr::V6(b)) => {
118 let bits = bits.min(128);
119 if bits == 0 {
120 return true;
121 }
122 let ma = a.segments();
123 let mb = b.segments();
124 let mut done = 0u32;
125 for i in 0..8 {
126 if done >= bits {
127 return true;
128 }
129 let remain = bits - done;
130 let m: u16 = if remain >= 16 {
131 0xFFFF
132 } else {
133 !(0xFFFFu16 >> remain)
134 };
135 if (ma[i] & m) != (mb[i] & m) {
136 return false;
137 }
138 done += 16;
139 }
140 true
141 }
142 _ => false,
143 }
144}
145
146pub fn extract_client_ip_trusted(
153 headers: &http::HeaderMap,
154 connect_info: &SocketAddr,
155 trusted: &TrustedProxies,
156) -> String {
157 let peer = connect_info.ip();
158 if !trusted.contains(&peer) {
159 return peer.to_string();
160 }
161
162 if let Some(v) = headers
164 .get("CF-Connecting-IP")
165 .and_then(|h| h.to_str().ok())
166 {
167 if let Ok(ip) = v.trim().parse::<std::net::IpAddr>() {
168 if !trusted.contains(&ip) {
169 return ip.to_string();
170 }
171 }
172 }
173
174 if let Some(v) = headers.get("X-Forwarded-For").and_then(|h| h.to_str().ok()) {
175 let ips: Vec<std::net::IpAddr> = v
176 .split(',')
177 .filter_map(|p| p.trim().parse::<std::net::IpAddr>().ok())
178 .collect();
179 for ip in ips.iter().rev() {
180 if trusted.contains(ip) || is_internal_ip(ip) {
181 continue;
182 }
183 return ip.to_string();
184 }
185 }
186
187 peer.to_string()
188}
189
190fn is_internal_ip(ip: &std::net::IpAddr) -> bool {
192 match ip {
193 std::net::IpAddr::V4(a) => a.is_private() || a.is_loopback() || a.is_unspecified(),
194 std::net::IpAddr::V6(a) => {
195 a.is_loopback() || a.is_unspecified() || (a.segments()[0] & 0xfe00) == 0xfc00
197 }
198 }
199}
200
201pub struct WebExt;
205
206impl WebExt {
207 fn split_authority(url_str: &str) -> Option<(&str, Option<&str>)> {
210 let rest = url_str.split_once("://")?.1;
211 let (authority, path_part) = match rest.find(['/', '?', '#']) {
212 Some(i) => (&rest[..i], Some(&rest[i..])),
213 None => (rest, None),
214 };
215 let host_port = authority
217 .rsplit_once('@')
218 .map(|(_, h)| h)
219 .unwrap_or(authority);
220 Some((host_port, path_part))
221 }
222
223 pub fn domain(url_str: &str) -> Option<String> {
227 let (host_port, _) = Self::split_authority(url_str)?;
228 if host_port.is_empty() {
229 return None;
230 }
231 if let Some(ipv6) = host_port.strip_prefix('[') {
232 return ipv6.find(']').map(|end| ipv6[..end].to_string());
233 }
234 host_port.split(':').next().map(|h| h.to_string())
235 }
236
237 pub fn path(url_str: &str) -> Option<String> {
239 let (_, path_part) = Self::split_authority(url_str)?;
240 match path_part {
241 None => Some("/".to_string()),
242 Some(p) => {
243 if p.starts_with('?') || p.starts_with('#') {
244 return Some("/".to_string());
245 }
246 let end = p.find(['?', '#']).unwrap_or(p.len());
247 Some(p[..end].to_string())
248 }
249 }
250 }
251
252 pub fn real_ip(headers: &[(String, String)], remote_addr: &str) -> String {
263 for (key, val) in headers {
264 if key.eq_ignore_ascii_case("x-forwarded-for") {
265 if let Some(ip) = val
267 .split(',')
268 .filter_map(|p| p.trim().parse::<std::net::IpAddr>().ok())
269 .next()
270 {
271 return ip.to_string();
272 }
273 }
274 if key.eq_ignore_ascii_case("x-real-ip") {
275 if let Ok(ip) = val.trim().parse::<std::net::IpAddr>() {
276 return ip.to_string();
277 }
278 }
279 }
280 let trimmed = remote_addr.trim();
282 if let Ok(sa) = trimmed.parse::<SocketAddr>() {
283 return sa.ip().to_string();
284 }
285 if let Ok(ip) = trimmed.parse::<std::net::IpAddr>() {
286 return ip.to_string();
287 }
288 trimmed.split(':').next().unwrap_or(trimmed).to_string()
289 }
290 pub fn is_private_ip(ip: &str) -> bool {
292 is_private_ip(ip)
293 }
294 pub fn build_query(params: &[(&str, &str)]) -> String {
296 if params.is_empty() {
297 return String::new();
298 }
299 let parts: Vec<String> = params
300 .iter()
301 .map(|(k, v)| format!("{}={}", Self::percent_encode(k), Self::percent_encode(v)))
302 .collect();
303 format!("?{}", parts.join("&"))
304 }
305
306 pub fn percent_encode(seg: &str) -> String {
322 const HEX: &[u8; 16] = b"0123456789ABCDEF";
323 let mut out = String::with_capacity(seg.len() * 3);
325 for &byte in seg.as_bytes() {
326 if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
327 out.push(byte as char);
328 } else {
329 out.push('%');
330 out.push(HEX[(byte >> 4) as usize] as char);
331 out.push(HEX[(byte & 0x0f) as usize] as char);
332 }
333 }
334 out
335 }
336
337 pub fn mime_guess(filename: &str) -> &'static str {
348 let ext = std::path::Path::new(filename)
349 .extension()
350 .and_then(|e| e.to_str())
351 .unwrap_or("bin");
352
353 match ext.to_ascii_lowercase().as_str() {
354 "jpg" | "jpeg" => "image/jpeg",
355 "png" => "image/png",
356 "gif" => "image/gif",
357 "webp" => "image/webp",
358 "svg" => "image/svg+xml",
359 "pdf" => "application/pdf",
360 "json" => "application/json",
361 "html" | "htm" => "text/html",
362 "css" => "text/css",
363 "js" => "application/javascript",
364 "txt" => "text/plain",
365 "csv" => "text/csv",
366 "zip" => "application/zip",
367 "mp4" => "video/mp4",
368 "mp3" => "audio/mpeg",
369 "doc" => "application/msword",
370 "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
371 "xls" => "application/vnd.ms-excel",
372 "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
373 _ => "application/octet-stream",
374 }
375 }
376
377 pub fn url_decode(s: &str) -> String {
382 urldecode(s)
383 }
384
385 pub fn content_type_mime(content_type: &str) -> Option<String> {
402 content_type
403 .split(';')
404 .next()
405 .map(|s| s.trim().to_lowercase())
406 .filter(|s| !s.is_empty())
407 }
408}
409
410fn urldecode(s: &str) -> String {
411 fn hex_val(c: u8) -> Option<u8> {
412 match c {
413 b'0'..=b'9' => Some(c - b'0'),
414 b'a'..=b'f' => Some(c - b'a' + 10),
415 b'A'..=b'F' => Some(c - b'A' + 10),
416 _ => None,
417 }
418 }
419 let bytes = s.as_bytes();
420 let mut out = Vec::with_capacity(bytes.len());
421 let mut i = 0;
422 while i < bytes.len() {
423 match bytes[i] {
424 b'%' => match (bytes.get(i + 1), bytes.get(i + 2)) {
425 (Some(&h), Some(&l)) => match (hex_val(h), hex_val(l)) {
426 (Some(h), Some(l)) => {
427 out.push((h << 4) | l);
428 i += 3;
429 }
430 _ => {
432 out.push(b'%');
433 i += 1;
434 }
435 },
436 _ => {
438 out.push(b'%');
439 i += 1;
440 }
441 },
442 b'+' => {
443 out.push(b' ');
445 i += 1;
446 }
447 b => {
448 out.push(b);
449 i += 1;
450 }
451 }
452 }
453 String::from_utf8(out).unwrap_or_else(|_| s.to_string())
455}
456
457#[cfg(test)]
458mod tests {
459 use super::*;
460
461 #[test]
462 fn test_url_decode_basic() {
463 assert_eq!(WebExt::url_decode("hello%20world"), "hello world");
464 assert_eq!(WebExt::url_decode("hello+world"), "hello world");
465 }
466
467 #[test]
468 fn test_url_decode_utf8() {
469 assert_eq!(WebExt::url_decode("%E4%BD%A0%E5%A5%BD"), "你好");
471 }
472
473 #[test]
474 fn test_url_decode_invalid() {
475 assert_eq!(WebExt::url_decode("%ZZ"), "%ZZ");
477 assert_eq!(WebExt::url_decode("%E"), "%E");
479 }
480
481 #[test]
482 fn test_url_decode_no_encoding() {
483 assert_eq!(WebExt::url_decode("hello"), "hello");
484 }
485
486 #[test]
487 fn test_percent_encode_keeps_unreserved() {
488 assert_eq!(WebExt::percent_encode("a-b_c.d~"), "a-b_c.d~");
489 assert_eq!(WebExt::percent_encode("a b"), "a%20b");
490 assert_eq!(WebExt::percent_encode("/"), "%2F");
491 assert_eq!(WebExt::percent_encode("中文"), "%E4%B8%AD%E6%96%87");
492 }
493
494 #[test]
495 fn test_mime_guess_extensions() {
496 assert_eq!(WebExt::mime_guess("a.PNG"), "image/png");
497 assert_eq!(WebExt::mime_guess("a.jpeg"), "image/jpeg");
498 assert_eq!(WebExt::mime_guess("noext"), "application/octet-stream");
499 }
500
501 #[test]
502 fn test_content_type_mime_json() {
503 assert_eq!(
504 WebExt::content_type_mime("application/json; charset=utf-8"),
505 Some("application/json".to_string())
506 );
507 }
508
509 #[test]
510 fn test_content_type_mime_html() {
511 assert_eq!(
512 WebExt::content_type_mime("text/html"),
513 Some("text/html".to_string())
514 );
515 }
516
517 #[test]
518 fn test_content_type_mime_with_params() {
519 assert_eq!(
520 WebExt::content_type_mime("multipart/form-data; boundary=something"),
521 Some("multipart/form-data".to_string())
522 );
523 }
524
525 #[test]
526 fn test_content_type_mime_empty() {
527 assert_eq!(WebExt::content_type_mime(""), None);
528 }
529
530 #[test]
531 fn test_content_type_mime_case_insensitive() {
532 assert_eq!(
533 WebExt::content_type_mime("Application/JSON"),
534 Some("application/json".to_string())
535 );
536 }
537}
538
539#[cfg(test)]
540mod extra_web_tests {
541 use super::*;
542 use std::net::{IpAddr, SocketAddr};
543
544 fn ip(s: &str) -> IpAddr {
545 s.parse().unwrap()
546 }
547
548 #[test]
549 fn is_private_ip_all_families() {
550 assert!(is_private_ip("10.1.2.3")); assert!(is_private_ip("172.16.0.1")); assert!(is_private_ip("192.168.0.1"));
553 assert!(is_private_ip("127.0.0.1")); assert!(is_private_ip("169.254.1.1")); assert!(is_private_ip("0.0.0.0")); assert!(is_private_ip("224.0.0.1")); assert!(!is_private_ip("8.8.8.8"));
558 assert!(is_private_ip("::1")); assert!(is_private_ip("::")); assert!(is_private_ip("fe80::1")); assert!(is_private_ip("fc00::1")); assert!(is_private_ip("fd12::34")); assert!(is_private_ip("ff02::1")); assert!(!is_private_ip("2606:4700::1")); assert!(!is_private_ip("not-an-ip")); }
567
568 #[test]
569 fn extract_client_ip_never_reads_headers() {
570 let mut headers = http::HeaderMap::new();
571 headers.insert("x-forwarded-for", "8.8.8.8".parse().unwrap());
572 let peer: SocketAddr = "127.0.0.1:1234".parse().unwrap();
573 assert_eq!(extract_client_ip(&headers, &peer), "127.0.0.1");
574 }
575
576 #[test]
577 fn trusted_proxies_parse_contains() {
578 let t = TrustedProxies::new(&[
579 "10.0.0.0/8".into(),
580 "192.168.1.10".into(), "fc00::/7".into(),
582 "garbage".into(), "".into(), "10.0.0.0/abc".into(), ]);
586 assert!(!t.is_empty());
587 assert!(t.contains(&ip("10.1.2.3")));
588 assert!(t.contains(&ip("192.168.1.10")));
589 assert!(!t.contains(&ip("192.168.1.11"))); assert!(t.contains(&ip("fd00::1"))); let v4only = TrustedProxies::new(&["172.16.0.0/12".into()]);
593 assert!(!v4only.contains(&ip("::1")));
594 let any = TrustedProxies::new(&["0.0.0.0/0".into()]);
596 assert!(any.contains(&ip("8.8.8.8")));
597 assert!(TrustedProxies::new(&[]).is_empty());
599 }
600
601 #[test]
602 fn ip_in_net_edge_prefixes() {
603 let t = TrustedProxies::new(&["10.0.0.0/99".into()]); assert!(t.contains(&ip("10.0.0.0")));
606 assert!(!t.contains(&ip("10.0.0.1"))); let t6 = TrustedProxies::new(&["fe80::/10".into()]);
608 assert!(t6.contains(&ip("fe80::1")));
609 assert!(t6.contains(&ip("febf::1"))); assert!(!t6.contains(&ip("fec0::1"))); }
612
613 fn hm(pairs: &[(&str, &str)]) -> http::HeaderMap {
614 let mut h = http::HeaderMap::new();
615 for (k, v) in pairs {
616 h.insert(k.parse::<http::header::HeaderName>().unwrap(), v.parse().unwrap());
617 }
618 h
619 }
620
621 #[test]
622 fn extract_client_ip_trusted_paths() {
623 let trusted = TrustedProxies::new(&["127.0.0.1".into(), "10.0.0.0/8".into()]);
624 let peer_trusted: SocketAddr = "127.0.0.1:443".parse().unwrap();
625 let peer_untrusted: SocketAddr = "8.8.8.8:443".parse().unwrap();
626
627 let headers = hm(&[("x-forwarded-for", "1.2.3.4")]);
629 assert_eq!(
630 extract_client_ip_trusted(&headers, &peer_untrusted, &trusted),
631 "8.8.8.8"
632 );
633
634 let headers = hm(&[("cf-connecting-ip", "203.0.113.9"), ("x-forwarded-for", "1.1.1.1")]);
636 assert_eq!(
637 extract_client_ip_trusted(&headers, &peer_trusted, &trusted),
638 "203.0.113.9"
639 );
640
641 let headers = hm(&[("cf-connecting-ip", "127.0.0.1"), ("x-forwarded-for", "198.51.100.7, 10.0.0.9")]);
643 assert_eq!(
644 extract_client_ip_trusted(&headers, &peer_trusted, &trusted),
645 "198.51.100.7"
646 );
647
648 let headers = hm(&[("x-forwarded-for", "127.0.0.1, 10.1.1.1, 192.168.5.5")]);
650 assert_eq!(
651 extract_client_ip_trusted(&headers, &peer_trusted, &trusted),
652 "127.0.0.1"
653 );
654
655 let headers = hm(&[("x-forwarded-for", "not, an, ip")]);
657 assert_eq!(
658 extract_client_ip_trusted(&headers, &peer_trusted, &trusted),
659 "127.0.0.1"
660 );
661
662 assert_eq!(
664 extract_client_ip_trusted(&http::HeaderMap::new(), &peer_trusted, &trusted),
665 "127.0.0.1"
666 );
667 }
668
669 #[test]
670 fn webext_domain_and_path() {
671 assert_eq!(
672 WebExt::domain("http://user:pass@ex.com:8080/a/b?c=1#frag"),
673 Some("ex.com".into())
674 );
675 assert_eq!(WebExt::domain("https://ex.com"), Some("ex.com".into()));
676 assert_eq!(WebExt::domain("http://[::1]:80/x"), Some("::1".into()));
677 assert_eq!(WebExt::domain("[unclosed"), None); assert_eq!(WebExt::domain("http://"), None); assert_eq!(WebExt::domain("http://[::1"), None); assert_eq!(WebExt::path("http://ex.com/a/b?c=1"), Some("/a/b".into()));
682 assert_eq!(WebExt::path("http://ex.com"), Some("/".into()));
683 assert_eq!(WebExt::path("http://ex.com?q=1"), Some("/".into()));
684 assert_eq!(WebExt::path("http://ex.com#f"), Some("/".into()));
685 assert_eq!(WebExt::path("http://ex.com/a#f"), Some("/a".into()));
686 assert_eq!(WebExt::path("relative/path"), None); }
688
689 #[test]
690 fn webext_real_ip_resolution() {
691 let h = |pairs: Vec<(String, String)>| pairs;
692 assert_eq!(
694 WebExt::real_ip(
695 &h(vec![("X-Forwarded-For".into(), "1.2.3.4, 5.6.7.8".into())]),
696 "9.9.9.9:443"
697 ),
698 "1.2.3.4"
699 );
700 assert_eq!(
702 WebExt::real_ip(&h(vec![("x-real-ip".into(), "42.42.42.42".into())]), "peer"),
703 "42.42.42.42"
704 );
705 assert_eq!(
707 WebExt::real_ip(&h(vec![("x-forwarded-for".into(), "garbage".into())]), "9.9.9.9:443"),
708 "9.9.9.9"
709 );
710 assert_eq!(WebExt::real_ip(&h(vec![]), "1.1.1.1"), "1.1.1.1"); assert_eq!(WebExt::real_ip(&h(vec![]), "[::1]:8080"), "::1"); assert_eq!(WebExt::real_ip(&h(vec![]), "abc:123"), "abc"); assert_eq!(WebExt::real_ip(&h(vec![]), ""), "");
714 assert!(WebExt::is_private_ip("10.0.0.1"));
715 }
716
717 #[test]
718 fn build_query_percent_encodes() {
719 assert_eq!(WebExt::build_query(&[]), "");
720 assert_eq!(
721 WebExt::build_query(&[("a b", "中/文"), ("k", "v1")]),
722 "?a%20b=%E4%B8%AD%2F%E6%96%87&k=v1"
723 );
724 }
725
726 #[test]
727 fn urldecode_invalid_utf8_falls_back() {
728 assert_eq!(WebExt::url_decode("%FF%FE"), "%FF%FE");
730 assert_eq!(WebExt::url_decode("a%"), "a%");
732 }
733}