parsec_client/core/ipc_handler/
unix_socket.rs

1// Copyright 2020 Contributors to the Parsec project.
2// SPDX-License-Identifier: Apache-2.0
3//! Handler for Unix domain sockets
4use super::{Connect, ReadWrite};
5use crate::error::{ClientErrorKind, Error, Result};
6use std::os::unix::fs::FileTypeExt;
7use std::os::unix::net::UnixStream;
8use std::path::PathBuf;
9use std::time::Duration;
10
11/// Default socket path used by the service.
12pub const DEFAULT_SOCKET_PATH: &str = "/run/parsec/parsec.sock";
13
14/// IPC handler for Unix domain sockets
15#[derive(Debug, Clone)]
16pub struct Handler {
17    /// Path at which the socket can be found
18    path: PathBuf,
19    /// Timeout for reads and writes on the streams
20    timeout: Option<Duration>,
21}
22
23impl Connect for Handler {
24    fn connect(&self) -> Result<Box<dyn ReadWrite>> {
25        let stream = UnixStream::connect(self.path.clone()).map_err(ClientErrorKind::Ipc)?;
26
27        stream
28            .set_read_timeout(self.timeout)
29            .map_err(ClientErrorKind::Ipc)?;
30        stream
31            .set_write_timeout(self.timeout)
32            .map_err(ClientErrorKind::Ipc)?;
33
34        Ok(Box::from(stream))
35    }
36
37    fn set_timeout(&mut self, timeout: Option<Duration>) {
38        self.timeout = timeout;
39    }
40}
41
42impl Handler {
43    /// Create new client using given socket path and timeout duration
44    pub fn new(path: PathBuf, timeout: Option<Duration>) -> Result<Self> {
45        if path.exists()
46            && std::fs::metadata(&path)
47                .map_err(|_| Error::Client(ClientErrorKind::InvalidSocketAddress))?
48                .file_type()
49                .is_socket()
50        {
51            Ok(Handler { path, timeout })
52        } else {
53            Err(Error::Client(ClientErrorKind::InvalidSocketAddress))
54        }
55    }
56}
57
58impl Default for Handler {
59    fn default() -> Self {
60        Handler {
61            path: DEFAULT_SOCKET_PATH.into(),
62            timeout: Some(super::DEFAULT_TIMEOUT),
63        }
64    }
65}