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
use std::io::Result;
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
use futures::{future::poll_fn, ready, stream::Stream};
use std::mem;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::io::unix::AsyncFd;
use crate::stream::VsockStream;
use crate::VsockAddr;
#[derive(Debug)]
pub struct VsockListener {
inner: AsyncFd<vsock::VsockListener>,
}
impl VsockListener {
fn new(listener: vsock::VsockListener) -> Result<Self> {
listener.set_nonblocking(true)?;
Ok(Self {
inner: AsyncFd::new(listener)?,
})
}
pub fn bind(cid: u32, port: u32) -> Result<Self> {
let l = vsock::VsockListener::bind_with_cid_port(cid, port)?;
Self::new(l)
}
pub async fn accept(&mut self) -> Result<(VsockStream, VsockAddr)> {
poll_fn(|cx| self.poll_accept(cx)).await
}
pub fn poll_accept(&mut self, cx: &mut Context<'_>) -> Poll<Result<(VsockStream, VsockAddr)>> {
let (inner, addr) = ready!(self.poll_accept_std(cx))?;
let inner = VsockStream::new(inner)?;
Ok((inner, addr)).into()
}
pub fn poll_accept_std(
&mut self,
cx: &mut Context<'_>,
) -> Poll<Result<(vsock::VsockStream, VsockAddr)>> {
loop {
let mut guard = ready!(self.inner.poll_read_ready(cx))?;
match guard.try_io(|inner| inner.get_ref().accept()) {
Ok(Ok((inner, addr))) => return Ok((inner, addr)).into(),
Ok(Err(ref e)) if e.kind() == std::io::ErrorKind::Interrupted => continue,
Ok(Err(e)) => return Err(e).into(),
Err(_would_block) => continue,
}
}
}
pub fn local_addr(&self) -> Result<VsockAddr> {
self.inner.get_ref().local_addr()
}
pub fn incoming(self) -> Incoming {
Incoming::new(self)
}
}
impl FromRawFd for VsockListener {
unsafe fn from_raw_fd(fd: RawFd) -> Self {
Self::new(vsock::VsockListener::from_raw_fd(fd)).unwrap()
}
}
impl AsRawFd for VsockListener {
fn as_raw_fd(&self) -> RawFd {
self.inner.get_ref().as_raw_fd()
}
}
impl IntoRawFd for VsockListener {
fn into_raw_fd(self) -> RawFd {
let fd = self.inner.get_ref().as_raw_fd();
mem::forget(self);
fd
}
}
#[derive(Debug)]
pub struct Incoming {
inner: VsockListener,
}
impl Incoming {
fn new(listener: VsockListener) -> Incoming {
Incoming { inner: listener }
}
}
impl Stream for Incoming {
type Item = Result<VsockStream>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let (socket, _) = ready!(self.inner.poll_accept(cx))?;
Poll::Ready(Some(Ok(socket)))
}
}
impl AsRawFd for Incoming {
fn as_raw_fd(&self) -> RawFd {
self.inner.as_raw_fd()
}
}