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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
use tokio::io::{AsyncRead, AsyncWrite, Error, ReadBuf};
use tokio::net::{TcpStream,TcpListener};
#[cfg(unix)]
use tokio::net::{UnixStream,UnixListener};
use std::pin::Pin;
use std::task::{Context, Poll};
use std::net;
use std::fmt;
use std::str::FromStr;
use std::io;
#[cfg(unix)]
use std::path::{Path,PathBuf};
#[cfg(unix)]
use std::os::unix::net as unix;
#[cfg(unix)]
use std::os::unix::io::{RawFd,AsRawFd};
#[derive(Debug,Clone,PartialEq,Eq,Hash)]
pub enum FCGIAddr {
Inet(net::SocketAddr),
#[cfg(unix)]
Unix(PathBuf)
}
impl From<net::SocketAddr> for FCGIAddr {
fn from(s: net::SocketAddr) -> FCGIAddr {
FCGIAddr::Inet(s)
}
}
#[cfg(unix)]
impl From<&Path> for FCGIAddr {
fn from(s: &Path) -> FCGIAddr {
FCGIAddr::Unix(s.to_path_buf())
}
}
#[cfg(unix)]
impl From<PathBuf> for FCGIAddr {
fn from(s: PathBuf) -> FCGIAddr {
FCGIAddr::Unix(s)
}
}
#[cfg(unix)]
impl From<unix::SocketAddr> for FCGIAddr {
fn from(s: unix::SocketAddr) -> FCGIAddr {
FCGIAddr::Unix(match s.as_pathname() {
None => Path::new("unnamed").to_path_buf(),
Some(p) => p.to_path_buf()
})
}
}
#[cfg(unix)]
impl From<tokio::net::unix::SocketAddr> for FCGIAddr {
fn from(s: tokio::net::unix::SocketAddr) -> FCGIAddr {
FCGIAddr::Unix(match s.as_pathname() {
None => Path::new("unnamed").to_path_buf(),
Some(p) => p.to_path_buf()
})
}
}
impl fmt::Display for FCGIAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
FCGIAddr::Inet(n) => write!(f, "{}", n),
#[cfg(unix)]
FCGIAddr::Unix(n) => write!(f, "{}", n.to_string_lossy())
}
}
}
impl FromStr for FCGIAddr {
type Err = net::AddrParseError;
#[cfg(unix)]
fn from_str(s: &str) -> Result<FCGIAddr, net::AddrParseError> {
if s.starts_with("/") {
Ok(FCGIAddr::Unix(Path::new(s).to_path_buf()))
} else {
s.parse().map(FCGIAddr::Inet)
}
}
#[cfg(not(unix))]
fn from_str(s: &str) -> Result<FCGIAddr, net::AddrParseError> {
s.parse().map(FCGIAddr::Inet)
}
}
#[derive(Debug)]
pub enum Stream {
Inet(TcpStream),
#[cfg(unix)]
Unix(UnixStream)
}
impl From<TcpStream> for Stream {
fn from(s: TcpStream) -> Stream {
Stream::Inet(s)
}
}
#[cfg(unix)]
impl From<UnixStream> for Stream {
fn from(s: UnixStream) -> Stream {
Stream::Unix(s)
}
}
impl Stream {
pub async fn connect(s: &FCGIAddr) -> io::Result<Stream> {
match s {
FCGIAddr::Inet(s) => TcpStream::connect(s).await.map(Stream::Inet),
#[cfg(unix)]
FCGIAddr::Unix(s) => UnixStream::connect(s).await.map(Stream::Unix)
}
}
pub fn local_addr(&self) -> io::Result<FCGIAddr> {
match self {
Stream::Inet(s) => s.local_addr().map(FCGIAddr::Inet),
#[cfg(unix)]
Stream::Unix(s) => s.local_addr().map(|e| e.into())
}
}
pub fn peer_addr(&self) -> io::Result<FCGIAddr> {
match self {
Stream::Inet(s) => s.peer_addr().map(FCGIAddr::Inet),
#[cfg(unix)]
Stream::Unix(s) => s.peer_addr().map(|e| e.into())
}
}
}
impl AsyncRead for Stream {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context,
buf: &mut ReadBuf<'_>
) -> Poll<Result<(), Error>> {
match &mut *self {
Stream::Inet(s) => Pin::new(s).as_mut().poll_read(cx, buf),
#[cfg(unix)]
Stream::Unix(s) => Pin::new(s).as_mut().poll_read(cx, buf)
}
}
}
impl AsyncWrite for Stream {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context,
buf: &[u8]
) -> Poll<Result<usize, Error>> {
match &mut *self {
Stream::Inet(s) => Pin::new(s).as_mut().poll_write(cx, buf),
#[cfg(unix)]
Stream::Unix(s) => Pin::new(s).as_mut().poll_write(cx, buf)
}
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Error>> {
match &mut *self {
Stream::Inet(s) => Pin::new(s).as_mut().poll_flush(cx),
#[cfg(unix)]
Stream::Unix(s) => Pin::new(s).as_mut().poll_flush(cx)
}
}
fn poll_shutdown(
mut self: Pin<&mut Self>,
cx: &mut Context
) -> Poll<Result<(), Error>> {
match &mut *self {
Stream::Inet(s) => Pin::new(s).as_mut().poll_shutdown(cx),
#[cfg(unix)]
Stream::Unix(s) => Pin::new(s).as_mut().poll_shutdown(cx)
}
}
}
pub enum Listener {
Inet(TcpListener),
#[cfg(unix)]
Unix(UnixListener)
}
impl Listener {
pub async fn bind(s: &FCGIAddr) -> io::Result<Listener> {
match s {
FCGIAddr::Inet(s) => TcpListener::bind(s).await.map(Listener::Inet),
#[cfg(unix)]
FCGIAddr::Unix(s) => UnixListener::bind(s).map(Listener::Unix)
}
}
pub async fn accept(&mut self) -> io::Result<(Stream, FCGIAddr)> {
match &mut *self {
Listener::Inet(s) => s.accept().await.map(|(s,a)|(Stream::Inet(s),FCGIAddr::Inet(a))),
#[cfg(unix)]
Listener::Unix(s) => s.accept().await.map(|(s,a)|(Stream::Unix(s),FCGIAddr::from(a)))
}
}
}
#[cfg(unix)]
impl AsRawFd for Listener {
fn as_raw_fd(&self) -> RawFd {
match self {
Listener::Inet(s) => s.as_raw_fd(),
#[cfg(unix)]
Listener::Unix(s) => s.as_raw_fd()
}
}
}
#[cfg(unix)]
impl Drop for Listener {
fn drop(&mut self) {
if let Listener::Unix(l) = self {
if let Ok(a) = l.local_addr() {
if let Some(path) = a.as_pathname() {
std::fs::remove_file(path).unwrap();
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::runtime::Builder;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use std::net::SocketAddr;
use bytes::{BytesMut, Bytes};
use tokio::net::TcpListener;
#[cfg(unix)]
use tokio::net::UnixListener;
#[test]
fn tcp_connect() {
let rt = Builder::new_current_thread().enable_all().build().unwrap();
async fn mock_app(app_listener: TcpListener) {
let (mut app_socket, _) = app_listener.accept().await.unwrap();
let mut buf = BytesMut::with_capacity(4096);
app_socket.read_buf(&mut buf).await.unwrap();
app_socket.write_buf(&mut buf.freeze()).await.unwrap();
}
async fn con() {
let a: SocketAddr = "127.0.0.1:59003".parse().unwrap();
let app_listener = TcpListener::bind(a).await.unwrap();
tokio::spawn(mock_app(app_listener));
let a: FCGIAddr = "127.0.0.1:59003".parse().expect("tcp parse failed");
let mut s = Stream::connect(&a).await.expect("tcp connect failed");
let data = b"1234";
s.write_buf(&mut Bytes::from(&data[..])).await.expect("tcp write failed");
let mut buf = BytesMut::with_capacity(4096);
s.read_buf(&mut buf).await.expect("tcp read failed");
assert_eq!(buf, &data[..]);
}
rt.block_on(con());
}
#[cfg(unix)]
#[test]
fn unix_connect() {
let rt = Builder::new_current_thread().enable_all().build().unwrap();
async fn mock_app(app_listener: UnixListener) {
let (mut app_socket, _) = app_listener.accept().await.unwrap();
let mut buf = BytesMut::with_capacity(4096);
app_socket.read_buf(&mut buf).await.unwrap();
app_socket.write_buf(&mut buf.freeze()).await.unwrap();
}
async fn con() {
let a: &Path = Path::new("/tmp/afcgi.sock");
let app_listener = UnixListener::bind(a).unwrap();
tokio::spawn(mock_app(app_listener));
let a: FCGIAddr = "/tmp/afcgi.sock".parse().expect("unix parse failed");
println!("unix: {}", &a);
let mut s = Stream::connect(&a).await.expect("unix connect failed");
let data = b"1234";
s.write_buf(&mut Bytes::from(&data[..])).await.expect("unix write failed");
let mut buf = BytesMut::with_capacity(4096);
s.read_buf(&mut buf).await.expect("unix read failed");
assert_eq!(buf, &data[..]);
}
rt.block_on(con());
std::fs::remove_file("/tmp/afcgi.sock").unwrap();
}
}