unix.rs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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. use std::path::{Path, PathBuf};
  19. use async_trait::async_trait;
  20. use log::debug;
  21. use smol::{
  22. fs,
  23. net::unix::{UnixListener as SmolUnixListener, UnixStream},
  24. };
  25. use url::Url;
  26. use super::{PtListener, PtStream};
  27. use crate::Result;
  28. /// Unix Dialer implementation
  29. #[derive(Debug, Clone)]
  30. pub struct UnixDialer;
  31. impl UnixDialer {
  32. /// Instantiate a new [`UnixDialer`] object
  33. pub(crate) async fn new() -> Result<Self> {
  34. Ok(Self {})
  35. }
  36. /// Internal dial function
  37. pub(crate) async fn do_dial(
  38. &self,
  39. path: impl AsRef<Path> + core::fmt::Debug,
  40. ) -> Result<UnixStream> {
  41. debug!(target: "net::unix::do_dial", "Dialing {:?} Unix socket...", path);
  42. let stream = UnixStream::connect(path).await?;
  43. Ok(stream)
  44. }
  45. }
  46. /// Unix Listener implementation
  47. #[derive(Debug, Clone)]
  48. pub struct UnixListener;
  49. impl UnixListener {
  50. /// Instantiate a new [`UnixListener`] object
  51. pub(crate) async fn new() -> Result<Self> {
  52. Ok(Self {})
  53. }
  54. /// Internal listen function
  55. pub(crate) async fn do_listen(&self, path: &PathBuf) -> Result<SmolUnixListener> {
  56. // This rm is a bit aggressive, but c'est la vie.
  57. let _ = fs::remove_file(path).await;
  58. let listener = SmolUnixListener::bind(path)?;
  59. Ok(listener)
  60. }
  61. }
  62. #[async_trait]
  63. impl PtListener for SmolUnixListener {
  64. async fn next(&self) -> std::io::Result<(Box<dyn PtStream>, Url)> {
  65. let (stream, _peer_addr) = match self.accept().await {
  66. Ok((s, a)) => (s, a),
  67. Err(e) => return Err(e),
  68. };
  69. let addr = self.local_addr().unwrap();
  70. let addr = addr.as_pathname().unwrap().to_str().unwrap();
  71. let url = Url::parse(&format!("unix://{}", addr)).unwrap();
  72. Ok((Box::new(stream), url))
  73. }
  74. }