Skip to main content

libdd_common/connector/
uds.rs

1// Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/
2// SPDX-License-Identifier: Apache-2.0
3
4use std::ffi::OsString;
5use std::os::unix::ffi::{OsStrExt, OsStringExt};
6use std::path::{Path, PathBuf};
7
8/// Creates a new Uri, with the `unix` scheme, and the path to the socket
9/// encoded as a hex string, to prevent special characters in the url authority
10pub fn socket_path_to_uri(path: &Path) -> Result<hyper::Uri, hyper::http::Error> {
11    let path = hex::encode(path.as_os_str().as_bytes());
12    hyper::Uri::builder()
13        .scheme("unix")
14        .authority(path)
15        .path_and_query("")
16        .build()
17}
18
19pub fn socket_path_from_uri(uri: &hyper::Uri) -> anyhow::Result<PathBuf> {
20    if uri.scheme_str() != Some("unix") {
21        return Err(super::errors::Error::InvalidUrl.into());
22    }
23
24    let path = hex::decode(
25        uri.authority()
26            .ok_or(super::errors::Error::InvalidUrl)?
27            .as_str(),
28    )
29    .map_err(|_| super::errors::Error::InvalidUrl)?;
30    Ok(PathBuf::from(OsString::from_vec(path)))
31}
32
33#[test]
34fn test_encode_unix_socket_path_absolute() {
35    let expected_path = "/path/to/a/socket.sock".as_ref();
36    let uri = socket_path_to_uri(expected_path).unwrap();
37    assert_eq!(uri.scheme_str(), Some("unix"));
38
39    let actual_path = socket_path_from_uri(&uri).unwrap();
40    assert_eq!(actual_path.as_path(), Path::new(expected_path))
41}
42
43#[test]
44fn test_encode_unix_socket_relative_path() {
45    let expected_path = "relative/path/to/a/socket.sock".as_ref();
46    let uri = socket_path_to_uri(expected_path).unwrap();
47    let actual_path = socket_path_from_uri(&uri).unwrap();
48    assert_eq!(actual_path.as_path(), Path::new(expected_path));
49
50    let expected_path = "./relative/path/to/a/socket.sock".as_ref();
51    let uri = socket_path_to_uri(expected_path).unwrap();
52    let actual_path = socket_path_from_uri(&uri).unwrap();
53    assert_eq!(actual_path.as_path(), Path::new(expected_path));
54}