saluki_components/common/proxy/
destination.rs1use std::net::{IpAddr, SocketAddr};
4#[cfg(unix)]
5use std::path::PathBuf;
6use std::time::Duration;
7
8use http::{uri::Authority, Uri};
9use saluki_error::{generic_error, ErrorContext as _, GenericError};
10use saluki_io::net::{client::http::HttpClientBuilder, ListenAddress};
11
12#[derive(Clone, Debug, Eq, PartialEq)]
14pub enum Destination {
15 Tcp {
17 host: String,
22
23 port: u16,
25 },
26
27 #[cfg(unix)]
29 Unix(PathBuf),
30}
31
32impl Destination {
33 pub fn from_tcp_address(address: &str) -> Result<Self, GenericError> {
39 if address.contains('@') {
40 return Err(generic_error!(
41 "Invalid address `{address}`: expected a host and a port, without credentials."
42 ));
43 }
44 let authority = address
45 .parse::<Authority>()
46 .with_error_context(|| format!("Invalid address `{address}`: expected a host and a port."))?;
47 let port = authority
48 .port_u16()
49 .ok_or_else(|| generic_error!("Invalid address `{address}`: expected a host and a port."))?;
50 let host = authority
52 .host()
53 .trim_start_matches('[')
54 .trim_end_matches(']')
55 .to_string();
56 Ok(Self::Tcp { host, port })
57 }
58
59 pub(crate) fn base_uri(&self) -> Result<Uri, http::Error> {
68 match self {
69 Self::Tcp { host, port } => {
70 let authority = if host.contains(':') {
72 format!("[{host}]:{port}")
73 } else {
74 format!("{host}:{port}")
75 };
76 Uri::builder()
77 .scheme("http")
78 .authority(authority)
79 .path_and_query("/")
80 .build()
81 }
82 #[cfg(unix)]
83 Self::Unix(_) => Ok(Uri::from_static("http://localhost/")),
84 }
85 }
86
87 pub(crate) fn configure_client(&self, builder: HttpClientBuilder) -> HttpClientBuilder {
89 match self {
90 Self::Tcp { .. } => builder,
92 #[cfg(unix)]
93 Self::Unix(path) => builder.with_unix_socket_path(path.clone()),
94 }
95 }
96}
97
98const LOOKUP_TIMEOUT: Duration = Duration::from_secs(2);
103
104pub async fn listener_reached_by<'a, I>(destination: &Destination, listeners: I) -> Option<&'a ListenAddress>
110where
111 I: IntoIterator<Item = &'a ListenAddress>,
112{
113 match destination {
114 Destination::Tcp { host, port } => {
115 let tcp_listeners = listeners
116 .into_iter()
117 .filter_map(|endpoint| match endpoint {
118 ListenAddress::Tcp(listener) => Some((endpoint, *listener)),
119 _ => None,
120 })
121 .collect::<Vec<_>>();
122 if tcp_listeners.is_empty() {
123 return None;
124 }
125
126 let destinations = tokio::time::timeout(LOOKUP_TIMEOUT, tokio::net::lookup_host((host.as_str(), *port)))
129 .await
130 .ok()?
131 .ok()?
132 .collect::<Vec<_>>();
133 tcp_listeners
134 .into_iter()
135 .find(|(_, listener)| {
136 destinations
137 .iter()
138 .any(|destination| tcp_reaches(*destination, *listener))
139 })
140 .map(|(endpoint, _)| endpoint)
141 }
142 #[cfg(unix)]
143 Destination::Unix(path) => listeners
144 .into_iter()
145 .find(|endpoint| matches!(endpoint, ListenAddress::Unix(listener) if listener == path)),
146 }
147}
148
149fn tcp_reaches(destination: SocketAddr, listener: SocketAddr) -> bool {
154 let is_local = |ip: IpAddr| ip.is_loopback() || ip.is_unspecified();
155 let (destination_ip, listener_ip) = (destination.ip(), listener.ip());
156
157 destination.port() == listener.port()
158 && (destination_ip == listener_ip
159 || ((destination_ip.is_unspecified() || listener_ip.is_unspecified())
160 && destination_ip.is_ipv4() == listener_ip.is_ipv4()
161 && is_local(destination_ip)
162 && is_local(listener_ip)))
163}
164
165#[cfg(test)]
166mod tests {
167 use super::*;
168
169 #[test]
170 fn base_uri_brackets_an_ipv6_host() {
171 let uri = |host: &str| {
172 Destination::Tcp {
173 host: host.to_string(),
174 port: 8126,
175 }
176 .base_uri()
177 .unwrap()
178 .to_string()
179 };
180
181 assert_eq!(uri("127.0.0.1"), "http://127.0.0.1:8126/");
182 assert_eq!(uri("localhost"), "http://localhost:8126/");
183 assert_eq!(uri("::1"), "http://[::1]:8126/");
184 }
185
186 #[test]
187 fn from_tcp_address_splits_the_host_and_port() {
188 let tcp = |host: &str, port| Destination::Tcp {
189 host: host.to_string(),
190 port,
191 };
192
193 assert_eq!(
194 Destination::from_tcp_address("127.0.0.1:4319").unwrap(),
195 tcp("127.0.0.1", 4319)
196 );
197 assert_eq!(
198 Destination::from_tcp_address("localhost:4320").unwrap(),
199 tcp("localhost", 4320)
200 );
201 assert_eq!(Destination::from_tcp_address("[::1]:4319").unwrap(), tcp("::1", 4319));
202
203 for address in [
204 "127.0.0.1",
205 "localhost:",
206 "http://127.0.0.1:4319",
207 "user@127.0.0.1:4319",
208 "",
209 ] {
210 assert!(Destination::from_tcp_address(address).is_err(), "{address:?}");
211 }
212 }
213
214 #[tokio::test]
215 async fn listener_reached_by_matches_a_listener_of_the_same_transport() {
216 let tcp = |host: &str, port| Destination::Tcp {
217 host: host.to_string(),
218 port,
219 };
220 let listen = |address: &str| ListenAddress::try_from(address).unwrap();
221 let wildcard = listen("tcp://0.0.0.0:4319");
222 let loopback = listen("tcp://127.0.0.1:4320");
223 let listeners = [&wildcard, &loopback];
224
225 assert_eq!(
226 listener_reached_by(&tcp("127.0.0.1", 4319), listeners).await,
227 Some(&wildcard)
228 );
229 assert_eq!(
230 listener_reached_by(&tcp("localhost", 4320), listeners).await,
231 Some(&loopback)
232 );
233 assert_eq!(listener_reached_by(&tcp("127.0.0.1", 4321), listeners).await, None);
234 }
235
236 #[cfg(unix)]
237 #[tokio::test]
238 async fn listener_reached_by_matches_a_unix_socket_listener_only_by_path() {
239 let tcp = |host: &str, port| Destination::Tcp {
240 host: host.to_string(),
241 port,
242 };
243 let unix = |path: &str| Destination::Unix(PathBuf::from(path));
244 let listen = |address: &str| ListenAddress::try_from(address).unwrap();
245 let loopback = listen("tcp://127.0.0.1:4320");
246 let socket = listen("unix:///tmp/otlp.sock");
247 let listeners = [&loopback, &socket];
248
249 assert_eq!(
250 listener_reached_by(&unix("/tmp/otlp.sock"), listeners).await,
251 Some(&socket)
252 );
253 assert_eq!(listener_reached_by(&unix("/tmp/other.sock"), listeners).await, None);
254 assert_eq!(listener_reached_by(&tcp("127.0.0.1", 4320), [&socket]).await, None);
256 assert_eq!(
257 listener_reached_by(&tcp("127.0.0.1", 4320), [&socket, &loopback]).await,
258 Some(&loopback)
259 );
260 }
261
262 #[test]
263 fn tcp_reaches_only_a_listener_on_the_same_port_and_address() {
264 let addr = |s: &str| s.parse::<SocketAddr>().unwrap();
265
266 assert!(tcp_reaches(addr("127.0.0.1:8126"), addr("127.0.0.1:8126")));
267 assert!(tcp_reaches(addr("127.0.0.1:8126"), addr("0.0.0.0:8126")));
268 assert!(tcp_reaches(addr("0.0.0.0:8126"), addr("127.0.0.1:8126")));
269 assert!(tcp_reaches(addr("[::1]:8126"), addr("[::]:8126")));
270
271 assert!(!tcp_reaches(addr("127.0.0.1:8127"), addr("127.0.0.1:8126")));
272 assert!(!tcp_reaches(addr("10.0.0.2:8126"), addr("10.0.0.1:8126")));
273 assert!(!tcp_reaches(addr("[::1]:8126"), addr("0.0.0.0:8126")));
274 assert!(!tcp_reaches(addr("127.0.0.1:8126"), addr("10.0.0.1:8126")));
275 }
276}