1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#[cfg(unix)]
use std::fs;

#[cfg(unix)]
use std::os::unix::fs::FileTypeExt;

#[cfg(unix)]
use std::path::Path;

use tokio::net::{TcpListener, TcpStream};

#[cfg(unix)]
use tokio::net::{UnixListener, UnixStream};

#[cfg(unix)]
use tokio_util::either::Either;

#[cfg(unix)]
pub type Stream = Either<TcpStream, UnixStream>;

#[cfg(windows)]
pub type Stream = TcpStream;

use crate::ProtAddr;

pub async fn connect(pa: &ProtAddr) -> Result<Stream, std::io::Error> {
  let strm = match pa {
    ProtAddr::Tcp(sa) => connect_tcp(sa).await?,

    #[cfg(unix)]
    ProtAddr::Uds(sa) => connect_uds(sa).await?
  };

  Ok(strm)
}

/// Attempt to establish a TCP/IP socket connection.
async fn connect_tcp(addr: &str) -> Result<Stream, std::io::Error> {
  let stream = TcpStream::connect(addr).await?;

  #[cfg(unix)]
  return Ok(Either::Left(stream));

  #[cfg(windows)]
  return Ok(stream);
}

/// Attempt to establish a unix domain socket connection.
/// Currently only available on unix-like platforms.
#[cfg(unix)]
async fn connect_uds(addr: &Path) -> Result<Stream, std::io::Error> {
  let addr = match addr.to_str() {
    Some(a) => a.to_string(),
    None => unreachable!()
  };
  let stream = UnixStream::connect(addr).await?;
  Ok(Either::Right(stream))
}

pub enum Listener {
  #[cfg(unix)]
  Unix(UnixListener),
  Tcp(TcpListener)
}

#[derive(Debug)]
pub enum SockAddr {
  Std(std::net::SocketAddr),

  #[cfg(unix)]
  TokioUnix(tokio::net::unix::SocketAddr)
}

impl Listener {
  pub async fn accept(&self) -> Result<(Stream, SockAddr), tokio::io::Error> {
    match self {
      #[cfg(unix)]
      Listener::Unix(u) => {
        let (stream, sa) = u.accept().await?;

        let sa = SockAddr::TokioUnix(sa);

        return Ok((Either::Right(stream), sa));
      }
      Listener::Tcp(t) => {
        let (stream, sa) = t.accept().await?;

        let sa = SockAddr::Std(sa);

        #[cfg(unix)]
        return Ok((Either::Left(stream), sa));

        #[cfg(windows)]
        return Ok((stream, sa));
      }
    }
  }
}

pub async fn bind(pa: &ProtAddr) -> Result<Listener, std::io::Error> {
  let listener = match pa {
    ProtAddr::Tcp(sa) => Listener::Tcp(TcpListener::bind(sa).await?),

    #[cfg(unix)]
    ProtAddr::Uds(sa) => Listener::Unix(UnixListener::bind(Path::new(sa))?)
  };

  Ok(listener)
}

pub async fn force_bind(pa: &ProtAddr) -> Result<Listener, std::io::Error> {
  let listener = match pa {
    ProtAddr::Tcp(_) => bind(pa).await?,

    #[cfg(unix)]
    ProtAddr::Uds(sa) => {
      if sa.exists() {
        let md = fs::metadata(sa)?;
        let ft = md.file_type();
        if !ft.is_socket() {
          return Err(std::io::Error::new(
            std::io::ErrorKind::Other,
            "Not a socket"
          ));
        }
        fs::remove_file(sa)?;
      }
      Listener::Unix(UnixListener::bind(Path::new(sa))?)
    }
  };

  Ok(listener)
}

// vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 :