1use alloc::borrow::Cow;
5use anyhow::Context;
6use core::{ops::Deref, str::FromStr};
7use http::uri::{self, PathAndQuery, Uri};
8use serde::de::Error;
9use serde::{Deserialize, Deserializer, Serialize, Serializer};
10use std::path::PathBuf;
11
12use crate::HttpRequestBuilder;
13
14#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
15pub struct Endpoint {
16 #[serde(serialize_with = "serialize_uri", deserialize_with = "deserialize_uri")]
17 pub url: http::Uri,
18 pub api_key: Option<Cow<'static, str>>,
19 pub timeout_ms: u64,
20 pub test_token: Option<Cow<'static, str>>,
22 #[serde(default)]
25 pub use_system_resolver: bool,
26}
27
28impl core::fmt::Debug for Endpoint {
29 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
30 f.debug_struct("Endpoint")
31 .field("url", &self.url)
32 .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
33 .field("timeout_ms", &self.timeout_ms)
34 .field("test_token", &self.test_token)
35 .field("use_system_resolver", &self.use_system_resolver)
36 .finish()
37 }
38}
39
40impl Default for Endpoint {
41 fn default() -> Self {
42 Endpoint {
43 url: http::Uri::default(),
44 api_key: None,
45 timeout_ms: Self::DEFAULT_TIMEOUT,
46 test_token: None,
47 use_system_resolver: false,
48 }
49 }
50}
51
52#[derive(serde::Deserialize, serde::Serialize)]
53struct SerializedUri<'a> {
54 scheme: Option<Cow<'a, str>>,
55 authority: Option<Cow<'a, str>>,
56 path_and_query: Option<Cow<'a, str>>,
57}
58
59fn serialize_uri<S>(uri: &http::Uri, serializer: S) -> Result<S::Ok, S::Error>
60where
61 S: Serializer,
62{
63 let parts = uri.clone().into_parts();
64 let uri = SerializedUri {
65 scheme: parts.scheme.as_ref().map(|s| Cow::Borrowed(s.as_str())),
66 authority: parts.authority.as_ref().map(|s| Cow::Borrowed(s.as_str())),
67 path_and_query: parts
68 .path_and_query
69 .as_ref()
70 .map(|s| Cow::Borrowed(s.as_str())),
71 };
72 uri.serialize(serializer)
73}
74
75fn deserialize_uri<'de, D>(deserializer: D) -> Result<http::Uri, D::Error>
76where
77 D: Deserializer<'de>,
78{
79 let uri = SerializedUri::deserialize(deserializer)?;
80 let mut builder = http::Uri::builder();
81 if let Some(v) = uri.authority {
82 builder = builder.authority(v.deref());
83 }
84 if let Some(v) = uri.scheme {
85 builder = builder.scheme(v.deref());
86 }
87 if let Some(v) = uri.path_and_query {
88 builder = builder.path_and_query(v.deref());
89 }
90
91 builder.build().map_err(Error::custom)
92}
93
94pub fn parse_uri(uri: &str) -> anyhow::Result<http::Uri> {
117 if let Some(path) = uri.strip_prefix("unix://") {
118 encode_uri_path_in_authority("unix", path)
119 } else if let Some(path) = uri.strip_prefix("windows:") {
120 encode_uri_path_in_authority("windows", path)
121 } else if let Some(path) = uri.strip_prefix("file://") {
122 encode_uri_path_in_authority("file", path)
123 } else {
124 Ok(http::Uri::from_str(uri)?)
125 }
126}
127
128fn encode_uri_path_in_authority(scheme: &str, path: &str) -> anyhow::Result<http::Uri> {
129 let mut parts = uri::Parts::default();
130 parts.scheme = uri::Scheme::from_str(scheme).ok();
131
132 let path = hex::encode(path);
133
134 parts.authority = uri::Authority::from_str(path.as_str()).ok();
135 parts.path_and_query = Some(uri::PathAndQuery::from_static("/"));
136 Ok(http::Uri::from_parts(parts)?)
137}
138
139pub fn decode_uri_path_in_authority(uri: &http::Uri) -> anyhow::Result<PathBuf> {
140 let path = hex::decode(uri.authority().context("missing uri authority")?.as_str())?;
141 #[cfg(unix)]
142 {
143 use std::os::unix::ffi::OsStringExt;
144 Ok(PathBuf::from(std::ffi::OsString::from_vec(path)))
145 }
146 #[cfg(not(unix))]
147 {
148 match String::from_utf8(path) {
149 Ok(s) => Ok(PathBuf::from(s.as_str())),
150 _ => Err(anyhow::anyhow!("file uri should be utf-8")),
151 }
152 }
153}
154
155impl Endpoint {
156 pub const DEFAULT_TIMEOUT: u64 = 3_000;
158
159 pub fn agentless(site: &str, api_key: String) -> anyhow::Result<Self> {
160 Ok(Self {
161 url: Uri::builder()
162 .scheme("https")
163 .authority(
164 uri::Authority::try_from(site)
165 .with_context(|| format!("dd_site is an invalid url: {site}"))?,
166 )
167 .path_and_query(PathAndQuery::from_static(""))
168 .build()
169 .with_context(|| format!("rc url is invalid for site: {site}"))?,
170 api_key: Some(api_key.into()),
171 timeout_ms: Self::DEFAULT_TIMEOUT,
172 test_token: None,
173 use_system_resolver: true,
174 })
175 }
176
177 pub fn get_optional_headers(&self) -> impl Iterator<Item = (&'static str, &str)> {
180 [
181 self.api_key.as_ref().map(|v| ("dd-api-key", v.as_ref())),
182 self.test_token
183 .as_ref()
184 .map(|v| ("x-datadog-test-session-token", v.as_ref())),
185 ]
186 .into_iter()
187 .flatten()
188 }
189
190 pub fn set_standard_headers(
193 &self,
194 mut builder: http::request::Builder,
195 user_agent: &str,
196 ) -> http::request::Builder {
197 builder = builder.header("user-agent", user_agent);
198 for (name, value) in self.get_optional_headers() {
199 builder = builder.header(name, value);
200 }
201 for (name, value) in crate::entity_id::get_entity_headers() {
202 builder = builder.header(name, value);
203 }
204 builder
205 }
206
207 pub fn to_request_builder(&self, user_agent: &str) -> anyhow::Result<HttpRequestBuilder> {
212 let mut builder = http::Request::builder()
213 .uri(self.url.clone())
214 .header(http::header::USER_AGENT, user_agent);
215
216 for (name, value) in self.get_optional_headers() {
218 builder = builder.header(name, value);
219 }
220
221 for (name, value) in crate::entity_id::get_entity_headers() {
223 builder = builder.header(name, value);
224 }
225
226 Ok(builder)
227 }
228
229 #[inline]
230 pub fn from_slice(url: &str) -> Endpoint {
231 Endpoint {
232 #[allow(clippy::unwrap_used)]
233 url: parse_uri(url).unwrap(),
234 ..Default::default()
235 }
236 }
237
238 #[inline]
239 pub fn from_url(url: http::Uri) -> Endpoint {
240 Endpoint {
241 url,
242 ..Default::default()
243 }
244 }
245
246 pub fn is_file_endpoint(&self) -> bool {
247 self.url.scheme_str() == Some("file")
248 }
249
250 pub fn with_timeout(mut self, timeout_ms: u64) -> Self {
259 self.timeout_ms = if timeout_ms == 0 {
260 Self::DEFAULT_TIMEOUT
261 } else {
262 timeout_ms
263 };
264 self
265 }
266
267 pub fn with_system_resolver(mut self, use_system_resolver: bool) -> Self {
270 self.use_system_resolver = use_system_resolver;
271 self
272 }
273
274 #[cfg(feature = "reqwest")]
298 pub fn to_reqwest_client_builder(&self) -> anyhow::Result<(reqwest::ClientBuilder, String)> {
299 use anyhow::Context;
300
301 let mut builder = reqwest::Client::builder()
306 .timeout(core::time::Duration::from_millis(self.timeout_ms))
307 .hickory_dns(!self.use_system_resolver)
308 .no_proxy();
309
310 let request_url = match self.url.scheme_str() {
311 Some("https") => {
317 #[cfg(feature = "tls-core")]
318 {
319 builder = builder
320 .tls_backend_preconfigured(crate::connector::https::build_tls_config()?);
321 }
322 self.url.to_string()
323 }
324 Some("http") => self.url.to_string(),
329
330 Some("file") => {
332 let output_path = decode_uri_path_in_authority(&self.url)
333 .context("Failed to decode file path from URI")?;
334 let socket_or_pipe_path = crate::dump_server::spawn_dump_server(output_path)?;
335
336 #[cfg(unix)]
338 {
339 builder = builder.unix_socket(socket_or_pipe_path);
340 }
341 #[cfg(windows)]
342 {
343 builder = builder
344 .windows_named_pipe(socket_or_pipe_path.to_string_lossy().to_string());
345 }
346
347 "http://localhost/".to_string()
348 }
349
350 #[cfg(unix)]
352 Some("unix") => {
353 use crate::connector::uds::socket_path_from_uri;
354 let socket_path = socket_path_from_uri(&self.url)?;
355 builder = builder.unix_socket(socket_path);
356 format!("http://localhost{}", self.url.path())
357 }
358
359 #[cfg(windows)]
361 Some("windows") => {
362 use crate::connector::named_pipe::named_pipe_path_from_uri;
363 let pipe_path = named_pipe_path_from_uri(&self.url)?;
364 builder = builder.windows_named_pipe(pipe_path.to_string_lossy().to_string());
365 format!("http://localhost{}", self.url.path())
366 }
367
368 scheme => anyhow::bail!("Unsupported endpoint scheme: {:?}", scheme),
370 };
371
372 Ok((builder, request_url))
373 }
374}
375
376#[cfg(test)]
377mod tests {
378 use super::parse_uri;
379
380 #[test]
384 fn empty_authority_uris_are_rejected() {
385 for input in ["unix://", "windows:", "file://"] {
386 let result = parse_uri(input);
387 assert!(
388 result.is_err(),
389 "expected {input:?} to be rejected, got {result:?}"
390 );
391 }
392 }
393}