pueue_lib/network_blocking/socket/
unix.rs

1use std::net::TcpStream;
2use std::os::unix::net::{UnixListener, UnixStream};
3
4use super::{
5    BlockingListener, BlockingStream, ConnectionSettings, GenericBlockingStream, get_tls_connector,
6};
7use crate::error::Error;
8
9impl BlockingListener for UnixListener {
10    fn accept(&self) -> Result<GenericBlockingStream, Error> {
11        let (stream, _) = self
12            .accept()
13            .map_err(|err| Error::IoError("accepting new unix connection.".to_string(), err))?;
14        Ok(Box::new(stream))
15    }
16}
17
18/// A new trait, which can be used to represent Unix- and Tls encrypted TcpStreams. \
19/// This is necessary to write generic functions where both types can be used.
20impl BlockingStream for UnixStream {}
21
22/// Get a new stream for the client. \
23/// This can either be a UnixStream or a Tls encrypted TCPStream, depending on the parameters.
24pub fn get_client_stream(settings: ConnectionSettings<'_>) -> Result<GenericBlockingStream, Error> {
25    match settings {
26        // Create a unix socket
27        ConnectionSettings::UnixSocket { path } => {
28            let stream = UnixStream::connect(&path).map_err(|err| {
29                Error::IoPathError(path, "connecting to daemon. Did you start it?", err)
30            })?;
31
32            Ok(Box::new(stream))
33        }
34        // Connect to the daemon via TCP
35        ConnectionSettings::TlsTcpSocket {
36            host,
37            port,
38            certificate,
39        } => {
40            let address = format!("{host}:{port}");
41            let tcp_stream = TcpStream::connect(&address).map_err(|_| {
42                Error::Connection(format!(
43                    "Failed to connect to the daemon on {address}. Did you start it?"
44                ))
45            })?;
46
47            // Get the configured rustls TlsConnector
48            let tls_connector = get_tls_connector(certificate).map_err(|err| {
49                Error::Connection(format!("Failed to initialize tls connector:\n{err}."))
50            })?;
51
52            // Initialize the TLS layer
53            let stream = tls_connector
54                .connect("pueue.local", tcp_stream)
55                .map_err(|err| Error::Connection(format!("Failed to initialize tls:\n{err}.")))?;
56
57            Ok(Box::new(stream))
58        }
59    }
60}