agentmux_srv_core/muxbus/
ws_connect.rs1use std::io;
21use std::net::IpAddr;
22use std::time::Duration;
23
24use base64::Engine;
25use tokio::io::{AsyncReadExt, AsyncWriteExt};
26use tokio::net::TcpStream;
27use tokio_tungstenite::tungstenite::client::IntoClientRequest;
28use tokio_tungstenite::tungstenite::error::UrlError;
29use tokio_tungstenite::tungstenite::handshake::client::Response;
30use tokio_tungstenite::tungstenite::Error;
31use tokio_tungstenite::{client_async_tls_with_config, connect_async_tls_with_config, MaybeTlsStream, WebSocketStream};
32
33const PROXY_TIMEOUT: Duration = Duration::from_secs(15);
35const MAX_REPLY_HEAD: usize = 16 * 1024;
37
38pub(crate) type Socket = WebSocketStream<MaybeTlsStream<TcpStream>>;
39
40#[derive(Debug, Clone, PartialEq, Eq)]
42pub(crate) struct Proxy {
43 host: String,
44 port: u16,
45 authorization: Option<String>,
46}
47
48pub(crate) fn parse_proxy(address: &str) -> Result<Proxy, String> {
50 const BAD: &str = "the proxy address must look like http://host:port";
51 let rest = address.trim();
52 let rest = match rest.get(..7) {
53 Some(scheme) if scheme.eq_ignore_ascii_case("http://") => &rest[7..],
54 _ => return Err("only http:// proxies are supported".to_string()),
55 };
56 let rest = rest.split(['/', '?', '#']).next().unwrap_or("");
57 let (userinfo, hostport) = match rest.rsplit_once('@') {
58 Some((u, h)) => (Some(u), h),
59 None => (None, rest),
60 };
61 let (host, port) = if let Some(v6) = hostport.strip_prefix('[') {
62 let (h, tail) = v6.split_once(']').ok_or(BAD)?;
63 (h, tail.strip_prefix(':'))
64 } else {
65 match hostport.rsplit_once(':') {
66 Some((h, p)) => (h, Some(p)),
67 None => (hostport, None),
68 }
69 };
70 if host.is_empty() {
71 return Err(BAD.to_string());
72 }
73 let port = match port {
74 Some(p) if !p.is_empty() => p.parse::<u16>().map_err(|_| BAD.to_string())?,
75 _ => 80,
76 };
77 let authorization = userinfo.map(|u| {
78 let mut pair = percent_decode(u);
80 if !pair.contains(&b':') {
81 pair.push(b':');
82 }
83 format!("Basic {}", base64::engine::general_purpose::STANDARD.encode(pair))
84 });
85 Ok(Proxy { host: host.to_string(), port, authorization })
86}
87
88fn percent_decode(s: &str) -> Vec<u8> {
91 let bytes = s.as_bytes();
92 let mut out = Vec::with_capacity(bytes.len());
93 let mut i = 0;
94 while i < bytes.len() {
95 let hex = |b: u8| (b as char).to_digit(16);
96 match (bytes[i], bytes.get(i + 1).copied().and_then(hex), bytes.get(i + 2).copied().and_then(hex)) {
97 (b'%', Some(hi), Some(lo)) => {
98 out.push((hi * 16 + lo) as u8);
99 i += 3;
100 }
101 (b, _, _) => {
102 out.push(b);
103 i += 1;
104 }
105 }
106 }
107 out
108}
109
110pub(crate) fn no_proxy_matches(list: &str, host: &str, port: u16) -> bool {
113 let host = host.trim_matches(['[', ']']).to_ascii_lowercase();
114 let ip = host.parse::<IpAddr>().ok();
115 list.split(',').map(str::trim).filter(|e| !e.is_empty()).any(|entry| {
116 if entry == "*" {
117 return true;
118 }
119 let entry = entry.to_ascii_lowercase();
120 let (name, wanted_port) = split_entry_port(&entry);
121 if wanted_port.is_some_and(|p| p != port) {
122 return false;
123 }
124 if let (Some(ip), Some((net, bits))) = (ip, name.split_once('/')) {
125 return net.trim_matches(['[', ']']).parse::<IpAddr>().ok().zip(bits.parse::<u8>().ok()).is_some_and(|(net, bits)| in_range(ip, net, bits));
126 }
127 let name = name.trim_matches(['[', ']']);
128 if let (Some(ip), Ok(listed)) = (ip, name.parse::<IpAddr>()) {
130 return ip == listed;
131 }
132 let name = name.strip_prefix("*.").or_else(|| name.strip_prefix('.')).unwrap_or(name);
133 !name.is_empty() && (host == name || host.ends_with(&format!(".{name}")))
134 })
135}
136
137fn split_entry_port(entry: &str) -> (&str, Option<u16>) {
139 if entry.matches(':').count() > 1 && !entry.starts_with('[') {
140 return (entry, None);
141 }
142 match entry.rsplit_once(':') {
143 Some((name, port)) if !name.ends_with(']') || entry.starts_with('[') => match port.parse::<u16>() {
144 Ok(p) => (name, Some(p)),
145 Err(_) => (entry, None),
146 },
147 _ => (entry, None),
148 }
149}
150
151fn in_range(ip: IpAddr, net: IpAddr, bits: u8) -> bool {
152 match (ip, net) {
153 (IpAddr::V4(a), IpAddr::V4(b)) if bits <= 32 => mask_eq(u128::from(u32::from(a)), u128::from(u32::from(b)), 32, bits),
154 (IpAddr::V6(a), IpAddr::V6(b)) if bits <= 128 => mask_eq(u128::from(a), u128::from(b), 128, bits),
155 _ => false,
156 }
157}
158
159fn mask_eq(a: u128, b: u128, width: u32, bits: u8) -> bool {
160 let shift = width - u32::from(bits);
161 shift >= 128 || (a >> shift) == (b >> shift)
162}
163
164pub(crate) fn proxy_for(get: impl Fn(&str) -> Option<String>, host: &str, port: u16, tls: bool) -> Result<Option<Proxy>, String> {
167 let first = |names: &[&str]| names.iter().find_map(|n| get(n).map(|v| v.trim().to_string()).filter(|v| !v.is_empty()));
168 let configured = if tls {
169 first(&["HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"])
170 } else {
171 first(&["HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"])
172 };
173 let Some(address) = configured else { return Ok(None) };
174 if first(&["NO_PROXY", "no_proxy"]).is_some_and(|list| no_proxy_matches(&list, host, port)) {
175 return Ok(None);
176 }
177 parse_proxy(&address).map(Some)
178}
179
180async fn tunnel(proxy: &Proxy, host: &str, port: u16) -> io::Result<TcpStream> {
183 let authority = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
184 let attempt = async {
185 let mut stream = TcpStream::connect((proxy.host.as_str(), proxy.port)).await?;
186 let mut head = format!("CONNECT {authority} HTTP/1.1\r\nHost: {authority}\r\n");
187 if let Some(auth) = &proxy.authorization {
188 head.push_str(&format!("Proxy-Authorization: {auth}\r\n"));
189 }
190 head.push_str("\r\n");
191 stream.write_all(head.as_bytes()).await?;
192 let mut reply = Vec::new();
194 while !reply.ends_with(b"\r\n\r\n") {
195 if reply.len() >= MAX_REPLY_HEAD {
196 return Err(io::Error::other("the proxy's reply was too long"));
197 }
198 reply.push(stream.read_u8().await?);
199 }
200 let status = String::from_utf8_lossy(&reply);
201 let status_line = status.lines().next().unwrap_or("").trim();
202 if status_line.split_whitespace().nth(1) == Some("200") {
203 Ok(stream)
204 } else {
205 Err(io::Error::other(format!("the proxy refused CONNECT {authority}: {status_line}")))
206 }
207 };
208 match tokio::time::timeout(PROXY_TIMEOUT, attempt).await {
209 Ok(result) => result,
210 Err(_) => Err(io::Error::new(io::ErrorKind::TimedOut, format!("the proxy did not answer CONNECT {authority}"))),
211 }
212}
213
214pub async fn connect(request: impl IntoClientRequest + Unpin) -> Result<(Socket, Response), Error> {
216 connect_with_env(request, |name| std::env::var(name).ok()).await
217}
218
219pub(crate) async fn connect_within(request: impl IntoClientRequest + Unpin, limit: std::time::Duration) -> Result<(Socket, Response), Error> {
221 tokio::time::timeout(limit, connect(request))
222 .await
223 .unwrap_or_else(|_| Err(Error::Io(io::Error::new(io::ErrorKind::TimedOut, "the WebSocket handshake took too long"))))
224}
225
226async fn connect_with_env(request: impl IntoClientRequest + Unpin, get: impl Fn(&str) -> Option<String>) -> Result<(Socket, Response), Error> {
227 let request = request.into_client_request()?;
228 let uri = request.uri();
229 let host = uri.host().ok_or(Error::Url(UrlError::NoHostName))?.trim_matches(['[', ']']).to_string();
231 let tls = uri.scheme_str() == Some("wss");
232 let port = uri.port_u16().unwrap_or(if tls { 443 } else { 80 });
233 match proxy_for(get, &host, port, tls) {
234 Ok(None) => connect_async_tls_with_config(request, None, false, None).await,
235 Ok(Some(proxy)) => {
236 tracing::debug!(host = %host, port, proxy_host = %proxy.host, proxy_port = proxy.port, "ws: connecting through the proxy");
237 let stream = tunnel(&proxy, &host, port).await.map_err(Error::Io)?;
238 client_async_tls_with_config(request, stream, None, None).await
239 }
240 Err(why) => {
241 tracing::warn!("ws: a proxy is configured but cannot be used ({why}); not connecting direct");
242 Err(Error::Io(io::Error::other(format!("proxy not usable: {why}"))))
243 }
244 }
245}
246
247#[cfg(test)]
248#[path = "ws_connect_tests.rs"]
249mod tests;