Skip to content

Commit 9f15c4d

Browse files
authored
Rollup merge of rust-lang#93158 - haraldh:wasi_sock_accept, r=dtolnay
wasi: implement `sock_accept` and enable networking With the addition of `sock_accept()` to snapshot1, simple networking via a passed `TcpListener` is possible. This PR implements the basics to make a simple server work. See also: * [wasmtime tracking issue](bytecodealliance/wasmtime#3730) * [wasmtime PR](bytecodealliance/wasmtime#3711) TODO: * [ ] Discussion of `SocketAddr` return value for `::accept()` ```rust Ok(( TcpStream::from_inner(unsafe { Socket::from_raw_fd(fd as _) }), // WASI has no concept of SocketAddr yet // return an unspecified IPv4Addr SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), 0), )) ```
2 parents db6ca25 + d2a1369 commit 9f15c4d

File tree

10 files changed

+131
-41
lines changed

10 files changed

+131
-41
lines changed

Cargo.lock

+9-3
Original file line numberDiff line numberDiff line change
@@ -1473,7 +1473,7 @@ checksum = "7abc8dd8451921606d809ba32e95b6111925cd2906060d2dcc29c070220503eb"
14731473
dependencies = [
14741474
"cfg-if 0.1.10",
14751475
"libc",
1476-
"wasi",
1476+
"wasi 0.9.0+wasi-snapshot-preview1",
14771477
]
14781478

14791479
[[package]]
@@ -1484,7 +1484,7 @@ checksum = "ee8025cf36f917e6a52cce185b7c7177689b838b7ec138364e50cc2277a56cf4"
14841484
dependencies = [
14851485
"cfg-if 0.1.10",
14861486
"libc",
1487-
"wasi",
1487+
"wasi 0.9.0+wasi-snapshot-preview1",
14881488
]
14891489

14901490
[[package]]
@@ -4854,7 +4854,7 @@ dependencies = [
48544854
"rustc-demangle",
48554855
"std_detect",
48564856
"unwind",
4857-
"wasi",
4857+
"wasi 0.11.0+wasi-snapshot-preview1",
48584858
]
48594859

48604860
[[package]]
@@ -5612,6 +5612,12 @@ name = "wasi"
56125612
version = "0.9.0+wasi-snapshot-preview1"
56135613
source = "registry+https://github.com/rust-lang/crates.io-index"
56145614
checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519"
5615+
5616+
[[package]]
5617+
name = "wasi"
5618+
version = "0.11.0+wasi-snapshot-preview1"
5619+
source = "registry+https://github.com/rust-lang/crates.io-index"
5620+
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
56155621
dependencies = [
56165622
"compiler_builtins",
56175623
"rustc-std-workspace-alloc",

library/std/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ fortanix-sgx-abi = { version = "0.3.2", features = ['rustc-dep-of-std'] }
4545
hermit-abi = { version = "0.1.19", features = ['rustc-dep-of-std'] }
4646

4747
[target.wasm32-wasi.dependencies]
48-
wasi = { version = "0.9.0", features = ['rustc-dep-of-std'], default-features = false }
48+
wasi = { version = "0.11.0", features = ['rustc-dep-of-std'], default-features = false }
4949

5050
[features]
5151
backtrace = [

library/std/src/os/wasi/fs.rs

+15
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,21 @@ impl FileExt for fs::File {
250250
}
251251

252252
fn advise(&self, offset: u64, len: u64, advice: u8) -> io::Result<()> {
253+
let advice = match advice {
254+
a if a == wasi::ADVICE_NORMAL.raw() => wasi::ADVICE_NORMAL,
255+
a if a == wasi::ADVICE_SEQUENTIAL.raw() => wasi::ADVICE_SEQUENTIAL,
256+
a if a == wasi::ADVICE_RANDOM.raw() => wasi::ADVICE_RANDOM,
257+
a if a == wasi::ADVICE_WILLNEED.raw() => wasi::ADVICE_WILLNEED,
258+
a if a == wasi::ADVICE_DONTNEED.raw() => wasi::ADVICE_DONTNEED,
259+
a if a == wasi::ADVICE_NOREUSE.raw() => wasi::ADVICE_NOREUSE,
260+
_ => {
261+
return Err(io::Error::new_const(
262+
io::ErrorKind::InvalidInput,
263+
&"invalid parameter 'advice'",
264+
));
265+
}
266+
};
267+
253268
self.as_inner().as_inner().advise(offset, len, advice)
254269
}
255270

library/std/src/os/wasi/net/mod.rs

+20
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,23 @@
11
//! WASI-specific networking functionality
22
33
#![unstable(feature = "wasi_ext", issue = "71213")]
4+
5+
use crate::io;
6+
use crate::net;
7+
use crate::sys_common::AsInner;
8+
9+
/// WASI-specific extensions to [`std::net::TcpListener`].
10+
///
11+
/// [`std::net::TcpListener`]: crate::net::TcpListener
12+
pub trait TcpListenerExt {
13+
/// Accept a socket.
14+
///
15+
/// This corresponds to the `sock_accept` syscall.
16+
fn sock_accept(&self, flags: u16) -> io::Result<u32>;
17+
}
18+
19+
impl TcpListenerExt for net::TcpListener {
20+
fn sock_accept(&self, flags: u16) -> io::Result<u32> {
21+
self.as_inner().as_inner().as_inner().sock_accept(flags)
22+
}
23+
}

library/std/src/sys/wasi/fd.rs

+4
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,10 @@ impl WasiFd {
228228
unsafe { wasi::path_remove_directory(self.as_raw_fd() as wasi::Fd, path).map_err(err2io) }
229229
}
230230

231+
pub fn sock_accept(&self, flags: wasi::Fdflags) -> io::Result<wasi::Fd> {
232+
unsafe { wasi::sock_accept(self.as_raw_fd() as wasi::Fd, flags).map_err(err2io) }
233+
}
234+
231235
pub fn sock_recv(
232236
&self,
233237
ri_data: &mut [IoSliceMut<'_>],

library/std/src/sys/wasi/mod.rs

+22-19
Original file line numberDiff line numberDiff line change
@@ -61,23 +61,26 @@ pub fn decode_error_kind(errno: i32) -> std_io::ErrorKind {
6161
if errno > u16::MAX as i32 || errno < 0 {
6262
return Uncategorized;
6363
}
64-
match errno as u16 {
65-
wasi::ERRNO_CONNREFUSED => ConnectionRefused,
66-
wasi::ERRNO_CONNRESET => ConnectionReset,
67-
wasi::ERRNO_PERM | wasi::ERRNO_ACCES => PermissionDenied,
68-
wasi::ERRNO_PIPE => BrokenPipe,
69-
wasi::ERRNO_NOTCONN => NotConnected,
70-
wasi::ERRNO_CONNABORTED => ConnectionAborted,
71-
wasi::ERRNO_ADDRNOTAVAIL => AddrNotAvailable,
72-
wasi::ERRNO_ADDRINUSE => AddrInUse,
73-
wasi::ERRNO_NOENT => NotFound,
74-
wasi::ERRNO_INTR => Interrupted,
75-
wasi::ERRNO_INVAL => InvalidInput,
76-
wasi::ERRNO_TIMEDOUT => TimedOut,
77-
wasi::ERRNO_EXIST => AlreadyExists,
78-
wasi::ERRNO_AGAIN => WouldBlock,
79-
wasi::ERRNO_NOSYS => Unsupported,
80-
wasi::ERRNO_NOMEM => OutOfMemory,
64+
65+
match errno {
66+
e if e == wasi::ERRNO_CONNREFUSED.raw().into() => ConnectionRefused,
67+
e if e == wasi::ERRNO_CONNRESET.raw().into() => ConnectionReset,
68+
e if e == wasi::ERRNO_PERM.raw().into() || e == wasi::ERRNO_ACCES.raw().into() => {
69+
PermissionDenied
70+
}
71+
e if e == wasi::ERRNO_PIPE.raw().into() => BrokenPipe,
72+
e if e == wasi::ERRNO_NOTCONN.raw().into() => NotConnected,
73+
e if e == wasi::ERRNO_CONNABORTED.raw().into() => ConnectionAborted,
74+
e if e == wasi::ERRNO_ADDRNOTAVAIL.raw().into() => AddrNotAvailable,
75+
e if e == wasi::ERRNO_ADDRINUSE.raw().into() => AddrInUse,
76+
e if e == wasi::ERRNO_NOENT.raw().into() => NotFound,
77+
e if e == wasi::ERRNO_INTR.raw().into() => Interrupted,
78+
e if e == wasi::ERRNO_INVAL.raw().into() => InvalidInput,
79+
e if e == wasi::ERRNO_TIMEDOUT.raw().into() => TimedOut,
80+
e if e == wasi::ERRNO_EXIST.raw().into() => AlreadyExists,
81+
e if e == wasi::ERRNO_AGAIN.raw().into() => WouldBlock,
82+
e if e == wasi::ERRNO_NOSYS.raw().into() => Unsupported,
83+
e if e == wasi::ERRNO_NOMEM.raw().into() => OutOfMemory,
8184
_ => Uncategorized,
8285
}
8386
}
@@ -96,6 +99,6 @@ pub fn hashmap_random_keys() -> (u64, u64) {
9699
return ret;
97100
}
98101

99-
fn err2io(err: wasi::Error) -> std_io::Error {
100-
std_io::Error::from_raw_os_error(err.raw_error().into())
102+
fn err2io(err: wasi::Errno) -> std_io::Error {
103+
std_io::Error::from_raw_os_error(err.raw().into())
101104
}

library/std/src/sys/wasi/net.rs

+53-13
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#![deny(unsafe_op_in_unsafe_fn)]
22

3+
use super::err2io;
34
use super::fd::WasiFd;
45
use crate::convert::TryFrom;
56
use crate::fmt;
@@ -87,24 +88,24 @@ impl TcpStream {
8788
unsupported()
8889
}
8990

90-
pub fn read(&self, _: &mut [u8]) -> io::Result<usize> {
91-
unsupported()
91+
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
92+
self.read_vectored(&mut [IoSliceMut::new(buf)])
9293
}
9394

94-
pub fn read_vectored(&self, _: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
95-
unsupported()
95+
pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
96+
self.socket().as_inner().read(bufs)
9697
}
9798

9899
pub fn is_read_vectored(&self) -> bool {
99100
true
100101
}
101102

102-
pub fn write(&self, _: &[u8]) -> io::Result<usize> {
103-
unsupported()
103+
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
104+
self.write_vectored(&[IoSlice::new(buf)])
104105
}
105106

106-
pub fn write_vectored(&self, _: &[IoSlice<'_>]) -> io::Result<usize> {
107-
unsupported()
107+
pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
108+
self.socket().as_inner().write(bufs)
108109
}
109110

110111
pub fn is_write_vectored(&self) -> bool {
@@ -155,8 +156,23 @@ impl TcpStream {
155156
unsupported()
156157
}
157158

158-
pub fn set_nonblocking(&self, _: bool) -> io::Result<()> {
159-
unsupported()
159+
pub fn set_nonblocking(&self, state: bool) -> io::Result<()> {
160+
let fdstat = unsafe {
161+
wasi::fd_fdstat_get(self.socket().as_inner().as_raw_fd() as wasi::Fd).map_err(err2io)?
162+
};
163+
164+
let mut flags = fdstat.fs_flags;
165+
166+
if state {
167+
flags |= wasi::FDFLAGS_NONBLOCK;
168+
} else {
169+
flags &= !wasi::FDFLAGS_NONBLOCK;
170+
}
171+
172+
unsafe {
173+
wasi::fd_fdstat_set_flags(self.socket().as_inner().as_raw_fd() as wasi::Fd, flags)
174+
.map_err(err2io)
175+
}
160176
}
161177

162178
pub fn socket(&self) -> &Socket {
@@ -194,7 +210,16 @@ impl TcpListener {
194210
}
195211

196212
pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
197-
unsupported()
213+
let fd = unsafe {
214+
wasi::sock_accept(self.as_inner().as_inner().as_raw_fd() as _, 0).map_err(err2io)?
215+
};
216+
217+
Ok((
218+
TcpStream::from_inner(unsafe { Socket::from_raw_fd(fd as _) }),
219+
// WASI has no concept of SocketAddr yet
220+
// return an unspecified IPv4Addr
221+
SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), 0),
222+
))
198223
}
199224

200225
pub fn duplicate(&self) -> io::Result<TcpListener> {
@@ -221,8 +246,23 @@ impl TcpListener {
221246
unsupported()
222247
}
223248

224-
pub fn set_nonblocking(&self, _: bool) -> io::Result<()> {
225-
unsupported()
249+
pub fn set_nonblocking(&self, state: bool) -> io::Result<()> {
250+
let fdstat = unsafe {
251+
wasi::fd_fdstat_get(self.socket().as_inner().as_raw_fd() as wasi::Fd).map_err(err2io)?
252+
};
253+
254+
let mut flags = fdstat.fs_flags;
255+
256+
if state {
257+
flags |= wasi::FDFLAGS_NONBLOCK;
258+
} else {
259+
flags &= !wasi::FDFLAGS_NONBLOCK;
260+
}
261+
262+
unsafe {
263+
wasi::fd_fdstat_set_flags(self.socket().as_inner().as_raw_fd() as wasi::Fd, flags)
264+
.map_err(err2io)
265+
}
226266
}
227267

228268
pub fn socket(&self) -> &Socket {

library/std/src/sys/wasi/stdio.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ impl io::Write for Stderr {
104104
pub const STDIN_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE;
105105

106106
pub fn is_ebadf(err: &io::Error) -> bool {
107-
err.raw_os_error() == Some(wasi::ERRNO_BADF.into())
107+
err.raw_os_error() == Some(wasi::ERRNO_BADF.raw().into())
108108
}
109109

110110
pub fn panic_output() -> Option<impl io::Write> {

library/std/src/sys/wasi/thread.rs

+5-3
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,7 @@ impl Thread {
4141

4242
let in_ = wasi::Subscription {
4343
userdata: USERDATA,
44-
r#type: wasi::EVENTTYPE_CLOCK,
45-
u: wasi::SubscriptionU { clock },
44+
u: wasi::SubscriptionU { tag: 0, u: wasi::SubscriptionUU { clock } },
4645
};
4746
unsafe {
4847
let mut event: wasi::Event = mem::zeroed();
@@ -51,7 +50,10 @@ impl Thread {
5150
(
5251
Ok(1),
5352
wasi::Event {
54-
userdata: USERDATA, error: 0, r#type: wasi::EVENTTYPE_CLOCK, ..
53+
userdata: USERDATA,
54+
error: wasi::ERRNO_SUCCESS,
55+
type_: wasi::EVENTTYPE_CLOCK,
56+
..
5557
},
5658
) => {}
5759
_ => panic!("thread::sleep(): unexpected result of poll_oneoff"),

library/std/src/sys/wasi/time.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pub struct SystemTime(Duration);
1010

1111
pub const UNIX_EPOCH: SystemTime = SystemTime(Duration::from_secs(0));
1212

13-
fn current_time(clock: u32) -> Duration {
13+
fn current_time(clock: wasi::Clockid) -> Duration {
1414
let ts = unsafe {
1515
wasi::clock_time_get(
1616
clock, 1, // precision... seems ignored though?

0 commit comments

Comments
 (0)