1use crate::wasm_byte_vec_t;
4use bytes::Bytes;
5use std::ffi::{CStr, c_char, c_void};
6use std::fs::File;
7use std::path::Path;
8use std::pin::Pin;
9use std::task::{Context, Poll};
10use tokio::io::{self, AsyncWrite};
11use wasmtime::Result;
12use wasmtime_wasi::WasiCtxBuilder;
13use wasmtime_wasi::p1::WasiP1Ctx;
14use wasmtime_wasi_io::streams::StreamError;
15
16unsafe fn cstr_to_path<'a>(path: *const c_char) -> Option<&'a Path> {
17 CStr::from_ptr(path).to_str().map(Path::new).ok()
18}
19
20unsafe fn cstr_to_str<'a>(s: *const c_char) -> Option<&'a str> {
21 CStr::from_ptr(s).to_str().ok()
22}
23
24unsafe fn open_file(path: *const c_char) -> Option<File> {
25 File::open(cstr_to_path(path)?).ok()
26}
27
28unsafe fn create_file(path: *const c_char) -> Option<File> {
29 File::create(cstr_to_path(path)?).ok()
30}
31
32#[repr(C)]
33pub struct wasi_config_t {
34 builder: WasiCtxBuilder,
35}
36
37wasmtime_c_api_macros::declare_own!(wasi_config_t);
38
39impl wasi_config_t {
40 pub fn into_wasi_ctx(mut self) -> Result<WasiP1Ctx> {
41 Ok(self.builder.build_p1())
42 }
43}
44
45#[unsafe(no_mangle)]
46pub extern "C" fn wasi_config_new() -> Box<wasi_config_t> {
47 Box::new(wasi_config_t {
48 builder: WasiCtxBuilder::new(),
49 })
50}
51
52#[unsafe(no_mangle)]
53pub unsafe extern "C" fn wasi_config_inherit_network(config: &mut wasi_config_t) {
54 config.builder.inherit_network();
55}
56
57#[unsafe(no_mangle)]
58pub unsafe extern "C" fn wasi_config_allow_ip_name_lookup(
59 config: &mut wasi_config_t,
60 enable: bool,
61) {
62 config.builder.allow_ip_name_lookup(enable);
63}
64
65#[unsafe(no_mangle)]
66pub unsafe extern "C" fn wasi_config_set_argv(
67 config: &mut wasi_config_t,
68 argc: usize,
69 argv: *const *const c_char,
70) -> bool {
71 for arg in crate::slice_from_raw_parts(argv, argc) {
72 let arg = match CStr::from_ptr(*arg).to_str() {
73 Ok(s) => s,
74 Err(_) => return false,
75 };
76 config.builder.arg(arg);
77 }
78 true
79}
80
81#[unsafe(no_mangle)]
82pub extern "C" fn wasi_config_inherit_argv(config: &mut wasi_config_t) {
83 config.builder.inherit_args();
84}
85
86#[unsafe(no_mangle)]
87pub unsafe extern "C" fn wasi_config_set_env(
88 config: &mut wasi_config_t,
89 envc: usize,
90 names: *const *const c_char,
91 values: *const *const c_char,
92) -> bool {
93 let names = crate::slice_from_raw_parts(names, envc);
94 let values = crate::slice_from_raw_parts(values, envc);
95
96 for (k, v) in names.iter().zip(values) {
97 let k = match cstr_to_str(*k) {
98 Some(s) => s,
99 None => return false,
100 };
101 let v = match cstr_to_str(*v) {
102 Some(s) => s,
103 None => return false,
104 };
105 config.builder.env(k, v);
106 }
107 true
108}
109
110#[unsafe(no_mangle)]
111pub extern "C" fn wasi_config_inherit_env(config: &mut wasi_config_t) {
112 config.builder.inherit_env();
113}
114
115#[unsafe(no_mangle)]
116pub unsafe extern "C" fn wasi_config_set_stdin_file(
117 config: &mut wasi_config_t,
118 path: *const c_char,
119) -> bool {
120 let file = match open_file(path) {
121 Some(f) => f,
122 None => return false,
123 };
124
125 let file = tokio::fs::File::from_std(file);
126 let stdin_stream = wasmtime_wasi::cli::AsyncStdinStream::new(file);
127 config.builder.stdin(stdin_stream);
128
129 true
130}
131
132#[unsafe(no_mangle)]
133pub unsafe extern "C" fn wasi_config_set_stdin_bytes(
134 config: &mut wasi_config_t,
135 binary: &mut wasm_byte_vec_t,
136) {
137 let binary = binary.take();
138 let binary = wasmtime_wasi::p2::pipe::MemoryInputPipe::new(binary);
139 config.builder.stdin(binary);
140}
141
142#[unsafe(no_mangle)]
143pub extern "C" fn wasi_config_inherit_stdin(config: &mut wasi_config_t) {
144 config.builder.inherit_stdin();
145}
146
147#[unsafe(no_mangle)]
148pub unsafe extern "C" fn wasi_config_set_stdout_file(
149 config: &mut wasi_config_t,
150 path: *const c_char,
151) -> bool {
152 let file = match create_file(path) {
153 Some(f) => f,
154 None => return false,
155 };
156
157 config
158 .builder
159 .stdout(wasmtime_wasi::cli::OutputFile::new(file));
160
161 true
162}
163
164#[unsafe(no_mangle)]
165pub extern "C" fn wasi_config_inherit_stdout(config: &mut wasi_config_t) {
166 config.builder.inherit_stdout();
167}
168
169struct CustomOutputStreamInner {
170 foreign_data: crate::ForeignData,
171 callback: extern "C" fn(*mut c_void, *const u8, usize) -> isize,
172}
173
174impl CustomOutputStreamInner {
175 pub fn raw_write(&self, buf: &[u8]) -> io::Result<usize> {
176 let wrote = (self.callback)(self.foreign_data.data, buf.as_ptr(), buf.len());
177
178 if wrote >= 0 {
179 Ok(wrote as _)
180 } else {
181 Err(io::Error::from_raw_os_error(wrote.abs() as _))
182 }
183 }
184}
185
186#[derive(Clone)]
187pub struct CustomOutputStream {
188 inner: std::sync::Arc<CustomOutputStreamInner>,
189}
190
191impl CustomOutputStream {
192 pub fn new(
193 foreign_data: crate::ForeignData,
194 callback: extern "C" fn(*mut c_void, *const u8, usize) -> isize,
195 ) -> Self {
196 Self {
197 inner: std::sync::Arc::new(CustomOutputStreamInner {
198 foreign_data,
199 callback,
200 }),
201 }
202 }
203}
204
205const WRITE_BUDGET: usize = 64 * 1024;
207
208#[async_trait::async_trait]
209impl wasmtime_wasi::p2::Pollable for CustomOutputStream {
210 async fn ready(&mut self) {}
211}
212
213#[async_trait::async_trait]
214impl wasmtime_wasi::p2::OutputStream for CustomOutputStream {
215 fn write(&mut self, bytes: Bytes) -> Result<(), StreamError> {
216 if bytes.len() > WRITE_BUDGET {
217 return Err(StreamError::Trap(wasmtime::format_err!(
218 "write exceeded budget"
219 )));
220 }
221 let wrote = self
222 .inner
223 .raw_write(&bytes)
224 .map_err(|e| StreamError::LastOperationFailed(e.into()))?;
225
226 if wrote != bytes.len() {
227 return Err(StreamError::LastOperationFailed(wasmtime::format_err!(
228 "Partial writes in wasip2 implementation are not allowed"
229 )));
230 }
231
232 Ok(())
233 }
234 fn flush(&mut self) -> Result<(), StreamError> {
235 Ok(())
236 }
237 fn check_write(&mut self) -> Result<usize, StreamError> {
238 Ok(WRITE_BUDGET)
239 }
240}
241
242impl AsyncWrite for CustomOutputStream {
243 fn poll_write(
244 self: Pin<&mut Self>,
245 _cx: &mut Context<'_>,
246 buf: &[u8],
247 ) -> Poll<io::Result<usize>> {
248 Poll::Ready(self.inner.raw_write(buf))
249 }
250 fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
251 Poll::Ready(Ok(()))
252 }
253 fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
254 Poll::Ready(Ok(()))
255 }
256}
257
258impl wasmtime_wasi::cli::IsTerminal for CustomOutputStream {
259 fn is_terminal(&self) -> bool {
260 false
261 }
262}
263
264impl wasmtime_wasi::cli::StdoutStream for CustomOutputStream {
265 fn async_stream(&self) -> Box<dyn AsyncWrite + Send + Sync> {
266 Box::new(self.clone())
267 }
268}
269
270#[unsafe(no_mangle)]
271pub extern "C" fn wasi_config_set_stdout_custom(
272 config: &mut wasi_config_t,
273 callback: extern "C" fn(*mut c_void, *const u8, usize) -> isize,
274 data: *mut c_void,
275 finalizer: Option<extern "C" fn(*mut c_void)>,
276) {
277 config.builder.stdout(CustomOutputStream::new(
278 crate::ForeignData { data, finalizer },
279 callback,
280 ));
281}
282
283#[unsafe(no_mangle)]
284pub unsafe extern "C" fn wasi_config_set_stderr_file(
285 config: &mut wasi_config_t,
286 path: *const c_char,
287) -> bool {
288 let file = match create_file(path) {
289 Some(f) => f,
290 None => return false,
291 };
292
293 config
294 .builder
295 .stderr(wasmtime_wasi::cli::OutputFile::new(file));
296
297 true
298}
299
300#[unsafe(no_mangle)]
301pub extern "C" fn wasi_config_inherit_stderr(config: &mut wasi_config_t) {
302 config.builder.inherit_stderr();
303}
304
305#[unsafe(no_mangle)]
306pub extern "C" fn wasi_config_set_stderr_custom(
307 config: &mut wasi_config_t,
308 callback: extern "C" fn(*mut c_void, *const u8, usize) -> isize,
309 data: *mut c_void,
310 finalizer: Option<extern "C" fn(*mut c_void)>,
311) {
312 config.builder.stderr(CustomOutputStream::new(
313 crate::ForeignData { data, finalizer },
314 callback,
315 ));
316}
317
318#[unsafe(no_mangle)]
319pub unsafe extern "C" fn wasi_config_preopen_dir(
320 config: &mut wasi_config_t,
321 path: *const c_char,
322 guest_path: *const c_char,
323 fs_mutable: bool,
324) -> bool {
325 let guest_path = match cstr_to_str(guest_path) {
326 Some(p) => p,
327 None => return false,
328 };
329
330 let host_path = match cstr_to_path(path) {
331 Some(p) => p,
332 None => return false,
333 };
334
335 let fs_perms = if fs_mutable {
336 wasmtime_wasi::FsPerms::ReadWrite
337 } else {
338 wasmtime_wasi::FsPerms::ReadOnly
339 };
340
341 config
342 .builder
343 .preopened_dir(host_path, guest_path, fs_perms)
344 .is_ok()
345}