1use std::fmt;
16use std::net::IpAddr;
17
18use http::header::HeaderValue;
19use ipnet::IpNet;
20use percent_encoding::percent_decode_str;
21
22#[cfg(docsrs)]
23pub use self::builder::IntoValue;
24#[cfg(not(docsrs))]
25use self::builder::IntoValue;
26
27pub struct Matcher {
29 http: Option<Intercept>,
30 https: Option<Intercept>,
31 no: NoProxy,
32}
33
34#[derive(Clone)]
38pub struct Intercept {
39 uri: http::Uri,
40 auth: Auth,
41}
42
43#[derive(Default)]
47pub struct Builder {
48 is_cgi: bool,
49 all: String,
50 http: String,
51 https: String,
52 no: String,
53}
54
55#[derive(Clone)]
56enum Auth {
57 Empty,
58 Basic(http::header::HeaderValue),
59 Raw(String, String),
60}
61
62#[derive(Clone, Debug, Default)]
66struct NoProxy {
67 ips: IpMatcher,
68 domains: DomainMatcher,
69}
70
71#[derive(Clone, Debug, Default)]
72struct DomainMatcher(Vec<String>);
73
74#[derive(Clone, Debug, Default)]
75struct IpMatcher(Vec<Ip>);
76
77#[derive(Clone, Debug)]
78enum Ip {
79 Address(IpAddr),
80 Network(IpNet),
81}
82
83impl Matcher {
86 pub fn from_env() -> Self {
96 Builder::from_env().build()
97 }
98
99 pub fn from_system() -> Self {
110 Builder::from_system().build()
111 }
112
113 pub fn builder() -> Builder {
115 Builder::default()
116 }
117
118 pub fn intercept(&self, dst: &http::Uri) -> Option<Intercept> {
123 if self.no.contains(dst.host()?) {
125 return None;
126 }
127
128 match dst.scheme_str() {
129 Some("http") => self.http.clone(),
130 Some("https") => self.https.clone(),
131 _ => None,
132 }
133 }
134}
135
136impl fmt::Debug for Matcher {
137 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138 let mut b = f.debug_struct("Matcher");
139
140 if let Some(ref http) = self.http {
141 b.field("http", http);
142 }
143
144 if let Some(ref https) = self.https {
145 b.field("https", https);
146 }
147
148 if !self.no.is_empty() {
149 b.field("no", &self.no);
150 }
151 b.finish()
152 }
153}
154
155impl Intercept {
158 pub fn uri(&self) -> &http::Uri {
160 &self.uri
161 }
162
163 pub fn basic_auth(&self) -> Option<&HeaderValue> {
182 if let Auth::Basic(ref val) = self.auth {
183 Some(val)
184 } else {
185 None
186 }
187 }
188
189 pub fn raw_auth(&self) -> Option<(&str, &str)> {
208 if let Auth::Raw(ref u, ref p) = self.auth {
209 Some((u.as_str(), p.as_str()))
210 } else {
211 None
212 }
213 }
214}
215
216impl fmt::Debug for Intercept {
217 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218 f.debug_struct("Intercept")
219 .field("uri", &self.uri)
220 .finish()
222 }
223}
224
225impl Builder {
228 fn from_env() -> Self {
229 Builder {
230 is_cgi: std::env::var_os("REQUEST_METHOD").is_some(),
231 all: get_first_env(&["ALL_PROXY", "all_proxy"]),
232 http: get_first_env(&["HTTP_PROXY", "http_proxy"]),
233 https: get_first_env(&["HTTPS_PROXY", "https_proxy"]),
234 no: get_first_env(&["NO_PROXY", "no_proxy"]),
235 }
236 }
237
238 fn from_system() -> Self {
239 #[allow(unused_mut)]
240 let mut builder = Self::from_env();
241
242 #[cfg(all(feature = "client-proxy-system", target_os = "macos"))]
243 mac::with_system(&mut builder);
244
245 #[cfg(all(feature = "client-proxy-system", windows))]
246 win::with_system(&mut builder);
247
248 builder
249 }
250
251 pub fn all<S>(mut self, val: S) -> Self
253 where
254 S: IntoValue,
255 {
256 self.all = val.into_value();
257 self
258 }
259
260 pub fn http<S>(mut self, val: S) -> Self
262 where
263 S: IntoValue,
264 {
265 self.http = val.into_value();
266 self
267 }
268
269 pub fn https<S>(mut self, val: S) -> Self
271 where
272 S: IntoValue,
273 {
274 self.https = val.into_value();
275 self
276 }
277
278 pub fn no<S>(mut self, val: S) -> Self
296 where
297 S: IntoValue,
298 {
299 self.no = val.into_value();
300 self
301 }
302
303 pub fn build(self) -> Matcher {
305 if self.is_cgi {
306 return Matcher {
307 http: None,
308 https: None,
309 no: NoProxy::empty(),
310 };
311 }
312
313 let all = parse_env_uri(&self.all);
314
315 Matcher {
316 http: parse_env_uri(&self.http).or_else(|| all.clone()),
317 https: parse_env_uri(&self.https).or(all),
318 no: NoProxy::from_string(&self.no),
319 }
320 }
321}
322
323fn get_first_env(names: &[&str]) -> String {
324 for name in names {
325 if let Ok(val) = std::env::var(name) {
326 return val;
327 }
328 }
329
330 String::new()
331}
332
333fn parse_env_uri(val: &str) -> Option<Intercept> {
334 use std::borrow::Cow;
335
336 let uri = val.parse::<http::Uri>().ok()?;
337 let mut builder = http::Uri::builder();
338 let mut is_httpish = false;
339 let mut auth = Auth::Empty;
340
341 builder = builder.scheme(match uri.scheme() {
342 Some(s) => {
343 if s == &http::uri::Scheme::HTTP || s == &http::uri::Scheme::HTTPS {
344 is_httpish = true;
345 s.clone()
346 } else if matches!(s.as_str(), "socks4" | "socks4a" | "socks5" | "socks5h") {
347 s.clone()
348 } else {
349 return None;
351 }
352 }
353 None => {
355 is_httpish = true;
356 http::uri::Scheme::HTTP
357 }
358 });
359
360 let authority = uri.authority()?;
361
362 if let Some((userinfo, host_port)) = authority.as_str().split_once('@') {
363 let (user, pass) = match userinfo.split_once(':') {
364 Some((user, pass)) => (user, Some(pass)),
365 None => (userinfo, None),
366 };
367 let user = percent_decode_str(user).decode_utf8_lossy();
368 let pass = pass.map(|pass| percent_decode_str(pass).decode_utf8_lossy());
369 if is_httpish {
370 auth = Auth::Basic(encode_basic_auth(&user, pass.as_deref()));
371 } else {
372 auth = Auth::Raw(
373 user.into_owned(),
374 pass.map_or_else(String::new, Cow::into_owned),
375 );
376 }
377 builder = builder.authority(host_port);
378 } else {
379 builder = builder.authority(authority.clone());
380 }
381
382 builder = builder.path_and_query("/");
384
385 let dst = builder.build().ok()?;
386
387 Some(Intercept { uri: dst, auth })
388}
389
390fn encode_basic_auth(user: &str, pass: Option<&str>) -> HeaderValue {
391 use base64::prelude::BASE64_STANDARD;
392 use base64::write::EncoderWriter;
393 use std::io::Write;
394
395 let mut buf = b"Basic ".to_vec();
396 {
397 let mut encoder = EncoderWriter::new(&mut buf, &BASE64_STANDARD);
398 let _ = write!(encoder, "{user}:");
399 if let Some(password) = pass {
400 let _ = write!(encoder, "{password}");
401 }
402 }
403 let mut header = HeaderValue::from_bytes(&buf).expect("base64 is always valid HeaderValue");
404 header.set_sensitive(true);
405 header
406}
407
408impl NoProxy {
409 fn empty() -> NoProxy {
420 NoProxy {
421 ips: IpMatcher(Vec::new()),
422 domains: DomainMatcher(Vec::new()),
423 }
424 }
425
426 pub fn from_string(no_proxy_list: &str) -> Self {
446 let mut ips = Vec::new();
447 let mut domains = Vec::new();
448 let parts = no_proxy_list.split(',').map(str::trim);
449 for part in parts {
450 match part.parse::<IpNet>() {
451 Ok(ip) => ips.push(Ip::Network(ip)),
453 Err(_) => match part.parse::<IpAddr>() {
454 Ok(addr) => ips.push(Ip::Address(addr)),
455 Err(_) => {
456 if !part.trim().is_empty() {
457 domains.push(part.to_owned())
458 }
459 }
460 },
461 }
462 }
463 NoProxy {
464 ips: IpMatcher(ips),
465 domains: DomainMatcher(domains),
466 }
467 }
468
469 pub fn contains(&self, host: &str) -> bool {
471 let host = if host.starts_with('[') {
474 let x: &[_] = &['[', ']'];
475 host.trim_matches(x)
476 } else {
477 host
478 };
479 match host.parse::<IpAddr>() {
480 Ok(ip) => self.ips.contains(ip),
482 Err(_) => self.domains.contains(host),
483 }
484 }
485
486 fn is_empty(&self) -> bool {
487 self.ips.0.is_empty() && self.domains.0.is_empty()
488 }
489}
490
491impl IpMatcher {
492 fn contains(&self, addr: IpAddr) -> bool {
493 for ip in &self.0 {
494 match ip {
495 Ip::Address(address) => {
496 if &addr == address {
497 return true;
498 }
499 }
500 Ip::Network(net) => {
501 if net.contains(&addr) {
502 return true;
503 }
504 }
505 }
506 }
507 false
508 }
509}
510
511impl DomainMatcher {
512 fn contains(&self, domain: &str) -> bool {
516 let domain_len = domain.len();
517 for d in &self.0 {
518 if d == domain || d.strip_prefix('.') == Some(domain) {
519 return true;
520 } else if domain.ends_with(d) {
521 if d.starts_with('.') {
522 return true;
525 } else if domain.as_bytes().get(domain_len - d.len() - 1) == Some(&b'.') {
526 return true;
529 }
530 } else if d == "*" {
531 return true;
532 }
533 }
534 false
535 }
536}
537
538mod builder {
539 pub trait IntoValue {
543 #[doc(hidden)]
544 fn into_value(self) -> String;
545 }
546
547 impl IntoValue for String {
548 #[doc(hidden)]
549 fn into_value(self) -> String {
550 self
551 }
552 }
553
554 impl IntoValue for &String {
555 #[doc(hidden)]
556 fn into_value(self) -> String {
557 self.into()
558 }
559 }
560
561 impl IntoValue for &str {
562 #[doc(hidden)]
563 fn into_value(self) -> String {
564 self.into()
565 }
566 }
567}
568
569#[cfg(feature = "client-proxy-system")]
570#[cfg(target_os = "macos")]
571mod mac {
572 use system_configuration::core_foundation::base::{CFType, TCFType, TCFTypeRef};
573 use system_configuration::core_foundation::dictionary::CFDictionary;
574 use system_configuration::core_foundation::number::CFNumber;
575 use system_configuration::core_foundation::string::{CFString, CFStringRef};
576 use system_configuration::dynamic_store::SCDynamicStoreBuilder;
577 use system_configuration::sys::schema_definitions::{
578 kSCPropNetProxiesHTTPEnable, kSCPropNetProxiesHTTPPort, kSCPropNetProxiesHTTPProxy,
579 kSCPropNetProxiesHTTPSEnable, kSCPropNetProxiesHTTPSPort, kSCPropNetProxiesHTTPSProxy,
580 };
581
582 pub(super) fn with_system(builder: &mut super::Builder) {
583 let store = SCDynamicStoreBuilder::new("").build();
584
585 let proxies_map = if let Some(proxies_map) = store.get_proxies() {
586 proxies_map
587 } else {
588 return;
589 };
590
591 if builder.http.is_empty() {
592 let http_proxy_config = parse_setting_from_dynamic_store(
593 &proxies_map,
594 unsafe { kSCPropNetProxiesHTTPEnable },
595 unsafe { kSCPropNetProxiesHTTPProxy },
596 unsafe { kSCPropNetProxiesHTTPPort },
597 );
598 if let Some(http) = http_proxy_config {
599 builder.http = http;
600 }
601 }
602
603 if builder.https.is_empty() {
604 let https_proxy_config = parse_setting_from_dynamic_store(
605 &proxies_map,
606 unsafe { kSCPropNetProxiesHTTPSEnable },
607 unsafe { kSCPropNetProxiesHTTPSProxy },
608 unsafe { kSCPropNetProxiesHTTPSPort },
609 );
610
611 if let Some(https) = https_proxy_config {
612 builder.https = https;
613 }
614 }
615 }
616
617 fn parse_setting_from_dynamic_store(
618 proxies_map: &CFDictionary<CFString, CFType>,
619 enabled_key: CFStringRef,
620 host_key: CFStringRef,
621 port_key: CFStringRef,
622 ) -> Option<String> {
623 let proxy_enabled = proxies_map
624 .find(enabled_key)
625 .and_then(|flag| flag.downcast::<CFNumber>())
626 .and_then(|flag| flag.to_i32())
627 .unwrap_or(0)
628 == 1;
629
630 if proxy_enabled {
631 let proxy_host = proxies_map
632 .find(host_key)
633 .and_then(|host| host.downcast::<CFString>())
634 .map(|host| host.to_string());
635 let proxy_port = proxies_map
636 .find(port_key)
637 .and_then(|port| port.downcast::<CFNumber>())
638 .and_then(|port| port.to_i32());
639
640 return match (proxy_host, proxy_port) {
641 (Some(proxy_host), Some(proxy_port)) => Some(format!("{proxy_host}:{proxy_port}")),
642 (Some(proxy_host), None) => Some(proxy_host),
643 (None, Some(_)) => None,
644 (None, None) => None,
645 };
646 }
647
648 None
649 }
650}
651
652#[cfg(feature = "client-proxy-system")]
653#[cfg(windows)]
654mod win {
655 pub(super) fn with_system(builder: &mut super::Builder) {
656 let settings = if let Ok(settings) = windows_registry::CURRENT_USER
657 .open("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings")
658 {
659 settings
660 } else {
661 return;
662 };
663
664 if settings.get_u32("ProxyEnable").unwrap_or(0) == 0 {
665 return;
666 }
667
668 if let Ok(val) = settings.get_string("ProxyServer") {
669 if builder.http.is_empty() {
670 builder.http = val.clone();
671 }
672 if builder.https.is_empty() {
673 builder.https = val;
674 }
675 }
676
677 if builder.no.is_empty() {
678 if let Ok(val) = settings.get_string("ProxyOverride") {
679 builder.no = val
680 .split(';')
681 .map(|s| s.trim())
682 .collect::<Vec<&str>>()
683 .join(",")
684 .replace("*.", "");
685 }
686 }
687 }
688}
689
690#[cfg(test)]
691mod tests {
692 use super::*;
693
694 #[test]
695 fn test_domain_matcher() {
696 let domains = vec![".foo.bar".into(), "bar.foo".into()];
697 let matcher = DomainMatcher(domains);
698
699 assert!(matcher.contains("foo.bar"));
701 assert!(matcher.contains("www.foo.bar"));
703
704 assert!(matcher.contains("bar.foo"));
706 assert!(matcher.contains("www.bar.foo"));
708
709 assert!(!matcher.contains("notfoo.bar"));
711 assert!(!matcher.contains("notbar.foo"));
712 }
713
714 #[test]
715 fn test_no_proxy_wildcard() {
716 let no_proxy = NoProxy::from_string("*");
717 assert!(no_proxy.contains("any.where"));
718 }
719
720 #[test]
721 fn test_no_proxy_ip_ranges() {
722 let no_proxy =
723 NoProxy::from_string(".foo.bar, bar.baz,10.42.1.1/24,::1,10.124.7.8,2001::/17");
724
725 let should_not_match = [
726 "hyper.rs",
728 "notfoo.bar",
730 "notbar.baz",
732 "10.43.1.1",
734 "10.124.7.7",
736 "[ffff:db8:a0b:12f0::1]",
738 "[2005:db8:a0b:12f0::1]",
740 ];
741
742 for host in &should_not_match {
743 assert!(!no_proxy.contains(host), "should not contain {host:?}");
744 }
745
746 let should_match = [
747 "hello.foo.bar",
749 "bar.baz",
751 "foo.bar.baz",
753 "foo.bar",
755 "10.42.1.100",
757 "[::1]",
759 "[2001:db8:a0b:12f0::1]",
761 "10.124.7.8",
763 ];
764
765 for host in &should_match {
766 assert!(no_proxy.contains(host), "should contain {host:?}");
767 }
768 }
769
770 macro_rules! p {
771 ($($n:ident = $v:expr,)*) => ({Builder {
772 $($n: $v.into(),)*
773 ..Builder::default()
774 }.build()});
775 }
776
777 fn intercept(p: &Matcher, u: &str) -> Intercept {
778 p.intercept(&u.parse().unwrap()).unwrap()
779 }
780
781 #[test]
782 fn test_all_proxy() {
783 let p = p! {
784 all = "http://om.nom",
785 };
786
787 assert_eq!("http://om.nom", intercept(&p, "http://example.com").uri());
788
789 assert_eq!("http://om.nom", intercept(&p, "https://example.com").uri());
790 }
791
792 #[test]
793 fn test_specific_overrides_all() {
794 let p = p! {
795 all = "http://no.pe",
796 http = "http://y.ep",
797 };
798
799 assert_eq!("http://no.pe", intercept(&p, "https://example.com").uri());
800
801 assert_eq!("http://y.ep", intercept(&p, "http://example.com").uri());
803 }
804
805 #[test]
806 fn test_parse_no_scheme_defaults_to_http() {
807 let p = p! {
808 https = "y.ep",
809 http = "127.0.0.1:8887",
810 };
811
812 assert_eq!(intercept(&p, "https://example.local").uri(), "http://y.ep");
813 assert_eq!(
814 intercept(&p, "http://example.local").uri(),
815 "http://127.0.0.1:8887"
816 );
817 }
818
819 #[test]
820 fn test_parse_http_auth() {
821 let p = p! {
822 all = "http://Aladdin:opensesame@y.ep",
823 };
824
825 let proxy = intercept(&p, "https://example.local");
826 assert_eq!(proxy.uri(), "http://y.ep");
827 assert_eq!(
828 proxy.basic_auth().expect("basic_auth"),
829 "Basic QWxhZGRpbjpvcGVuc2VzYW1l"
830 );
831 }
832
833 #[test]
834 fn test_parse_http_auth_without_password() {
835 let p = p! {
836 all = "http://Aladdin@y.ep",
837 };
838 let proxy = intercept(&p, "https://example.local");
839 assert_eq!(proxy.uri(), "http://y.ep");
840 assert_eq!(
841 proxy.basic_auth().expect("basic_auth"),
842 "Basic QWxhZGRpbjo="
843 );
844 }
845
846 #[test]
847 fn test_parse_http_auth_without_scheme() {
848 let p = p! {
849 all = "Aladdin:opensesame@y.ep",
850 };
851
852 let proxy = intercept(&p, "https://example.local");
853 assert_eq!(proxy.uri(), "http://y.ep");
854 assert_eq!(
855 proxy.basic_auth().expect("basic_auth"),
856 "Basic QWxhZGRpbjpvcGVuc2VzYW1l"
857 );
858 }
859
860 #[test]
861 fn test_dont_parse_http_when_is_cgi() {
862 let mut builder = Matcher::builder();
863 builder.is_cgi = true;
864 builder.http = "http://never.gonna.let.you.go".into();
865 let m = builder.build();
866
867 assert!(m.intercept(&"http://rick.roll".parse().unwrap()).is_none());
868 }
869}