darkfi/net/transport/
unix.rs

1/* This file is part of DarkFi (https://dark.fi)
2 *
3 * Copyright (C) 2020-2026 Dyne.org foundation
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Affero General Public License as
7 * published by the Free Software Foundation, either version 3 of the
8 * License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU Affero General Public License for more details.
14 *
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17 */
18
19use std::{
20    io,
21    path::{Path, PathBuf},
22};
23
24use async_trait::async_trait;
25use smol::{
26    fs,
27    net::unix::{UnixListener as SmolUnixListener, UnixStream},
28};
29use tracing::debug;
30use url::Url;
31
32use super::{PtListener, PtStream};
33
34/// Unix Dialer implementation
35#[derive(Debug, Clone)]
36pub struct UnixDialer;
37
38impl UnixDialer {
39    /// Instantiate a new [`UnixDialer`] object
40    pub(crate) async fn new() -> io::Result<Self> {
41        Ok(Self {})
42    }
43
44    /// Internal dial function
45    pub(crate) async fn do_dial(
46        &self,
47        path: impl AsRef<Path> + core::fmt::Debug,
48    ) -> io::Result<UnixStream> {
49        debug!(target: "net::unix::do_dial", "Dialing {path:?} Unix socket...");
50        let stream = UnixStream::connect(path).await?;
51        Ok(stream)
52    }
53}
54
55/// Unix Listener implementation
56#[derive(Debug, Clone)]
57pub struct UnixListener;
58
59impl UnixListener {
60    /// Instantiate a new [`UnixListener`] object
61    pub(crate) async fn new() -> io::Result<Self> {
62        Ok(Self {})
63    }
64
65    /// Internal listen function
66    pub(crate) async fn do_listen(&self, path: &PathBuf) -> io::Result<SmolUnixListener> {
67        // This rm is a bit aggressive, but c'est la vie.
68        let _ = fs::remove_file(path).await;
69        let listener = SmolUnixListener::bind(path)?;
70        Ok(listener)
71    }
72}
73
74#[async_trait]
75impl PtListener for SmolUnixListener {
76    async fn next(&self) -> io::Result<(Box<dyn PtStream>, Url)> {
77        let (stream, _peer_addr) = match self.accept().await {
78            Ok((s, a)) => (s, a),
79            Err(e) => return Err(e),
80        };
81
82        let addr = self.local_addr().unwrap();
83        let addr = addr.as_pathname().unwrap().to_str().unwrap();
84        let url = Url::parse(&format!("unix://{addr}")).unwrap();
85
86        Ok((Box::new(stream), url))
87    }
88}