1use alloc::format;
21use alloc::string::String;
22use alloc::vec::Vec;
23
24use plat::net::IpAddr;
25
26use crate::url::{percent_decode, Url};
27
28#[derive(Clone, PartialEq, Eq)]
30pub struct Endpoint {
31 pub host: String,
32 pub port: u16,
33 auth: Option<String>,
35}
36
37impl core::fmt::Debug for Endpoint {
38 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
39 write!(f, "Endpoint({}:{}{})", self.host, self.port, if self.auth.is_some() { ", with credentials" } else { "" })
41 }
42}
43
44impl Endpoint {
45 pub fn parse(s: &str) -> Option<Endpoint> {
48 let s = s.trim();
49 let rest = match s.split_once("://") {
50 Some((scheme, rest)) if scheme.eq_ignore_ascii_case("http") => rest,
51 Some(_) => return None,
52 None => s,
53 };
54 let rest = rest.strip_suffix('/').unwrap_or(rest);
55 if rest.contains(['/', '?', '#']) {
56 return None;
57 }
58 let (userinfo, hostport) = match rest.rsplit_once('@') {
59 Some((u, h)) => (Some(u), h),
60 None => (None, rest),
61 };
62 let u = Url::parse(&format!("http://{}/", hostport))?;
63 let auth = userinfo.map(|ui| {
64 let (user, pw) = ui.split_once(':').unwrap_or((ui, ""));
65 let plain = format!("{}:{}", percent_decode(user, false), percent_decode(pw, false));
66 format!("Basic {}", crate::smtp::b64(plain.as_bytes()))
67 });
68 Some(Endpoint { host: u.host, port: u.port, auth })
69 }
70
71 pub fn with_auth(mut self, user: &str, password: &str) -> Endpoint {
73 self.auth = Some(format!("Basic {}", crate::smtp::b64(format!("{}:{}", user, password).as_bytes())));
74 self
75 }
76
77 pub fn authorization(&self) -> Option<&str> {
79 self.auth.as_deref()
80 }
81
82 pub fn url(&self) -> Url {
84 Url { scheme: String::from("http"), host: self.host.clone(), port: self.port, target: String::from("/") }
85 }
86
87 pub fn key(&self) -> String {
89 self.url().authority()
90 }
91}
92
93#[derive(Clone, Debug, PartialEq, Eq)]
94enum NoProxy {
95 All,
96 Name(String, Option<u16>),
98 Net(IpAddr, u8, Option<u16>),
100}
101
102fn cidr_match(a: &IpAddr, net: &IpAddr, bits: u8) -> bool {
103 let (x, y): (&[u8], &[u8]) = match (a, net) {
104 (IpAddr::V4(x), IpAddr::V4(y)) => (x, y),
105 (IpAddr::V6(x), IpAddr::V6(y)) => (x, y),
106 _ => return false,
107 };
108 let full = bits as usize / 8;
109 if x[..full] != y[..full] {
110 return false;
111 }
112 let rest = bits % 8;
113 rest == 0 || (x[full] ^ y[full]) >> (8 - rest) == 0
114}
115
116fn no_proxy_entry(e: &str) -> Option<NoProxy> {
117 let e = e.trim().to_ascii_lowercase();
118 if e.is_empty() {
119 return None;
120 }
121 if e == "*" {
122 return Some(NoProxy::All);
123 }
124 let (body, port) = if let Some(r) = e.strip_prefix('[') {
126 let (h, p) = r.split_once(']')?;
127 (String::from(h), if p.is_empty() { None } else { Some(p.strip_prefix(':')?.parse().ok()?) })
129 } else if e.matches(':').count() == 1 {
130 let (h, p) = e.split_once(':')?;
131 (String::from(h), Some(p.parse().ok()?))
132 } else {
133 (e.clone(), None)
134 };
135 let (addr, bits) = match body.split_once('/') {
136 Some((a, b)) => (a, Some(b.parse::<u8>().ok()?)),
137 None => (body.as_str(), None),
138 };
139 if let Some(ip) = IpAddr::parse(addr) {
140 let max = if matches!(ip, IpAddr::V4(_)) { 32 } else { 128 };
141 let bits = bits.unwrap_or(max);
142 return (bits <= max).then_some(NoProxy::Net(ip, bits, port));
143 }
144 if bits.is_some() {
145 return None;
146 }
147 let name = body.trim_start_matches("*.").trim_start_matches('.').trim_end_matches('.');
148 (!name.is_empty()).then(|| NoProxy::Name(String::from(name), port))
149}
150
151#[derive(Clone, Debug, Default, PartialEq, Eq)]
153pub struct Proxy {
154 http: Option<Endpoint>,
155 https: Option<Endpoint>,
156 no: Vec<NoProxy>,
157}
158
159impl Proxy {
160 pub fn none() -> Proxy {
162 Proxy::default()
163 }
164
165 pub fn new(url: &str) -> Option<Proxy> {
167 let e = Endpoint::parse(url)?;
168 Some(Proxy { http: Some(e.clone()), https: Some(e), no: Vec::new() })
169 }
170
171 pub fn http(mut self, e: Endpoint) -> Proxy {
173 self.http = Some(e);
174 self
175 }
176
177 pub fn https(mut self, e: Endpoint) -> Proxy {
179 self.https = Some(e);
180 self
181 }
182
183 pub fn no_proxy(mut self, list: &str) -> Proxy {
186 self.no.extend(list.split(',').filter_map(no_proxy_entry));
187 self
188 }
189
190 pub fn from_env() -> Option<Proxy> {
192 Proxy::from_vars(&|name| plat::env(name))
193 }
194
195 pub fn from_vars(get: &dyn Fn(&str) -> Option<String>) -> Option<Proxy> {
197 let var = |names: &[&str]| names.iter().find_map(|n| get(n).filter(|v| !v.trim().is_empty()));
198 let all = var(&["all_proxy", "ALL_PROXY"]).and_then(|v| Endpoint::parse(&v));
199 let http = var(&["http_proxy"]).and_then(|v| Endpoint::parse(&v)).or_else(|| all.clone());
201 let https = var(&["https_proxy", "HTTPS_PROXY"]).and_then(|v| Endpoint::parse(&v)).or(all);
202 if http.is_none() && https.is_none() {
203 return None;
204 }
205 let p = Proxy { http, https, no: Vec::new() };
206 Some(match var(&["no_proxy", "NO_PROXY"]) {
207 Some(list) => p.no_proxy(&list),
208 None => p,
209 })
210 }
211
212 pub fn bypass(&self, url: &Url) -> bool {
214 let host = url.host.trim_end_matches('.');
215 let ip = IpAddr::parse(host.split('%').next().unwrap_or(host));
216 if ip.is_some_and(|a| a.is_loopback()) || host == "localhost" || host.ends_with(".localhost") {
217 return true;
218 }
219 self.no.iter().any(|n| match n {
220 NoProxy::All => true,
221 NoProxy::Name(name, port) => {
222 port.is_none_or(|p| p == url.port) && (host == name || (host.len() > name.len() && host.ends_with(name.as_str()) && host.as_bytes()[host.len() - name.len() - 1] == b'.'))
223 }
224 NoProxy::Net(net, bits, port) => port.is_none_or(|p| p == url.port) && ip.is_some_and(|a| cidr_match(&a, net, *bits)),
225 })
226 }
227
228 pub fn for_url(&self, url: &Url) -> Option<&Endpoint> {
230 if self.bypass(url) {
231 return None;
232 }
233 if url.is_https() { self.https.as_ref() } else { self.http.as_ref() }
234 }
235}