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
//! UDP sockets.
use core::future::poll_fn;
use core::task::{Context, Poll};
use std::io;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, UdpSocket};
use super::addr::{ToSocketAddrs, resolve};
use super::none_worked;
use crate::io::source::write::Dest;
use crate::io::source::{Addr, Kind};
use crate::io::{Handle, Interest, ReadBuf, Ready};
impl Handle<UdpSocket> {
/// A socket bound to the first of the addresses `addr` names that it
/// can bind.
///
/// # Errors
///
/// The last address's error when none could be bound, or the lookup's.
pub async fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<Handle<UdpSocket>> {
let mut last = None;
for addr in resolve(&addr).await? {
match UdpSocket::bind(addr) {
Ok(socket) => return Handle::adopt(socket, Kind::Udp),
Err(err) => last = Some(err),
}
}
Err(none_worked(last))
}
/// A socket on an ephemeral local port, connected to the first of
/// `sock_addrs` it can connect to: `send` and `recv` then talk to that
/// peer only.
///
/// # Errors
///
/// The last address's error when none worked, or the lookup's.
pub async fn connect<A: ToSocketAddrs>(sock_addrs: A) -> io::Result<Handle<UdpSocket>> {
let mut last = None;
for addr in resolve(&sock_addrs).await? {
let local: IpAddr = if addr.is_ipv4() {
Ipv4Addr::UNSPECIFIED.into()
} else {
Ipv6Addr::UNSPECIFIED.into()
};
let attempt = UdpSocket::bind((local, 0)).and_then(|socket| {
socket.connect(addr)?;
Handle::adopt(socket, Kind::Udp)
});
match attempt {
Ok(socket) => return Ok(socket),
Err(err) => last = Some(err),
}
}
Err(none_worked(last))
}
/// Sends a datagram to the connected peer.
///
/// # Errors
///
/// As `send(2)`, or the error of an earlier datagram sent after its call
/// returned.
pub async fn send(&self, buf: &[u8]) -> io::Result<usize> {
poll_fn(|cx| self.source().poll_send(cx, buf, Dest::Connected)).await
}
/// Receives a datagram from the connected peer; what does not fit `buf`
/// is cut.
///
/// # Errors
///
/// As `recv(2)`.
pub async fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
self.receive(buf, false).await.map(|(n, _)| n)
}
/// Looks at the next datagram without taking it.
///
/// # Errors
///
/// As `recv(2)` with `MSG_PEEK`.
pub async fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
self.receive(buf, true).await.map(|(n, _)| n)
}
/// Sends a datagram to the first address `addr` names.
///
/// # Errors
///
/// As `sendto(2)`, the lookup's, or an earlier datagram's.
pub async fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], addr: A) -> io::Result<usize> {
let addr = resolve(&addr)
.await?
.next()
.ok_or_else(|| none_worked(None))?;
poll_fn(|cx| self.source().poll_send(cx, buf, Dest::Inet(addr))).await
}
/// Receives a datagram with its sender's address.
///
/// # Errors
///
/// As `recvfrom(2)`.
pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
self.receive(buf, false).await
}
/// Looks at the next datagram and its sender without taking it.
///
/// # Errors
///
/// As `recvfrom(2)` with `MSG_PEEK`.
pub async fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
self.receive(buf, true).await
}
/// Waits until a receive would end at once: a datagram came, or an
/// error (which the receive reports).
///
/// # Errors
///
/// When the socket cannot be watched.
pub async fn readable(&self) -> io::Result<()> {
self.ready(Interest::READABLE).await.map(drop)
}
/// Waits until a send would be taken at once.
///
/// # Errors
///
/// When the socket cannot be watched.
pub async fn writable(&self) -> io::Result<()> {
self.ready(Interest::WRITABLE).await.map(drop)
}
/// Waits until some of `interest` is ready, and says what is.
///
/// # Errors
///
/// When the socket cannot be watched.
pub async fn ready(&self, interest: Interest) -> io::Result<Ready> {
poll_fn(|cx| super::poll_ready(self.source(), cx, interest)).await
}
/// Polls until a receive would end at once.
///
/// # Errors
///
/// When the socket cannot be watched.
pub fn poll_recv_ready(
&self,
cx: &mut core::task::Context<'_>,
) -> core::task::Poll<io::Result<()>> {
self.source().poll_read_ready(cx).map(|r| r.map(drop))
}
/// Polls until a send would be taken at once.
///
/// # Errors
///
/// When the socket cannot be watched.
pub fn poll_send_ready(
&self,
cx: &mut core::task::Context<'_>,
) -> core::task::Poll<io::Result<()>> {
self.source().poll_write_ready(cx).map(|r| r.map(drop))
}
/// Sends a datagram to the connected peer without waiting.
///
/// # Errors
///
/// `WouldBlock` when a datagram is still queued, and as `send(2)`.
pub fn try_send(&self, buf: &[u8]) -> io::Result<usize> {
super::at_once(|cx| self.source().poll_send(cx, buf, Dest::Connected))
}
/// Receives a datagram from the connected peer without waiting; what
/// does not fit `buf` is cut.
///
/// # Errors
///
/// `WouldBlock` when none came yet, and as `recv(2)`.
pub fn try_recv(&self, buf: &mut [u8]) -> io::Result<usize> {
super::at_once(|cx| self.poll_receive(cx, buf, false)).map(|(n, _)| n)
}
/// Looks at the next datagram without taking it or waiting.
///
/// # Errors
///
/// `WouldBlock` when none came yet, and as `recv(2)` with `MSG_PEEK`.
pub fn try_peek(&self, buf: &mut [u8]) -> io::Result<usize> {
super::at_once(|cx| self.poll_receive(cx, buf, true)).map(|(n, _)| n)
}
/// Sends a datagram to `target` without waiting.
///
/// # Errors
///
/// `WouldBlock` when a datagram is still queued, and as `sendto(2)`.
pub fn try_send_to(&self, buf: &[u8], target: SocketAddr) -> io::Result<usize> {
super::at_once(|cx| self.source().poll_send(cx, buf, Dest::Inet(target)))
}
/// Receives a datagram and its sender's address without waiting.
///
/// # Errors
///
/// `WouldBlock` when none came yet, and as `recvfrom(2)`.
pub fn try_recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
super::at_once(|cx| self.poll_receive(cx, buf, false))
}
/// Looks at the next datagram and its sender without taking it or
/// waiting.
///
/// # Errors
///
/// `WouldBlock` when none came yet, and as `recvfrom(2)` with `MSG_PEEK`.
pub fn try_peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
super::at_once(|cx| self.poll_receive(cx, buf, true))
}
/// The sender of the next datagram, which stays to be received.
///
/// # Errors
///
/// As `recvfrom(2)` with `MSG_PEEK`.
pub async fn peek_sender(&self) -> io::Result<SocketAddr> {
poll_fn(|cx| self.poll_peek_sender(cx)).await
}
/// Polls for the sender of the next datagram, which stays to be
/// received. No byte of it is copied.
///
/// # Errors
///
/// As `recvfrom(2)` with `MSG_PEEK`.
pub fn poll_peek_sender(&self, cx: &mut Context<'_>) -> Poll<io::Result<SocketAddr>> {
self.poll_receive(cx, &mut [], true)
.map(|r| r.map(|(_, addr)| addr))
}
/// Receives a datagram from the connected peer into the unfilled part of
/// `buf`, which advances by its length; what does not fit is cut.
///
/// # Errors
///
/// As `recv(2)`.
pub async fn recv_buf(&self, buf: &mut ReadBuf<'_>) -> io::Result<usize> {
self.recv_buf_from(buf).await.map(|(n, _)| n)
}
/// Receives a datagram and its sender's address into the unfilled part
/// of `buf`, which advances by its length; what does not fit is cut.
///
/// # Errors
///
/// As `recvfrom(2)`.
pub async fn recv_buf_from(&self, buf: &mut ReadBuf<'_>) -> io::Result<(usize, SocketAddr)> {
// vertexia: the unfilled part is zeroed the first time a buffer offers
// it (a `ReadBuf` remembers what it initialized); the receive path
// takes initialized bytes. Uninitialized memory through the receive
// paths if a profile shows the zeroing.
let (n, addr) = self.receive(buf.initialize_unfilled(), false).await?;
buf.advance(n);
Ok((n, addr))
}
async fn receive(&self, buf: &mut [u8], peek: bool) -> io::Result<(usize, SocketAddr)> {
poll_fn(|cx| self.poll_receive(cx, buf, peek)).await
}
fn poll_receive(
&self,
cx: &mut Context<'_>,
buf: &mut [u8],
peek: bool,
) -> Poll<io::Result<(usize, SocketAddr)>> {
let (n, addr) = core::task::ready!(self.source().poll_receive(cx, buf, peek))?;
Poll::Ready(match addr {
Addr::Inet(addr) => Ok((n, addr)),
#[cfg(unix)]
Addr::Unix(_) => Err(io::Error::new(
io::ErrorKind::InvalidData,
"a UDP datagram came with no internet address",
)),
})
}
}