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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
use crate::runtime::with_ambient_tokio_runtime;
use crate::sockets::{
ErrorCode, SocketAddrCheck, SocketAddrUse, SocketAddressFamily, WasiSocketsCtx,
get_receive_buffer_size, get_send_buffer_size, get_unicast_hop_limit, is_valid_address_family,
is_valid_remote_address, set_receive_buffer_size, set_send_buffer_size, set_unicast_hop_limit,
unspecified_addr,
};
use rustix::fd::AsFd;
use rustix::io::Errno;
use std::net::SocketAddr;
use std::sync::Arc;
use tracing::debug;
/// Theoretical maximum byte size of a UDP datagram, the real limit is lower,
/// but we do not account for e.g. the transport layer here for simplicity.
/// In practice, datagrams are typically less than 1500 bytes.
pub(crate) const MAX_DATAGRAM_SIZE: usize = u16::MAX as usize;
/// A host UDP socket, plus associated bookkeeping.
///
/// The inner state is wrapped in an Arc because the same underlying socket is
/// used for implementing the stream types.
pub struct UdpSocket {
socket: Arc<tokio::net::UdpSocket>,
family: SocketAddressFamily,
/// The checks to perform before doing any noteworthy syscall.
permissions: SocketAddrCheck,
/// Cached value of whether the socket is bound. This is cached to avoid
/// redundant syscalls in every `send` & `receive`.
is_bound: bool,
/// Cached value of the remote address. This is cached to avoid redundant
/// syscalls in every `send`.
remote_addr: Option<SocketAddr>,
}
impl UdpSocket {
/// Create a new socket in the given family.
pub(crate) async fn new(
cx: &WasiSocketsCtx,
family: SocketAddressFamily,
) -> Result<Self, ErrorCode> {
cx.allowed_network_uses.check_allowed_udp()?;
let socket = with_ambient_tokio_runtime(|| socket(family))?;
// Native UDP sockets are immediately writable after creation and
// existing guest code out in the wild depends on that. However, due to
// the way Tokio is structured internally, a newly created Tokio socket
// starts out as "not writable" and a background tokio thread updates
// this state asynchronously soon after. Some more info in this thread:
// https://github.com/bytecodealliance/wasmtime/issues/12612#issuecomment-3923714174
//
// To prevent exposing guests to this race condition, we wait for Tokio
// to finish its internal setup:
socket.writable().await?;
Ok(Self {
socket: Arc::new(socket),
is_bound: false,
remote_addr: None,
permissions: cx.socket_addr_check.clone(),
family,
})
}
pub(crate) fn is_bound(&mut self) -> bool {
// Once bound, a UDP socket can never become unbound again. So we can
// skip all work after a previous call has already determined the
// socket to be bound.
if !self.is_bound {
self.is_bound = self
.socket
.local_addr()
.is_ok_and(|addr| addr != unspecified_addr(self.family));
}
self.is_bound
}
pub(crate) fn local_address(&mut self) -> Result<SocketAddr, ErrorCode> {
if !self.is_bound() {
return Err(ErrorCode::InvalidState);
}
self.socket.local_addr().map_err(|e| e.into())
}
pub(crate) fn remote_address(&mut self) -> Result<SocketAddr, ErrorCode> {
self.remote_addr.ok_or(ErrorCode::InvalidState)
}
pub(crate) fn is_connected(&mut self) -> bool {
self.remote_addr.is_some()
}
pub(crate) async fn bind(&mut self, addr: SocketAddr) -> Result<(), ErrorCode> {
if self.is_bound() {
return Err(ErrorCode::InvalidState);
}
if !is_valid_address_family(addr.ip(), self.family) {
return Err(ErrorCode::InvalidArgument);
}
self.permissions.check(addr, SocketAddrUse::UdpBind).await?;
bind(&self.socket, addr)?;
Ok(())
}
pub(crate) async fn connect(&mut self, addr: SocketAddr) -> Result<(), ErrorCode> {
if !is_valid_address_family(addr.ip(), self.family) || !is_valid_remote_address(addr) {
return Err(ErrorCode::InvalidArgument);
}
// Perform all permission checks before doing any syscalls.
{
if !self.is_bound() {
// If not explicitly bound, the OS will implicitly bind the
// socket to an ephemeral port when connecting.
let implicit_bind_addr = unspecified_addr(self.family);
self.permissions
.check(implicit_bind_addr, SocketAddrUse::UdpBind)
.await?;
}
// On UDP sockets, "connecting" is just a local operation that sets the
// default remote address for future sends and receives. It does not
// actually do any I/O on its own. We'll allow the `connect` call
// if the address is permitted for sending or receiving.
if self
.permissions
.check(addr, SocketAddrUse::UdpSend)
.await
.is_err()
{
self.permissions
.check(addr, SocketAddrUse::UdpReceive)
.await?;
}
}
let result = connect(&self.socket, addr);
self.update_remote_address();
result.map_err(|e| e.into())
}
pub(crate) fn disconnect(&mut self) -> Result<(), ErrorCode> {
if !self.is_connected() {
return Err(ErrorCode::InvalidState);
}
// On Linux, disconnecting a UDP socket relinquishes its local port
// assignment in some cases. If the socket was bound to the wildcard
// address, its local address will then read `0.0.0.0:0` or `[::]:0`
// which is indistinguishable from an unbound socket. To ensure
// `is_bound()` will continue to return `true` after the disconnect, we
// manually settle the `is_bound` state here:
self.is_bound = true;
let result = disconnect(&self.socket);
self.update_remote_address();
result.map_err(|e| e.into())
}
/// Update our internal bookkeeping based on the actual state of the socket.
/// This should be called after any operation that may change the remote
/// address.
fn update_remote_address(&mut self) {
self.remote_addr = if let Ok(addr) = self.socket.peer_addr()
&& addr != unspecified_addr(self.family)
{
Some(addr)
} else {
None
}
}
pub(crate) fn send(
&mut self,
data: Vec<u8>,
addr: Option<SocketAddr>,
) -> impl Future<Output = Result<(), ErrorCode>> + Send + use<> {
let family = self.family;
let socket = self.socket.clone();
let permissions = self.permissions.clone();
let connected_addr = self.remote_address().ok();
let is_bound = self.is_bound();
async move {
if data.len() > MAX_DATAGRAM_SIZE {
return Err(ErrorCode::DatagramTooLarge);
}
let effective_addr = if let Some(addr) = addr {
if !is_valid_remote_address(addr) || !is_valid_address_family(addr.ip(), family) {
return Err(ErrorCode::InvalidArgument);
}
// If the socket is connected, the provided address must match the
// connected address.
if connected_addr.is_some() && connected_addr != Some(addr) {
return Err(ErrorCode::InvalidArgument);
}
addr
} else if let Some(connected_addr) = connected_addr {
connected_addr
} else {
return Err(ErrorCode::InvalidArgument);
};
// Perform all permission checks before doing any syscalls.
{
if !is_bound {
// If not explicitly bound, the OS will implicitly bind the
// socket to an ephemeral port when sending.
let implicit_bind_addr = unspecified_addr(family);
permissions
.check(implicit_bind_addr, SocketAddrUse::UdpBind)
.await?;
}
permissions
.check(effective_addr, SocketAddrUse::UdpSend)
.await?;
}
if connected_addr == Some(effective_addr) {
socket.send(&data).await?;
} else {
socket.send_to(&data, effective_addr).await?;
}
Ok(())
}
}
pub(crate) fn recv(
&mut self,
) -> impl Future<Output = Result<(Vec<u8>, SocketAddr), ErrorCode>> + Send + use<> {
let socket = self.socket.clone();
let permissions = self.permissions.clone();
let is_bound = self.is_bound();
async move {
if !is_bound {
return Err(ErrorCode::InvalidState);
}
loop {
let mut data = vec![0; MAX_DATAGRAM_SIZE];
let (len, addr) = socket.recv_from(&mut data).await?;
data.truncate(len);
match permissions.check(addr, SocketAddrUse::UdpReceive).await {
Ok(()) => return Ok((data, addr)),
Err(_) => {
// Not allowed. Drop the packet and poll again.
continue;
}
}
}
}
}
pub(crate) fn address_family(&self) -> SocketAddressFamily {
self.family
}
pub(crate) fn unicast_hop_limit(&self) -> Result<u8, ErrorCode> {
let n = get_unicast_hop_limit(&self.socket, self.family)?;
Ok(n)
}
pub(crate) fn set_unicast_hop_limit(&self, value: u8) -> Result<(), ErrorCode> {
set_unicast_hop_limit(&self.socket, self.family, value)?;
Ok(())
}
pub(crate) fn receive_buffer_size(&self) -> Result<u64, ErrorCode> {
let n = get_receive_buffer_size(&self.socket)?;
Ok(n)
}
pub(crate) fn set_receive_buffer_size(&self, value: u64) -> Result<(), ErrorCode> {
set_receive_buffer_size(&self.socket, value)?;
Ok(())
}
pub(crate) fn send_buffer_size(&self) -> Result<u64, ErrorCode> {
let n = get_send_buffer_size(&self.socket)?;
Ok(n)
}
pub(crate) fn set_send_buffer_size(&self, value: u64) -> Result<(), ErrorCode> {
set_send_buffer_size(&self.socket, value)?;
Ok(())
}
}
/// Creates a non-blocking/cloexec UDP socket.
fn socket(family: SocketAddressFamily) -> std::io::Result<tokio::net::UdpSocket> {
// Let the standard library be responsible for handling `WSAStartup`.
#[cfg(windows)]
static INIT: std::sync::Once = std::sync::Once::new();
#[cfg(windows)]
INIT.call_once(|| {
let _ = std::net::TcpStream::connect(std::net::SocketAddrV4::new(
std::net::Ipv4Addr::UNSPECIFIED,
0,
));
});
#[cfg(not(any(windows, target_vendor = "apple")))]
let flags = rustix::net::SocketFlags::CLOEXEC | rustix::net::SocketFlags::NONBLOCK;
#[cfg(any(windows, target_vendor = "apple"))]
let flags = rustix::net::SocketFlags::empty();
let socket = rustix::net::socket_with(
match family {
SocketAddressFamily::Ipv4 => rustix::net::AddressFamily::INET,
SocketAddressFamily::Ipv6 => rustix::net::AddressFamily::INET6,
},
rustix::net::SocketType::DGRAM,
flags,
None,
)?;
#[cfg(target_vendor = "apple")]
rustix::io::ioctl_fioclex(&socket)?;
#[cfg(any(windows, target_vendor = "apple"))]
rustix::io::ioctl_fionbio(&socket, true)?;
// From the WASI spec:
// > On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't
// > be configured otherwise.
if family == SocketAddressFamily::Ipv6 {
rustix::net::sockopt::set_ipv6_v6only(&socket, true)?;
}
Ok(tokio::net::UdpSocket::try_from(std::net::UdpSocket::from(
socket,
))?)
}
fn bind(sockfd: impl AsFd, addr: SocketAddr) -> Result<(), Errno> {
rustix::net::bind(sockfd, &addr).map_err(|err| match err {
// See: https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-bind#:~:text=WSAENOBUFS
// Windows returns WSAENOBUFS when the ephemeral ports have been exhausted.
#[cfg(windows)]
Errno::NOBUFS => Errno::ADDRINUSE,
// From https://pubs.opengroup.org/onlinepubs/9699919799/functions/bind.html:
// > [EAFNOSUPPORT] The specified address is not a valid address for the address family of the specified socket
//
// The most common reasons for this error should have already
// been handled by our own validation. This error mapping is here just
// in case there is an edge case we didn't catch.
Errno::AFNOSUPPORT => Errno::INVAL,
_ => err,
})
}
fn connect(sockfd: impl AsFd, addr: SocketAddr) -> Result<(), Errno> {
match rustix::net::connect(sockfd.as_fd(), &addr) {
// When connecting a UDP socket, the OS looks up the best route to the
// remote address and selects an appropriate outgoing interface.
// If the new destination routes through an interface different than the
// previously selected interface, most operating systems will
// automatically update the socket's local address to match that route.
//
// Linux however doesn't do that automatically and we manually
// dissolve the existing association and then connect again to the
// new destination.
#[cfg(target_os = "linux")]
Err(Errno::INVAL) => {
_ = disconnect(sockfd.as_fd());
return rustix::net::connect(sockfd.as_fd(), &addr);
}
// The most common reason for AFNOSUPPORT is an invalid address
// family. This should have already been handled by our own
// validation. This error mapping is here just in case there is an
// edge case we didn't catch.
Err(Errno::AFNOSUPPORT) => Err(Errno::INVAL),
// EINPROGRESS should only returned by non-blocking TCP sockets,
// not UDP sockets.
Err(Errno::INPROGRESS) => {
debug!("UDP connect returned EINPROGRESS, which should never happen");
Ok(())
}
r => r,
}
}
fn disconnect(sockfd: impl AsFd) -> Result<(), Errno> {
match rustix::net::connect_unspec(sockfd) {
// BSD platforms return an error even if the UDP socket was disconnected successfully.
//
// MacOS was kind enough to document this: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/connect.2.html
// > Datagram sockets may dissolve the association by connecting to an
// > invalid address, such as a null address or an address with the address
// > family set to AF_UNSPEC (the error EAFNOSUPPORT will be harmlessly
// > returned).
//
// ... except that this appears to be incomplete, because experiments
// have shown that MacOS actually returns EINVAL, depending on the
// address family of the socket.
#[cfg(target_os = "macos")]
Err(Errno::INVAL | Errno::AFNOSUPPORT) => Ok(()),
r => r,
}
}