diff --git a/CHANGELOG.md b/CHANGELOG.md index cdc493be..4a4d0b51 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), - Method `wit.(*Package).WIT()` now interprets the non-empty string `name` argument as signal to render in single-file, multi-package braced form. - `wit.(*Resolve).WIT()` and `wit.(*Package).WIT()` now accept a `*wit.World` as context to filter serialized WIT to a specific world. +- Packages are now sorted topologically by dependency in generated WIT files. For example, `wasi:cli` would be followed by its dependencies like `wasi:io`, `wasi:filesystem`, or `wasi:random`. ## [v0.2.4] — 2024-10-06 @@ -165,7 +166,7 @@ Initial version, supporting [TinyGo](https://tinygo.org/) + [WASI](https://wasi. - Support for mainline [Go](https://go.dev/). [Unreleased]: -[v0.2.3]: +[v0.2.4]: [v0.2.3]: [v0.2.2]: [v0.2.1]: diff --git a/cmd/wit-bindgen-go/main.go b/cmd/wit-bindgen-go/main.go index d1cb1ffc..ce4828af 100644 --- a/cmd/wit-bindgen-go/main.go +++ b/cmd/wit-bindgen-go/main.go @@ -58,7 +58,7 @@ func main() { err := cmd.Run(context.Background(), os.Args) if err != nil { - fmt.Printf("error: %v\n", err) + fmt.Fprintf(os.Stderr, "error: %v\n", err) os.Exit(1) } } diff --git a/internal/witcli/witcli.go b/internal/witcli/witcli.go index 9e2f8807..093d0322 100644 --- a/internal/witcli/witcli.go +++ b/internal/witcli/witcli.go @@ -26,7 +26,7 @@ func LoadWIT(ctx context.Context, forceWIT bool, path string) (*wit.Resolve, err return wit.ParseWIT(bytes) } } - if forceWIT || !strings.HasSuffix(path, ".json") { + if forceWIT || (path != "" && path != "-" && !strings.HasSuffix(path, ".json")) { return wit.LoadWIT(path) } return wit.LoadJSON(path) diff --git a/testdata/wasi/cli-command.wit b/testdata/wasi/cli-command.wit new file mode 100644 index 00000000..7b2af2ae --- /dev/null +++ b/testdata/wasi/cli-command.wit @@ -0,0 +1,2099 @@ +package wasi:cli@0.2.0; + +interface environment { + /// Get the POSIX-style environment variables. + /// + /// Each environment variable is provided as a pair of string variable names + /// and string value. + /// + /// Morally, these are a value import, but until value imports are available + /// in the component model, this import function should return the same + /// values each time it is called. + get-environment: func() -> list>; + + /// Get the POSIX-style arguments to the program. + get-arguments: func() -> list; + + /// Return a path that programs should use as their initial current working + /// directory, interpreting `.` as shorthand for this. + initial-cwd: func() -> option; +} + +interface exit { + /// Exit the current instance and any linked instances. + exit: func(status: result); +} + +interface run { + /// Run the program. + run: func() -> result; +} + +interface stdin { + use wasi:io/streams@0.2.0.{input-stream}; + get-stdin: func() -> input-stream; +} + +interface stdout { + use wasi:io/streams@0.2.0.{output-stream}; + get-stdout: func() -> output-stream; +} + +interface stderr { + use wasi:io/streams@0.2.0.{output-stream}; + get-stderr: func() -> output-stream; +} + +/// Terminal input. +/// +/// In the future, this may include functions for disabling echoing, +/// disabling input buffering so that keyboard events are sent through +/// immediately, querying supported features, and so on. +interface terminal-input { + /// The input side of a terminal. + resource terminal-input; +} + +/// Terminal output. +/// +/// In the future, this may include functions for querying the terminal +/// size, being notified of terminal size changes, querying supported +/// features, and so on. +interface terminal-output { + /// The output side of a terminal. + resource terminal-output; +} + +/// An interface providing an optional `terminal-input` for stdin as a +/// link-time authority. +interface terminal-stdin { + use terminal-input.{terminal-input}; + + /// If stdin is connected to a terminal, return a `terminal-input` handle + /// allowing further interaction with it. + get-terminal-stdin: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stdout as a +/// link-time authority. +interface terminal-stdout { + use terminal-output.{terminal-output}; + + /// If stdout is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + get-terminal-stdout: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stderr as a +/// link-time authority. +interface terminal-stderr { + use terminal-output.{terminal-output}; + + /// If stderr is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + get-terminal-stderr: func() -> option; +} + +world command { + import environment; + import exit; + import wasi:io/error@0.2.0; + import wasi:io/poll@0.2.0; + import wasi:io/streams@0.2.0; + import stdin; + import stdout; + import stderr; + import terminal-input; + import terminal-output; + import terminal-stdin; + import terminal-stdout; + import terminal-stderr; + import wasi:clocks/monotonic-clock@0.2.0; + import wasi:clocks/wall-clock@0.2.0; + import wasi:filesystem/types@0.2.0; + import wasi:filesystem/preopens@0.2.0; + import wasi:sockets/network@0.2.0; + import wasi:sockets/instance-network@0.2.0; + import wasi:sockets/udp@0.2.0; + import wasi:sockets/udp-create-socket@0.2.0; + import wasi:sockets/tcp@0.2.0; + import wasi:sockets/tcp-create-socket@0.2.0; + import wasi:sockets/ip-name-lookup@0.2.0; + import wasi:random/random@0.2.0; + import wasi:random/insecure@0.2.0; + import wasi:random/insecure-seed@0.2.0; + export run; +} + +package wasi:filesystem@0.2.0 { + /// WASI filesystem is a filesystem API primarily intended to let users run WASI + /// programs that access their files on their existing filesystems, without + /// significant overhead. + /// + /// It is intended to be roughly portable between Unix-family platforms and + /// Windows, though it does not hide many of the major differences. + /// + /// Paths are passed as interface-type `string`s, meaning they must consist of + /// a sequence of Unicode Scalar Values (USVs). Some filesystems may contain + /// paths which are not accessible by this API. + /// + /// The directory separator in WASI is always the forward-slash (`/`). + /// + /// All paths in WASI are relative paths, and are interpreted relative to a + /// `descriptor` referring to a base directory. If a `path` argument to any WASI + /// function starts with `/`, or if any step of resolving a `path`, including + /// `..` and symbolic link steps, reaches a directory outside of the base + /// directory, or reaches a symlink to an absolute or rooted path in the + /// underlying filesystem, the function fails with `error-code::not-permitted`. + /// + /// For more information about WASI path resolution and sandboxing, see + /// [WASI filesystem path resolution]. + /// + /// [WASI filesystem path resolution]: https://github.com/WebAssembly/wasi-filesystem/blob/main/path-resolution.md + interface types { + use wasi:io/streams@0.2.0.{input-stream}; + use wasi:io/streams@0.2.0.{output-stream}; + use wasi:io/streams@0.2.0.{error}; + use wasi:clocks/wall-clock@0.2.0.{datetime}; + + /// File size or length of a region within a file. + type filesize = u64; + + /// The type of a filesystem object referenced by a descriptor. + /// + /// Note: This was called `filetype` in earlier versions of WASI. + enum descriptor-type { + /// The type of the descriptor or file is unknown or is different from + /// any of the other types specified. + unknown, + /// The descriptor refers to a block device inode. + block-device, + /// The descriptor refers to a character device inode. + character-device, + /// The descriptor refers to a directory inode. + directory, + /// The descriptor refers to a named pipe. + fifo, + /// The file refers to a symbolic link inode. + symbolic-link, + /// The descriptor refers to a regular file inode. + regular-file, + /// The descriptor refers to a socket. + socket + } + + /// Descriptor flags. + /// + /// Note: This was called `fdflags` in earlier versions of WASI. + flags descriptor-flags { + /// Read mode: Data can be read. + read, + /// Write mode: Data can be written to. + write, + /// Request that writes be performed according to synchronized I/O file + /// integrity completion. The data stored in the file and the file's + /// metadata are synchronized. This is similar to `O_SYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + file-integrity-sync, + /// Request that writes be performed according to synchronized I/O data + /// integrity completion. Only the data stored in the file is + /// synchronized. This is similar to `O_DSYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + data-integrity-sync, + /// Requests that reads be performed at the same level of integrety + /// requested for writes. This is similar to `O_RSYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + requested-write-sync, + /// Mutating directories mode: Directory contents may be mutated. + /// + /// When this flag is unset on a descriptor, operations using the + /// descriptor which would create, rename, delete, modify the data or + /// metadata of filesystem objects, or obtain another handle which + /// would permit any of those, shall fail with `error-code::read-only` if + /// they would otherwise succeed. + /// + /// This may only be set on directories. + mutate-directory, + } + + /// Flags determining the method of how paths are resolved. + flags path-flags { + /// As long as the resolved path corresponds to a symbolic link, it is + /// expanded. + symlink-follow, + } + + /// Open flags used by `open-at`. + flags open-flags { + /// Create file if it does not exist, similar to `O_CREAT` in POSIX. + create, + /// Fail if not a directory, similar to `O_DIRECTORY` in POSIX. + directory, + /// Fail if file already exists, similar to `O_EXCL` in POSIX. + exclusive, + /// Truncate file to size 0, similar to `O_TRUNC` in POSIX. + truncate, + } + + /// Number of hard links to an inode. + type link-count = u64; + + /// File attributes. + /// + /// Note: This was called `filestat` in earlier versions of WASI. + record descriptor-stat { + /// File type. + %type: descriptor-type, + /// Number of hard links to the file. + link-count: link-count, + /// For regular files, the file size in bytes. For symbolic links, the + /// length in bytes of the pathname contained in the symbolic link. + size: filesize, + /// Last data access timestamp. + /// + /// If the `option` is none, the platform doesn't maintain an access + /// timestamp for this file. + data-access-timestamp: option, + /// Last data modification timestamp. + /// + /// If the `option` is none, the platform doesn't maintain a + /// modification timestamp for this file. + data-modification-timestamp: option, + /// Last file status-change timestamp. + /// + /// If the `option` is none, the platform doesn't maintain a + /// status-change timestamp for this file. + status-change-timestamp: option, + } + + /// When setting a timestamp, this gives the value to set it to. + variant new-timestamp { + /// Leave the timestamp set to its previous value. + no-change, + /// Set the timestamp to the current time of the system clock associated + /// with the filesystem. + now, + /// Set the timestamp to the given value. + timestamp(datetime), + } + + /// A directory entry. + record directory-entry { + /// The type of the file referred to by this directory entry. + %type: descriptor-type, + /// The name of the object. + name: string, + } + + /// Error codes returned by functions, similar to `errno` in POSIX. + /// Not all of these error codes are returned by the functions provided by this + /// API; some are used in higher-level library layers, and others are provided + /// merely for alignment with POSIX. + enum error-code { + /// Permission denied, similar to `EACCES` in POSIX. + access, + /// Resource unavailable, or operation would block, similar to `EAGAIN` and `EWOULDBLOCK` + /// in POSIX. + would-block, + /// Connection already in progress, similar to `EALREADY` in POSIX. + already, + /// Bad descriptor, similar to `EBADF` in POSIX. + bad-descriptor, + /// Device or resource busy, similar to `EBUSY` in POSIX. + busy, + /// Resource deadlock would occur, similar to `EDEADLK` in POSIX. + deadlock, + /// Storage quota exceeded, similar to `EDQUOT` in POSIX. + quota, + /// File exists, similar to `EEXIST` in POSIX. + exist, + /// File too large, similar to `EFBIG` in POSIX. + file-too-large, + /// Illegal byte sequence, similar to `EILSEQ` in POSIX. + illegal-byte-sequence, + /// Operation in progress, similar to `EINPROGRESS` in POSIX. + in-progress, + /// Interrupted function, similar to `EINTR` in POSIX. + interrupted, + /// Invalid argument, similar to `EINVAL` in POSIX. + invalid, + /// I/O error, similar to `EIO` in POSIX. + io, + /// Is a directory, similar to `EISDIR` in POSIX. + is-directory, + /// Too many levels of symbolic links, similar to `ELOOP` in POSIX. + loop, + /// Too many links, similar to `EMLINK` in POSIX. + too-many-links, + /// Message too large, similar to `EMSGSIZE` in POSIX. + message-size, + /// Filename too long, similar to `ENAMETOOLONG` in POSIX. + name-too-long, + /// No such device, similar to `ENODEV` in POSIX. + no-device, + /// No such file or directory, similar to `ENOENT` in POSIX. + no-entry, + /// No locks available, similar to `ENOLCK` in POSIX. + no-lock, + /// Not enough space, similar to `ENOMEM` in POSIX. + insufficient-memory, + /// No space left on device, similar to `ENOSPC` in POSIX. + insufficient-space, + /// Not a directory or a symbolic link to a directory, similar to `ENOTDIR` in POSIX. + not-directory, + /// Directory not empty, similar to `ENOTEMPTY` in POSIX. + not-empty, + /// State not recoverable, similar to `ENOTRECOVERABLE` in POSIX. + not-recoverable, + /// Not supported, similar to `ENOTSUP` and `ENOSYS` in POSIX. + unsupported, + /// Inappropriate I/O control operation, similar to `ENOTTY` in POSIX. + no-tty, + /// No such device or address, similar to `ENXIO` in POSIX. + no-such-device, + /// Value too large to be stored in data type, similar to `EOVERFLOW` in POSIX. + overflow, + /// Operation not permitted, similar to `EPERM` in POSIX. + not-permitted, + /// Broken pipe, similar to `EPIPE` in POSIX. + pipe, + /// Read-only file system, similar to `EROFS` in POSIX. + read-only, + /// Invalid seek, similar to `ESPIPE` in POSIX. + invalid-seek, + /// Text file busy, similar to `ETXTBSY` in POSIX. + text-file-busy, + /// Cross-device link, similar to `EXDEV` in POSIX. + cross-device + } + + /// File or memory access pattern advisory information. + enum advice { + /// The application has no advice to give on its behavior with respect + /// to the specified data. + normal, + /// The application expects to access the specified data sequentially + /// from lower offsets to higher offsets. + sequential, + /// The application expects to access the specified data in a random + /// order. + random, + /// The application expects to access the specified data in the near + /// future. + will-need, + /// The application expects that it will not access the specified data + /// in the near future. + dont-need, + /// The application expects to access the specified data once and then + /// not reuse it thereafter. + no-reuse + } + + /// A 128-bit hash value, split into parts because wasm doesn't have a + /// 128-bit integer type. + record metadata-hash-value { + /// 64 bits of a 128-bit hash value. + lower: u64, + /// Another 64 bits of a 128-bit hash value. + upper: u64, + } + + /// A descriptor is a reference to a filesystem object, which may be a file, + /// directory, named pipe, special file, or other object on which filesystem + /// calls may be made. + resource descriptor { + + /// Provide file advisory information on a descriptor. + /// + /// This is similar to `posix_fadvise` in POSIX. + advise: func(offset: filesize, length: filesize, advice: advice) -> result<_, error-code>; + + /// Return a stream for appending to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be appended. + /// + /// Note: This allows using `write-stream`, which is similar to `write` with + /// `O_APPEND` in in POSIX. + append-via-stream: func() -> result; + + /// Create a directory. + /// + /// Note: This is similar to `mkdirat` in POSIX. + create-directory-at: func(path: string) -> result<_, error-code>; + + /// Get flags associated with a descriptor. + /// + /// Note: This returns similar flags to `fcntl(fd, F_GETFL)` in POSIX. + /// + /// Note: This returns the value that was the `fs_flags` value returned + /// from `fdstat_get` in earlier versions of WASI. + get-flags: func() -> result; + + /// Get the dynamic type of a descriptor. + /// + /// Note: This returns the same value as the `type` field of the `fd-stat` + /// returned by `stat`, `stat-at` and similar. + /// + /// Note: This returns similar flags to the `st_mode & S_IFMT` value provided + /// by `fstat` in POSIX. + /// + /// Note: This returns the value that was the `fs_filetype` value returned + /// from `fdstat_get` in earlier versions of WASI. + get-type: func() -> result; + + /// Test whether two descriptors refer to the same filesystem object. + /// + /// In POSIX, this corresponds to testing whether the two descriptors have the + /// same device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers. + /// wasi-filesystem does not expose device and inode numbers, so this function + /// may be used instead. + is-same-object: func(other: borrow) -> bool; + + /// Create a hard link. + /// + /// Note: This is similar to `linkat` in POSIX. + link-at: func(old-path-flags: path-flags, old-path: string, new-descriptor: borrow, new-path: string) -> result<_, error-code>; + + /// Return a hash of the metadata associated with a filesystem object referred + /// to by a descriptor. + /// + /// This returns a hash of the last-modification timestamp and file size, and + /// may also include the inode number, device number, birth timestamp, and + /// other metadata fields that may change when the file is modified or + /// replaced. It may also include a secret value chosen by the + /// implementation and not otherwise exposed. + /// + /// Implementations are encourated to provide the following properties: + /// + /// - If the file is not modified or replaced, the computed hash value should + /// usually not change. + /// - If the object is modified or replaced, the computed hash value should + /// usually change. + /// - The inputs to the hash should not be easily computable from the + /// computed hash. + /// + /// However, none of these is required. + metadata-hash: func() -> result; + + /// Return a hash of the metadata associated with a filesystem object referred + /// to by a directory descriptor and a relative path. + /// + /// This performs the same hash computation as `metadata-hash`. + metadata-hash-at: func(path-flags: path-flags, path: string) -> result; + + /// Open a file or directory. + /// + /// The returned descriptor is not guaranteed to be the lowest-numbered + /// descriptor not currently open/ it is randomized to prevent applications + /// from depending on making assumptions about indexes, since this is + /// error-prone in multi-threaded contexts. The returned descriptor is + /// guaranteed to be less than 2**31. + /// + /// If `flags` contains `descriptor-flags::mutate-directory`, and the base + /// descriptor doesn't have `descriptor-flags::mutate-directory` set, + /// `open-at` fails with `error-code::read-only`. + /// + /// If `flags` contains `write` or `mutate-directory`, or `open-flags` + /// contains `truncate` or `create`, and the base descriptor doesn't have + /// `descriptor-flags::mutate-directory` set, `open-at` fails with + /// `error-code::read-only`. + /// + /// Note: This is similar to `openat` in POSIX. + open-at: func(path-flags: path-flags, path: string, open-flags: open-flags, %flags: descriptor-flags) -> result; + + /// Read from a descriptor, without using and updating the descriptor's offset. + /// + /// This function returns a list of bytes containing the data that was + /// read, along with a bool which, when true, indicates that the end of the + /// file was reached. The returned list will contain up to `length` bytes; it + /// may return fewer than requested, if the end of the file is reached or + /// if the I/O operation is interrupted. + /// + /// In the future, this may change to return a `stream`. + /// + /// Note: This is similar to `pread` in POSIX. + read: func(length: filesize, offset: filesize) -> result, bool>, error-code>; + + /// Read directory entries from a directory. + /// + /// On filesystems where directories contain entries referring to themselves + /// and their parents, often named `.` and `..` respectively, these entries + /// are omitted. + /// + /// This always returns a new stream which starts at the beginning of the + /// directory. Multiple streams may be active on the same directory, and they + /// do not interfere with each other. + read-directory: func() -> result; + + /// Return a stream for reading from a file, if available. + /// + /// May fail with an error-code describing why the file cannot be read. + /// + /// Multiple read, write, and append streams may be active on the same open + /// file and they do not interfere with each other. + /// + /// Note: This allows using `read-stream`, which is similar to `read` in POSIX. + read-via-stream: func(offset: filesize) -> result; + + /// Read the contents of a symbolic link. + /// + /// If the contents contain an absolute or rooted path in the underlying + /// filesystem, this function fails with `error-code::not-permitted`. + /// + /// Note: This is similar to `readlinkat` in POSIX. + readlink-at: func(path: string) -> result; + + /// Remove a directory. + /// + /// Return `error-code::not-empty` if the directory is not empty. + /// + /// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. + remove-directory-at: func(path: string) -> result<_, error-code>; + + /// Rename a filesystem object. + /// + /// Note: This is similar to `renameat` in POSIX. + rename-at: func(old-path: string, new-descriptor: borrow, new-path: string) -> result<_, error-code>; + + /// Adjust the size of an open file. If this increases the file's size, the + /// extra bytes are filled with zeros. + /// + /// Note: This was called `fd_filestat_set_size` in earlier versions of WASI. + set-size: func(size: filesize) -> result<_, error-code>; + + /// Adjust the timestamps of an open file or directory. + /// + /// Note: This is similar to `futimens` in POSIX. + /// + /// Note: This was called `fd_filestat_set_times` in earlier versions of WASI. + set-times: func(data-access-timestamp: new-timestamp, data-modification-timestamp: new-timestamp) -> result<_, error-code>; + + /// Adjust the timestamps of a file or directory. + /// + /// Note: This is similar to `utimensat` in POSIX. + /// + /// Note: This was called `path_filestat_set_times` in earlier versions of + /// WASI. + set-times-at: func(path-flags: path-flags, path: string, data-access-timestamp: new-timestamp, data-modification-timestamp: new-timestamp) -> result<_, error-code>; + + /// Return the attributes of an open file or directory. + /// + /// Note: This is similar to `fstat` in POSIX, except that it does not return + /// device and inode information. For testing whether two descriptors refer to + /// the same underlying filesystem object, use `is-same-object`. To obtain + /// additional data that can be used do determine whether a file has been + /// modified, use `metadata-hash`. + /// + /// Note: This was called `fd_filestat_get` in earlier versions of WASI. + stat: func() -> result; + + /// Return the attributes of a file or directory. + /// + /// Note: This is similar to `fstatat` in POSIX, except that it does not + /// return device and inode information. See the `stat` description for a + /// discussion of alternatives. + /// + /// Note: This was called `path_filestat_get` in earlier versions of WASI. + stat-at: func(path-flags: path-flags, path: string) -> result; + + /// Create a symbolic link (also known as a "symlink"). + /// + /// If `old-path` starts with `/`, the function fails with + /// `error-code::not-permitted`. + /// + /// Note: This is similar to `symlinkat` in POSIX. + symlink-at: func(old-path: string, new-path: string) -> result<_, error-code>; + + /// Synchronize the data and metadata of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fsync` in POSIX. + sync: func() -> result<_, error-code>; + + /// Synchronize the data of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fdatasync` in POSIX. + sync-data: func() -> result<_, error-code>; + + /// Unlink a filesystem object that is not a directory. + /// + /// Return `error-code::is-directory` if the path refers to a directory. + /// Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. + unlink-file-at: func(path: string) -> result<_, error-code>; + + /// Write to a descriptor, without using and updating the descriptor's offset. + /// + /// It is valid to write past the end of a file; the file is extended to the + /// extent of the write, with bytes between the previous end and the start of + /// the write set to zero. + /// + /// In the future, this may change to take a `stream`. + /// + /// Note: This is similar to `pwrite` in POSIX. + write: func(buffer: list, offset: filesize) -> result; + + /// Return a stream for writing to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be written. + /// + /// Note: This allows using `write-stream`, which is similar to `write` in + /// POSIX. + write-via-stream: func(offset: filesize) -> result; + } + + /// A stream of directory entries. + resource directory-entry-stream { + + /// Read a single directory entry from a `directory-entry-stream`. + read-directory-entry: func() -> result, error-code>; + } + + /// Attempts to extract a filesystem-related `error-code` from the stream + /// `error` provided. + /// + /// Stream operations which return `stream-error::last-operation-failed` + /// have a payload with more information about the operation that failed. + /// This payload can be passed through to this function to see if there's + /// filesystem-related information about the error to return. + /// + /// Note that this function is fallible because not all stream-related + /// errors are filesystem-related errors. + filesystem-error-code: func(err: borrow) -> option; + } + + interface preopens { + use types.{descriptor}; + + /// Return the set of preopened directories, and their path. + get-directories: func() -> list>; + } +} + +package wasi:sockets@0.2.0 { + interface network { + /// An opaque resource that represents access to (a subset of) the network. + /// This enables context-based security for networking. + /// There is no need for this to map 1:1 to a physical network interface. + resource network; + + /// Error codes. + /// + /// In theory, every API can return any error code. + /// In practice, API's typically only return the errors documented per API + /// combined with a couple of errors that are always possible: + /// - `unknown` + /// - `access-denied` + /// - `not-supported` + /// - `out-of-memory` + /// - `concurrency-conflict` + /// + /// See each individual API for what the POSIX equivalents are. They sometimes differ + /// per API. + enum error-code { + /// Unknown error + unknown, + /// Access denied. + /// + /// POSIX equivalent: EACCES, EPERM + access-denied, + /// The operation is not supported. + /// + /// POSIX equivalent: EOPNOTSUPP + not-supported, + /// One of the arguments is invalid. + /// + /// POSIX equivalent: EINVAL + invalid-argument, + /// Not enough memory to complete the operation. + /// + /// POSIX equivalent: ENOMEM, ENOBUFS, EAI_MEMORY + out-of-memory, + /// The operation timed out before it could finish completely. + timeout, + /// This operation is incompatible with another asynchronous operation that is already + /// in progress. + /// + /// POSIX equivalent: EALREADY + concurrency-conflict, + /// Trying to finish an asynchronous operation that: + /// - has not been started yet, or: + /// - was already finished by a previous `finish-*` call. + /// + /// Note: this is scheduled to be removed when `future`s are natively supported. + not-in-progress, + /// The operation has been aborted because it could not be completed immediately. + /// + /// Note: this is scheduled to be removed when `future`s are natively supported. + would-block, + /// The operation is not valid in the socket's current state. + invalid-state, + /// A new socket resource could not be created because of a system limit. + new-socket-limit, + /// A bind operation failed because the provided address is not an address that the + /// `network` can bind to. + address-not-bindable, + /// A bind operation failed because the provided address is already in use or because + /// there are no ephemeral ports available. + address-in-use, + /// The remote address is not reachable + remote-unreachable, + /// The TCP connection was forcefully rejected + connection-refused, + /// The TCP connection was reset. + connection-reset, + /// A TCP connection was aborted. + connection-aborted, + /// The size of a datagram sent to a UDP socket exceeded the maximum + /// supported size. + datagram-too-large, + /// Name does not exist or has no suitable associated IP addresses. + name-unresolvable, + /// A temporary failure in name resolution occurred. + temporary-resolver-failure, + /// A permanent failure in name resolution occurred. + permanent-resolver-failure + } + enum ip-address-family { + /// Similar to `AF_INET` in POSIX. + ipv4, + /// Similar to `AF_INET6` in POSIX. + ipv6 + } + type ipv4-address = tuple; + type ipv6-address = tuple; + variant ip-address { + ipv4(ipv4-address), + ipv6(ipv6-address), + } + record ipv4-socket-address { + /// sin_port + port: u16, + /// sin_addr + address: ipv4-address, + } + record ipv6-socket-address { + /// sin6_port + port: u16, + /// sin6_flowinfo + flow-info: u32, + /// sin6_addr + address: ipv6-address, + /// sin6_scope_id + scope-id: u32, + } + variant ip-socket-address { + ipv4(ipv4-socket-address), + ipv6(ipv6-socket-address), + } + } + + /// This interface provides a value-export of the default network handle.. + interface instance-network { + use network.{network}; + + /// Get a handle to the default network. + instance-network: func() -> network; + } + + interface ip-name-lookup { + use wasi:io/poll@0.2.0.{pollable}; + use network.{network}; + use network.{error-code}; + use network.{ip-address}; + resource resolve-address-stream { + + /// Returns the next address from the resolver. + /// + /// This function should be called multiple times. On each call, it will + /// return the next address in connection order preference. If all + /// addresses have been exhausted, this function returns `none`. + /// + /// This function never returns IPv4-mapped IPv6 addresses. + /// + /// # Typical errors + /// - `name-unresolvable`: Name does not exist or has no suitable associated + /// IP addresses. (EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY) + /// - `temporary-resolver-failure`: A temporary failure in name resolution occurred. + /// (EAI_AGAIN) + /// - `permanent-resolver-failure`: A permanent failure in name resolution occurred. + /// (EAI_FAIL) + /// - `would-block`: A result is not available yet. (EWOULDBLOCK, EAGAIN) + resolve-next-address: func() -> result, error-code>; + + /// Create a `pollable` which will resolve once the stream is ready for I/O. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } + + /// Resolve an internet host name to a list of IP addresses. + /// + /// Unicode domain names are automatically converted to ASCII using IDNA encoding. + /// If the input is an IP address string, the address is parsed and returned + /// as-is without making any external requests. + /// + /// See the wasi-socket proposal README.md for a comparison with getaddrinfo. + /// + /// This function never blocks. It either immediately fails or immediately + /// returns successfully with a `resolve-address-stream` that can be used + /// to (asynchronously) fetch the results. + /// + /// # Typical errors + /// - `invalid-argument`: `name` is a syntactically invalid domain name or IP address. + /// + /// # References: + /// - + /// - + /// - + /// - + resolve-addresses: func(network: borrow, name: string) -> result; + } + + interface tcp { + use wasi:io/streams@0.2.0.{input-stream}; + use wasi:io/streams@0.2.0.{output-stream}; + use wasi:io/poll@0.2.0.{pollable}; + use wasi:clocks/monotonic-clock@0.2.0.{duration}; + use network.{network}; + use network.{error-code}; + use network.{ip-socket-address}; + use network.{ip-address-family}; + enum shutdown-type { + /// Similar to `SHUT_RD` in POSIX. + receive, + /// Similar to `SHUT_WR` in POSIX. + send, + /// Similar to `SHUT_RDWR` in POSIX. + both + } + + /// A TCP socket resource. + /// + /// The socket can be in one of the following states: + /// - `unbound` + /// - `bind-in-progress` + /// - `bound` (See note below) + /// - `listen-in-progress` + /// - `listening` + /// - `connect-in-progress` + /// - `connected` + /// - `closed` + /// See + /// for a more information. + /// + /// Note: Except where explicitly mentioned, whenever this documentation uses + /// the term "bound" without backticks it actually means: in the `bound` state *or + /// higher*. + /// (i.e. `bound`, `listen-in-progress`, `listening`, `connect-in-progress` or `connected`) + /// + /// In addition to the general error codes documented on the + /// `network::error-code` type, TCP socket methods may always return + /// `error(invalid-state)` when in the `closed` state. + resource tcp-socket { + + /// Accept a new client socket. + /// + /// The returned socket is bound and in the `connected` state. The following properties + /// are inherited from the listener socket: + /// - `address-family` + /// - `keep-alive-enabled` + /// - `keep-alive-idle-time` + /// - `keep-alive-interval` + /// - `keep-alive-count` + /// - `hop-limit` + /// - `receive-buffer-size` + /// - `send-buffer-size` + /// + /// On success, this function returns the newly accepted client socket along with + /// a pair of streams that can be used to read & write to the connection. + /// + /// # Typical errors + /// - `invalid-state`: Socket is not in the `listening` state. (EINVAL) + /// - `would-block`: No pending connections at the moment. (EWOULDBLOCK, EAGAIN) + /// - `connection-aborted`: An incoming connection was pending, but was terminated + /// by the client before this listener could accept it. (ECONNABORTED) + /// - `new-socket-limit`: The new socket resource could not be created because of + /// a system limit. (EMFILE, ENFILE) + /// + /// # References + /// - + /// - + /// - + /// - + accept: func() -> result, error-code>; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + address-family: func() -> ip-address-family; + finish-bind: func() -> result<_, error-code>; + finish-connect: func() -> result, error-code>; + finish-listen: func() -> result<_, error-code>; + + /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The TTL value must be 1 or higher. + hop-limit: func() -> result; + + /// Whether the socket is in the `listening` state. + /// + /// Equivalent to the SO_ACCEPTCONN socket option. + is-listening: func() -> bool; + + /// The maximum amount of keepalive packets TCP should send before aborting the connection. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// I.e. after setting a value, reading the same setting back may return a different + /// value. + /// + /// Equivalent to the TCP_KEEPCNT socket option. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-count: func() -> result; + + /// Enables or disables keepalive. + /// + /// The keepalive behavior can be adjusted using: + /// - `keep-alive-idle-time` + /// - `keep-alive-interval` + /// - `keep-alive-count` + /// These properties can be configured while `keep-alive-enabled` is false, but only + /// come into effect when `keep-alive-enabled` is true. + /// + /// Equivalent to the SO_KEEPALIVE socket option. + keep-alive-enabled: func() -> result; + + /// Amount of time the connection has to be idle before TCP starts sending keepalive + /// packets. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// I.e. after setting a value, reading the same setting back may return a different + /// value. + /// + /// Equivalent to the TCP_KEEPIDLE socket option. (TCP_KEEPALIVE on MacOS) + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-idle-time: func() -> result; + + /// The time between keepalive packets. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// I.e. after setting a value, reading the same setting back may return a different + /// value. + /// + /// Equivalent to the TCP_KEEPINTVL socket option. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-interval: func() -> result; + + /// Get the bound local address. + /// + /// POSIX mentions: + /// > If the socket has not been bound to a local name, the value + /// > stored in the object pointed to by `address` is unspecified. + /// + /// WASI is stricter and requires `local-address` to return `invalid-state` when the + /// socket hasn't been bound yet. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. + /// + /// # References + /// - + /// - + /// - + /// - + local-address: func() -> result; + + /// The kernel buffer space reserved for sends/receives on this socket. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// I.e. after setting a value, reading the same setting back may return a different + /// value. + /// + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + receive-buffer-size: func() -> result; + + /// Get the remote address. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + remote-address: func() -> result; + send-buffer-size: func() -> result; + set-hop-limit: func(value: u8) -> result<_, error-code>; + set-keep-alive-count: func(value: u32) -> result<_, error-code>; + set-keep-alive-enabled: func(value: bool) -> result<_, error-code>; + set-keep-alive-idle-time: func(value: duration) -> result<_, error-code>; + set-keep-alive-interval: func(value: duration) -> result<_, error-code>; + + /// Hints the desired listen queue size. Implementations are free to ignore this. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// + /// # Typical errors + /// - `not-supported`: (set) The platform does not support changing the backlog + /// size after the initial listen. + /// - `invalid-argument`: (set) The provided value was 0. + /// - `invalid-state`: (set) The socket is in the `connect-in-progress` or + /// `connected` state. + set-listen-backlog-size: func(value: u64) -> result<_, error-code>; + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + + /// Initiate a graceful shutdown. + /// + /// - `receive`: The socket is not expecting to receive any data from + /// the peer. The `input-stream` associated with this socket will be + /// closed. Any data still in the receive queue at time of calling + /// this method will be discarded. + /// - `send`: The socket has no more data to send to the peer. The `output-stream` + /// associated with this socket will be closed and a FIN packet will be sent. + /// - `both`: Same effect as `receive` & `send` combined. + /// + /// This function is idempotent. Shutting a down a direction more than once + /// has no effect and returns `ok`. + /// + /// The shutdown function does not close (drop) the socket. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code>; + + /// Bind the socket to a specific network on the provided IP address and port. + /// + /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the + /// implementation to decide which + /// network interface(s) to bind to. + /// If the TCP/UDP port is zero, the socket will be bound to a random free port. + /// + /// Bind can be attempted multiple times on the same socket, even with + /// different arguments on each iteration. But never concurrently and + /// only as long as the previous bind failed. Once a bind succeeds, the + /// binding can't be changed anymore. + /// + /// # Typical errors + /// - `invalid-argument`: The `local-address` has the wrong address family. + /// (EAFNOSUPPORT, EFAULT on Windows) + /// - `invalid-argument`: `local-address` is not a unicast address. (EINVAL) + /// - `invalid-argument`: `local-address` is an IPv4-mapped IPv6 address. + /// (EINVAL) + /// - `invalid-state`: The socket is already bound. (EINVAL) + /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS + /// on Windows) + /// - `address-in-use`: Address is already in use. (EADDRINUSE) + /// - `address-not-bindable`: `local-address` is not an address that the `network` + /// can bind to. (EADDRNOTAVAIL) + /// - `not-in-progress`: A `bind` operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. + /// (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// When binding to a non-zero port, this bind operation shouldn't be affected by + /// the TIME_WAIT + /// state of a recently closed socket on the same local address. In practice this + /// means that the SO_REUSEADDR + /// socket option should be set implicitly on all platforms, except on Windows where + /// this is the default behavior + /// and SO_REUSEADDR performs something different entirely. + /// + /// Unlike in POSIX, in WASI the bind operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `bind` as part of either `start-bind` or `finish-bind`. + /// + /// # References + /// - + /// - + /// - + /// - + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + + /// Connect to a remote endpoint. + /// + /// On success: + /// - the socket is transitioned into the `connection` state. + /// - a pair of streams is returned that can be used to read & write to the connection + /// + /// After a failed connection attempt, the socket will be in the `closed` + /// state and the only valid action left is to `drop` the socket. A single + /// socket can not be used to connect more than once. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. + /// (EAFNOSUPPORT) + /// - `invalid-argument`: `remote-address` is not a unicast address. (EINVAL, + /// ENETUNREACH on Linux, EAFNOSUPPORT on MacOS) + /// - `invalid-argument`: `remote-address` is an IPv4-mapped IPv6 address. + /// (EINVAL, EADDRNOTAVAIL on Illumos) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY + /// (`0.0.0.0` / `::`). (EADDRNOTAVAIL on Windows) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EADDRNOTAVAIL + /// on Windows) + /// - `invalid-argument`: The socket is already attached to a different network. + /// The `network` passed to `connect` must be identical to the one passed to `bind`. + /// - `invalid-state`: The socket is already in the `connected` state. + /// (EISCONN) + /// - `invalid-state`: The socket is already in the `listening` state. + /// (EOPNOTSUPP, EINVAL on Windows) + /// - `timeout`: Connection timed out. (ETIMEDOUT) + /// - `connection-refused`: The connection was forcefully rejected. (ECONNREFUSED) + /// - `connection-reset`: The connection was reset. (ECONNRESET) + /// - `connection-aborted`: The connection was aborted. (ECONNABORTED) + /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, + /// EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `address-in-use`: Tried to perform an implicit bind, but there were + /// no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// - `not-in-progress`: A connect operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. + /// (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// The POSIX equivalent of `start-connect` is the regular `connect` syscall. + /// Because all WASI sockets are non-blocking this is expected to return + /// EINPROGRESS, which should be translated to `ok()` in WASI. + /// + /// The POSIX equivalent of `finish-connect` is a `poll` for event `POLLOUT` + /// with a timeout of 0 on the socket descriptor. Followed by a check for + /// the `SO_ERROR` socket option, in case the poll signaled readiness. + /// + /// # References + /// - + /// - + /// - + /// - + start-connect: func(network: borrow, remote-address: ip-socket-address) -> result<_, error-code>; + + /// Start listening for new connections. + /// + /// Transitions the socket into the `listening` state. + /// + /// Unlike POSIX, the socket must already be explicitly bound. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. (EDESTADDRREQ) + /// - `invalid-state`: The socket is already in the `connected` state. + /// (EISCONN, EINVAL on BSD) + /// - `invalid-state`: The socket is already in the `listening` state. + /// - `address-in-use`: Tried to perform an implicit bind, but there were + /// no ephemeral ports available. (EADDRINUSE) + /// - `not-in-progress`: A listen operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. + /// (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// Unlike in POSIX, in WASI the listen operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `listen` as part of either `start-listen` or `finish-listen`. + /// + /// # References + /// - + /// - + /// - + /// - + start-listen: func() -> result<_, error-code>; + + /// Create a `pollable` which can be used to poll for, or block on, + /// completion of any of the asynchronous operations of this socket. + /// + /// When `finish-bind`, `finish-listen`, `finish-connect` or `accept` + /// return `error(would-block)`, this pollable can be used to wait for + /// their success or failure, after which the method can be retried. + /// + /// The pollable is not limited to the async operation that happens to be + /// in progress at the time of calling `subscribe` (if any). Theoretically, + /// `subscribe` only has to be called once per socket and can then be + /// (re)used for the remainder of the socket's lifetime. + /// + /// See + /// for a more information. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } + } + + interface tcp-create-socket { + use network.{network}; + use network.{error-code}; + use network.{ip-address-family}; + use tcp.{tcp-socket}; + + /// Create a new TCP socket. + /// + /// Similar to `socket(AF_INET or AF_INET6, SOCK_STREAM, IPPROTO_TCP)` in POSIX. + /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. + /// + /// This function does not require a network capability handle. This is considered + /// to be safe because + /// at time of creation, the socket is not bound to any `network` yet. Up to the moment + /// `bind`/`connect` + /// is called, the socket is effectively an in-memory configuration object, unable + /// to communicate with the outside world. + /// + /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous + /// operations. + /// + /// # Typical errors + /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) + /// - `new-socket-limit`: The new socket resource could not be created because of + /// a system limit. (EMFILE, ENFILE) + /// + /// # References + /// - + /// - + /// - + /// - + create-tcp-socket: func(address-family: ip-address-family) -> result; + } + + interface udp { + use wasi:io/poll@0.2.0.{pollable}; + use network.{network}; + use network.{error-code}; + use network.{ip-socket-address}; + use network.{ip-address-family}; + + /// A received datagram. + record incoming-datagram { + /// The payload. + /// + /// Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes. + data: list, + /// The source address. + /// + /// This field is guaranteed to match the remote address the stream was initialized + /// with, if any. + /// + /// Equivalent to the `src_addr` out parameter of `recvfrom`. + remote-address: ip-socket-address, + } + + /// A datagram to be sent out. + record outgoing-datagram { + /// The payload. + data: list, + /// The destination address. + /// + /// The requirements on this field depend on how the stream was initialized: + /// - with a remote address: this field must be None or match the stream's remote + /// address exactly. + /// - without a remote address: this field is required. + /// + /// If this value is None, the send operation is equivalent to `send` in POSIX. Otherwise + /// it is equivalent to `sendto`. + remote-address: option, + } + + /// A UDP socket handle. + resource udp-socket { + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + address-family: func() -> ip-address-family; + finish-bind: func() -> result<_, error-code>; + + /// Get the current bound address. + /// + /// POSIX mentions: + /// > If the socket has not been bound to a local name, the value + /// > stored in the object pointed to by `address` is unspecified. + /// + /// WASI is stricter and requires `local-address` to return `invalid-state` when the + /// socket hasn't been bound yet. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. + /// + /// # References + /// - + /// - + /// - + /// - + local-address: func() -> result; + + /// The kernel buffer space reserved for sends/receives on this socket. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// I.e. after setting a value, reading the same setting back may return a different + /// value. + /// + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + receive-buffer-size: func() -> result; + + /// Get the address the socket is currently streaming to. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not streaming to a specific remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + remote-address: func() -> result; + send-buffer-size: func() -> result; + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; + + /// Bind the socket to a specific network on the provided IP address and port. + /// + /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the + /// implementation to decide which + /// network interface(s) to bind to. + /// If the port is zero, the socket will be bound to a random free port. + /// + /// # Typical errors + /// - `invalid-argument`: The `local-address` has the wrong address family. + /// (EAFNOSUPPORT, EFAULT on Windows) + /// - `invalid-state`: The socket is already bound. (EINVAL) + /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS + /// on Windows) + /// - `address-in-use`: Address is already in use. (EADDRINUSE) + /// - `address-not-bindable`: `local-address` is not an address that the `network` + /// can bind to. (EADDRNOTAVAIL) + /// - `not-in-progress`: A `bind` operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. + /// (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// Unlike in POSIX, in WASI the bind operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `bind` as part of either `start-bind` or `finish-bind`. + /// + /// # References + /// - + /// - + /// - + /// - + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + + /// Set up inbound & outbound communication channels, optionally to a specific peer. + /// + /// This function only changes the local socket configuration and does not generate + /// any network traffic. + /// On success, the `remote-address` of the socket is updated. The `local-address` + /// may be updated as well, + /// based on the best network path to `remote-address`. + /// + /// When a `remote-address` is provided, the returned streams are limited to communicating + /// with that specific peer: + /// - `send` can only be used to send to this destination. + /// - `receive` will only return datagrams sent from the provided `remote-address`. + /// + /// This method may be called multiple times on the same socket to change its association, + /// but + /// only the most recently returned pair of streams will be operational. Implementations + /// may trap if + /// the streams returned by a previous invocation haven't been dropped yet before + /// calling `stream` again. + /// + /// The POSIX equivalent in pseudo-code is: + /// ```text + /// if (was previously connected) { + /// connect(s, AF_UNSPEC) + /// } + /// if (remote_address is Some) { + /// connect(s, remote_address) + /// } + /// ``` + /// + /// Unlike in POSIX, the socket must already be explicitly bound. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. + /// (EAFNOSUPPORT) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY + /// (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, + /// EADDRNOTAVAIL) + /// - `invalid-state`: The socket is not bound. + /// - `address-in-use`: Tried to perform an implicit bind, but there were + /// no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, + /// ENETRESET, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// + /// # References + /// - + /// - + /// - + /// - + %stream: func(remote-address: option) -> result, error-code>; + + /// Create a `pollable` which will resolve once the socket is ready for I/O. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + + /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The TTL value must be 1 or higher. + unicast-hop-limit: func() -> result; + } + resource incoming-datagram-stream { + + /// Receive messages on the socket. + /// + /// This function attempts to receive up to `max-results` datagrams on the socket + /// without blocking. + /// The returned list may contain fewer elements than requested, but never more. + /// + /// This function returns successfully with an empty list when either: + /// - `max-results` is 0, or: + /// - `max-results` is greater than 0, but no results are immediately available. + /// This function never returns `error(would-block)`. + /// + /// # Typical errors + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET + /// on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + receive: func(max-results: u64) -> result, error-code>; + + /// Create a `pollable` which will resolve once the stream is ready to receive again. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } + resource outgoing-datagram-stream { + + /// Check readiness for sending. This function never blocks. + /// + /// Returns the number of datagrams permitted for the next call to `send`, + /// or an error. Calling `send` with more datagrams than this function has + /// permitted will trap. + /// + /// When this function returns ok(0), the `subscribe` pollable will + /// become ready when this function will report at least ok(1), or an + /// error. + /// + /// Never returns `would-block`. + check-send: func() -> result; + + /// Send messages on the socket. + /// + /// This function attempts to send all provided `datagrams` on the socket without + /// blocking and + /// returns how many messages were actually sent (or queued for sending). This function + /// never + /// returns `error(would-block)`. If none of the datagrams were able to be sent, `ok(0)` + /// is returned. + /// + /// This function semantically behaves the same as iterating the `datagrams` list + /// and sequentially + /// sending each individual datagram until either the end of the list has been reached + /// or the first error occurred. + /// If at least one datagram has been sent successfully, this function never returns + /// an error. + /// + /// If the input list is empty, the function returns `ok(0)`. + /// + /// Each call to `send` must be permitted by a preceding `check-send`. Implementations + /// must trap if + /// either `check-send` was not called or `datagrams` contains more items than `check-send` + /// permitted. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. + /// (EAFNOSUPPORT) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY + /// (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, + /// EADDRNOTAVAIL) + /// - `invalid-argument`: The socket is in "connected" mode and `remote-address` + /// is `some` value that does not match the address passed to `stream`. (EISCONN) + /// - `invalid-argument`: The socket is not "connected" and no value for `remote-address` + /// was provided. (EDESTADDRREQ) + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, + /// ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// - `datagram-too-large`: The datagram is too large. (EMSGSIZE) + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + send: func(datagrams: list) -> result; + + /// Create a `pollable` which will resolve once the stream is ready to send again. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } + } + + interface udp-create-socket { + use network.{network}; + use network.{error-code}; + use network.{ip-address-family}; + use udp.{udp-socket}; + + /// Create a new UDP socket. + /// + /// Similar to `socket(AF_INET or AF_INET6, SOCK_DGRAM, IPPROTO_UDP)` in POSIX. + /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. + /// + /// This function does not require a network capability handle. This is considered + /// to be safe because + /// at time of creation, the socket is not bound to any `network` yet. Up to the moment + /// `bind` is called, + /// the socket is effectively an in-memory configuration object, unable to communicate + /// with the outside world. + /// + /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous + /// operations. + /// + /// # Typical errors + /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) + /// - `new-socket-limit`: The new socket resource could not be created because of + /// a system limit. (EMFILE, ENFILE) + /// + /// # References: + /// - + /// - + /// - + /// - + create-udp-socket: func(address-family: ip-address-family) -> result; + } +} + +package wasi:clocks@0.2.0 { + /// WASI Monotonic Clock is a clock API intended to let users measure elapsed + /// time. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + /// + /// A monotonic clock is a clock which has an unspecified initial value, and + /// successive reads of the clock will produce non-decreasing values. + /// + /// It is intended for measuring elapsed time. + interface monotonic-clock { + use wasi:io/poll@0.2.0.{pollable}; + + /// An instant in time, in nanoseconds. An instant is relative to an + /// unspecified initial value, and can only be compared to instances from + /// the same monotonic-clock. + type instant = u64; + + /// A duration of time, in nanoseconds. + type duration = u64; + + /// Read the current value of the clock. + /// + /// The clock is monotonic, therefore calling this function repeatedly will + /// produce a sequence of non-decreasing values. + now: func() -> instant; + + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + resolution: func() -> duration; + + /// Create a `pollable` which will resolve once the specified instant + /// occured. + subscribe-instant: func(when: instant) -> pollable; + + /// Create a `pollable` which will resolve once the given duration has + /// elapsed, starting at the time at which this function was called. + /// occured. + subscribe-duration: func(when: duration) -> pollable; + } + + /// WASI Wall Clock is a clock API intended to let users query the current + /// time. The name "wall" makes an analogy to a "clock on the wall", which + /// is not necessarily monotonic as it may be reset. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + /// + /// A wall clock is a clock which measures the date and time according to + /// some external reference. + /// + /// External references may be reset, so this clock is not necessarily + /// monotonic, making it unsuitable for measuring elapsed time. + /// + /// It is intended for reporting the current date and time for humans. + interface wall-clock { + /// A time and date in seconds plus nanoseconds. + record datetime { + seconds: u64, + nanoseconds: u32, + } + + /// Read the current value of the clock. + /// + /// This clock is not monotonic, therefore calling this function repeatedly + /// will not necessarily produce a sequence of non-decreasing values. + /// + /// The returned timestamps represent the number of seconds since + /// 1970-01-01T00:00:00Z, also known as [POSIX's Seconds Since the Epoch], + /// also known as [Unix Time]. + /// + /// The nanoseconds field of the output is always less than 1000000000. + /// + /// [POSIX's Seconds Since the Epoch]: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html#tag_21_04_16 + /// [Unix Time]: https://en.wikipedia.org/wiki/Unix_time + now: func() -> datetime; + + /// Query the resolution of the clock. + /// + /// The nanoseconds field of the output is always less than 1000000000. + resolution: func() -> datetime; + } +} + +package wasi:io@0.2.0 { + interface error { + /// A resource which represents some error information. + /// + /// The only method provided by this resource is `to-debug-string`, + /// which provides some human-readable information about the error. + /// + /// In the `wasi:io` package, this resource is returned through the + /// `wasi:io/streams/stream-error` type. + /// + /// To provide more specific error information, other interfaces may + /// provide functions to further "downcast" this error into more specific + /// error information. For example, `error`s returned in streams derived + /// from filesystem types to be described using the filesystem's own + /// error-code type, using the function + /// `wasi:filesystem/types/filesystem-error-code`, which takes a parameter + /// `borrow` and returns + /// `option`. + /// + /// The set of functions which can "downcast" an `error` into a more + /// concrete type is open. + resource error { + + /// Returns a string that is suitable to assist humans in debugging + /// this error. + /// + /// WARNING: The returned string should not be consumed mechanically! + /// It may change across platforms, hosts, or other implementation + /// details. Parsing this string is a major platform-compatibility + /// hazard. + to-debug-string: func() -> string; + } + } + + /// A poll API intended to let users wait for I/O events on multiple handles + /// at once. + interface poll { + /// `pollable` represents a single I/O event which may be ready, or not. + resource pollable { + + /// `block` returns immediately if the pollable is ready, and otherwise + /// blocks until ready. + /// + /// This function is equivalent to calling `poll.poll` on a list + /// containing only this pollable. + block: func(); + + /// Return the readiness of a pollable. This function never blocks. + /// + /// Returns `true` when the pollable is ready, and `false` otherwise. + ready: func() -> bool; + } + + /// Poll for completion on a set of pollables. + /// + /// This function takes a list of pollables, which identify I/O sources of + /// interest, and waits until one or more of the events is ready for I/O. + /// + /// The result `list` contains one or more indices of handles in the + /// argument list that is ready for I/O. + /// + /// If the list contains more elements than can be indexed with a `u32` + /// value, this function traps. + /// + /// A timeout can be implemented by adding a pollable from the + /// wasi-clocks API to the list. + /// + /// This function does not return a `result`; polling in itself does not + /// do any I/O so it doesn't fail. If any of the I/O sources identified by + /// the pollables has an error, it is indicated by marking the source as + /// being reaedy for I/O. + poll: func(in: list>) -> list; + } + + /// WASI I/O is an I/O abstraction API which is currently focused on providing + /// stream types. + /// + /// In the future, the component model is expected to add built-in stream types; + /// when it does, they are expected to subsume this API. + interface streams { + use error.{error}; + use poll.{pollable}; + + /// An error for input-stream and output-stream operations. + variant stream-error { + /// The last operation (a write or flush) failed before completion. + /// + /// More information is available in the `error` payload. + last-operation-failed(error), + /// The stream is closed: no more input will be accepted by the + /// stream. A closed output-stream will return this error on all + /// future operations. + closed, + } + + /// An input bytestream. + /// + /// `input-stream`s are *non-blocking* to the extent practical on underlying + /// platforms. I/O operations always return promptly; if fewer bytes are + /// promptly available than requested, they return the number of bytes promptly + /// available, which could even be zero. To wait for data to be available, + /// use the `subscribe` function to obtain a `pollable` which can be polled + /// for using `wasi:io/poll`. + resource input-stream { + + /// Read bytes from a stream, after blocking until at least one byte can + /// be read. Except for blocking, behavior is identical to `read`. + blocking-read: func(len: u64) -> result, stream-error>; + + /// Skip bytes from a stream, after blocking until at least one byte + /// can be skipped. Except for blocking behavior, identical to `skip`. + blocking-skip: func(len: u64) -> result; + + /// Perform a non-blocking read from the stream. + /// + /// When the source of a `read` is binary data, the bytes from the source + /// are returned verbatim. When the source of a `read` is known to the + /// implementation to be text, bytes containing the UTF-8 encoding of the + /// text are returned. + /// + /// This function returns a list of bytes containing the read data, + /// when successful. The returned list will contain up to `len` bytes; + /// it may return fewer than requested, but not more. The list is + /// empty when no bytes are available for reading at this time. The + /// pollable given by `subscribe` will be ready when more bytes are + /// available. + /// + /// This function fails with a `stream-error` when the operation + /// encounters an error, giving `last-operation-failed`, or when the + /// stream is closed, giving `closed`. + /// + /// When the caller gives a `len` of 0, it represents a request to + /// read 0 bytes. If the stream is still open, this call should + /// succeed and return an empty list, or otherwise fail with `closed`. + /// + /// The `len` parameter is a `u64`, which could represent a list of u8 which + /// is not possible to allocate in wasm32, or not desirable to allocate as + /// as a return value by the callee. The callee may return a list of bytes + /// less than `len` in size while more bytes are available for reading. + read: func(len: u64) -> result, stream-error>; + + /// Skip bytes from a stream. Returns number of bytes skipped. + /// + /// Behaves identical to `read`, except instead of returning a list + /// of bytes, returns the number of bytes consumed from the stream. + skip: func(len: u64) -> result; + + /// Create a `pollable` which will resolve once either the specified stream + /// has bytes available to read or the other end of the stream has been + /// closed. + /// The created `pollable` is a child resource of the `input-stream`. + /// Implementations may trap if the `input-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + subscribe: func() -> pollable; + } + + /// An output bytestream. + /// + /// `output-stream`s are *non-blocking* to the extent practical on + /// underlying platforms. Except where specified otherwise, I/O operations also + /// always return promptly, after the number of bytes that can be written + /// promptly, which could even be zero. To wait for the stream to be ready to + /// accept data, the `subscribe` function to obtain a `pollable` which can be + /// polled for using `wasi:io/poll`. + resource output-stream { + + /// Request to flush buffered output, and block until flush completes + /// and stream is ready for writing again. + blocking-flush: func() -> result<_, stream-error>; + + /// Read from one stream and write to another, with blocking. + /// + /// This is similar to `splice`, except that it blocks until the + /// `output-stream` is ready for writing, and the `input-stream` + /// is ready for reading, before performing the `splice`. + blocking-splice: func(src: borrow, len: u64) -> result; + + /// Perform a write of up to 4096 bytes, and then flush the stream. Block + /// until all of these operations are complete, or an error occurs. + /// + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write`, and `flush`, and is implemented with the + /// following pseudo-code: + /// + /// ```text + /// let pollable = this.subscribe(); + /// while !contents.is_empty() { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, contents.len()); + /// let (chunk, rest) = contents.split_at(len); + /// this.write(chunk ); // eliding error handling + /// contents = rest; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + blocking-write-and-flush: func(contents: list) -> result<_, stream-error>; + + /// Perform a write of up to 4096 zeroes, and then flush the stream. + /// Block until all of these operations are complete, or an error + /// occurs. + /// + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write-zeroes`, and `flush`, and is implemented with + /// the following pseudo-code: + /// + /// ```text + /// let pollable = this.subscribe(); + /// while num_zeroes != 0 { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, num_zeroes); + /// this.write-zeroes(len); // eliding error handling + /// num_zeroes -= len; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + blocking-write-zeroes-and-flush: func(len: u64) -> result<_, stream-error>; + + /// Check readiness for writing. This function never blocks. + /// + /// Returns the number of bytes permitted for the next call to `write`, + /// or an error. Calling `write` with more bytes than this function has + /// permitted will trap. + /// + /// When this function returns 0 bytes, the `subscribe` pollable will + /// become ready when this function will report at least 1 byte, or an + /// error. + check-write: func() -> result; + + /// Request to flush buffered output. This function never blocks. + /// + /// This tells the output-stream that the caller intends any buffered + /// output to be flushed. the output which is expected to be flushed + /// is all that has been passed to `write` prior to this call. + /// + /// Upon calling this function, the `output-stream` will not accept any + /// writes (`check-write` will return `ok(0)`) until the flush has + /// completed. The `subscribe` pollable will become ready when the + /// flush has completed and the stream can accept more writes. + flush: func() -> result<_, stream-error>; + + /// Read from one stream and write to another. + /// + /// The behavior of splice is equivelant to: + /// 1. calling `check-write` on the `output-stream` + /// 2. calling `read` on the `input-stream` with the smaller of the + /// `check-write` permitted length and the `len` provided to `splice` + /// 3. calling `write` on the `output-stream` with that read data. + /// + /// Any error reported by the call to `check-write`, `read`, or + /// `write` ends the splice and reports that error. + /// + /// This function returns the number of bytes transferred; it may be less + /// than `len`. + splice: func(src: borrow, len: u64) -> result; + + /// Create a `pollable` which will resolve once the output-stream + /// is ready for more writing, or an error has occured. When this + /// pollable is ready, `check-write` will return `ok(n)` with n>0, or an + /// error. + /// + /// If the stream is closed, this pollable is always ready immediately. + /// + /// The created `pollable` is a child resource of the `output-stream`. + /// Implementations may trap if the `output-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + subscribe: func() -> pollable; + + /// Perform a write. This function never blocks. + /// + /// When the destination of a `write` is binary data, the bytes from + /// `contents` are written verbatim. When the destination of a `write` is + /// known to the implementation to be text, the bytes of `contents` are + /// transcoded from UTF-8 into the encoding of the destination and then + /// written. + /// + /// Precondition: check-write gave permit of Ok(n) and contents has a + /// length of less than or equal to n. Otherwise, this function will trap. + /// + /// returns Err(closed) without writing if the stream has closed since + /// the last call to check-write provided a permit. + write: func(contents: list) -> result<_, stream-error>; + + /// Write zeroes to a stream. + /// + /// This should be used precisely like `write` with the exact same + /// preconditions (must use check-write first), but instead of + /// passing a list of bytes, you simply pass the number of zero-bytes + /// that should be written. + write-zeroes: func(len: u64) -> result<_, stream-error>; + } + } +} + +package wasi:random@0.2.0 { + /// The insecure-seed interface for seeding hash-map DoS resistance. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + interface insecure-seed { + /// Return a 128-bit value that may contain a pseudo-random value. + /// + /// The returned value is not required to be computed from a CSPRNG, and may + /// even be entirely deterministic. Host implementations are encouraged to + /// provide pseudo-random values to any program exposed to + /// attacker-controlled content, to enable DoS protection built into many + /// languages' hash-map implementations. + /// + /// This function is intended to only be called once, by a source language + /// to initialize Denial Of Service (DoS) protection in its hash-map + /// implementation. + /// + /// # Expected future evolution + /// + /// This will likely be changed to a value import, to prevent it from being + /// called multiple times and potentially used for purposes other than DoS + /// protection. + insecure-seed: func() -> tuple; + } + + /// The insecure interface for insecure pseudo-random numbers. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + interface insecure { + /// Return `len` insecure pseudo-random bytes. + /// + /// This function is not cryptographically secure. Do not use it for + /// anything related to security. + /// + /// There are no requirements on the values of the returned bytes, however + /// implementations are encouraged to return evenly distributed values with + /// a long period. + get-insecure-random-bytes: func(len: u64) -> list; + + /// Return an insecure pseudo-random `u64` value. + /// + /// This function returns the same type of pseudo-random data as + /// `get-insecure-random-bytes`, represented as a `u64`. + get-insecure-random-u64: func() -> u64; + } + + /// WASI Random is a random data API. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + interface random { + /// Return `len` cryptographically-secure random or pseudo-random bytes. + /// + /// This function must produce data at least as cryptographically secure and + /// fast as an adequately seeded cryptographically-secure pseudo-random + /// number generator (CSPRNG). It must not block, from the perspective of + /// the calling program, under any circumstances, including on the first + /// request and on requests for numbers of bytes. The returned data must + /// always be unpredictable. + /// + /// This function must always return fresh data. Deterministic environments + /// must omit this function, rather than implementing it with deterministic + /// data. + get-random-bytes: func(len: u64) -> list; + + /// Return a cryptographically-secure random or pseudo-random `u64` value. + /// + /// This function returns the same type of data as `get-random-bytes`, + /// represented as a `u64`. + get-random-u64: func() -> u64; + } +} diff --git a/testdata/wasi/cli-command.wit.json b/testdata/wasi/cli-command.wit.json new file mode 100644 index 00000000..870584ab --- /dev/null +++ b/testdata/wasi/cli-command.wit.json @@ -0,0 +1,5645 @@ +{ + "worlds": [ + { + "name": "command", + "imports": { + "interface-17": { + "interface": { + "id": 17 + } + }, + "interface-18": { + "interface": { + "id": 18 + } + }, + "interface-0": { + "interface": { + "id": 0 + } + }, + "interface-1": { + "interface": { + "id": 1 + } + }, + "interface-2": { + "interface": { + "id": 2 + } + }, + "interface-20": { + "interface": { + "id": 20 + } + }, + "interface-21": { + "interface": { + "id": 21 + } + }, + "interface-22": { + "interface": { + "id": 22 + } + }, + "interface-23": { + "interface": { + "id": 23 + } + }, + "interface-24": { + "interface": { + "id": 24 + } + }, + "interface-25": { + "interface": { + "id": 25 + } + }, + "interface-26": { + "interface": { + "id": 26 + } + }, + "interface-27": { + "interface": { + "id": 27 + } + }, + "interface-3": { + "interface": { + "id": 3 + } + }, + "interface-4": { + "interface": { + "id": 4 + } + }, + "interface-5": { + "interface": { + "id": 5 + } + }, + "interface-6": { + "interface": { + "id": 6 + } + }, + "interface-7": { + "interface": { + "id": 7 + } + }, + "interface-8": { + "interface": { + "id": 8 + } + }, + "interface-12": { + "interface": { + "id": 12 + } + }, + "interface-13": { + "interface": { + "id": 13 + } + }, + "interface-10": { + "interface": { + "id": 10 + } + }, + "interface-11": { + "interface": { + "id": 11 + } + }, + "interface-9": { + "interface": { + "id": 9 + } + }, + "interface-16": { + "interface": { + "id": 16 + } + }, + "interface-15": { + "interface": { + "id": 15 + } + }, + "interface-14": { + "interface": { + "id": 14 + } + } + }, + "exports": { + "interface-19": { + "interface": { + "id": 19 + } + } + }, + "package": 5 + } + ], + "interfaces": [ + { + "name": "error", + "types": { + "error": 0 + }, + "functions": { + "[method]error.to-debug-string": { + "name": "[method]error.to-debug-string", + "kind": { + "method": 0 + }, + "params": [ + { + "name": "self", + "type": 1 + } + ], + "results": [ + { + "type": "string" + } + ], + "docs": { + "contents": "Returns a string that is suitable to assist humans in debugging\nthis error.\n\nWARNING: The returned string should not be consumed mechanically!\nIt may change across platforms, hosts, or other implementation\ndetails. Parsing this string is a major platform-compatibility\nhazard." + } + } + }, + "package": 0 + }, + { + "name": "poll", + "types": { + "pollable": 2 + }, + "functions": { + "[method]pollable.block": { + "name": "[method]pollable.block", + "kind": { + "method": 2 + }, + "params": [ + { + "name": "self", + "type": 3 + } + ], + "results": [], + "docs": { + "contents": "`block` returns immediately if the pollable is ready, and otherwise\nblocks until ready.\n\nThis function is equivalent to calling `poll.poll` on a list\ncontaining only this pollable." + } + }, + "[method]pollable.ready": { + "name": "[method]pollable.ready", + "kind": { + "method": 2 + }, + "params": [ + { + "name": "self", + "type": 3 + } + ], + "results": [ + { + "type": "bool" + } + ], + "docs": { + "contents": "Return the readiness of a pollable. This function never blocks.\n\nReturns `true` when the pollable is ready, and `false` otherwise." + } + }, + "poll": { + "name": "poll", + "kind": "freestanding", + "params": [ + { + "name": "in", + "type": 4 + } + ], + "results": [ + { + "type": 5 + } + ], + "docs": { + "contents": "Poll for completion on a set of pollables.\n\nThis function takes a list of pollables, which identify I/O sources of\ninterest, and waits until one or more of the events is ready for I/O.\n\nThe result `list` contains one or more indices of handles in the\nargument list that is ready for I/O.\n\nIf the list contains more elements than can be indexed with a `u32`\nvalue, this function traps.\n\nA timeout can be implemented by adding a pollable from the\nwasi-clocks API to the list.\n\nThis function does not return a `result`; polling in itself does not\ndo any I/O so it doesn't fail. If any of the I/O sources identified by\nthe pollables has an error, it is indicated by marking the source as\nbeing reaedy for I/O." + } + } + }, + "docs": { + "contents": "A poll API intended to let users wait for I/O events on multiple handles\nat once." + }, + "package": 0 + }, + { + "name": "streams", + "types": { + "error": 6, + "pollable": 7, + "stream-error": 9, + "input-stream": 10, + "output-stream": 11 + }, + "functions": { + "[method]input-stream.blocking-read": { + "name": "[method]input-stream.blocking-read", + "kind": { + "method": 10 + }, + "params": [ + { + "name": "self", + "type": 12 + }, + { + "name": "len", + "type": "u64" + } + ], + "results": [ + { + "type": 14 + } + ], + "docs": { + "contents": "Read bytes from a stream, after blocking until at least one byte can\nbe read. Except for blocking, behavior is identical to `read`." + } + }, + "[method]input-stream.blocking-skip": { + "name": "[method]input-stream.blocking-skip", + "kind": { + "method": 10 + }, + "params": [ + { + "name": "self", + "type": 12 + }, + { + "name": "len", + "type": "u64" + } + ], + "results": [ + { + "type": 15 + } + ], + "docs": { + "contents": "Skip bytes from a stream, after blocking until at least one byte\ncan be skipped. Except for blocking behavior, identical to `skip`." + } + }, + "[method]input-stream.read": { + "name": "[method]input-stream.read", + "kind": { + "method": 10 + }, + "params": [ + { + "name": "self", + "type": 12 + }, + { + "name": "len", + "type": "u64" + } + ], + "results": [ + { + "type": 14 + } + ], + "docs": { + "contents": "Perform a non-blocking read from the stream.\n\nWhen the source of a `read` is binary data, the bytes from the source\nare returned verbatim. When the source of a `read` is known to the\nimplementation to be text, bytes containing the UTF-8 encoding of the\ntext are returned.\n\nThis function returns a list of bytes containing the read data,\nwhen successful. The returned list will contain up to `len` bytes;\nit may return fewer than requested, but not more. The list is\nempty when no bytes are available for reading at this time. The\npollable given by `subscribe` will be ready when more bytes are\navailable.\n\nThis function fails with a `stream-error` when the operation\nencounters an error, giving `last-operation-failed`, or when the\nstream is closed, giving `closed`.\n\nWhen the caller gives a `len` of 0, it represents a request to\nread 0 bytes. If the stream is still open, this call should\nsucceed and return an empty list, or otherwise fail with `closed`.\n\nThe `len` parameter is a `u64`, which could represent a list of u8 which\nis not possible to allocate in wasm32, or not desirable to allocate as\nas a return value by the callee. The callee may return a list of bytes\nless than `len` in size while more bytes are available for reading." + } + }, + "[method]input-stream.skip": { + "name": "[method]input-stream.skip", + "kind": { + "method": 10 + }, + "params": [ + { + "name": "self", + "type": 12 + }, + { + "name": "len", + "type": "u64" + } + ], + "results": [ + { + "type": 15 + } + ], + "docs": { + "contents": "Skip bytes from a stream. Returns number of bytes skipped.\n\nBehaves identical to `read`, except instead of returning a list\nof bytes, returns the number of bytes consumed from the stream." + } + }, + "[method]input-stream.subscribe": { + "name": "[method]input-stream.subscribe", + "kind": { + "method": 10 + }, + "params": [ + { + "name": "self", + "type": 12 + } + ], + "results": [ + { + "type": 18 + } + ], + "docs": { + "contents": "Create a `pollable` which will resolve once either the specified stream\nhas bytes available to read or the other end of the stream has been\nclosed.\nThe created `pollable` is a child resource of the `input-stream`.\nImplementations may trap if the `input-stream` is dropped before\nall derived `pollable`s created with this function are dropped." + } + }, + "[method]output-stream.blocking-flush": { + "name": "[method]output-stream.blocking-flush", + "kind": { + "method": 11 + }, + "params": [ + { + "name": "self", + "type": 16 + } + ], + "results": [ + { + "type": 17 + } + ], + "docs": { + "contents": "Request to flush buffered output, and block until flush completes\nand stream is ready for writing again." + } + }, + "[method]output-stream.blocking-splice": { + "name": "[method]output-stream.blocking-splice", + "kind": { + "method": 11 + }, + "params": [ + { + "name": "self", + "type": 16 + }, + { + "name": "src", + "type": 12 + }, + { + "name": "len", + "type": "u64" + } + ], + "results": [ + { + "type": 15 + } + ], + "docs": { + "contents": "Read from one stream and write to another, with blocking.\n\nThis is similar to `splice`, except that it blocks until the\n`output-stream` is ready for writing, and the `input-stream`\nis ready for reading, before performing the `splice`." + } + }, + "[method]output-stream.blocking-write-and-flush": { + "name": "[method]output-stream.blocking-write-and-flush", + "kind": { + "method": 11 + }, + "params": [ + { + "name": "self", + "type": 16 + }, + { + "name": "contents", + "type": 13 + } + ], + "results": [ + { + "type": 17 + } + ], + "docs": { + "contents": "Perform a write of up to 4096 bytes, and then flush the stream. Block\nuntil all of these operations are complete, or an error occurs.\n\nThis is a convenience wrapper around the use of `check-write`,\n`subscribe`, `write`, and `flush`, and is implemented with the\nfollowing pseudo-code:\n\n```text\nlet pollable = this.subscribe();\nwhile !contents.is_empty() {\n// Wait for the stream to become writable\npollable.block();\nlet Ok(n) = this.check-write(); // eliding error handling\nlet len = min(n, contents.len());\nlet (chunk, rest) = contents.split_at(len);\nthis.write(chunk ); // eliding error handling\ncontents = rest;\n}\nthis.flush();\n// Wait for completion of `flush`\npollable.block();\n// Check for any errors that arose during `flush`\nlet _ = this.check-write(); // eliding error handling\n```" + } + }, + "[method]output-stream.blocking-write-zeroes-and-flush": { + "name": "[method]output-stream.blocking-write-zeroes-and-flush", + "kind": { + "method": 11 + }, + "params": [ + { + "name": "self", + "type": 16 + }, + { + "name": "len", + "type": "u64" + } + ], + "results": [ + { + "type": 17 + } + ], + "docs": { + "contents": "Perform a write of up to 4096 zeroes, and then flush the stream.\nBlock until all of these operations are complete, or an error\noccurs.\n\nThis is a convenience wrapper around the use of `check-write`,\n`subscribe`, `write-zeroes`, and `flush`, and is implemented with\nthe following pseudo-code:\n\n```text\nlet pollable = this.subscribe();\nwhile num_zeroes != 0 {\n// Wait for the stream to become writable\npollable.block();\nlet Ok(n) = this.check-write(); // eliding error handling\nlet len = min(n, num_zeroes);\nthis.write-zeroes(len); // eliding error handling\nnum_zeroes -= len;\n}\nthis.flush();\n// Wait for completion of `flush`\npollable.block();\n// Check for any errors that arose during `flush`\nlet _ = this.check-write(); // eliding error handling\n```" + } + }, + "[method]output-stream.check-write": { + "name": "[method]output-stream.check-write", + "kind": { + "method": 11 + }, + "params": [ + { + "name": "self", + "type": 16 + } + ], + "results": [ + { + "type": 15 + } + ], + "docs": { + "contents": "Check readiness for writing. This function never blocks.\n\nReturns the number of bytes permitted for the next call to `write`,\nor an error. Calling `write` with more bytes than this function has\npermitted will trap.\n\nWhen this function returns 0 bytes, the `subscribe` pollable will\nbecome ready when this function will report at least 1 byte, or an\nerror." + } + }, + "[method]output-stream.flush": { + "name": "[method]output-stream.flush", + "kind": { + "method": 11 + }, + "params": [ + { + "name": "self", + "type": 16 + } + ], + "results": [ + { + "type": 17 + } + ], + "docs": { + "contents": "Request to flush buffered output. This function never blocks.\n\nThis tells the output-stream that the caller intends any buffered\noutput to be flushed. the output which is expected to be flushed\nis all that has been passed to `write` prior to this call.\n\nUpon calling this function, the `output-stream` will not accept any\nwrites (`check-write` will return `ok(0)`) until the flush has\ncompleted. The `subscribe` pollable will become ready when the\nflush has completed and the stream can accept more writes." + } + }, + "[method]output-stream.splice": { + "name": "[method]output-stream.splice", + "kind": { + "method": 11 + }, + "params": [ + { + "name": "self", + "type": 16 + }, + { + "name": "src", + "type": 12 + }, + { + "name": "len", + "type": "u64" + } + ], + "results": [ + { + "type": 15 + } + ], + "docs": { + "contents": "Read from one stream and write to another.\n\nThe behavior of splice is equivelant to:\n1. calling `check-write` on the `output-stream`\n2. calling `read` on the `input-stream` with the smaller of the\n`check-write` permitted length and the `len` provided to `splice`\n3. calling `write` on the `output-stream` with that read data.\n\nAny error reported by the call to `check-write`, `read`, or\n`write` ends the splice and reports that error.\n\nThis function returns the number of bytes transferred; it may be less\nthan `len`." + } + }, + "[method]output-stream.subscribe": { + "name": "[method]output-stream.subscribe", + "kind": { + "method": 11 + }, + "params": [ + { + "name": "self", + "type": 16 + } + ], + "results": [ + { + "type": 18 + } + ], + "docs": { + "contents": "Create a `pollable` which will resolve once the output-stream\nis ready for more writing, or an error has occured. When this\npollable is ready, `check-write` will return `ok(n)` with n>0, or an\nerror.\n\nIf the stream is closed, this pollable is always ready immediately.\n\nThe created `pollable` is a child resource of the `output-stream`.\nImplementations may trap if the `output-stream` is dropped before\nall derived `pollable`s created with this function are dropped." + } + }, + "[method]output-stream.write": { + "name": "[method]output-stream.write", + "kind": { + "method": 11 + }, + "params": [ + { + "name": "self", + "type": 16 + }, + { + "name": "contents", + "type": 13 + } + ], + "results": [ + { + "type": 17 + } + ], + "docs": { + "contents": "Perform a write. This function never blocks.\n\nWhen the destination of a `write` is binary data, the bytes from\n`contents` are written verbatim. When the destination of a `write` is\nknown to the implementation to be text, the bytes of `contents` are\ntranscoded from UTF-8 into the encoding of the destination and then\nwritten.\n\nPrecondition: check-write gave permit of Ok(n) and contents has a\nlength of less than or equal to n. Otherwise, this function will trap.\n\nreturns Err(closed) without writing if the stream has closed since\nthe last call to check-write provided a permit." + } + }, + "[method]output-stream.write-zeroes": { + "name": "[method]output-stream.write-zeroes", + "kind": { + "method": 11 + }, + "params": [ + { + "name": "self", + "type": 16 + }, + { + "name": "len", + "type": "u64" + } + ], + "results": [ + { + "type": 17 + } + ], + "docs": { + "contents": "Write zeroes to a stream.\n\nThis should be used precisely like `write` with the exact same\npreconditions (must use check-write first), but instead of\npassing a list of bytes, you simply pass the number of zero-bytes\nthat should be written." + } + } + }, + "docs": { + "contents": "WASI I/O is an I/O abstraction API which is currently focused on providing\nstream types.\n\nIn the future, the component model is expected to add built-in stream types;\nwhen it does, they are expected to subsume this API." + }, + "package": 0 + }, + { + "name": "monotonic-clock", + "types": { + "pollable": 19, + "instant": 20, + "duration": 21 + }, + "functions": { + "now": { + "name": "now", + "kind": "freestanding", + "params": [], + "results": [ + { + "type": 20 + } + ], + "docs": { + "contents": "Read the current value of the clock.\n\nThe clock is monotonic, therefore calling this function repeatedly will\nproduce a sequence of non-decreasing values." + } + }, + "resolution": { + "name": "resolution", + "kind": "freestanding", + "params": [], + "results": [ + { + "type": 21 + } + ], + "docs": { + "contents": "Query the resolution of the clock. Returns the duration of time\ncorresponding to a clock tick." + } + }, + "subscribe-instant": { + "name": "subscribe-instant", + "kind": "freestanding", + "params": [ + { + "name": "when", + "type": 20 + } + ], + "results": [ + { + "type": 23 + } + ], + "docs": { + "contents": "Create a `pollable` which will resolve once the specified instant\noccured." + } + }, + "subscribe-duration": { + "name": "subscribe-duration", + "kind": "freestanding", + "params": [ + { + "name": "when", + "type": 21 + } + ], + "results": [ + { + "type": 23 + } + ], + "docs": { + "contents": "Create a `pollable` which will resolve once the given duration has\nelapsed, starting at the time at which this function was called.\noccured." + } + } + }, + "docs": { + "contents": "WASI Monotonic Clock is a clock API intended to let users measure elapsed\ntime.\n\nIt is intended to be portable at least between Unix-family platforms and\nWindows.\n\nA monotonic clock is a clock which has an unspecified initial value, and\nsuccessive reads of the clock will produce non-decreasing values.\n\nIt is intended for measuring elapsed time." + }, + "package": 1 + }, + { + "name": "wall-clock", + "types": { + "datetime": 22 + }, + "functions": { + "now": { + "name": "now", + "kind": "freestanding", + "params": [], + "results": [ + { + "type": 22 + } + ], + "docs": { + "contents": "Read the current value of the clock.\n\nThis clock is not monotonic, therefore calling this function repeatedly\nwill not necessarily produce a sequence of non-decreasing values.\n\nThe returned timestamps represent the number of seconds since\n1970-01-01T00:00:00Z, also known as [POSIX's Seconds Since the Epoch],\nalso known as [Unix Time].\n\nThe nanoseconds field of the output is always less than 1000000000.\n\n[POSIX's Seconds Since the Epoch]: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html#tag_21_04_16\n[Unix Time]: https://en.wikipedia.org/wiki/Unix_time" + } + }, + "resolution": { + "name": "resolution", + "kind": "freestanding", + "params": [], + "results": [ + { + "type": 22 + } + ], + "docs": { + "contents": "Query the resolution of the clock.\n\nThe nanoseconds field of the output is always less than 1000000000." + } + } + }, + "docs": { + "contents": "WASI Wall Clock is a clock API intended to let users query the current\ntime. The name \"wall\" makes an analogy to a \"clock on the wall\", which\nis not necessarily monotonic as it may be reset.\n\nIt is intended to be portable at least between Unix-family platforms and\nWindows.\n\nA wall clock is a clock which measures the date and time according to\nsome external reference.\n\nExternal references may be reset, so this clock is not necessarily\nmonotonic, making it unsuitable for measuring elapsed time.\n\nIt is intended for reporting the current date and time for humans." + }, + "package": 1 + }, + { + "name": "types", + "types": { + "input-stream": 24, + "output-stream": 25, + "error": 26, + "datetime": 27, + "filesize": 28, + "descriptor-type": 29, + "descriptor-flags": 30, + "path-flags": 31, + "open-flags": 32, + "link-count": 33, + "descriptor-stat": 35, + "new-timestamp": 36, + "directory-entry": 37, + "error-code": 38, + "advice": 39, + "metadata-hash-value": 40, + "descriptor": 41, + "directory-entry-stream": 42 + }, + "functions": { + "[method]descriptor.advise": { + "name": "[method]descriptor.advise", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + }, + { + "name": "offset", + "type": 28 + }, + { + "name": "length", + "type": 28 + }, + { + "name": "advice", + "type": 39 + } + ], + "results": [ + { + "type": 44 + } + ], + "docs": { + "contents": "Provide file advisory information on a descriptor.\n\nThis is similar to `posix_fadvise` in POSIX." + } + }, + "[method]descriptor.append-via-stream": { + "name": "[method]descriptor.append-via-stream", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + } + ], + "results": [ + { + "type": 46 + } + ], + "docs": { + "contents": "Return a stream for appending to a file, if available.\n\nMay fail with an error-code describing why the file cannot be appended.\n\nNote: This allows using `write-stream`, which is similar to `write` with\n`O_APPEND` in in POSIX." + } + }, + "[method]descriptor.create-directory-at": { + "name": "[method]descriptor.create-directory-at", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + }, + { + "name": "path", + "type": "string" + } + ], + "results": [ + { + "type": 44 + } + ], + "docs": { + "contents": "Create a directory.\n\nNote: This is similar to `mkdirat` in POSIX." + } + }, + "[method]descriptor.get-flags": { + "name": "[method]descriptor.get-flags", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + } + ], + "results": [ + { + "type": 47 + } + ], + "docs": { + "contents": "Get flags associated with a descriptor.\n\nNote: This returns similar flags to `fcntl(fd, F_GETFL)` in POSIX.\n\nNote: This returns the value that was the `fs_flags` value returned\nfrom `fdstat_get` in earlier versions of WASI." + } + }, + "[method]descriptor.get-type": { + "name": "[method]descriptor.get-type", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + } + ], + "results": [ + { + "type": 48 + } + ], + "docs": { + "contents": "Get the dynamic type of a descriptor.\n\nNote: This returns the same value as the `type` field of the `fd-stat`\nreturned by `stat`, `stat-at` and similar.\n\nNote: This returns similar flags to the `st_mode & S_IFMT` value provided\nby `fstat` in POSIX.\n\nNote: This returns the value that was the `fs_filetype` value returned\nfrom `fdstat_get` in earlier versions of WASI." + } + }, + "[method]descriptor.is-same-object": { + "name": "[method]descriptor.is-same-object", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + }, + { + "name": "other", + "type": 43 + } + ], + "results": [ + { + "type": "bool" + } + ], + "docs": { + "contents": "Test whether two descriptors refer to the same filesystem object.\n\nIn POSIX, this corresponds to testing whether the two descriptors have the\nsame device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers.\nwasi-filesystem does not expose device and inode numbers, so this function\nmay be used instead." + } + }, + "[method]descriptor.link-at": { + "name": "[method]descriptor.link-at", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + }, + { + "name": "old-path-flags", + "type": 31 + }, + { + "name": "old-path", + "type": "string" + }, + { + "name": "new-descriptor", + "type": 43 + }, + { + "name": "new-path", + "type": "string" + } + ], + "results": [ + { + "type": 44 + } + ], + "docs": { + "contents": "Create a hard link.\n\nNote: This is similar to `linkat` in POSIX." + } + }, + "[method]descriptor.metadata-hash": { + "name": "[method]descriptor.metadata-hash", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + } + ], + "results": [ + { + "type": 49 + } + ], + "docs": { + "contents": "Return a hash of the metadata associated with a filesystem object referred\nto by a descriptor.\n\nThis returns a hash of the last-modification timestamp and file size, and\nmay also include the inode number, device number, birth timestamp, and\nother metadata fields that may change when the file is modified or\nreplaced. It may also include a secret value chosen by the\nimplementation and not otherwise exposed.\n\nImplementations are encourated to provide the following properties:\n\n- If the file is not modified or replaced, the computed hash value should\nusually not change.\n- If the object is modified or replaced, the computed hash value should\nusually change.\n- The inputs to the hash should not be easily computable from the\ncomputed hash.\n\nHowever, none of these is required." + } + }, + "[method]descriptor.metadata-hash-at": { + "name": "[method]descriptor.metadata-hash-at", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + }, + { + "name": "path-flags", + "type": 31 + }, + { + "name": "path", + "type": "string" + } + ], + "results": [ + { + "type": 49 + } + ], + "docs": { + "contents": "Return a hash of the metadata associated with a filesystem object referred\nto by a directory descriptor and a relative path.\n\nThis performs the same hash computation as `metadata-hash`." + } + }, + "[method]descriptor.open-at": { + "name": "[method]descriptor.open-at", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + }, + { + "name": "path-flags", + "type": 31 + }, + { + "name": "path", + "type": "string" + }, + { + "name": "open-flags", + "type": 32 + }, + { + "name": "flags", + "type": 30 + } + ], + "results": [ + { + "type": 51 + } + ], + "docs": { + "contents": "Open a file or directory.\n\nThe returned descriptor is not guaranteed to be the lowest-numbered\ndescriptor not currently open/ it is randomized to prevent applications\nfrom depending on making assumptions about indexes, since this is\nerror-prone in multi-threaded contexts. The returned descriptor is\nguaranteed to be less than 2**31.\n\nIf `flags` contains `descriptor-flags::mutate-directory`, and the base\ndescriptor doesn't have `descriptor-flags::mutate-directory` set,\n`open-at` fails with `error-code::read-only`.\n\nIf `flags` contains `write` or `mutate-directory`, or `open-flags`\ncontains `truncate` or `create`, and the base descriptor doesn't have\n`descriptor-flags::mutate-directory` set, `open-at` fails with\n`error-code::read-only`.\n\nNote: This is similar to `openat` in POSIX." + } + }, + "[method]descriptor.read": { + "name": "[method]descriptor.read", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + }, + { + "name": "length", + "type": 28 + }, + { + "name": "offset", + "type": 28 + } + ], + "results": [ + { + "type": 54 + } + ], + "docs": { + "contents": "Read from a descriptor, without using and updating the descriptor's offset.\n\nThis function returns a list of bytes containing the data that was\nread, along with a bool which, when true, indicates that the end of the\nfile was reached. The returned list will contain up to `length` bytes; it\nmay return fewer than requested, if the end of the file is reached or\nif the I/O operation is interrupted.\n\nIn the future, this may change to return a `stream`.\n\nNote: This is similar to `pread` in POSIX." + } + }, + "[method]descriptor.read-directory": { + "name": "[method]descriptor.read-directory", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + } + ], + "results": [ + { + "type": 56 + } + ], + "docs": { + "contents": "Read directory entries from a directory.\n\nOn filesystems where directories contain entries referring to themselves\nand their parents, often named `.` and `..` respectively, these entries\nare omitted.\n\nThis always returns a new stream which starts at the beginning of the\ndirectory. Multiple streams may be active on the same directory, and they\ndo not interfere with each other." + } + }, + "[method]descriptor.read-via-stream": { + "name": "[method]descriptor.read-via-stream", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + }, + { + "name": "offset", + "type": 28 + } + ], + "results": [ + { + "type": 58 + } + ], + "docs": { + "contents": "Return a stream for reading from a file, if available.\n\nMay fail with an error-code describing why the file cannot be read.\n\nMultiple read, write, and append streams may be active on the same open\nfile and they do not interfere with each other.\n\nNote: This allows using `read-stream`, which is similar to `read` in POSIX." + } + }, + "[method]descriptor.readlink-at": { + "name": "[method]descriptor.readlink-at", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + }, + { + "name": "path", + "type": "string" + } + ], + "results": [ + { + "type": 59 + } + ], + "docs": { + "contents": "Read the contents of a symbolic link.\n\nIf the contents contain an absolute or rooted path in the underlying\nfilesystem, this function fails with `error-code::not-permitted`.\n\nNote: This is similar to `readlinkat` in POSIX." + } + }, + "[method]descriptor.remove-directory-at": { + "name": "[method]descriptor.remove-directory-at", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + }, + { + "name": "path", + "type": "string" + } + ], + "results": [ + { + "type": 44 + } + ], + "docs": { + "contents": "Remove a directory.\n\nReturn `error-code::not-empty` if the directory is not empty.\n\nNote: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX." + } + }, + "[method]descriptor.rename-at": { + "name": "[method]descriptor.rename-at", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + }, + { + "name": "old-path", + "type": "string" + }, + { + "name": "new-descriptor", + "type": 43 + }, + { + "name": "new-path", + "type": "string" + } + ], + "results": [ + { + "type": 44 + } + ], + "docs": { + "contents": "Rename a filesystem object.\n\nNote: This is similar to `renameat` in POSIX." + } + }, + "[method]descriptor.set-size": { + "name": "[method]descriptor.set-size", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + }, + { + "name": "size", + "type": 28 + } + ], + "results": [ + { + "type": 44 + } + ], + "docs": { + "contents": "Adjust the size of an open file. If this increases the file's size, the\nextra bytes are filled with zeros.\n\nNote: This was called `fd_filestat_set_size` in earlier versions of WASI." + } + }, + "[method]descriptor.set-times": { + "name": "[method]descriptor.set-times", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + }, + { + "name": "data-access-timestamp", + "type": 36 + }, + { + "name": "data-modification-timestamp", + "type": 36 + } + ], + "results": [ + { + "type": 44 + } + ], + "docs": { + "contents": "Adjust the timestamps of an open file or directory.\n\nNote: This is similar to `futimens` in POSIX.\n\nNote: This was called `fd_filestat_set_times` in earlier versions of WASI." + } + }, + "[method]descriptor.set-times-at": { + "name": "[method]descriptor.set-times-at", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + }, + { + "name": "path-flags", + "type": 31 + }, + { + "name": "path", + "type": "string" + }, + { + "name": "data-access-timestamp", + "type": 36 + }, + { + "name": "data-modification-timestamp", + "type": 36 + } + ], + "results": [ + { + "type": 44 + } + ], + "docs": { + "contents": "Adjust the timestamps of a file or directory.\n\nNote: This is similar to `utimensat` in POSIX.\n\nNote: This was called `path_filestat_set_times` in earlier versions of\nWASI." + } + }, + "[method]descriptor.stat": { + "name": "[method]descriptor.stat", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + } + ], + "results": [ + { + "type": 60 + } + ], + "docs": { + "contents": "Return the attributes of an open file or directory.\n\nNote: This is similar to `fstat` in POSIX, except that it does not return\ndevice and inode information. For testing whether two descriptors refer to\nthe same underlying filesystem object, use `is-same-object`. To obtain\nadditional data that can be used do determine whether a file has been\nmodified, use `metadata-hash`.\n\nNote: This was called `fd_filestat_get` in earlier versions of WASI." + } + }, + "[method]descriptor.stat-at": { + "name": "[method]descriptor.stat-at", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + }, + { + "name": "path-flags", + "type": 31 + }, + { + "name": "path", + "type": "string" + } + ], + "results": [ + { + "type": 60 + } + ], + "docs": { + "contents": "Return the attributes of a file or directory.\n\nNote: This is similar to `fstatat` in POSIX, except that it does not\nreturn device and inode information. See the `stat` description for a\ndiscussion of alternatives.\n\nNote: This was called `path_filestat_get` in earlier versions of WASI." + } + }, + "[method]descriptor.symlink-at": { + "name": "[method]descriptor.symlink-at", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + }, + { + "name": "old-path", + "type": "string" + }, + { + "name": "new-path", + "type": "string" + } + ], + "results": [ + { + "type": 44 + } + ], + "docs": { + "contents": "Create a symbolic link (also known as a \"symlink\").\n\nIf `old-path` starts with `/`, the function fails with\n`error-code::not-permitted`.\n\nNote: This is similar to `symlinkat` in POSIX." + } + }, + "[method]descriptor.sync": { + "name": "[method]descriptor.sync", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + } + ], + "results": [ + { + "type": 44 + } + ], + "docs": { + "contents": "Synchronize the data and metadata of a file to disk.\n\nThis function succeeds with no effect if the file descriptor is not\nopened for writing.\n\nNote: This is similar to `fsync` in POSIX." + } + }, + "[method]descriptor.sync-data": { + "name": "[method]descriptor.sync-data", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + } + ], + "results": [ + { + "type": 44 + } + ], + "docs": { + "contents": "Synchronize the data of a file to disk.\n\nThis function succeeds with no effect if the file descriptor is not\nopened for writing.\n\nNote: This is similar to `fdatasync` in POSIX." + } + }, + "[method]descriptor.unlink-file-at": { + "name": "[method]descriptor.unlink-file-at", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + }, + { + "name": "path", + "type": "string" + } + ], + "results": [ + { + "type": 44 + } + ], + "docs": { + "contents": "Unlink a filesystem object that is not a directory.\n\nReturn `error-code::is-directory` if the path refers to a directory.\nNote: This is similar to `unlinkat(fd, path, 0)` in POSIX." + } + }, + "[method]descriptor.write": { + "name": "[method]descriptor.write", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + }, + { + "name": "buffer", + "type": 52 + }, + { + "name": "offset", + "type": 28 + } + ], + "results": [ + { + "type": 61 + } + ], + "docs": { + "contents": "Write to a descriptor, without using and updating the descriptor's offset.\n\nIt is valid to write past the end of a file; the file is extended to the\nextent of the write, with bytes between the previous end and the start of\nthe write set to zero.\n\nIn the future, this may change to take a `stream`.\n\nNote: This is similar to `pwrite` in POSIX." + } + }, + "[method]descriptor.write-via-stream": { + "name": "[method]descriptor.write-via-stream", + "kind": { + "method": 41 + }, + "params": [ + { + "name": "self", + "type": 43 + }, + { + "name": "offset", + "type": 28 + } + ], + "results": [ + { + "type": 46 + } + ], + "docs": { + "contents": "Return a stream for writing to a file, if available.\n\nMay fail with an error-code describing why the file cannot be written.\n\nNote: This allows using `write-stream`, which is similar to `write` in\nPOSIX." + } + }, + "[method]directory-entry-stream.read-directory-entry": { + "name": "[method]directory-entry-stream.read-directory-entry", + "kind": { + "method": 42 + }, + "params": [ + { + "name": "self", + "type": 62 + } + ], + "results": [ + { + "type": 64 + } + ], + "docs": { + "contents": "Read a single directory entry from a `directory-entry-stream`." + } + }, + "filesystem-error-code": { + "name": "filesystem-error-code", + "kind": "freestanding", + "params": [ + { + "name": "err", + "type": 65 + } + ], + "results": [ + { + "type": 66 + } + ], + "docs": { + "contents": "Attempts to extract a filesystem-related `error-code` from the stream\n`error` provided.\n\nStream operations which return `stream-error::last-operation-failed`\nhave a payload with more information about the operation that failed.\nThis payload can be passed through to this function to see if there's\nfilesystem-related information about the error to return.\n\nNote that this function is fallible because not all stream-related\nerrors are filesystem-related errors." + } + } + }, + "docs": { + "contents": "WASI filesystem is a filesystem API primarily intended to let users run WASI\nprograms that access their files on their existing filesystems, without\nsignificant overhead.\n\nIt is intended to be roughly portable between Unix-family platforms and\nWindows, though it does not hide many of the major differences.\n\nPaths are passed as interface-type `string`s, meaning they must consist of\na sequence of Unicode Scalar Values (USVs). Some filesystems may contain\npaths which are not accessible by this API.\n\nThe directory separator in WASI is always the forward-slash (`/`).\n\nAll paths in WASI are relative paths, and are interpreted relative to a\n`descriptor` referring to a base directory. If a `path` argument to any WASI\nfunction starts with `/`, or if any step of resolving a `path`, including\n`..` and symbolic link steps, reaches a directory outside of the base\ndirectory, or reaches a symlink to an absolute or rooted path in the\nunderlying filesystem, the function fails with `error-code::not-permitted`.\n\nFor more information about WASI path resolution and sandboxing, see\n[WASI filesystem path resolution].\n\n[WASI filesystem path resolution]: https://github.com/WebAssembly/wasi-filesystem/blob/main/path-resolution.md" + }, + "package": 2 + }, + { + "name": "preopens", + "types": { + "descriptor": 67 + }, + "functions": { + "get-directories": { + "name": "get-directories", + "kind": "freestanding", + "params": [], + "results": [ + { + "type": 70 + } + ], + "docs": { + "contents": "Return the set of preopened directories, and their path." + } + } + }, + "package": 2 + }, + { + "name": "network", + "types": { + "network": 71, + "error-code": 72, + "ip-address-family": 73, + "ipv4-address": 74, + "ipv6-address": 75, + "ip-address": 76, + "ipv4-socket-address": 77, + "ipv6-socket-address": 78, + "ip-socket-address": 79 + }, + "functions": {}, + "package": 3 + }, + { + "name": "instance-network", + "types": { + "network": 80 + }, + "functions": { + "instance-network": { + "name": "instance-network", + "kind": "freestanding", + "params": [], + "results": [ + { + "type": 157 + } + ], + "docs": { + "contents": "Get a handle to the default network." + } + } + }, + "docs": { + "contents": "This interface provides a value-export of the default network handle.." + }, + "package": 3 + }, + { + "name": "ip-name-lookup", + "types": { + "pollable": 81, + "network": 82, + "error-code": 83, + "ip-address": 84, + "resolve-address-stream": 85 + }, + "functions": { + "[method]resolve-address-stream.resolve-next-address": { + "name": "[method]resolve-address-stream.resolve-next-address", + "kind": { + "method": 85 + }, + "params": [ + { + "name": "self", + "type": 86 + } + ], + "results": [ + { + "type": 88 + } + ], + "docs": { + "contents": "Returns the next address from the resolver.\n\nThis function should be called multiple times. On each call, it will\nreturn the next address in connection order preference. If all\naddresses have been exhausted, this function returns `none`.\n\nThis function never returns IPv4-mapped IPv6 addresses.\n\n# Typical errors\n- `name-unresolvable`: Name does not exist or has no suitable associated\nIP addresses. (EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY)\n- `temporary-resolver-failure`: A temporary failure in name resolution occurred.\n(EAI_AGAIN)\n- `permanent-resolver-failure`: A permanent failure in name resolution occurred.\n(EAI_FAIL)\n- `would-block`: A result is not available yet. (EWOULDBLOCK, EAGAIN)" + } + }, + "[method]resolve-address-stream.subscribe": { + "name": "[method]resolve-address-stream.subscribe", + "kind": { + "method": 85 + }, + "params": [ + { + "name": "self", + "type": 86 + } + ], + "results": [ + { + "type": 158 + } + ], + "docs": { + "contents": "Create a `pollable` which will resolve once the stream is ready for I/O.\n\nNote: this function is here for WASI Preview2 only.\nIt's planned to be removed when `future` is natively supported in Preview3." + } + }, + "resolve-addresses": { + "name": "resolve-addresses", + "kind": "freestanding", + "params": [ + { + "name": "network", + "type": 89 + }, + { + "name": "name", + "type": "string" + } + ], + "results": [ + { + "type": 91 + } + ], + "docs": { + "contents": "Resolve an internet host name to a list of IP addresses.\n\nUnicode domain names are automatically converted to ASCII using IDNA encoding.\nIf the input is an IP address string, the address is parsed and returned\nas-is without making any external requests.\n\nSee the wasi-socket proposal README.md for a comparison with getaddrinfo.\n\nThis function never blocks. It either immediately fails or immediately\nreturns successfully with a `resolve-address-stream` that can be used\nto (asynchronously) fetch the results.\n\n# Typical errors\n- `invalid-argument`: `name` is a syntactically invalid domain name or IP address.\n\n# References:\n- \n- \n- \n- " + } + } + }, + "package": 3 + }, + { + "name": "tcp", + "types": { + "input-stream": 92, + "output-stream": 93, + "pollable": 94, + "duration": 95, + "network": 96, + "error-code": 97, + "ip-socket-address": 98, + "ip-address-family": 99, + "shutdown-type": 100, + "tcp-socket": 101 + }, + "functions": { + "[method]tcp-socket.accept": { + "name": "[method]tcp-socket.accept", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + } + ], + "results": [ + { + "type": 107 + } + ], + "docs": { + "contents": "Accept a new client socket.\n\nThe returned socket is bound and in the `connected` state. The following properties\nare inherited from the listener socket:\n- `address-family`\n- `keep-alive-enabled`\n- `keep-alive-idle-time`\n- `keep-alive-interval`\n- `keep-alive-count`\n- `hop-limit`\n- `receive-buffer-size`\n- `send-buffer-size`\n\nOn success, this function returns the newly accepted client socket along with\na pair of streams that can be used to read & write to the connection.\n\n# Typical errors\n- `invalid-state`: Socket is not in the `listening` state. (EINVAL)\n- `would-block`: No pending connections at the moment. (EWOULDBLOCK, EAGAIN)\n- `connection-aborted`: An incoming connection was pending, but was terminated\nby the client before this listener could accept it. (ECONNABORTED)\n- `new-socket-limit`: The new socket resource could not be created because of\na system limit. (EMFILE, ENFILE)\n\n# References\n- \n- \n- \n- " + } + }, + "[method]tcp-socket.address-family": { + "name": "[method]tcp-socket.address-family", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + } + ], + "results": [ + { + "type": 99 + } + ], + "docs": { + "contents": "Whether this is a IPv4 or IPv6 socket.\n\nEquivalent to the SO_DOMAIN socket option." + } + }, + "[method]tcp-socket.finish-bind": { + "name": "[method]tcp-socket.finish-bind", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + } + ], + "results": [ + { + "type": 108 + } + ] + }, + "[method]tcp-socket.finish-connect": { + "name": "[method]tcp-socket.finish-connect", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + } + ], + "results": [ + { + "type": 110 + } + ] + }, + "[method]tcp-socket.finish-listen": { + "name": "[method]tcp-socket.finish-listen", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + } + ], + "results": [ + { + "type": 108 + } + ] + }, + "[method]tcp-socket.hop-limit": { + "name": "[method]tcp-socket.hop-limit", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + } + ], + "results": [ + { + "type": 111 + } + ], + "docs": { + "contents": "Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options.\n\nIf the provided value is 0, an `invalid-argument` error is returned.\n\n# Typical errors\n- `invalid-argument`: (set) The TTL value must be 1 or higher." + } + }, + "[method]tcp-socket.is-listening": { + "name": "[method]tcp-socket.is-listening", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + } + ], + "results": [ + { + "type": "bool" + } + ], + "docs": { + "contents": "Whether the socket is in the `listening` state.\n\nEquivalent to the SO_ACCEPTCONN socket option." + } + }, + "[method]tcp-socket.keep-alive-count": { + "name": "[method]tcp-socket.keep-alive-count", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + } + ], + "results": [ + { + "type": 112 + } + ], + "docs": { + "contents": "The maximum amount of keepalive packets TCP should send before aborting the connection.\n\nIf the provided value is 0, an `invalid-argument` error is returned.\nAny other value will never cause an error, but it might be silently clamped and/or\nrounded.\nI.e. after setting a value, reading the same setting back may return a different\nvalue.\n\nEquivalent to the TCP_KEEPCNT socket option.\n\n# Typical errors\n- `invalid-argument`: (set) The provided value was 0." + } + }, + "[method]tcp-socket.keep-alive-enabled": { + "name": "[method]tcp-socket.keep-alive-enabled", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + } + ], + "results": [ + { + "type": 113 + } + ], + "docs": { + "contents": "Enables or disables keepalive.\n\nThe keepalive behavior can be adjusted using:\n- `keep-alive-idle-time`\n- `keep-alive-interval`\n- `keep-alive-count`\nThese properties can be configured while `keep-alive-enabled` is false, but only\ncome into effect when `keep-alive-enabled` is true.\n\nEquivalent to the SO_KEEPALIVE socket option." + } + }, + "[method]tcp-socket.keep-alive-idle-time": { + "name": "[method]tcp-socket.keep-alive-idle-time", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + } + ], + "results": [ + { + "type": 114 + } + ], + "docs": { + "contents": "Amount of time the connection has to be idle before TCP starts sending keepalive\npackets.\n\nIf the provided value is 0, an `invalid-argument` error is returned.\nAny other value will never cause an error, but it might be silently clamped and/or\nrounded.\nI.e. after setting a value, reading the same setting back may return a different\nvalue.\n\nEquivalent to the TCP_KEEPIDLE socket option. (TCP_KEEPALIVE on MacOS)\n\n# Typical errors\n- `invalid-argument`: (set) The provided value was 0." + } + }, + "[method]tcp-socket.keep-alive-interval": { + "name": "[method]tcp-socket.keep-alive-interval", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + } + ], + "results": [ + { + "type": 114 + } + ], + "docs": { + "contents": "The time between keepalive packets.\n\nIf the provided value is 0, an `invalid-argument` error is returned.\nAny other value will never cause an error, but it might be silently clamped and/or\nrounded.\nI.e. after setting a value, reading the same setting back may return a different\nvalue.\n\nEquivalent to the TCP_KEEPINTVL socket option.\n\n# Typical errors\n- `invalid-argument`: (set) The provided value was 0." + } + }, + "[method]tcp-socket.local-address": { + "name": "[method]tcp-socket.local-address", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + } + ], + "results": [ + { + "type": 115 + } + ], + "docs": { + "contents": "Get the bound local address.\n\nPOSIX mentions:\n> If the socket has not been bound to a local name, the value\n> stored in the object pointed to by `address` is unspecified.\n\nWASI is stricter and requires `local-address` to return `invalid-state` when the\nsocket hasn't been bound yet.\n\n# Typical errors\n- `invalid-state`: The socket is not bound to any local address.\n\n# References\n- \n- \n- \n- " + } + }, + "[method]tcp-socket.receive-buffer-size": { + "name": "[method]tcp-socket.receive-buffer-size", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + } + ], + "results": [ + { + "type": 116 + } + ], + "docs": { + "contents": "The kernel buffer space reserved for sends/receives on this socket.\n\nIf the provided value is 0, an `invalid-argument` error is returned.\nAny other value will never cause an error, but it might be silently clamped and/or\nrounded.\nI.e. after setting a value, reading the same setting back may return a different\nvalue.\n\nEquivalent to the SO_RCVBUF and SO_SNDBUF socket options.\n\n# Typical errors\n- `invalid-argument`: (set) The provided value was 0." + } + }, + "[method]tcp-socket.remote-address": { + "name": "[method]tcp-socket.remote-address", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + } + ], + "results": [ + { + "type": 115 + } + ], + "docs": { + "contents": "Get the remote address.\n\n# Typical errors\n- `invalid-state`: The socket is not connected to a remote address. (ENOTCONN)\n\n# References\n- \n- \n- \n- " + } + }, + "[method]tcp-socket.send-buffer-size": { + "name": "[method]tcp-socket.send-buffer-size", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + } + ], + "results": [ + { + "type": 116 + } + ] + }, + "[method]tcp-socket.set-hop-limit": { + "name": "[method]tcp-socket.set-hop-limit", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + }, + { + "name": "value", + "type": "u8" + } + ], + "results": [ + { + "type": 108 + } + ] + }, + "[method]tcp-socket.set-keep-alive-count": { + "name": "[method]tcp-socket.set-keep-alive-count", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + }, + { + "name": "value", + "type": "u32" + } + ], + "results": [ + { + "type": 108 + } + ] + }, + "[method]tcp-socket.set-keep-alive-enabled": { + "name": "[method]tcp-socket.set-keep-alive-enabled", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + }, + { + "name": "value", + "type": "bool" + } + ], + "results": [ + { + "type": 108 + } + ] + }, + "[method]tcp-socket.set-keep-alive-idle-time": { + "name": "[method]tcp-socket.set-keep-alive-idle-time", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + }, + { + "name": "value", + "type": 95 + } + ], + "results": [ + { + "type": 108 + } + ] + }, + "[method]tcp-socket.set-keep-alive-interval": { + "name": "[method]tcp-socket.set-keep-alive-interval", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + }, + { + "name": "value", + "type": 95 + } + ], + "results": [ + { + "type": 108 + } + ] + }, + "[method]tcp-socket.set-listen-backlog-size": { + "name": "[method]tcp-socket.set-listen-backlog-size", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + }, + { + "name": "value", + "type": "u64" + } + ], + "results": [ + { + "type": 108 + } + ], + "docs": { + "contents": "Hints the desired listen queue size. Implementations are free to ignore this.\n\nIf the provided value is 0, an `invalid-argument` error is returned.\nAny other value will never cause an error, but it might be silently clamped and/or\nrounded.\n\n# Typical errors\n- `not-supported`: (set) The platform does not support changing the backlog\nsize after the initial listen.\n- `invalid-argument`: (set) The provided value was 0.\n- `invalid-state`: (set) The socket is in the `connect-in-progress` or\n`connected` state." + } + }, + "[method]tcp-socket.set-receive-buffer-size": { + "name": "[method]tcp-socket.set-receive-buffer-size", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + }, + { + "name": "value", + "type": "u64" + } + ], + "results": [ + { + "type": 108 + } + ] + }, + "[method]tcp-socket.set-send-buffer-size": { + "name": "[method]tcp-socket.set-send-buffer-size", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + }, + { + "name": "value", + "type": "u64" + } + ], + "results": [ + { + "type": 108 + } + ] + }, + "[method]tcp-socket.shutdown": { + "name": "[method]tcp-socket.shutdown", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + }, + { + "name": "shutdown-type", + "type": 100 + } + ], + "results": [ + { + "type": 108 + } + ], + "docs": { + "contents": "Initiate a graceful shutdown.\n\n- `receive`: The socket is not expecting to receive any data from\nthe peer. The `input-stream` associated with this socket will be\nclosed. Any data still in the receive queue at time of calling\nthis method will be discarded.\n- `send`: The socket has no more data to send to the peer. The `output-stream`\nassociated with this socket will be closed and a FIN packet will be sent.\n- `both`: Same effect as `receive` & `send` combined.\n\nThis function is idempotent. Shutting a down a direction more than once\nhas no effect and returns `ok`.\n\nThe shutdown function does not close (drop) the socket.\n\n# Typical errors\n- `invalid-state`: The socket is not in the `connected` state. (ENOTCONN)\n\n# References\n- \n- \n- \n- " + } + }, + "[method]tcp-socket.start-bind": { + "name": "[method]tcp-socket.start-bind", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + }, + { + "name": "network", + "type": 117 + }, + { + "name": "local-address", + "type": 98 + } + ], + "results": [ + { + "type": 108 + } + ], + "docs": { + "contents": "Bind the socket to a specific network on the provided IP address and port.\n\nIf the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the\nimplementation to decide which\nnetwork interface(s) to bind to.\nIf the TCP/UDP port is zero, the socket will be bound to a random free port.\n\nBind can be attempted multiple times on the same socket, even with\ndifferent arguments on each iteration. But never concurrently and\nonly as long as the previous bind failed. Once a bind succeeds, the\nbinding can't be changed anymore.\n\n# Typical errors\n- `invalid-argument`: The `local-address` has the wrong address family.\n(EAFNOSUPPORT, EFAULT on Windows)\n- `invalid-argument`: `local-address` is not a unicast address. (EINVAL)\n- `invalid-argument`: `local-address` is an IPv4-mapped IPv6 address.\n(EINVAL)\n- `invalid-state`: The socket is already bound. (EINVAL)\n- `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS\non Windows)\n- `address-in-use`: Address is already in use. (EADDRINUSE)\n- `address-not-bindable`: `local-address` is not an address that the `network`\ncan bind to. (EADDRNOTAVAIL)\n- `not-in-progress`: A `bind` operation is not in progress.\n- `would-block`: Can't finish the operation, it is still in progress.\n(EWOULDBLOCK, EAGAIN)\n\n# Implementors note\nWhen binding to a non-zero port, this bind operation shouldn't be affected by\nthe TIME_WAIT\nstate of a recently closed socket on the same local address. In practice this\nmeans that the SO_REUSEADDR\nsocket option should be set implicitly on all platforms, except on Windows where\nthis is the default behavior\nand SO_REUSEADDR performs something different entirely.\n\nUnlike in POSIX, in WASI the bind operation is async. This enables\ninteractive WASI hosts to inject permission prompts. Runtimes that\ndon't want to make use of this ability can simply call the native\n`bind` as part of either `start-bind` or `finish-bind`.\n\n# References\n- \n- \n- \n- " + } + }, + "[method]tcp-socket.start-connect": { + "name": "[method]tcp-socket.start-connect", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + }, + { + "name": "network", + "type": 117 + }, + { + "name": "remote-address", + "type": 98 + } + ], + "results": [ + { + "type": 108 + } + ], + "docs": { + "contents": "Connect to a remote endpoint.\n\nOn success:\n- the socket is transitioned into the `connection` state.\n- a pair of streams is returned that can be used to read & write to the connection\n\nAfter a failed connection attempt, the socket will be in the `closed`\nstate and the only valid action left is to `drop` the socket. A single\nsocket can not be used to connect more than once.\n\n# Typical errors\n- `invalid-argument`: The `remote-address` has the wrong address family.\n(EAFNOSUPPORT)\n- `invalid-argument`: `remote-address` is not a unicast address. (EINVAL,\nENETUNREACH on Linux, EAFNOSUPPORT on MacOS)\n- `invalid-argument`: `remote-address` is an IPv4-mapped IPv6 address.\n(EINVAL, EADDRNOTAVAIL on Illumos)\n- `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY\n(`0.0.0.0` / `::`). (EADDRNOTAVAIL on Windows)\n- `invalid-argument`: The port in `remote-address` is set to 0. (EADDRNOTAVAIL\non Windows)\n- `invalid-argument`: The socket is already attached to a different network.\nThe `network` passed to `connect` must be identical to the one passed to `bind`.\n- `invalid-state`: The socket is already in the `connected` state.\n(EISCONN)\n- `invalid-state`: The socket is already in the `listening` state.\n(EOPNOTSUPP, EINVAL on Windows)\n- `timeout`: Connection timed out. (ETIMEDOUT)\n- `connection-refused`: The connection was forcefully rejected. (ECONNREFUSED)\n- `connection-reset`: The connection was reset. (ECONNRESET)\n- `connection-aborted`: The connection was aborted. (ECONNABORTED)\n- `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH,\nEHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET)\n- `address-in-use`: Tried to perform an implicit bind, but there were\nno ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD)\n- `not-in-progress`: A connect operation is not in progress.\n- `would-block`: Can't finish the operation, it is still in progress.\n(EWOULDBLOCK, EAGAIN)\n\n# Implementors note\nThe POSIX equivalent of `start-connect` is the regular `connect` syscall.\nBecause all WASI sockets are non-blocking this is expected to return\nEINPROGRESS, which should be translated to `ok()` in WASI.\n\nThe POSIX equivalent of `finish-connect` is a `poll` for event `POLLOUT`\nwith a timeout of 0 on the socket descriptor. Followed by a check for\nthe `SO_ERROR` socket option, in case the poll signaled readiness.\n\n# References\n- \n- \n- \n- " + } + }, + "[method]tcp-socket.start-listen": { + "name": "[method]tcp-socket.start-listen", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + } + ], + "results": [ + { + "type": 108 + } + ], + "docs": { + "contents": "Start listening for new connections.\n\nTransitions the socket into the `listening` state.\n\nUnlike POSIX, the socket must already be explicitly bound.\n\n# Typical errors\n- `invalid-state`: The socket is not bound to any local address. (EDESTADDRREQ)\n- `invalid-state`: The socket is already in the `connected` state.\n(EISCONN, EINVAL on BSD)\n- `invalid-state`: The socket is already in the `listening` state.\n- `address-in-use`: Tried to perform an implicit bind, but there were\nno ephemeral ports available. (EADDRINUSE)\n- `not-in-progress`: A listen operation is not in progress.\n- `would-block`: Can't finish the operation, it is still in progress.\n(EWOULDBLOCK, EAGAIN)\n\n# Implementors note\nUnlike in POSIX, in WASI the listen operation is async. This enables\ninteractive WASI hosts to inject permission prompts. Runtimes that\ndon't want to make use of this ability can simply call the native\n`listen` as part of either `start-listen` or `finish-listen`.\n\n# References\n- \n- \n- \n- " + } + }, + "[method]tcp-socket.subscribe": { + "name": "[method]tcp-socket.subscribe", + "kind": { + "method": 101 + }, + "params": [ + { + "name": "self", + "type": 102 + } + ], + "results": [ + { + "type": 159 + } + ], + "docs": { + "contents": "Create a `pollable` which can be used to poll for, or block on,\ncompletion of any of the asynchronous operations of this socket.\n\nWhen `finish-bind`, `finish-listen`, `finish-connect` or `accept`\nreturn `error(would-block)`, this pollable can be used to wait for\ntheir success or failure, after which the method can be retried.\n\nThe pollable is not limited to the async operation that happens to be\nin progress at the time of calling `subscribe` (if any). Theoretically,\n`subscribe` only has to be called once per socket and can then be\n(re)used for the remainder of the socket's lifetime.\n\nSee \nfor a more information.\n\nNote: this function is here for WASI Preview2 only.\nIt's planned to be removed when `future` is natively supported in Preview3." + } + } + }, + "package": 3 + }, + { + "name": "tcp-create-socket", + "types": { + "network": 118, + "error-code": 119, + "ip-address-family": 120, + "tcp-socket": 121 + }, + "functions": { + "create-tcp-socket": { + "name": "create-tcp-socket", + "kind": "freestanding", + "params": [ + { + "name": "address-family", + "type": 120 + } + ], + "results": [ + { + "type": 123 + } + ], + "docs": { + "contents": "Create a new TCP socket.\n\nSimilar to `socket(AF_INET or AF_INET6, SOCK_STREAM, IPPROTO_TCP)` in POSIX.\nOn IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise.\n\nThis function does not require a network capability handle. This is considered\nto be safe because\nat time of creation, the socket is not bound to any `network` yet. Up to the moment\n`bind`/`connect`\nis called, the socket is effectively an in-memory configuration object, unable\nto communicate with the outside world.\n\nAll sockets are non-blocking. Use the wasi-poll interface to block on asynchronous\noperations.\n\n# Typical errors\n- `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT)\n- `new-socket-limit`: The new socket resource could not be created because of\na system limit. (EMFILE, ENFILE)\n\n# References\n- \n- \n- \n- " + } + } + }, + "package": 3 + }, + { + "name": "udp", + "types": { + "pollable": 124, + "network": 125, + "error-code": 126, + "ip-socket-address": 127, + "ip-address-family": 128, + "incoming-datagram": 130, + "outgoing-datagram": 132, + "udp-socket": 133, + "incoming-datagram-stream": 134, + "outgoing-datagram-stream": 135 + }, + "functions": { + "[method]udp-socket.address-family": { + "name": "[method]udp-socket.address-family", + "kind": { + "method": 133 + }, + "params": [ + { + "name": "self", + "type": 136 + } + ], + "results": [ + { + "type": 128 + } + ], + "docs": { + "contents": "Whether this is a IPv4 or IPv6 socket.\n\nEquivalent to the SO_DOMAIN socket option." + } + }, + "[method]udp-socket.finish-bind": { + "name": "[method]udp-socket.finish-bind", + "kind": { + "method": 133 + }, + "params": [ + { + "name": "self", + "type": 136 + } + ], + "results": [ + { + "type": 137 + } + ] + }, + "[method]udp-socket.local-address": { + "name": "[method]udp-socket.local-address", + "kind": { + "method": 133 + }, + "params": [ + { + "name": "self", + "type": 136 + } + ], + "results": [ + { + "type": 138 + } + ], + "docs": { + "contents": "Get the current bound address.\n\nPOSIX mentions:\n> If the socket has not been bound to a local name, the value\n> stored in the object pointed to by `address` is unspecified.\n\nWASI is stricter and requires `local-address` to return `invalid-state` when the\nsocket hasn't been bound yet.\n\n# Typical errors\n- `invalid-state`: The socket is not bound to any local address.\n\n# References\n- \n- \n- \n- " + } + }, + "[method]udp-socket.receive-buffer-size": { + "name": "[method]udp-socket.receive-buffer-size", + "kind": { + "method": 133 + }, + "params": [ + { + "name": "self", + "type": 136 + } + ], + "results": [ + { + "type": 139 + } + ], + "docs": { + "contents": "The kernel buffer space reserved for sends/receives on this socket.\n\nIf the provided value is 0, an `invalid-argument` error is returned.\nAny other value will never cause an error, but it might be silently clamped and/or\nrounded.\nI.e. after setting a value, reading the same setting back may return a different\nvalue.\n\nEquivalent to the SO_RCVBUF and SO_SNDBUF socket options.\n\n# Typical errors\n- `invalid-argument`: (set) The provided value was 0." + } + }, + "[method]udp-socket.remote-address": { + "name": "[method]udp-socket.remote-address", + "kind": { + "method": 133 + }, + "params": [ + { + "name": "self", + "type": 136 + } + ], + "results": [ + { + "type": 138 + } + ], + "docs": { + "contents": "Get the address the socket is currently streaming to.\n\n# Typical errors\n- `invalid-state`: The socket is not streaming to a specific remote address. (ENOTCONN)\n\n# References\n- \n- \n- \n- " + } + }, + "[method]udp-socket.send-buffer-size": { + "name": "[method]udp-socket.send-buffer-size", + "kind": { + "method": 133 + }, + "params": [ + { + "name": "self", + "type": 136 + } + ], + "results": [ + { + "type": 139 + } + ] + }, + "[method]udp-socket.set-receive-buffer-size": { + "name": "[method]udp-socket.set-receive-buffer-size", + "kind": { + "method": 133 + }, + "params": [ + { + "name": "self", + "type": 136 + }, + { + "name": "value", + "type": "u64" + } + ], + "results": [ + { + "type": 137 + } + ] + }, + "[method]udp-socket.set-send-buffer-size": { + "name": "[method]udp-socket.set-send-buffer-size", + "kind": { + "method": 133 + }, + "params": [ + { + "name": "self", + "type": 136 + }, + { + "name": "value", + "type": "u64" + } + ], + "results": [ + { + "type": 137 + } + ] + }, + "[method]udp-socket.set-unicast-hop-limit": { + "name": "[method]udp-socket.set-unicast-hop-limit", + "kind": { + "method": 133 + }, + "params": [ + { + "name": "self", + "type": 136 + }, + { + "name": "value", + "type": "u8" + } + ], + "results": [ + { + "type": 137 + } + ] + }, + "[method]udp-socket.start-bind": { + "name": "[method]udp-socket.start-bind", + "kind": { + "method": 133 + }, + "params": [ + { + "name": "self", + "type": 136 + }, + { + "name": "network", + "type": 140 + }, + { + "name": "local-address", + "type": 127 + } + ], + "results": [ + { + "type": 137 + } + ], + "docs": { + "contents": "Bind the socket to a specific network on the provided IP address and port.\n\nIf the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the\nimplementation to decide which\nnetwork interface(s) to bind to.\nIf the port is zero, the socket will be bound to a random free port.\n\n# Typical errors\n- `invalid-argument`: The `local-address` has the wrong address family.\n(EAFNOSUPPORT, EFAULT on Windows)\n- `invalid-state`: The socket is already bound. (EINVAL)\n- `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS\non Windows)\n- `address-in-use`: Address is already in use. (EADDRINUSE)\n- `address-not-bindable`: `local-address` is not an address that the `network`\ncan bind to. (EADDRNOTAVAIL)\n- `not-in-progress`: A `bind` operation is not in progress.\n- `would-block`: Can't finish the operation, it is still in progress.\n(EWOULDBLOCK, EAGAIN)\n\n# Implementors note\nUnlike in POSIX, in WASI the bind operation is async. This enables\ninteractive WASI hosts to inject permission prompts. Runtimes that\ndon't want to make use of this ability can simply call the native\n`bind` as part of either `start-bind` or `finish-bind`.\n\n# References\n- \n- \n- \n- " + } + }, + "[method]udp-socket.stream": { + "name": "[method]udp-socket.stream", + "kind": { + "method": 133 + }, + "params": [ + { + "name": "self", + "type": 136 + }, + { + "name": "remote-address", + "type": 131 + } + ], + "results": [ + { + "type": 144 + } + ], + "docs": { + "contents": "Set up inbound & outbound communication channels, optionally to a specific peer.\n\nThis function only changes the local socket configuration and does not generate\nany network traffic.\nOn success, the `remote-address` of the socket is updated. The `local-address`\nmay be updated as well,\nbased on the best network path to `remote-address`.\n\nWhen a `remote-address` is provided, the returned streams are limited to communicating\nwith that specific peer:\n- `send` can only be used to send to this destination.\n- `receive` will only return datagrams sent from the provided `remote-address`.\n\nThis method may be called multiple times on the same socket to change its association,\nbut\nonly the most recently returned pair of streams will be operational. Implementations\nmay trap if\nthe streams returned by a previous invocation haven't been dropped yet before\ncalling `stream` again.\n\nThe POSIX equivalent in pseudo-code is:\n```text\nif (was previously connected) {\nconnect(s, AF_UNSPEC)\n}\nif (remote_address is Some) {\nconnect(s, remote_address)\n}\n```\n\nUnlike in POSIX, the socket must already be explicitly bound.\n\n# Typical errors\n- `invalid-argument`: The `remote-address` has the wrong address family.\n(EAFNOSUPPORT)\n- `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY\n(`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL)\n- `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ,\nEADDRNOTAVAIL)\n- `invalid-state`: The socket is not bound.\n- `address-in-use`: Tried to perform an implicit bind, but there were\nno ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD)\n- `remote-unreachable`: The remote address is not reachable. (ECONNRESET,\nENETRESET, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET)\n- `connection-refused`: The connection was refused. (ECONNREFUSED)\n\n# References\n- \n- \n- \n- " + } + }, + "[method]udp-socket.subscribe": { + "name": "[method]udp-socket.subscribe", + "kind": { + "method": 133 + }, + "params": [ + { + "name": "self", + "type": 136 + } + ], + "results": [ + { + "type": 160 + } + ], + "docs": { + "contents": "Create a `pollable` which will resolve once the socket is ready for I/O.\n\nNote: this function is here for WASI Preview2 only.\nIt's planned to be removed when `future` is natively supported in Preview3." + } + }, + "[method]udp-socket.unicast-hop-limit": { + "name": "[method]udp-socket.unicast-hop-limit", + "kind": { + "method": 133 + }, + "params": [ + { + "name": "self", + "type": 136 + } + ], + "results": [ + { + "type": 145 + } + ], + "docs": { + "contents": "Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options.\n\nIf the provided value is 0, an `invalid-argument` error is returned.\n\n# Typical errors\n- `invalid-argument`: (set) The TTL value must be 1 or higher." + } + }, + "[method]incoming-datagram-stream.receive": { + "name": "[method]incoming-datagram-stream.receive", + "kind": { + "method": 134 + }, + "params": [ + { + "name": "self", + "type": 146 + }, + { + "name": "max-results", + "type": "u64" + } + ], + "results": [ + { + "type": 148 + } + ], + "docs": { + "contents": "Receive messages on the socket.\n\nThis function attempts to receive up to `max-results` datagrams on the socket\nwithout blocking.\nThe returned list may contain fewer elements than requested, but never more.\n\nThis function returns successfully with an empty list when either:\n- `max-results` is 0, or:\n- `max-results` is greater than 0, but no results are immediately available.\nThis function never returns `error(would-block)`.\n\n# Typical errors\n- `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET\non Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET)\n- `connection-refused`: The connection was refused. (ECONNREFUSED)\n\n# References\n- \n- \n- \n- \n- \n- \n- \n- " + } + }, + "[method]incoming-datagram-stream.subscribe": { + "name": "[method]incoming-datagram-stream.subscribe", + "kind": { + "method": 134 + }, + "params": [ + { + "name": "self", + "type": 146 + } + ], + "results": [ + { + "type": 160 + } + ], + "docs": { + "contents": "Create a `pollable` which will resolve once the stream is ready to receive again.\n\nNote: this function is here for WASI Preview2 only.\nIt's planned to be removed when `future` is natively supported in Preview3." + } + }, + "[method]outgoing-datagram-stream.check-send": { + "name": "[method]outgoing-datagram-stream.check-send", + "kind": { + "method": 135 + }, + "params": [ + { + "name": "self", + "type": 149 + } + ], + "results": [ + { + "type": 139 + } + ], + "docs": { + "contents": "Check readiness for sending. This function never blocks.\n\nReturns the number of datagrams permitted for the next call to `send`,\nor an error. Calling `send` with more datagrams than this function has\npermitted will trap.\n\nWhen this function returns ok(0), the `subscribe` pollable will\nbecome ready when this function will report at least ok(1), or an\nerror.\n\nNever returns `would-block`." + } + }, + "[method]outgoing-datagram-stream.send": { + "name": "[method]outgoing-datagram-stream.send", + "kind": { + "method": 135 + }, + "params": [ + { + "name": "self", + "type": 149 + }, + { + "name": "datagrams", + "type": 150 + } + ], + "results": [ + { + "type": 139 + } + ], + "docs": { + "contents": "Send messages on the socket.\n\nThis function attempts to send all provided `datagrams` on the socket without\nblocking and\nreturns how many messages were actually sent (or queued for sending). This function\nnever\nreturns `error(would-block)`. If none of the datagrams were able to be sent, `ok(0)`\nis returned.\n\nThis function semantically behaves the same as iterating the `datagrams` list\nand sequentially\nsending each individual datagram until either the end of the list has been reached\nor the first error occurred.\nIf at least one datagram has been sent successfully, this function never returns\nan error.\n\nIf the input list is empty, the function returns `ok(0)`.\n\nEach call to `send` must be permitted by a preceding `check-send`. Implementations\nmust trap if\neither `check-send` was not called or `datagrams` contains more items than `check-send`\npermitted.\n\n# Typical errors\n- `invalid-argument`: The `remote-address` has the wrong address family.\n(EAFNOSUPPORT)\n- `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY\n(`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL)\n- `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ,\nEADDRNOTAVAIL)\n- `invalid-argument`: The socket is in \"connected\" mode and `remote-address`\nis `some` value that does not match the address passed to `stream`. (EISCONN)\n- `invalid-argument`: The socket is not \"connected\" and no value for `remote-address`\nwas provided. (EDESTADDRREQ)\n- `remote-unreachable`: The remote address is not reachable. (ECONNRESET,\nENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET)\n- `connection-refused`: The connection was refused. (ECONNREFUSED)\n- `datagram-too-large`: The datagram is too large. (EMSGSIZE)\n\n# References\n- \n- \n- \n- \n- \n- \n- \n- " + } + }, + "[method]outgoing-datagram-stream.subscribe": { + "name": "[method]outgoing-datagram-stream.subscribe", + "kind": { + "method": 135 + }, + "params": [ + { + "name": "self", + "type": 149 + } + ], + "results": [ + { + "type": 160 + } + ], + "docs": { + "contents": "Create a `pollable` which will resolve once the stream is ready to send again.\n\nNote: this function is here for WASI Preview2 only.\nIt's planned to be removed when `future` is natively supported in Preview3." + } + } + }, + "package": 3 + }, + { + "name": "udp-create-socket", + "types": { + "network": 151, + "error-code": 152, + "ip-address-family": 153, + "udp-socket": 154 + }, + "functions": { + "create-udp-socket": { + "name": "create-udp-socket", + "kind": "freestanding", + "params": [ + { + "name": "address-family", + "type": 153 + } + ], + "results": [ + { + "type": 156 + } + ], + "docs": { + "contents": "Create a new UDP socket.\n\nSimilar to `socket(AF_INET or AF_INET6, SOCK_DGRAM, IPPROTO_UDP)` in POSIX.\nOn IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise.\n\nThis function does not require a network capability handle. This is considered\nto be safe because\nat time of creation, the socket is not bound to any `network` yet. Up to the moment\n`bind` is called,\nthe socket is effectively an in-memory configuration object, unable to communicate\nwith the outside world.\n\nAll sockets are non-blocking. Use the wasi-poll interface to block on asynchronous\noperations.\n\n# Typical errors\n- `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT)\n- `new-socket-limit`: The new socket resource could not be created because of\na system limit. (EMFILE, ENFILE)\n\n# References:\n- \n- \n- \n- " + } + } + }, + "package": 3 + }, + { + "name": "insecure-seed", + "types": {}, + "functions": { + "insecure-seed": { + "name": "insecure-seed", + "kind": "freestanding", + "params": [], + "results": [ + { + "type": 161 + } + ], + "docs": { + "contents": "Return a 128-bit value that may contain a pseudo-random value.\n\nThe returned value is not required to be computed from a CSPRNG, and may\neven be entirely deterministic. Host implementations are encouraged to\nprovide pseudo-random values to any program exposed to\nattacker-controlled content, to enable DoS protection built into many\nlanguages' hash-map implementations.\n\nThis function is intended to only be called once, by a source language\nto initialize Denial Of Service (DoS) protection in its hash-map\nimplementation.\n\n# Expected future evolution\n\nThis will likely be changed to a value import, to prevent it from being\ncalled multiple times and potentially used for purposes other than DoS\nprotection." + } + } + }, + "docs": { + "contents": "The insecure-seed interface for seeding hash-map DoS resistance.\n\nIt is intended to be portable at least between Unix-family platforms and\nWindows." + }, + "package": 4 + }, + { + "name": "insecure", + "types": {}, + "functions": { + "get-insecure-random-bytes": { + "name": "get-insecure-random-bytes", + "kind": "freestanding", + "params": [ + { + "name": "len", + "type": "u64" + } + ], + "results": [ + { + "type": 162 + } + ], + "docs": { + "contents": "Return `len` insecure pseudo-random bytes.\n\nThis function is not cryptographically secure. Do not use it for\nanything related to security.\n\nThere are no requirements on the values of the returned bytes, however\nimplementations are encouraged to return evenly distributed values with\na long period." + } + }, + "get-insecure-random-u64": { + "name": "get-insecure-random-u64", + "kind": "freestanding", + "params": [], + "results": [ + { + "type": "u64" + } + ], + "docs": { + "contents": "Return an insecure pseudo-random `u64` value.\n\nThis function returns the same type of pseudo-random data as\n`get-insecure-random-bytes`, represented as a `u64`." + } + } + }, + "docs": { + "contents": "The insecure interface for insecure pseudo-random numbers.\n\nIt is intended to be portable at least between Unix-family platforms and\nWindows." + }, + "package": 4 + }, + { + "name": "random", + "types": {}, + "functions": { + "get-random-bytes": { + "name": "get-random-bytes", + "kind": "freestanding", + "params": [ + { + "name": "len", + "type": "u64" + } + ], + "results": [ + { + "type": 162 + } + ], + "docs": { + "contents": "Return `len` cryptographically-secure random or pseudo-random bytes.\n\nThis function must produce data at least as cryptographically secure and\nfast as an adequately seeded cryptographically-secure pseudo-random\nnumber generator (CSPRNG). It must not block, from the perspective of\nthe calling program, under any circumstances, including on the first\nrequest and on requests for numbers of bytes. The returned data must\nalways be unpredictable.\n\nThis function must always return fresh data. Deterministic environments\nmust omit this function, rather than implementing it with deterministic\ndata." + } + }, + "get-random-u64": { + "name": "get-random-u64", + "kind": "freestanding", + "params": [], + "results": [ + { + "type": "u64" + } + ], + "docs": { + "contents": "Return a cryptographically-secure random or pseudo-random `u64` value.\n\nThis function returns the same type of data as `get-random-bytes`,\nrepresented as a `u64`." + } + } + }, + "docs": { + "contents": "WASI Random is a random data API.\n\nIt is intended to be portable at least between Unix-family platforms and\nWindows." + }, + "package": 4 + }, + { + "name": "environment", + "types": {}, + "functions": { + "get-environment": { + "name": "get-environment", + "kind": "freestanding", + "params": [], + "results": [ + { + "type": 164 + } + ], + "docs": { + "contents": "Get the POSIX-style environment variables.\n\nEach environment variable is provided as a pair of string variable names\nand string value.\n\nMorally, these are a value import, but until value imports are available\nin the component model, this import function should return the same\nvalues each time it is called." + } + }, + "get-arguments": { + "name": "get-arguments", + "kind": "freestanding", + "params": [], + "results": [ + { + "type": 165 + } + ], + "docs": { + "contents": "Get the POSIX-style arguments to the program." + } + }, + "initial-cwd": { + "name": "initial-cwd", + "kind": "freestanding", + "params": [], + "results": [ + { + "type": 166 + } + ], + "docs": { + "contents": "Return a path that programs should use as their initial current working\ndirectory, interpreting `.` as shorthand for this." + } + } + }, + "package": 5 + }, + { + "name": "exit", + "types": {}, + "functions": { + "exit": { + "name": "exit", + "kind": "freestanding", + "params": [ + { + "name": "status", + "type": 167 + } + ], + "results": [], + "docs": { + "contents": "Exit the current instance and any linked instances." + } + } + }, + "package": 5 + }, + { + "name": "run", + "types": {}, + "functions": { + "run": { + "name": "run", + "kind": "freestanding", + "params": [], + "results": [ + { + "type": 167 + } + ], + "docs": { + "contents": "Run the program." + } + } + }, + "package": 5 + }, + { + "name": "stdin", + "types": { + "input-stream": 168 + }, + "functions": { + "get-stdin": { + "name": "get-stdin", + "kind": "freestanding", + "params": [], + "results": [ + { + "type": 182 + } + ] + } + }, + "package": 5 + }, + { + "name": "stdout", + "types": { + "output-stream": 169 + }, + "functions": { + "get-stdout": { + "name": "get-stdout", + "kind": "freestanding", + "params": [], + "results": [ + { + "type": 183 + } + ] + } + }, + "package": 5 + }, + { + "name": "stderr", + "types": { + "output-stream": 170 + }, + "functions": { + "get-stderr": { + "name": "get-stderr", + "kind": "freestanding", + "params": [], + "results": [ + { + "type": 184 + } + ] + } + }, + "package": 5 + }, + { + "name": "terminal-input", + "types": { + "terminal-input": 171 + }, + "functions": {}, + "docs": { + "contents": "Terminal input.\n\nIn the future, this may include functions for disabling echoing,\ndisabling input buffering so that keyboard events are sent through\nimmediately, querying supported features, and so on." + }, + "package": 5 + }, + { + "name": "terminal-output", + "types": { + "terminal-output": 172 + }, + "functions": {}, + "docs": { + "contents": "Terminal output.\n\nIn the future, this may include functions for querying the terminal\nsize, being notified of terminal size changes, querying supported\nfeatures, and so on." + }, + "package": 5 + }, + { + "name": "terminal-stdin", + "types": { + "terminal-input": 173 + }, + "functions": { + "get-terminal-stdin": { + "name": "get-terminal-stdin", + "kind": "freestanding", + "params": [], + "results": [ + { + "type": 175 + } + ], + "docs": { + "contents": "If stdin is connected to a terminal, return a `terminal-input` handle\nallowing further interaction with it." + } + } + }, + "docs": { + "contents": "An interface providing an optional `terminal-input` for stdin as a\nlink-time authority." + }, + "package": 5 + }, + { + "name": "terminal-stdout", + "types": { + "terminal-output": 176 + }, + "functions": { + "get-terminal-stdout": { + "name": "get-terminal-stdout", + "kind": "freestanding", + "params": [], + "results": [ + { + "type": 178 + } + ], + "docs": { + "contents": "If stdout is connected to a terminal, return a `terminal-output` handle\nallowing further interaction with it." + } + } + }, + "docs": { + "contents": "An interface providing an optional `terminal-output` for stdout as a\nlink-time authority." + }, + "package": 5 + }, + { + "name": "terminal-stderr", + "types": { + "terminal-output": 179 + }, + "functions": { + "get-terminal-stderr": { + "name": "get-terminal-stderr", + "kind": "freestanding", + "params": [], + "results": [ + { + "type": 181 + } + ], + "docs": { + "contents": "If stderr is connected to a terminal, return a `terminal-output` handle\nallowing further interaction with it." + } + } + }, + "docs": { + "contents": "An interface providing an optional `terminal-output` for stderr as a\nlink-time authority." + }, + "package": 5 + } + ], + "types": [ + { + "name": "error", + "kind": "resource", + "owner": { + "interface": 0 + }, + "docs": { + "contents": "A resource which represents some error information.\n\nThe only method provided by this resource is `to-debug-string`,\nwhich provides some human-readable information about the error.\n\nIn the `wasi:io` package, this resource is returned through the\n`wasi:io/streams/stream-error` type.\n\nTo provide more specific error information, other interfaces may\nprovide functions to further \"downcast\" this error into more specific\nerror information. For example, `error`s returned in streams derived\nfrom filesystem types to be described using the filesystem's own\nerror-code type, using the function\n`wasi:filesystem/types/filesystem-error-code`, which takes a parameter\n`borrow` and returns\n`option`.\n\nThe set of functions which can \"downcast\" an `error` into a more\nconcrete type is open." + } + }, + { + "name": null, + "kind": { + "handle": { + "borrow": 0 + } + }, + "owner": null + }, + { + "name": "pollable", + "kind": "resource", + "owner": { + "interface": 1 + }, + "docs": { + "contents": "`pollable` represents a single I/O event which may be ready, or not." + } + }, + { + "name": null, + "kind": { + "handle": { + "borrow": 2 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "list": 3 + }, + "owner": null + }, + { + "name": null, + "kind": { + "list": "u32" + }, + "owner": null + }, + { + "name": "error", + "kind": { + "type": 0 + }, + "owner": { + "interface": 2 + } + }, + { + "name": "pollable", + "kind": { + "type": 2 + }, + "owner": { + "interface": 2 + } + }, + { + "name": null, + "kind": { + "handle": { + "own": 6 + } + }, + "owner": null + }, + { + "name": "stream-error", + "kind": { + "variant": { + "cases": [ + { + "name": "last-operation-failed", + "type": 8, + "docs": { + "contents": "The last operation (a write or flush) failed before completion.\n\nMore information is available in the `error` payload." + } + }, + { + "name": "closed", + "type": null, + "docs": { + "contents": "The stream is closed: no more input will be accepted by the\nstream. A closed output-stream will return this error on all\nfuture operations." + } + } + ] + } + }, + "owner": { + "interface": 2 + }, + "docs": { + "contents": "An error for input-stream and output-stream operations." + } + }, + { + "name": "input-stream", + "kind": "resource", + "owner": { + "interface": 2 + }, + "docs": { + "contents": "An input bytestream.\n\n`input-stream`s are *non-blocking* to the extent practical on underlying\nplatforms. I/O operations always return promptly; if fewer bytes are\npromptly available than requested, they return the number of bytes promptly\navailable, which could even be zero. To wait for data to be available,\nuse the `subscribe` function to obtain a `pollable` which can be polled\nfor using `wasi:io/poll`." + } + }, + { + "name": "output-stream", + "kind": "resource", + "owner": { + "interface": 2 + }, + "docs": { + "contents": "An output bytestream.\n\n`output-stream`s are *non-blocking* to the extent practical on\nunderlying platforms. Except where specified otherwise, I/O operations also\nalways return promptly, after the number of bytes that can be written\npromptly, which could even be zero. To wait for the stream to be ready to\naccept data, the `subscribe` function to obtain a `pollable` which can be\npolled for using `wasi:io/poll`." + } + }, + { + "name": null, + "kind": { + "handle": { + "borrow": 10 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "list": "u8" + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 13, + "err": 9 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": "u64", + "err": 9 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "borrow": 11 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": null, + "err": 9 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "own": 7 + } + }, + "owner": null + }, + { + "name": "pollable", + "kind": { + "type": 2 + }, + "owner": { + "interface": 3 + } + }, + { + "name": "instant", + "kind": { + "type": "u64" + }, + "owner": { + "interface": 3 + }, + "docs": { + "contents": "An instant in time, in nanoseconds. An instant is relative to an\nunspecified initial value, and can only be compared to instances from\nthe same monotonic-clock." + } + }, + { + "name": "duration", + "kind": { + "type": "u64" + }, + "owner": { + "interface": 3 + }, + "docs": { + "contents": "A duration of time, in nanoseconds." + } + }, + { + "name": "datetime", + "kind": { + "record": { + "fields": [ + { + "name": "seconds", + "type": "u64" + }, + { + "name": "nanoseconds", + "type": "u32" + } + ] + } + }, + "owner": { + "interface": 4 + }, + "docs": { + "contents": "A time and date in seconds plus nanoseconds." + } + }, + { + "name": null, + "kind": { + "handle": { + "own": 19 + } + }, + "owner": null + }, + { + "name": "input-stream", + "kind": { + "type": 10 + }, + "owner": { + "interface": 5 + } + }, + { + "name": "output-stream", + "kind": { + "type": 11 + }, + "owner": { + "interface": 5 + } + }, + { + "name": "error", + "kind": { + "type": 6 + }, + "owner": { + "interface": 5 + } + }, + { + "name": "datetime", + "kind": { + "type": 22 + }, + "owner": { + "interface": 5 + } + }, + { + "name": "filesize", + "kind": { + "type": "u64" + }, + "owner": { + "interface": 5 + }, + "docs": { + "contents": "File size or length of a region within a file." + } + }, + { + "name": "descriptor-type", + "kind": { + "enum": { + "cases": [ + { + "name": "unknown", + "docs": { + "contents": "The type of the descriptor or file is unknown or is different from\nany of the other types specified." + } + }, + { + "name": "block-device", + "docs": { + "contents": "The descriptor refers to a block device inode." + } + }, + { + "name": "character-device", + "docs": { + "contents": "The descriptor refers to a character device inode." + } + }, + { + "name": "directory", + "docs": { + "contents": "The descriptor refers to a directory inode." + } + }, + { + "name": "fifo", + "docs": { + "contents": "The descriptor refers to a named pipe." + } + }, + { + "name": "symbolic-link", + "docs": { + "contents": "The file refers to a symbolic link inode." + } + }, + { + "name": "regular-file", + "docs": { + "contents": "The descriptor refers to a regular file inode." + } + }, + { + "name": "socket", + "docs": { + "contents": "The descriptor refers to a socket." + } + } + ] + } + }, + "owner": { + "interface": 5 + }, + "docs": { + "contents": "The type of a filesystem object referenced by a descriptor.\n\nNote: This was called `filetype` in earlier versions of WASI." + } + }, + { + "name": "descriptor-flags", + "kind": { + "flags": { + "flags": [ + { + "name": "read", + "docs": { + "contents": "Read mode: Data can be read." + } + }, + { + "name": "write", + "docs": { + "contents": "Write mode: Data can be written to." + } + }, + { + "name": "file-integrity-sync", + "docs": { + "contents": "Request that writes be performed according to synchronized I/O file\nintegrity completion. The data stored in the file and the file's\nmetadata are synchronized. This is similar to `O_SYNC` in POSIX.\n\nThe precise semantics of this operation have not yet been defined for\nWASI. At this time, it should be interpreted as a request, and not a\nrequirement." + } + }, + { + "name": "data-integrity-sync", + "docs": { + "contents": "Request that writes be performed according to synchronized I/O data\nintegrity completion. Only the data stored in the file is\nsynchronized. This is similar to `O_DSYNC` in POSIX.\n\nThe precise semantics of this operation have not yet been defined for\nWASI. At this time, it should be interpreted as a request, and not a\nrequirement." + } + }, + { + "name": "requested-write-sync", + "docs": { + "contents": "Requests that reads be performed at the same level of integrety\nrequested for writes. This is similar to `O_RSYNC` in POSIX.\n\nThe precise semantics of this operation have not yet been defined for\nWASI. At this time, it should be interpreted as a request, and not a\nrequirement." + } + }, + { + "name": "mutate-directory", + "docs": { + "contents": "Mutating directories mode: Directory contents may be mutated.\n\nWhen this flag is unset on a descriptor, operations using the\ndescriptor which would create, rename, delete, modify the data or\nmetadata of filesystem objects, or obtain another handle which\nwould permit any of those, shall fail with `error-code::read-only` if\nthey would otherwise succeed.\n\nThis may only be set on directories." + } + } + ] + } + }, + "owner": { + "interface": 5 + }, + "docs": { + "contents": "Descriptor flags.\n\nNote: This was called `fdflags` in earlier versions of WASI." + } + }, + { + "name": "path-flags", + "kind": { + "flags": { + "flags": [ + { + "name": "symlink-follow", + "docs": { + "contents": "As long as the resolved path corresponds to a symbolic link, it is\nexpanded." + } + } + ] + } + }, + "owner": { + "interface": 5 + }, + "docs": { + "contents": "Flags determining the method of how paths are resolved." + } + }, + { + "name": "open-flags", + "kind": { + "flags": { + "flags": [ + { + "name": "create", + "docs": { + "contents": "Create file if it does not exist, similar to `O_CREAT` in POSIX." + } + }, + { + "name": "directory", + "docs": { + "contents": "Fail if not a directory, similar to `O_DIRECTORY` in POSIX." + } + }, + { + "name": "exclusive", + "docs": { + "contents": "Fail if file already exists, similar to `O_EXCL` in POSIX." + } + }, + { + "name": "truncate", + "docs": { + "contents": "Truncate file to size 0, similar to `O_TRUNC` in POSIX." + } + } + ] + } + }, + "owner": { + "interface": 5 + }, + "docs": { + "contents": "Open flags used by `open-at`." + } + }, + { + "name": "link-count", + "kind": { + "type": "u64" + }, + "owner": { + "interface": 5 + }, + "docs": { + "contents": "Number of hard links to an inode." + } + }, + { + "name": null, + "kind": { + "option": 27 + }, + "owner": null + }, + { + "name": "descriptor-stat", + "kind": { + "record": { + "fields": [ + { + "name": "type", + "type": 29, + "docs": { + "contents": "File type." + } + }, + { + "name": "link-count", + "type": 33, + "docs": { + "contents": "Number of hard links to the file." + } + }, + { + "name": "size", + "type": 28, + "docs": { + "contents": "For regular files, the file size in bytes. For symbolic links, the\nlength in bytes of the pathname contained in the symbolic link." + } + }, + { + "name": "data-access-timestamp", + "type": 34, + "docs": { + "contents": "Last data access timestamp.\n\nIf the `option` is none, the platform doesn't maintain an access\ntimestamp for this file." + } + }, + { + "name": "data-modification-timestamp", + "type": 34, + "docs": { + "contents": "Last data modification timestamp.\n\nIf the `option` is none, the platform doesn't maintain a\nmodification timestamp for this file." + } + }, + { + "name": "status-change-timestamp", + "type": 34, + "docs": { + "contents": "Last file status-change timestamp.\n\nIf the `option` is none, the platform doesn't maintain a\nstatus-change timestamp for this file." + } + } + ] + } + }, + "owner": { + "interface": 5 + }, + "docs": { + "contents": "File attributes.\n\nNote: This was called `filestat` in earlier versions of WASI." + } + }, + { + "name": "new-timestamp", + "kind": { + "variant": { + "cases": [ + { + "name": "no-change", + "type": null, + "docs": { + "contents": "Leave the timestamp set to its previous value." + } + }, + { + "name": "now", + "type": null, + "docs": { + "contents": "Set the timestamp to the current time of the system clock associated\nwith the filesystem." + } + }, + { + "name": "timestamp", + "type": 27, + "docs": { + "contents": "Set the timestamp to the given value." + } + } + ] + } + }, + "owner": { + "interface": 5 + }, + "docs": { + "contents": "When setting a timestamp, this gives the value to set it to." + } + }, + { + "name": "directory-entry", + "kind": { + "record": { + "fields": [ + { + "name": "type", + "type": 29, + "docs": { + "contents": "The type of the file referred to by this directory entry." + } + }, + { + "name": "name", + "type": "string", + "docs": { + "contents": "The name of the object." + } + } + ] + } + }, + "owner": { + "interface": 5 + }, + "docs": { + "contents": "A directory entry." + } + }, + { + "name": "error-code", + "kind": { + "enum": { + "cases": [ + { + "name": "access", + "docs": { + "contents": "Permission denied, similar to `EACCES` in POSIX." + } + }, + { + "name": "would-block", + "docs": { + "contents": "Resource unavailable, or operation would block, similar to `EAGAIN` and `EWOULDBLOCK`\nin POSIX." + } + }, + { + "name": "already", + "docs": { + "contents": "Connection already in progress, similar to `EALREADY` in POSIX." + } + }, + { + "name": "bad-descriptor", + "docs": { + "contents": "Bad descriptor, similar to `EBADF` in POSIX." + } + }, + { + "name": "busy", + "docs": { + "contents": "Device or resource busy, similar to `EBUSY` in POSIX." + } + }, + { + "name": "deadlock", + "docs": { + "contents": "Resource deadlock would occur, similar to `EDEADLK` in POSIX." + } + }, + { + "name": "quota", + "docs": { + "contents": "Storage quota exceeded, similar to `EDQUOT` in POSIX." + } + }, + { + "name": "exist", + "docs": { + "contents": "File exists, similar to `EEXIST` in POSIX." + } + }, + { + "name": "file-too-large", + "docs": { + "contents": "File too large, similar to `EFBIG` in POSIX." + } + }, + { + "name": "illegal-byte-sequence", + "docs": { + "contents": "Illegal byte sequence, similar to `EILSEQ` in POSIX." + } + }, + { + "name": "in-progress", + "docs": { + "contents": "Operation in progress, similar to `EINPROGRESS` in POSIX." + } + }, + { + "name": "interrupted", + "docs": { + "contents": "Interrupted function, similar to `EINTR` in POSIX." + } + }, + { + "name": "invalid", + "docs": { + "contents": "Invalid argument, similar to `EINVAL` in POSIX." + } + }, + { + "name": "io", + "docs": { + "contents": "I/O error, similar to `EIO` in POSIX." + } + }, + { + "name": "is-directory", + "docs": { + "contents": "Is a directory, similar to `EISDIR` in POSIX." + } + }, + { + "name": "loop", + "docs": { + "contents": "Too many levels of symbolic links, similar to `ELOOP` in POSIX." + } + }, + { + "name": "too-many-links", + "docs": { + "contents": "Too many links, similar to `EMLINK` in POSIX." + } + }, + { + "name": "message-size", + "docs": { + "contents": "Message too large, similar to `EMSGSIZE` in POSIX." + } + }, + { + "name": "name-too-long", + "docs": { + "contents": "Filename too long, similar to `ENAMETOOLONG` in POSIX." + } + }, + { + "name": "no-device", + "docs": { + "contents": "No such device, similar to `ENODEV` in POSIX." + } + }, + { + "name": "no-entry", + "docs": { + "contents": "No such file or directory, similar to `ENOENT` in POSIX." + } + }, + { + "name": "no-lock", + "docs": { + "contents": "No locks available, similar to `ENOLCK` in POSIX." + } + }, + { + "name": "insufficient-memory", + "docs": { + "contents": "Not enough space, similar to `ENOMEM` in POSIX." + } + }, + { + "name": "insufficient-space", + "docs": { + "contents": "No space left on device, similar to `ENOSPC` in POSIX." + } + }, + { + "name": "not-directory", + "docs": { + "contents": "Not a directory or a symbolic link to a directory, similar to `ENOTDIR` in POSIX." + } + }, + { + "name": "not-empty", + "docs": { + "contents": "Directory not empty, similar to `ENOTEMPTY` in POSIX." + } + }, + { + "name": "not-recoverable", + "docs": { + "contents": "State not recoverable, similar to `ENOTRECOVERABLE` in POSIX." + } + }, + { + "name": "unsupported", + "docs": { + "contents": "Not supported, similar to `ENOTSUP` and `ENOSYS` in POSIX." + } + }, + { + "name": "no-tty", + "docs": { + "contents": "Inappropriate I/O control operation, similar to `ENOTTY` in POSIX." + } + }, + { + "name": "no-such-device", + "docs": { + "contents": "No such device or address, similar to `ENXIO` in POSIX." + } + }, + { + "name": "overflow", + "docs": { + "contents": "Value too large to be stored in data type, similar to `EOVERFLOW` in POSIX." + } + }, + { + "name": "not-permitted", + "docs": { + "contents": "Operation not permitted, similar to `EPERM` in POSIX." + } + }, + { + "name": "pipe", + "docs": { + "contents": "Broken pipe, similar to `EPIPE` in POSIX." + } + }, + { + "name": "read-only", + "docs": { + "contents": "Read-only file system, similar to `EROFS` in POSIX." + } + }, + { + "name": "invalid-seek", + "docs": { + "contents": "Invalid seek, similar to `ESPIPE` in POSIX." + } + }, + { + "name": "text-file-busy", + "docs": { + "contents": "Text file busy, similar to `ETXTBSY` in POSIX." + } + }, + { + "name": "cross-device", + "docs": { + "contents": "Cross-device link, similar to `EXDEV` in POSIX." + } + } + ] + } + }, + "owner": { + "interface": 5 + }, + "docs": { + "contents": "Error codes returned by functions, similar to `errno` in POSIX.\nNot all of these error codes are returned by the functions provided by this\nAPI; some are used in higher-level library layers, and others are provided\nmerely for alignment with POSIX." + } + }, + { + "name": "advice", + "kind": { + "enum": { + "cases": [ + { + "name": "normal", + "docs": { + "contents": "The application has no advice to give on its behavior with respect\nto the specified data." + } + }, + { + "name": "sequential", + "docs": { + "contents": "The application expects to access the specified data sequentially\nfrom lower offsets to higher offsets." + } + }, + { + "name": "random", + "docs": { + "contents": "The application expects to access the specified data in a random\norder." + } + }, + { + "name": "will-need", + "docs": { + "contents": "The application expects to access the specified data in the near\nfuture." + } + }, + { + "name": "dont-need", + "docs": { + "contents": "The application expects that it will not access the specified data\nin the near future." + } + }, + { + "name": "no-reuse", + "docs": { + "contents": "The application expects to access the specified data once and then\nnot reuse it thereafter." + } + } + ] + } + }, + "owner": { + "interface": 5 + }, + "docs": { + "contents": "File or memory access pattern advisory information." + } + }, + { + "name": "metadata-hash-value", + "kind": { + "record": { + "fields": [ + { + "name": "lower", + "type": "u64", + "docs": { + "contents": "64 bits of a 128-bit hash value." + } + }, + { + "name": "upper", + "type": "u64", + "docs": { + "contents": "Another 64 bits of a 128-bit hash value." + } + } + ] + } + }, + "owner": { + "interface": 5 + }, + "docs": { + "contents": "A 128-bit hash value, split into parts because wasm doesn't have a\n128-bit integer type." + } + }, + { + "name": "descriptor", + "kind": "resource", + "owner": { + "interface": 5 + }, + "docs": { + "contents": "A descriptor is a reference to a filesystem object, which may be a file,\ndirectory, named pipe, special file, or other object on which filesystem\ncalls may be made." + } + }, + { + "name": "directory-entry-stream", + "kind": "resource", + "owner": { + "interface": 5 + }, + "docs": { + "contents": "A stream of directory entries." + } + }, + { + "name": null, + "kind": { + "handle": { + "borrow": 41 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": null, + "err": 38 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "own": 25 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 45, + "err": 38 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 30, + "err": 38 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 29, + "err": 38 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 40, + "err": 38 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "own": 41 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 50, + "err": 38 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "list": "u8" + }, + "owner": null + }, + { + "name": null, + "kind": { + "tuple": { + "types": [ + 52, + "bool" + ] + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 53, + "err": 38 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "own": 42 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 55, + "err": 38 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "own": 24 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 57, + "err": 38 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": "string", + "err": 38 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 35, + "err": 38 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 28, + "err": 38 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "borrow": 42 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "option": 37 + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 63, + "err": 38 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "borrow": 26 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "option": 38 + }, + "owner": null + }, + { + "name": "descriptor", + "kind": { + "type": 41 + }, + "owner": { + "interface": 6 + } + }, + { + "name": null, + "kind": { + "handle": { + "own": 67 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "tuple": { + "types": [ + 68, + "string" + ] + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "list": 69 + }, + "owner": null + }, + { + "name": "network", + "kind": "resource", + "owner": { + "interface": 7 + }, + "docs": { + "contents": "An opaque resource that represents access to (a subset of) the network.\nThis enables context-based security for networking.\nThere is no need for this to map 1:1 to a physical network interface." + } + }, + { + "name": "error-code", + "kind": { + "enum": { + "cases": [ + { + "name": "unknown", + "docs": { + "contents": "Unknown error" + } + }, + { + "name": "access-denied", + "docs": { + "contents": "Access denied.\n\nPOSIX equivalent: EACCES, EPERM" + } + }, + { + "name": "not-supported", + "docs": { + "contents": "The operation is not supported.\n\nPOSIX equivalent: EOPNOTSUPP" + } + }, + { + "name": "invalid-argument", + "docs": { + "contents": "One of the arguments is invalid.\n\nPOSIX equivalent: EINVAL" + } + }, + { + "name": "out-of-memory", + "docs": { + "contents": "Not enough memory to complete the operation.\n\nPOSIX equivalent: ENOMEM, ENOBUFS, EAI_MEMORY" + } + }, + { + "name": "timeout", + "docs": { + "contents": "The operation timed out before it could finish completely." + } + }, + { + "name": "concurrency-conflict", + "docs": { + "contents": "This operation is incompatible with another asynchronous operation that is already\nin progress.\n\nPOSIX equivalent: EALREADY" + } + }, + { + "name": "not-in-progress", + "docs": { + "contents": "Trying to finish an asynchronous operation that:\n- has not been started yet, or:\n- was already finished by a previous `finish-*` call.\n\nNote: this is scheduled to be removed when `future`s are natively supported." + } + }, + { + "name": "would-block", + "docs": { + "contents": "The operation has been aborted because it could not be completed immediately.\n\nNote: this is scheduled to be removed when `future`s are natively supported." + } + }, + { + "name": "invalid-state", + "docs": { + "contents": "The operation is not valid in the socket's current state." + } + }, + { + "name": "new-socket-limit", + "docs": { + "contents": "A new socket resource could not be created because of a system limit." + } + }, + { + "name": "address-not-bindable", + "docs": { + "contents": "A bind operation failed because the provided address is not an address that the\n`network` can bind to." + } + }, + { + "name": "address-in-use", + "docs": { + "contents": "A bind operation failed because the provided address is already in use or because\nthere are no ephemeral ports available." + } + }, + { + "name": "remote-unreachable", + "docs": { + "contents": "The remote address is not reachable" + } + }, + { + "name": "connection-refused", + "docs": { + "contents": "The TCP connection was forcefully rejected" + } + }, + { + "name": "connection-reset", + "docs": { + "contents": "The TCP connection was reset." + } + }, + { + "name": "connection-aborted", + "docs": { + "contents": "A TCP connection was aborted." + } + }, + { + "name": "datagram-too-large", + "docs": { + "contents": "The size of a datagram sent to a UDP socket exceeded the maximum\nsupported size." + } + }, + { + "name": "name-unresolvable", + "docs": { + "contents": "Name does not exist or has no suitable associated IP addresses." + } + }, + { + "name": "temporary-resolver-failure", + "docs": { + "contents": "A temporary failure in name resolution occurred." + } + }, + { + "name": "permanent-resolver-failure", + "docs": { + "contents": "A permanent failure in name resolution occurred." + } + } + ] + } + }, + "owner": { + "interface": 7 + }, + "docs": { + "contents": "Error codes.\n\nIn theory, every API can return any error code.\nIn practice, API's typically only return the errors documented per API\ncombined with a couple of errors that are always possible:\n- `unknown`\n- `access-denied`\n- `not-supported`\n- `out-of-memory`\n- `concurrency-conflict`\n\nSee each individual API for what the POSIX equivalents are. They sometimes differ\nper API." + } + }, + { + "name": "ip-address-family", + "kind": { + "enum": { + "cases": [ + { + "name": "ipv4", + "docs": { + "contents": "Similar to `AF_INET` in POSIX." + } + }, + { + "name": "ipv6", + "docs": { + "contents": "Similar to `AF_INET6` in POSIX." + } + } + ] + } + }, + "owner": { + "interface": 7 + } + }, + { + "name": "ipv4-address", + "kind": { + "tuple": { + "types": [ + "u8", + "u8", + "u8", + "u8" + ] + } + }, + "owner": { + "interface": 7 + } + }, + { + "name": "ipv6-address", + "kind": { + "tuple": { + "types": [ + "u16", + "u16", + "u16", + "u16", + "u16", + "u16", + "u16", + "u16" + ] + } + }, + "owner": { + "interface": 7 + } + }, + { + "name": "ip-address", + "kind": { + "variant": { + "cases": [ + { + "name": "ipv4", + "type": 74 + }, + { + "name": "ipv6", + "type": 75 + } + ] + } + }, + "owner": { + "interface": 7 + } + }, + { + "name": "ipv4-socket-address", + "kind": { + "record": { + "fields": [ + { + "name": "port", + "type": "u16", + "docs": { + "contents": "sin_port" + } + }, + { + "name": "address", + "type": 74, + "docs": { + "contents": "sin_addr" + } + } + ] + } + }, + "owner": { + "interface": 7 + } + }, + { + "name": "ipv6-socket-address", + "kind": { + "record": { + "fields": [ + { + "name": "port", + "type": "u16", + "docs": { + "contents": "sin6_port" + } + }, + { + "name": "flow-info", + "type": "u32", + "docs": { + "contents": "sin6_flowinfo" + } + }, + { + "name": "address", + "type": 75, + "docs": { + "contents": "sin6_addr" + } + }, + { + "name": "scope-id", + "type": "u32", + "docs": { + "contents": "sin6_scope_id" + } + } + ] + } + }, + "owner": { + "interface": 7 + } + }, + { + "name": "ip-socket-address", + "kind": { + "variant": { + "cases": [ + { + "name": "ipv4", + "type": 77 + }, + { + "name": "ipv6", + "type": 78 + } + ] + } + }, + "owner": { + "interface": 7 + } + }, + { + "name": "network", + "kind": { + "type": 71 + }, + "owner": { + "interface": 8 + } + }, + { + "name": "pollable", + "kind": { + "type": 2 + }, + "owner": { + "interface": 9 + } + }, + { + "name": "network", + "kind": { + "type": 71 + }, + "owner": { + "interface": 9 + } + }, + { + "name": "error-code", + "kind": { + "type": 72 + }, + "owner": { + "interface": 9 + } + }, + { + "name": "ip-address", + "kind": { + "type": 76 + }, + "owner": { + "interface": 9 + } + }, + { + "name": "resolve-address-stream", + "kind": "resource", + "owner": { + "interface": 9 + } + }, + { + "name": null, + "kind": { + "handle": { + "borrow": 85 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "option": 84 + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 87, + "err": 83 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "borrow": 82 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "own": 85 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 90, + "err": 83 + } + }, + "owner": null + }, + { + "name": "input-stream", + "kind": { + "type": 10 + }, + "owner": { + "interface": 10 + } + }, + { + "name": "output-stream", + "kind": { + "type": 11 + }, + "owner": { + "interface": 10 + } + }, + { + "name": "pollable", + "kind": { + "type": 2 + }, + "owner": { + "interface": 10 + } + }, + { + "name": "duration", + "kind": { + "type": 21 + }, + "owner": { + "interface": 10 + } + }, + { + "name": "network", + "kind": { + "type": 71 + }, + "owner": { + "interface": 10 + } + }, + { + "name": "error-code", + "kind": { + "type": 72 + }, + "owner": { + "interface": 10 + } + }, + { + "name": "ip-socket-address", + "kind": { + "type": 79 + }, + "owner": { + "interface": 10 + } + }, + { + "name": "ip-address-family", + "kind": { + "type": 73 + }, + "owner": { + "interface": 10 + } + }, + { + "name": "shutdown-type", + "kind": { + "enum": { + "cases": [ + { + "name": "receive", + "docs": { + "contents": "Similar to `SHUT_RD` in POSIX." + } + }, + { + "name": "send", + "docs": { + "contents": "Similar to `SHUT_WR` in POSIX." + } + }, + { + "name": "both", + "docs": { + "contents": "Similar to `SHUT_RDWR` in POSIX." + } + } + ] + } + }, + "owner": { + "interface": 10 + } + }, + { + "name": "tcp-socket", + "kind": "resource", + "owner": { + "interface": 10 + }, + "docs": { + "contents": "A TCP socket resource.\n\nThe socket can be in one of the following states:\n- `unbound`\n- `bind-in-progress`\n- `bound` (See note below)\n- `listen-in-progress`\n- `listening`\n- `connect-in-progress`\n- `connected`\n- `closed`\nSee \nfor a more information.\n\nNote: Except where explicitly mentioned, whenever this documentation uses\nthe term \"bound\" without backticks it actually means: in the `bound` state *or\nhigher*.\n(i.e. `bound`, `listen-in-progress`, `listening`, `connect-in-progress` or `connected`)\n\nIn addition to the general error codes documented on the\n`network::error-code` type, TCP socket methods may always return\n`error(invalid-state)` when in the `closed` state." + } + }, + { + "name": null, + "kind": { + "handle": { + "borrow": 101 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "own": 101 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "own": 92 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "own": 93 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "tuple": { + "types": [ + 103, + 104, + 105 + ] + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 106, + "err": 97 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": null, + "err": 97 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "tuple": { + "types": [ + 104, + 105 + ] + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 109, + "err": 97 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": "u8", + "err": 97 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": "u32", + "err": 97 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": "bool", + "err": 97 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 95, + "err": 97 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 98, + "err": 97 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": "u64", + "err": 97 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "borrow": 96 + } + }, + "owner": null + }, + { + "name": "network", + "kind": { + "type": 71 + }, + "owner": { + "interface": 11 + } + }, + { + "name": "error-code", + "kind": { + "type": 72 + }, + "owner": { + "interface": 11 + } + }, + { + "name": "ip-address-family", + "kind": { + "type": 73 + }, + "owner": { + "interface": 11 + } + }, + { + "name": "tcp-socket", + "kind": { + "type": 101 + }, + "owner": { + "interface": 11 + } + }, + { + "name": null, + "kind": { + "handle": { + "own": 121 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 122, + "err": 119 + } + }, + "owner": null + }, + { + "name": "pollable", + "kind": { + "type": 2 + }, + "owner": { + "interface": 12 + } + }, + { + "name": "network", + "kind": { + "type": 71 + }, + "owner": { + "interface": 12 + } + }, + { + "name": "error-code", + "kind": { + "type": 72 + }, + "owner": { + "interface": 12 + } + }, + { + "name": "ip-socket-address", + "kind": { + "type": 79 + }, + "owner": { + "interface": 12 + } + }, + { + "name": "ip-address-family", + "kind": { + "type": 73 + }, + "owner": { + "interface": 12 + } + }, + { + "name": null, + "kind": { + "list": "u8" + }, + "owner": null + }, + { + "name": "incoming-datagram", + "kind": { + "record": { + "fields": [ + { + "name": "data", + "type": 129, + "docs": { + "contents": "The payload.\n\nTheoretical max size: ~64 KiB. In practice, typically less than 1500 bytes." + } + }, + { + "name": "remote-address", + "type": 127, + "docs": { + "contents": "The source address.\n\nThis field is guaranteed to match the remote address the stream was initialized\nwith, if any.\n\nEquivalent to the `src_addr` out parameter of `recvfrom`." + } + } + ] + } + }, + "owner": { + "interface": 12 + }, + "docs": { + "contents": "A received datagram." + } + }, + { + "name": null, + "kind": { + "option": 127 + }, + "owner": null + }, + { + "name": "outgoing-datagram", + "kind": { + "record": { + "fields": [ + { + "name": "data", + "type": 129, + "docs": { + "contents": "The payload." + } + }, + { + "name": "remote-address", + "type": 131, + "docs": { + "contents": "The destination address.\n\nThe requirements on this field depend on how the stream was initialized:\n- with a remote address: this field must be None or match the stream's remote\naddress exactly.\n- without a remote address: this field is required.\n\nIf this value is None, the send operation is equivalent to `send` in POSIX. Otherwise\nit is equivalent to `sendto`." + } + } + ] + } + }, + "owner": { + "interface": 12 + }, + "docs": { + "contents": "A datagram to be sent out." + } + }, + { + "name": "udp-socket", + "kind": "resource", + "owner": { + "interface": 12 + }, + "docs": { + "contents": "A UDP socket handle." + } + }, + { + "name": "incoming-datagram-stream", + "kind": "resource", + "owner": { + "interface": 12 + } + }, + { + "name": "outgoing-datagram-stream", + "kind": "resource", + "owner": { + "interface": 12 + } + }, + { + "name": null, + "kind": { + "handle": { + "borrow": 133 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": null, + "err": 126 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 127, + "err": 126 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": "u64", + "err": 126 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "borrow": 125 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "own": 134 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "own": 135 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "tuple": { + "types": [ + 141, + 142 + ] + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 143, + "err": 126 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": "u8", + "err": 126 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "borrow": 134 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "list": 130 + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 147, + "err": 126 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "borrow": 135 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "list": 132 + }, + "owner": null + }, + { + "name": "network", + "kind": { + "type": 71 + }, + "owner": { + "interface": 13 + } + }, + { + "name": "error-code", + "kind": { + "type": 72 + }, + "owner": { + "interface": 13 + } + }, + { + "name": "ip-address-family", + "kind": { + "type": 73 + }, + "owner": { + "interface": 13 + } + }, + { + "name": "udp-socket", + "kind": { + "type": 133 + }, + "owner": { + "interface": 13 + } + }, + { + "name": null, + "kind": { + "handle": { + "own": 154 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": 155, + "err": 152 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "own": 80 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "own": 81 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "own": 94 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "own": 124 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "tuple": { + "types": [ + "u64", + "u64" + ] + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "list": "u8" + }, + "owner": null + }, + { + "name": null, + "kind": { + "tuple": { + "types": [ + "string", + "string" + ] + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "list": 163 + }, + "owner": null + }, + { + "name": null, + "kind": { + "list": "string" + }, + "owner": null + }, + { + "name": null, + "kind": { + "option": "string" + }, + "owner": null + }, + { + "name": null, + "kind": { + "result": { + "ok": null, + "err": null + } + }, + "owner": null + }, + { + "name": "input-stream", + "kind": { + "type": 10 + }, + "owner": { + "interface": 20 + } + }, + { + "name": "output-stream", + "kind": { + "type": 11 + }, + "owner": { + "interface": 21 + } + }, + { + "name": "output-stream", + "kind": { + "type": 11 + }, + "owner": { + "interface": 22 + } + }, + { + "name": "terminal-input", + "kind": "resource", + "owner": { + "interface": 23 + }, + "docs": { + "contents": "The input side of a terminal." + } + }, + { + "name": "terminal-output", + "kind": "resource", + "owner": { + "interface": 24 + }, + "docs": { + "contents": "The output side of a terminal." + } + }, + { + "name": "terminal-input", + "kind": { + "type": 171 + }, + "owner": { + "interface": 25 + } + }, + { + "name": null, + "kind": { + "handle": { + "own": 173 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "option": 174 + }, + "owner": null + }, + { + "name": "terminal-output", + "kind": { + "type": 172 + }, + "owner": { + "interface": 26 + } + }, + { + "name": null, + "kind": { + "handle": { + "own": 176 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "option": 177 + }, + "owner": null + }, + { + "name": "terminal-output", + "kind": { + "type": 172 + }, + "owner": { + "interface": 27 + } + }, + { + "name": null, + "kind": { + "handle": { + "own": 179 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "option": 180 + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "own": 168 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "own": 169 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "handle": { + "own": 170 + } + }, + "owner": null + } + ], + "packages": [ + { + "name": "wasi:io@0.2.0", + "interfaces": { + "error": 0, + "poll": 1, + "streams": 2 + }, + "worlds": {} + }, + { + "name": "wasi:clocks@0.2.0", + "interfaces": { + "monotonic-clock": 3, + "wall-clock": 4 + }, + "worlds": {} + }, + { + "name": "wasi:filesystem@0.2.0", + "interfaces": { + "types": 5, + "preopens": 6 + }, + "worlds": {} + }, + { + "name": "wasi:sockets@0.2.0", + "interfaces": { + "network": 7, + "instance-network": 8, + "ip-name-lookup": 9, + "tcp": 10, + "tcp-create-socket": 11, + "udp": 12, + "udp-create-socket": 13 + }, + "worlds": {} + }, + { + "name": "wasi:random@0.2.0", + "interfaces": { + "insecure-seed": 14, + "insecure": 15, + "random": 16 + }, + "worlds": {} + }, + { + "name": "wasi:cli@0.2.0", + "interfaces": { + "environment": 17, + "exit": 18, + "run": 19, + "stdin": 20, + "stdout": 21, + "stderr": 22, + "terminal-input": 23, + "terminal-output": 24, + "terminal-stdin": 25, + "terminal-stdout": 26, + "terminal-stderr": 27 + }, + "worlds": { + "command": 0 + } + } + ] +} \ No newline at end of file diff --git a/testdata/wasi/cli-command.wit.json.golden.wit b/testdata/wasi/cli-command.wit.json.golden.wit new file mode 100644 index 00000000..7b2af2ae --- /dev/null +++ b/testdata/wasi/cli-command.wit.json.golden.wit @@ -0,0 +1,2099 @@ +package wasi:cli@0.2.0; + +interface environment { + /// Get the POSIX-style environment variables. + /// + /// Each environment variable is provided as a pair of string variable names + /// and string value. + /// + /// Morally, these are a value import, but until value imports are available + /// in the component model, this import function should return the same + /// values each time it is called. + get-environment: func() -> list>; + + /// Get the POSIX-style arguments to the program. + get-arguments: func() -> list; + + /// Return a path that programs should use as their initial current working + /// directory, interpreting `.` as shorthand for this. + initial-cwd: func() -> option; +} + +interface exit { + /// Exit the current instance and any linked instances. + exit: func(status: result); +} + +interface run { + /// Run the program. + run: func() -> result; +} + +interface stdin { + use wasi:io/streams@0.2.0.{input-stream}; + get-stdin: func() -> input-stream; +} + +interface stdout { + use wasi:io/streams@0.2.0.{output-stream}; + get-stdout: func() -> output-stream; +} + +interface stderr { + use wasi:io/streams@0.2.0.{output-stream}; + get-stderr: func() -> output-stream; +} + +/// Terminal input. +/// +/// In the future, this may include functions for disabling echoing, +/// disabling input buffering so that keyboard events are sent through +/// immediately, querying supported features, and so on. +interface terminal-input { + /// The input side of a terminal. + resource terminal-input; +} + +/// Terminal output. +/// +/// In the future, this may include functions for querying the terminal +/// size, being notified of terminal size changes, querying supported +/// features, and so on. +interface terminal-output { + /// The output side of a terminal. + resource terminal-output; +} + +/// An interface providing an optional `terminal-input` for stdin as a +/// link-time authority. +interface terminal-stdin { + use terminal-input.{terminal-input}; + + /// If stdin is connected to a terminal, return a `terminal-input` handle + /// allowing further interaction with it. + get-terminal-stdin: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stdout as a +/// link-time authority. +interface terminal-stdout { + use terminal-output.{terminal-output}; + + /// If stdout is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + get-terminal-stdout: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stderr as a +/// link-time authority. +interface terminal-stderr { + use terminal-output.{terminal-output}; + + /// If stderr is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + get-terminal-stderr: func() -> option; +} + +world command { + import environment; + import exit; + import wasi:io/error@0.2.0; + import wasi:io/poll@0.2.0; + import wasi:io/streams@0.2.0; + import stdin; + import stdout; + import stderr; + import terminal-input; + import terminal-output; + import terminal-stdin; + import terminal-stdout; + import terminal-stderr; + import wasi:clocks/monotonic-clock@0.2.0; + import wasi:clocks/wall-clock@0.2.0; + import wasi:filesystem/types@0.2.0; + import wasi:filesystem/preopens@0.2.0; + import wasi:sockets/network@0.2.0; + import wasi:sockets/instance-network@0.2.0; + import wasi:sockets/udp@0.2.0; + import wasi:sockets/udp-create-socket@0.2.0; + import wasi:sockets/tcp@0.2.0; + import wasi:sockets/tcp-create-socket@0.2.0; + import wasi:sockets/ip-name-lookup@0.2.0; + import wasi:random/random@0.2.0; + import wasi:random/insecure@0.2.0; + import wasi:random/insecure-seed@0.2.0; + export run; +} + +package wasi:filesystem@0.2.0 { + /// WASI filesystem is a filesystem API primarily intended to let users run WASI + /// programs that access their files on their existing filesystems, without + /// significant overhead. + /// + /// It is intended to be roughly portable between Unix-family platforms and + /// Windows, though it does not hide many of the major differences. + /// + /// Paths are passed as interface-type `string`s, meaning they must consist of + /// a sequence of Unicode Scalar Values (USVs). Some filesystems may contain + /// paths which are not accessible by this API. + /// + /// The directory separator in WASI is always the forward-slash (`/`). + /// + /// All paths in WASI are relative paths, and are interpreted relative to a + /// `descriptor` referring to a base directory. If a `path` argument to any WASI + /// function starts with `/`, or if any step of resolving a `path`, including + /// `..` and symbolic link steps, reaches a directory outside of the base + /// directory, or reaches a symlink to an absolute or rooted path in the + /// underlying filesystem, the function fails with `error-code::not-permitted`. + /// + /// For more information about WASI path resolution and sandboxing, see + /// [WASI filesystem path resolution]. + /// + /// [WASI filesystem path resolution]: https://github.com/WebAssembly/wasi-filesystem/blob/main/path-resolution.md + interface types { + use wasi:io/streams@0.2.0.{input-stream}; + use wasi:io/streams@0.2.0.{output-stream}; + use wasi:io/streams@0.2.0.{error}; + use wasi:clocks/wall-clock@0.2.0.{datetime}; + + /// File size or length of a region within a file. + type filesize = u64; + + /// The type of a filesystem object referenced by a descriptor. + /// + /// Note: This was called `filetype` in earlier versions of WASI. + enum descriptor-type { + /// The type of the descriptor or file is unknown or is different from + /// any of the other types specified. + unknown, + /// The descriptor refers to a block device inode. + block-device, + /// The descriptor refers to a character device inode. + character-device, + /// The descriptor refers to a directory inode. + directory, + /// The descriptor refers to a named pipe. + fifo, + /// The file refers to a symbolic link inode. + symbolic-link, + /// The descriptor refers to a regular file inode. + regular-file, + /// The descriptor refers to a socket. + socket + } + + /// Descriptor flags. + /// + /// Note: This was called `fdflags` in earlier versions of WASI. + flags descriptor-flags { + /// Read mode: Data can be read. + read, + /// Write mode: Data can be written to. + write, + /// Request that writes be performed according to synchronized I/O file + /// integrity completion. The data stored in the file and the file's + /// metadata are synchronized. This is similar to `O_SYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + file-integrity-sync, + /// Request that writes be performed according to synchronized I/O data + /// integrity completion. Only the data stored in the file is + /// synchronized. This is similar to `O_DSYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + data-integrity-sync, + /// Requests that reads be performed at the same level of integrety + /// requested for writes. This is similar to `O_RSYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + requested-write-sync, + /// Mutating directories mode: Directory contents may be mutated. + /// + /// When this flag is unset on a descriptor, operations using the + /// descriptor which would create, rename, delete, modify the data or + /// metadata of filesystem objects, or obtain another handle which + /// would permit any of those, shall fail with `error-code::read-only` if + /// they would otherwise succeed. + /// + /// This may only be set on directories. + mutate-directory, + } + + /// Flags determining the method of how paths are resolved. + flags path-flags { + /// As long as the resolved path corresponds to a symbolic link, it is + /// expanded. + symlink-follow, + } + + /// Open flags used by `open-at`. + flags open-flags { + /// Create file if it does not exist, similar to `O_CREAT` in POSIX. + create, + /// Fail if not a directory, similar to `O_DIRECTORY` in POSIX. + directory, + /// Fail if file already exists, similar to `O_EXCL` in POSIX. + exclusive, + /// Truncate file to size 0, similar to `O_TRUNC` in POSIX. + truncate, + } + + /// Number of hard links to an inode. + type link-count = u64; + + /// File attributes. + /// + /// Note: This was called `filestat` in earlier versions of WASI. + record descriptor-stat { + /// File type. + %type: descriptor-type, + /// Number of hard links to the file. + link-count: link-count, + /// For regular files, the file size in bytes. For symbolic links, the + /// length in bytes of the pathname contained in the symbolic link. + size: filesize, + /// Last data access timestamp. + /// + /// If the `option` is none, the platform doesn't maintain an access + /// timestamp for this file. + data-access-timestamp: option, + /// Last data modification timestamp. + /// + /// If the `option` is none, the platform doesn't maintain a + /// modification timestamp for this file. + data-modification-timestamp: option, + /// Last file status-change timestamp. + /// + /// If the `option` is none, the platform doesn't maintain a + /// status-change timestamp for this file. + status-change-timestamp: option, + } + + /// When setting a timestamp, this gives the value to set it to. + variant new-timestamp { + /// Leave the timestamp set to its previous value. + no-change, + /// Set the timestamp to the current time of the system clock associated + /// with the filesystem. + now, + /// Set the timestamp to the given value. + timestamp(datetime), + } + + /// A directory entry. + record directory-entry { + /// The type of the file referred to by this directory entry. + %type: descriptor-type, + /// The name of the object. + name: string, + } + + /// Error codes returned by functions, similar to `errno` in POSIX. + /// Not all of these error codes are returned by the functions provided by this + /// API; some are used in higher-level library layers, and others are provided + /// merely for alignment with POSIX. + enum error-code { + /// Permission denied, similar to `EACCES` in POSIX. + access, + /// Resource unavailable, or operation would block, similar to `EAGAIN` and `EWOULDBLOCK` + /// in POSIX. + would-block, + /// Connection already in progress, similar to `EALREADY` in POSIX. + already, + /// Bad descriptor, similar to `EBADF` in POSIX. + bad-descriptor, + /// Device or resource busy, similar to `EBUSY` in POSIX. + busy, + /// Resource deadlock would occur, similar to `EDEADLK` in POSIX. + deadlock, + /// Storage quota exceeded, similar to `EDQUOT` in POSIX. + quota, + /// File exists, similar to `EEXIST` in POSIX. + exist, + /// File too large, similar to `EFBIG` in POSIX. + file-too-large, + /// Illegal byte sequence, similar to `EILSEQ` in POSIX. + illegal-byte-sequence, + /// Operation in progress, similar to `EINPROGRESS` in POSIX. + in-progress, + /// Interrupted function, similar to `EINTR` in POSIX. + interrupted, + /// Invalid argument, similar to `EINVAL` in POSIX. + invalid, + /// I/O error, similar to `EIO` in POSIX. + io, + /// Is a directory, similar to `EISDIR` in POSIX. + is-directory, + /// Too many levels of symbolic links, similar to `ELOOP` in POSIX. + loop, + /// Too many links, similar to `EMLINK` in POSIX. + too-many-links, + /// Message too large, similar to `EMSGSIZE` in POSIX. + message-size, + /// Filename too long, similar to `ENAMETOOLONG` in POSIX. + name-too-long, + /// No such device, similar to `ENODEV` in POSIX. + no-device, + /// No such file or directory, similar to `ENOENT` in POSIX. + no-entry, + /// No locks available, similar to `ENOLCK` in POSIX. + no-lock, + /// Not enough space, similar to `ENOMEM` in POSIX. + insufficient-memory, + /// No space left on device, similar to `ENOSPC` in POSIX. + insufficient-space, + /// Not a directory or a symbolic link to a directory, similar to `ENOTDIR` in POSIX. + not-directory, + /// Directory not empty, similar to `ENOTEMPTY` in POSIX. + not-empty, + /// State not recoverable, similar to `ENOTRECOVERABLE` in POSIX. + not-recoverable, + /// Not supported, similar to `ENOTSUP` and `ENOSYS` in POSIX. + unsupported, + /// Inappropriate I/O control operation, similar to `ENOTTY` in POSIX. + no-tty, + /// No such device or address, similar to `ENXIO` in POSIX. + no-such-device, + /// Value too large to be stored in data type, similar to `EOVERFLOW` in POSIX. + overflow, + /// Operation not permitted, similar to `EPERM` in POSIX. + not-permitted, + /// Broken pipe, similar to `EPIPE` in POSIX. + pipe, + /// Read-only file system, similar to `EROFS` in POSIX. + read-only, + /// Invalid seek, similar to `ESPIPE` in POSIX. + invalid-seek, + /// Text file busy, similar to `ETXTBSY` in POSIX. + text-file-busy, + /// Cross-device link, similar to `EXDEV` in POSIX. + cross-device + } + + /// File or memory access pattern advisory information. + enum advice { + /// The application has no advice to give on its behavior with respect + /// to the specified data. + normal, + /// The application expects to access the specified data sequentially + /// from lower offsets to higher offsets. + sequential, + /// The application expects to access the specified data in a random + /// order. + random, + /// The application expects to access the specified data in the near + /// future. + will-need, + /// The application expects that it will not access the specified data + /// in the near future. + dont-need, + /// The application expects to access the specified data once and then + /// not reuse it thereafter. + no-reuse + } + + /// A 128-bit hash value, split into parts because wasm doesn't have a + /// 128-bit integer type. + record metadata-hash-value { + /// 64 bits of a 128-bit hash value. + lower: u64, + /// Another 64 bits of a 128-bit hash value. + upper: u64, + } + + /// A descriptor is a reference to a filesystem object, which may be a file, + /// directory, named pipe, special file, or other object on which filesystem + /// calls may be made. + resource descriptor { + + /// Provide file advisory information on a descriptor. + /// + /// This is similar to `posix_fadvise` in POSIX. + advise: func(offset: filesize, length: filesize, advice: advice) -> result<_, error-code>; + + /// Return a stream for appending to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be appended. + /// + /// Note: This allows using `write-stream`, which is similar to `write` with + /// `O_APPEND` in in POSIX. + append-via-stream: func() -> result; + + /// Create a directory. + /// + /// Note: This is similar to `mkdirat` in POSIX. + create-directory-at: func(path: string) -> result<_, error-code>; + + /// Get flags associated with a descriptor. + /// + /// Note: This returns similar flags to `fcntl(fd, F_GETFL)` in POSIX. + /// + /// Note: This returns the value that was the `fs_flags` value returned + /// from `fdstat_get` in earlier versions of WASI. + get-flags: func() -> result; + + /// Get the dynamic type of a descriptor. + /// + /// Note: This returns the same value as the `type` field of the `fd-stat` + /// returned by `stat`, `stat-at` and similar. + /// + /// Note: This returns similar flags to the `st_mode & S_IFMT` value provided + /// by `fstat` in POSIX. + /// + /// Note: This returns the value that was the `fs_filetype` value returned + /// from `fdstat_get` in earlier versions of WASI. + get-type: func() -> result; + + /// Test whether two descriptors refer to the same filesystem object. + /// + /// In POSIX, this corresponds to testing whether the two descriptors have the + /// same device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers. + /// wasi-filesystem does not expose device and inode numbers, so this function + /// may be used instead. + is-same-object: func(other: borrow) -> bool; + + /// Create a hard link. + /// + /// Note: This is similar to `linkat` in POSIX. + link-at: func(old-path-flags: path-flags, old-path: string, new-descriptor: borrow, new-path: string) -> result<_, error-code>; + + /// Return a hash of the metadata associated with a filesystem object referred + /// to by a descriptor. + /// + /// This returns a hash of the last-modification timestamp and file size, and + /// may also include the inode number, device number, birth timestamp, and + /// other metadata fields that may change when the file is modified or + /// replaced. It may also include a secret value chosen by the + /// implementation and not otherwise exposed. + /// + /// Implementations are encourated to provide the following properties: + /// + /// - If the file is not modified or replaced, the computed hash value should + /// usually not change. + /// - If the object is modified or replaced, the computed hash value should + /// usually change. + /// - The inputs to the hash should not be easily computable from the + /// computed hash. + /// + /// However, none of these is required. + metadata-hash: func() -> result; + + /// Return a hash of the metadata associated with a filesystem object referred + /// to by a directory descriptor and a relative path. + /// + /// This performs the same hash computation as `metadata-hash`. + metadata-hash-at: func(path-flags: path-flags, path: string) -> result; + + /// Open a file or directory. + /// + /// The returned descriptor is not guaranteed to be the lowest-numbered + /// descriptor not currently open/ it is randomized to prevent applications + /// from depending on making assumptions about indexes, since this is + /// error-prone in multi-threaded contexts. The returned descriptor is + /// guaranteed to be less than 2**31. + /// + /// If `flags` contains `descriptor-flags::mutate-directory`, and the base + /// descriptor doesn't have `descriptor-flags::mutate-directory` set, + /// `open-at` fails with `error-code::read-only`. + /// + /// If `flags` contains `write` or `mutate-directory`, or `open-flags` + /// contains `truncate` or `create`, and the base descriptor doesn't have + /// `descriptor-flags::mutate-directory` set, `open-at` fails with + /// `error-code::read-only`. + /// + /// Note: This is similar to `openat` in POSIX. + open-at: func(path-flags: path-flags, path: string, open-flags: open-flags, %flags: descriptor-flags) -> result; + + /// Read from a descriptor, without using and updating the descriptor's offset. + /// + /// This function returns a list of bytes containing the data that was + /// read, along with a bool which, when true, indicates that the end of the + /// file was reached. The returned list will contain up to `length` bytes; it + /// may return fewer than requested, if the end of the file is reached or + /// if the I/O operation is interrupted. + /// + /// In the future, this may change to return a `stream`. + /// + /// Note: This is similar to `pread` in POSIX. + read: func(length: filesize, offset: filesize) -> result, bool>, error-code>; + + /// Read directory entries from a directory. + /// + /// On filesystems where directories contain entries referring to themselves + /// and their parents, often named `.` and `..` respectively, these entries + /// are omitted. + /// + /// This always returns a new stream which starts at the beginning of the + /// directory. Multiple streams may be active on the same directory, and they + /// do not interfere with each other. + read-directory: func() -> result; + + /// Return a stream for reading from a file, if available. + /// + /// May fail with an error-code describing why the file cannot be read. + /// + /// Multiple read, write, and append streams may be active on the same open + /// file and they do not interfere with each other. + /// + /// Note: This allows using `read-stream`, which is similar to `read` in POSIX. + read-via-stream: func(offset: filesize) -> result; + + /// Read the contents of a symbolic link. + /// + /// If the contents contain an absolute or rooted path in the underlying + /// filesystem, this function fails with `error-code::not-permitted`. + /// + /// Note: This is similar to `readlinkat` in POSIX. + readlink-at: func(path: string) -> result; + + /// Remove a directory. + /// + /// Return `error-code::not-empty` if the directory is not empty. + /// + /// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. + remove-directory-at: func(path: string) -> result<_, error-code>; + + /// Rename a filesystem object. + /// + /// Note: This is similar to `renameat` in POSIX. + rename-at: func(old-path: string, new-descriptor: borrow, new-path: string) -> result<_, error-code>; + + /// Adjust the size of an open file. If this increases the file's size, the + /// extra bytes are filled with zeros. + /// + /// Note: This was called `fd_filestat_set_size` in earlier versions of WASI. + set-size: func(size: filesize) -> result<_, error-code>; + + /// Adjust the timestamps of an open file or directory. + /// + /// Note: This is similar to `futimens` in POSIX. + /// + /// Note: This was called `fd_filestat_set_times` in earlier versions of WASI. + set-times: func(data-access-timestamp: new-timestamp, data-modification-timestamp: new-timestamp) -> result<_, error-code>; + + /// Adjust the timestamps of a file or directory. + /// + /// Note: This is similar to `utimensat` in POSIX. + /// + /// Note: This was called `path_filestat_set_times` in earlier versions of + /// WASI. + set-times-at: func(path-flags: path-flags, path: string, data-access-timestamp: new-timestamp, data-modification-timestamp: new-timestamp) -> result<_, error-code>; + + /// Return the attributes of an open file or directory. + /// + /// Note: This is similar to `fstat` in POSIX, except that it does not return + /// device and inode information. For testing whether two descriptors refer to + /// the same underlying filesystem object, use `is-same-object`. To obtain + /// additional data that can be used do determine whether a file has been + /// modified, use `metadata-hash`. + /// + /// Note: This was called `fd_filestat_get` in earlier versions of WASI. + stat: func() -> result; + + /// Return the attributes of a file or directory. + /// + /// Note: This is similar to `fstatat` in POSIX, except that it does not + /// return device and inode information. See the `stat` description for a + /// discussion of alternatives. + /// + /// Note: This was called `path_filestat_get` in earlier versions of WASI. + stat-at: func(path-flags: path-flags, path: string) -> result; + + /// Create a symbolic link (also known as a "symlink"). + /// + /// If `old-path` starts with `/`, the function fails with + /// `error-code::not-permitted`. + /// + /// Note: This is similar to `symlinkat` in POSIX. + symlink-at: func(old-path: string, new-path: string) -> result<_, error-code>; + + /// Synchronize the data and metadata of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fsync` in POSIX. + sync: func() -> result<_, error-code>; + + /// Synchronize the data of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fdatasync` in POSIX. + sync-data: func() -> result<_, error-code>; + + /// Unlink a filesystem object that is not a directory. + /// + /// Return `error-code::is-directory` if the path refers to a directory. + /// Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. + unlink-file-at: func(path: string) -> result<_, error-code>; + + /// Write to a descriptor, without using and updating the descriptor's offset. + /// + /// It is valid to write past the end of a file; the file is extended to the + /// extent of the write, with bytes between the previous end and the start of + /// the write set to zero. + /// + /// In the future, this may change to take a `stream`. + /// + /// Note: This is similar to `pwrite` in POSIX. + write: func(buffer: list, offset: filesize) -> result; + + /// Return a stream for writing to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be written. + /// + /// Note: This allows using `write-stream`, which is similar to `write` in + /// POSIX. + write-via-stream: func(offset: filesize) -> result; + } + + /// A stream of directory entries. + resource directory-entry-stream { + + /// Read a single directory entry from a `directory-entry-stream`. + read-directory-entry: func() -> result, error-code>; + } + + /// Attempts to extract a filesystem-related `error-code` from the stream + /// `error` provided. + /// + /// Stream operations which return `stream-error::last-operation-failed` + /// have a payload with more information about the operation that failed. + /// This payload can be passed through to this function to see if there's + /// filesystem-related information about the error to return. + /// + /// Note that this function is fallible because not all stream-related + /// errors are filesystem-related errors. + filesystem-error-code: func(err: borrow) -> option; + } + + interface preopens { + use types.{descriptor}; + + /// Return the set of preopened directories, and their path. + get-directories: func() -> list>; + } +} + +package wasi:sockets@0.2.0 { + interface network { + /// An opaque resource that represents access to (a subset of) the network. + /// This enables context-based security for networking. + /// There is no need for this to map 1:1 to a physical network interface. + resource network; + + /// Error codes. + /// + /// In theory, every API can return any error code. + /// In practice, API's typically only return the errors documented per API + /// combined with a couple of errors that are always possible: + /// - `unknown` + /// - `access-denied` + /// - `not-supported` + /// - `out-of-memory` + /// - `concurrency-conflict` + /// + /// See each individual API for what the POSIX equivalents are. They sometimes differ + /// per API. + enum error-code { + /// Unknown error + unknown, + /// Access denied. + /// + /// POSIX equivalent: EACCES, EPERM + access-denied, + /// The operation is not supported. + /// + /// POSIX equivalent: EOPNOTSUPP + not-supported, + /// One of the arguments is invalid. + /// + /// POSIX equivalent: EINVAL + invalid-argument, + /// Not enough memory to complete the operation. + /// + /// POSIX equivalent: ENOMEM, ENOBUFS, EAI_MEMORY + out-of-memory, + /// The operation timed out before it could finish completely. + timeout, + /// This operation is incompatible with another asynchronous operation that is already + /// in progress. + /// + /// POSIX equivalent: EALREADY + concurrency-conflict, + /// Trying to finish an asynchronous operation that: + /// - has not been started yet, or: + /// - was already finished by a previous `finish-*` call. + /// + /// Note: this is scheduled to be removed when `future`s are natively supported. + not-in-progress, + /// The operation has been aborted because it could not be completed immediately. + /// + /// Note: this is scheduled to be removed when `future`s are natively supported. + would-block, + /// The operation is not valid in the socket's current state. + invalid-state, + /// A new socket resource could not be created because of a system limit. + new-socket-limit, + /// A bind operation failed because the provided address is not an address that the + /// `network` can bind to. + address-not-bindable, + /// A bind operation failed because the provided address is already in use or because + /// there are no ephemeral ports available. + address-in-use, + /// The remote address is not reachable + remote-unreachable, + /// The TCP connection was forcefully rejected + connection-refused, + /// The TCP connection was reset. + connection-reset, + /// A TCP connection was aborted. + connection-aborted, + /// The size of a datagram sent to a UDP socket exceeded the maximum + /// supported size. + datagram-too-large, + /// Name does not exist or has no suitable associated IP addresses. + name-unresolvable, + /// A temporary failure in name resolution occurred. + temporary-resolver-failure, + /// A permanent failure in name resolution occurred. + permanent-resolver-failure + } + enum ip-address-family { + /// Similar to `AF_INET` in POSIX. + ipv4, + /// Similar to `AF_INET6` in POSIX. + ipv6 + } + type ipv4-address = tuple; + type ipv6-address = tuple; + variant ip-address { + ipv4(ipv4-address), + ipv6(ipv6-address), + } + record ipv4-socket-address { + /// sin_port + port: u16, + /// sin_addr + address: ipv4-address, + } + record ipv6-socket-address { + /// sin6_port + port: u16, + /// sin6_flowinfo + flow-info: u32, + /// sin6_addr + address: ipv6-address, + /// sin6_scope_id + scope-id: u32, + } + variant ip-socket-address { + ipv4(ipv4-socket-address), + ipv6(ipv6-socket-address), + } + } + + /// This interface provides a value-export of the default network handle.. + interface instance-network { + use network.{network}; + + /// Get a handle to the default network. + instance-network: func() -> network; + } + + interface ip-name-lookup { + use wasi:io/poll@0.2.0.{pollable}; + use network.{network}; + use network.{error-code}; + use network.{ip-address}; + resource resolve-address-stream { + + /// Returns the next address from the resolver. + /// + /// This function should be called multiple times. On each call, it will + /// return the next address in connection order preference. If all + /// addresses have been exhausted, this function returns `none`. + /// + /// This function never returns IPv4-mapped IPv6 addresses. + /// + /// # Typical errors + /// - `name-unresolvable`: Name does not exist or has no suitable associated + /// IP addresses. (EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY) + /// - `temporary-resolver-failure`: A temporary failure in name resolution occurred. + /// (EAI_AGAIN) + /// - `permanent-resolver-failure`: A permanent failure in name resolution occurred. + /// (EAI_FAIL) + /// - `would-block`: A result is not available yet. (EWOULDBLOCK, EAGAIN) + resolve-next-address: func() -> result, error-code>; + + /// Create a `pollable` which will resolve once the stream is ready for I/O. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } + + /// Resolve an internet host name to a list of IP addresses. + /// + /// Unicode domain names are automatically converted to ASCII using IDNA encoding. + /// If the input is an IP address string, the address is parsed and returned + /// as-is without making any external requests. + /// + /// See the wasi-socket proposal README.md for a comparison with getaddrinfo. + /// + /// This function never blocks. It either immediately fails or immediately + /// returns successfully with a `resolve-address-stream` that can be used + /// to (asynchronously) fetch the results. + /// + /// # Typical errors + /// - `invalid-argument`: `name` is a syntactically invalid domain name or IP address. + /// + /// # References: + /// - + /// - + /// - + /// - + resolve-addresses: func(network: borrow, name: string) -> result; + } + + interface tcp { + use wasi:io/streams@0.2.0.{input-stream}; + use wasi:io/streams@0.2.0.{output-stream}; + use wasi:io/poll@0.2.0.{pollable}; + use wasi:clocks/monotonic-clock@0.2.0.{duration}; + use network.{network}; + use network.{error-code}; + use network.{ip-socket-address}; + use network.{ip-address-family}; + enum shutdown-type { + /// Similar to `SHUT_RD` in POSIX. + receive, + /// Similar to `SHUT_WR` in POSIX. + send, + /// Similar to `SHUT_RDWR` in POSIX. + both + } + + /// A TCP socket resource. + /// + /// The socket can be in one of the following states: + /// - `unbound` + /// - `bind-in-progress` + /// - `bound` (See note below) + /// - `listen-in-progress` + /// - `listening` + /// - `connect-in-progress` + /// - `connected` + /// - `closed` + /// See + /// for a more information. + /// + /// Note: Except where explicitly mentioned, whenever this documentation uses + /// the term "bound" without backticks it actually means: in the `bound` state *or + /// higher*. + /// (i.e. `bound`, `listen-in-progress`, `listening`, `connect-in-progress` or `connected`) + /// + /// In addition to the general error codes documented on the + /// `network::error-code` type, TCP socket methods may always return + /// `error(invalid-state)` when in the `closed` state. + resource tcp-socket { + + /// Accept a new client socket. + /// + /// The returned socket is bound and in the `connected` state. The following properties + /// are inherited from the listener socket: + /// - `address-family` + /// - `keep-alive-enabled` + /// - `keep-alive-idle-time` + /// - `keep-alive-interval` + /// - `keep-alive-count` + /// - `hop-limit` + /// - `receive-buffer-size` + /// - `send-buffer-size` + /// + /// On success, this function returns the newly accepted client socket along with + /// a pair of streams that can be used to read & write to the connection. + /// + /// # Typical errors + /// - `invalid-state`: Socket is not in the `listening` state. (EINVAL) + /// - `would-block`: No pending connections at the moment. (EWOULDBLOCK, EAGAIN) + /// - `connection-aborted`: An incoming connection was pending, but was terminated + /// by the client before this listener could accept it. (ECONNABORTED) + /// - `new-socket-limit`: The new socket resource could not be created because of + /// a system limit. (EMFILE, ENFILE) + /// + /// # References + /// - + /// - + /// - + /// - + accept: func() -> result, error-code>; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + address-family: func() -> ip-address-family; + finish-bind: func() -> result<_, error-code>; + finish-connect: func() -> result, error-code>; + finish-listen: func() -> result<_, error-code>; + + /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The TTL value must be 1 or higher. + hop-limit: func() -> result; + + /// Whether the socket is in the `listening` state. + /// + /// Equivalent to the SO_ACCEPTCONN socket option. + is-listening: func() -> bool; + + /// The maximum amount of keepalive packets TCP should send before aborting the connection. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// I.e. after setting a value, reading the same setting back may return a different + /// value. + /// + /// Equivalent to the TCP_KEEPCNT socket option. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-count: func() -> result; + + /// Enables or disables keepalive. + /// + /// The keepalive behavior can be adjusted using: + /// - `keep-alive-idle-time` + /// - `keep-alive-interval` + /// - `keep-alive-count` + /// These properties can be configured while `keep-alive-enabled` is false, but only + /// come into effect when `keep-alive-enabled` is true. + /// + /// Equivalent to the SO_KEEPALIVE socket option. + keep-alive-enabled: func() -> result; + + /// Amount of time the connection has to be idle before TCP starts sending keepalive + /// packets. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// I.e. after setting a value, reading the same setting back may return a different + /// value. + /// + /// Equivalent to the TCP_KEEPIDLE socket option. (TCP_KEEPALIVE on MacOS) + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-idle-time: func() -> result; + + /// The time between keepalive packets. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// I.e. after setting a value, reading the same setting back may return a different + /// value. + /// + /// Equivalent to the TCP_KEEPINTVL socket option. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-interval: func() -> result; + + /// Get the bound local address. + /// + /// POSIX mentions: + /// > If the socket has not been bound to a local name, the value + /// > stored in the object pointed to by `address` is unspecified. + /// + /// WASI is stricter and requires `local-address` to return `invalid-state` when the + /// socket hasn't been bound yet. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. + /// + /// # References + /// - + /// - + /// - + /// - + local-address: func() -> result; + + /// The kernel buffer space reserved for sends/receives on this socket. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// I.e. after setting a value, reading the same setting back may return a different + /// value. + /// + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + receive-buffer-size: func() -> result; + + /// Get the remote address. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + remote-address: func() -> result; + send-buffer-size: func() -> result; + set-hop-limit: func(value: u8) -> result<_, error-code>; + set-keep-alive-count: func(value: u32) -> result<_, error-code>; + set-keep-alive-enabled: func(value: bool) -> result<_, error-code>; + set-keep-alive-idle-time: func(value: duration) -> result<_, error-code>; + set-keep-alive-interval: func(value: duration) -> result<_, error-code>; + + /// Hints the desired listen queue size. Implementations are free to ignore this. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// + /// # Typical errors + /// - `not-supported`: (set) The platform does not support changing the backlog + /// size after the initial listen. + /// - `invalid-argument`: (set) The provided value was 0. + /// - `invalid-state`: (set) The socket is in the `connect-in-progress` or + /// `connected` state. + set-listen-backlog-size: func(value: u64) -> result<_, error-code>; + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + + /// Initiate a graceful shutdown. + /// + /// - `receive`: The socket is not expecting to receive any data from + /// the peer. The `input-stream` associated with this socket will be + /// closed. Any data still in the receive queue at time of calling + /// this method will be discarded. + /// - `send`: The socket has no more data to send to the peer. The `output-stream` + /// associated with this socket will be closed and a FIN packet will be sent. + /// - `both`: Same effect as `receive` & `send` combined. + /// + /// This function is idempotent. Shutting a down a direction more than once + /// has no effect and returns `ok`. + /// + /// The shutdown function does not close (drop) the socket. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code>; + + /// Bind the socket to a specific network on the provided IP address and port. + /// + /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the + /// implementation to decide which + /// network interface(s) to bind to. + /// If the TCP/UDP port is zero, the socket will be bound to a random free port. + /// + /// Bind can be attempted multiple times on the same socket, even with + /// different arguments on each iteration. But never concurrently and + /// only as long as the previous bind failed. Once a bind succeeds, the + /// binding can't be changed anymore. + /// + /// # Typical errors + /// - `invalid-argument`: The `local-address` has the wrong address family. + /// (EAFNOSUPPORT, EFAULT on Windows) + /// - `invalid-argument`: `local-address` is not a unicast address. (EINVAL) + /// - `invalid-argument`: `local-address` is an IPv4-mapped IPv6 address. + /// (EINVAL) + /// - `invalid-state`: The socket is already bound. (EINVAL) + /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS + /// on Windows) + /// - `address-in-use`: Address is already in use. (EADDRINUSE) + /// - `address-not-bindable`: `local-address` is not an address that the `network` + /// can bind to. (EADDRNOTAVAIL) + /// - `not-in-progress`: A `bind` operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. + /// (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// When binding to a non-zero port, this bind operation shouldn't be affected by + /// the TIME_WAIT + /// state of a recently closed socket on the same local address. In practice this + /// means that the SO_REUSEADDR + /// socket option should be set implicitly on all platforms, except on Windows where + /// this is the default behavior + /// and SO_REUSEADDR performs something different entirely. + /// + /// Unlike in POSIX, in WASI the bind operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `bind` as part of either `start-bind` or `finish-bind`. + /// + /// # References + /// - + /// - + /// - + /// - + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + + /// Connect to a remote endpoint. + /// + /// On success: + /// - the socket is transitioned into the `connection` state. + /// - a pair of streams is returned that can be used to read & write to the connection + /// + /// After a failed connection attempt, the socket will be in the `closed` + /// state and the only valid action left is to `drop` the socket. A single + /// socket can not be used to connect more than once. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. + /// (EAFNOSUPPORT) + /// - `invalid-argument`: `remote-address` is not a unicast address. (EINVAL, + /// ENETUNREACH on Linux, EAFNOSUPPORT on MacOS) + /// - `invalid-argument`: `remote-address` is an IPv4-mapped IPv6 address. + /// (EINVAL, EADDRNOTAVAIL on Illumos) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY + /// (`0.0.0.0` / `::`). (EADDRNOTAVAIL on Windows) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EADDRNOTAVAIL + /// on Windows) + /// - `invalid-argument`: The socket is already attached to a different network. + /// The `network` passed to `connect` must be identical to the one passed to `bind`. + /// - `invalid-state`: The socket is already in the `connected` state. + /// (EISCONN) + /// - `invalid-state`: The socket is already in the `listening` state. + /// (EOPNOTSUPP, EINVAL on Windows) + /// - `timeout`: Connection timed out. (ETIMEDOUT) + /// - `connection-refused`: The connection was forcefully rejected. (ECONNREFUSED) + /// - `connection-reset`: The connection was reset. (ECONNRESET) + /// - `connection-aborted`: The connection was aborted. (ECONNABORTED) + /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, + /// EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `address-in-use`: Tried to perform an implicit bind, but there were + /// no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// - `not-in-progress`: A connect operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. + /// (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// The POSIX equivalent of `start-connect` is the regular `connect` syscall. + /// Because all WASI sockets are non-blocking this is expected to return + /// EINPROGRESS, which should be translated to `ok()` in WASI. + /// + /// The POSIX equivalent of `finish-connect` is a `poll` for event `POLLOUT` + /// with a timeout of 0 on the socket descriptor. Followed by a check for + /// the `SO_ERROR` socket option, in case the poll signaled readiness. + /// + /// # References + /// - + /// - + /// - + /// - + start-connect: func(network: borrow, remote-address: ip-socket-address) -> result<_, error-code>; + + /// Start listening for new connections. + /// + /// Transitions the socket into the `listening` state. + /// + /// Unlike POSIX, the socket must already be explicitly bound. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. (EDESTADDRREQ) + /// - `invalid-state`: The socket is already in the `connected` state. + /// (EISCONN, EINVAL on BSD) + /// - `invalid-state`: The socket is already in the `listening` state. + /// - `address-in-use`: Tried to perform an implicit bind, but there were + /// no ephemeral ports available. (EADDRINUSE) + /// - `not-in-progress`: A listen operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. + /// (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// Unlike in POSIX, in WASI the listen operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `listen` as part of either `start-listen` or `finish-listen`. + /// + /// # References + /// - + /// - + /// - + /// - + start-listen: func() -> result<_, error-code>; + + /// Create a `pollable` which can be used to poll for, or block on, + /// completion of any of the asynchronous operations of this socket. + /// + /// When `finish-bind`, `finish-listen`, `finish-connect` or `accept` + /// return `error(would-block)`, this pollable can be used to wait for + /// their success or failure, after which the method can be retried. + /// + /// The pollable is not limited to the async operation that happens to be + /// in progress at the time of calling `subscribe` (if any). Theoretically, + /// `subscribe` only has to be called once per socket and can then be + /// (re)used for the remainder of the socket's lifetime. + /// + /// See + /// for a more information. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } + } + + interface tcp-create-socket { + use network.{network}; + use network.{error-code}; + use network.{ip-address-family}; + use tcp.{tcp-socket}; + + /// Create a new TCP socket. + /// + /// Similar to `socket(AF_INET or AF_INET6, SOCK_STREAM, IPPROTO_TCP)` in POSIX. + /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. + /// + /// This function does not require a network capability handle. This is considered + /// to be safe because + /// at time of creation, the socket is not bound to any `network` yet. Up to the moment + /// `bind`/`connect` + /// is called, the socket is effectively an in-memory configuration object, unable + /// to communicate with the outside world. + /// + /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous + /// operations. + /// + /// # Typical errors + /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) + /// - `new-socket-limit`: The new socket resource could not be created because of + /// a system limit. (EMFILE, ENFILE) + /// + /// # References + /// - + /// - + /// - + /// - + create-tcp-socket: func(address-family: ip-address-family) -> result; + } + + interface udp { + use wasi:io/poll@0.2.0.{pollable}; + use network.{network}; + use network.{error-code}; + use network.{ip-socket-address}; + use network.{ip-address-family}; + + /// A received datagram. + record incoming-datagram { + /// The payload. + /// + /// Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes. + data: list, + /// The source address. + /// + /// This field is guaranteed to match the remote address the stream was initialized + /// with, if any. + /// + /// Equivalent to the `src_addr` out parameter of `recvfrom`. + remote-address: ip-socket-address, + } + + /// A datagram to be sent out. + record outgoing-datagram { + /// The payload. + data: list, + /// The destination address. + /// + /// The requirements on this field depend on how the stream was initialized: + /// - with a remote address: this field must be None or match the stream's remote + /// address exactly. + /// - without a remote address: this field is required. + /// + /// If this value is None, the send operation is equivalent to `send` in POSIX. Otherwise + /// it is equivalent to `sendto`. + remote-address: option, + } + + /// A UDP socket handle. + resource udp-socket { + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + address-family: func() -> ip-address-family; + finish-bind: func() -> result<_, error-code>; + + /// Get the current bound address. + /// + /// POSIX mentions: + /// > If the socket has not been bound to a local name, the value + /// > stored in the object pointed to by `address` is unspecified. + /// + /// WASI is stricter and requires `local-address` to return `invalid-state` when the + /// socket hasn't been bound yet. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. + /// + /// # References + /// - + /// - + /// - + /// - + local-address: func() -> result; + + /// The kernel buffer space reserved for sends/receives on this socket. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// I.e. after setting a value, reading the same setting back may return a different + /// value. + /// + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + receive-buffer-size: func() -> result; + + /// Get the address the socket is currently streaming to. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not streaming to a specific remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + remote-address: func() -> result; + send-buffer-size: func() -> result; + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; + + /// Bind the socket to a specific network on the provided IP address and port. + /// + /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the + /// implementation to decide which + /// network interface(s) to bind to. + /// If the port is zero, the socket will be bound to a random free port. + /// + /// # Typical errors + /// - `invalid-argument`: The `local-address` has the wrong address family. + /// (EAFNOSUPPORT, EFAULT on Windows) + /// - `invalid-state`: The socket is already bound. (EINVAL) + /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS + /// on Windows) + /// - `address-in-use`: Address is already in use. (EADDRINUSE) + /// - `address-not-bindable`: `local-address` is not an address that the `network` + /// can bind to. (EADDRNOTAVAIL) + /// - `not-in-progress`: A `bind` operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. + /// (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// Unlike in POSIX, in WASI the bind operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `bind` as part of either `start-bind` or `finish-bind`. + /// + /// # References + /// - + /// - + /// - + /// - + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + + /// Set up inbound & outbound communication channels, optionally to a specific peer. + /// + /// This function only changes the local socket configuration and does not generate + /// any network traffic. + /// On success, the `remote-address` of the socket is updated. The `local-address` + /// may be updated as well, + /// based on the best network path to `remote-address`. + /// + /// When a `remote-address` is provided, the returned streams are limited to communicating + /// with that specific peer: + /// - `send` can only be used to send to this destination. + /// - `receive` will only return datagrams sent from the provided `remote-address`. + /// + /// This method may be called multiple times on the same socket to change its association, + /// but + /// only the most recently returned pair of streams will be operational. Implementations + /// may trap if + /// the streams returned by a previous invocation haven't been dropped yet before + /// calling `stream` again. + /// + /// The POSIX equivalent in pseudo-code is: + /// ```text + /// if (was previously connected) { + /// connect(s, AF_UNSPEC) + /// } + /// if (remote_address is Some) { + /// connect(s, remote_address) + /// } + /// ``` + /// + /// Unlike in POSIX, the socket must already be explicitly bound. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. + /// (EAFNOSUPPORT) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY + /// (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, + /// EADDRNOTAVAIL) + /// - `invalid-state`: The socket is not bound. + /// - `address-in-use`: Tried to perform an implicit bind, but there were + /// no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, + /// ENETRESET, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// + /// # References + /// - + /// - + /// - + /// - + %stream: func(remote-address: option) -> result, error-code>; + + /// Create a `pollable` which will resolve once the socket is ready for I/O. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + + /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The TTL value must be 1 or higher. + unicast-hop-limit: func() -> result; + } + resource incoming-datagram-stream { + + /// Receive messages on the socket. + /// + /// This function attempts to receive up to `max-results` datagrams on the socket + /// without blocking. + /// The returned list may contain fewer elements than requested, but never more. + /// + /// This function returns successfully with an empty list when either: + /// - `max-results` is 0, or: + /// - `max-results` is greater than 0, but no results are immediately available. + /// This function never returns `error(would-block)`. + /// + /// # Typical errors + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET + /// on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + receive: func(max-results: u64) -> result, error-code>; + + /// Create a `pollable` which will resolve once the stream is ready to receive again. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } + resource outgoing-datagram-stream { + + /// Check readiness for sending. This function never blocks. + /// + /// Returns the number of datagrams permitted for the next call to `send`, + /// or an error. Calling `send` with more datagrams than this function has + /// permitted will trap. + /// + /// When this function returns ok(0), the `subscribe` pollable will + /// become ready when this function will report at least ok(1), or an + /// error. + /// + /// Never returns `would-block`. + check-send: func() -> result; + + /// Send messages on the socket. + /// + /// This function attempts to send all provided `datagrams` on the socket without + /// blocking and + /// returns how many messages were actually sent (or queued for sending). This function + /// never + /// returns `error(would-block)`. If none of the datagrams were able to be sent, `ok(0)` + /// is returned. + /// + /// This function semantically behaves the same as iterating the `datagrams` list + /// and sequentially + /// sending each individual datagram until either the end of the list has been reached + /// or the first error occurred. + /// If at least one datagram has been sent successfully, this function never returns + /// an error. + /// + /// If the input list is empty, the function returns `ok(0)`. + /// + /// Each call to `send` must be permitted by a preceding `check-send`. Implementations + /// must trap if + /// either `check-send` was not called or `datagrams` contains more items than `check-send` + /// permitted. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. + /// (EAFNOSUPPORT) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY + /// (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, + /// EADDRNOTAVAIL) + /// - `invalid-argument`: The socket is in "connected" mode and `remote-address` + /// is `some` value that does not match the address passed to `stream`. (EISCONN) + /// - `invalid-argument`: The socket is not "connected" and no value for `remote-address` + /// was provided. (EDESTADDRREQ) + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, + /// ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// - `datagram-too-large`: The datagram is too large. (EMSGSIZE) + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + send: func(datagrams: list) -> result; + + /// Create a `pollable` which will resolve once the stream is ready to send again. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } + } + + interface udp-create-socket { + use network.{network}; + use network.{error-code}; + use network.{ip-address-family}; + use udp.{udp-socket}; + + /// Create a new UDP socket. + /// + /// Similar to `socket(AF_INET or AF_INET6, SOCK_DGRAM, IPPROTO_UDP)` in POSIX. + /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. + /// + /// This function does not require a network capability handle. This is considered + /// to be safe because + /// at time of creation, the socket is not bound to any `network` yet. Up to the moment + /// `bind` is called, + /// the socket is effectively an in-memory configuration object, unable to communicate + /// with the outside world. + /// + /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous + /// operations. + /// + /// # Typical errors + /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) + /// - `new-socket-limit`: The new socket resource could not be created because of + /// a system limit. (EMFILE, ENFILE) + /// + /// # References: + /// - + /// - + /// - + /// - + create-udp-socket: func(address-family: ip-address-family) -> result; + } +} + +package wasi:clocks@0.2.0 { + /// WASI Monotonic Clock is a clock API intended to let users measure elapsed + /// time. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + /// + /// A monotonic clock is a clock which has an unspecified initial value, and + /// successive reads of the clock will produce non-decreasing values. + /// + /// It is intended for measuring elapsed time. + interface monotonic-clock { + use wasi:io/poll@0.2.0.{pollable}; + + /// An instant in time, in nanoseconds. An instant is relative to an + /// unspecified initial value, and can only be compared to instances from + /// the same monotonic-clock. + type instant = u64; + + /// A duration of time, in nanoseconds. + type duration = u64; + + /// Read the current value of the clock. + /// + /// The clock is monotonic, therefore calling this function repeatedly will + /// produce a sequence of non-decreasing values. + now: func() -> instant; + + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + resolution: func() -> duration; + + /// Create a `pollable` which will resolve once the specified instant + /// occured. + subscribe-instant: func(when: instant) -> pollable; + + /// Create a `pollable` which will resolve once the given duration has + /// elapsed, starting at the time at which this function was called. + /// occured. + subscribe-duration: func(when: duration) -> pollable; + } + + /// WASI Wall Clock is a clock API intended to let users query the current + /// time. The name "wall" makes an analogy to a "clock on the wall", which + /// is not necessarily monotonic as it may be reset. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + /// + /// A wall clock is a clock which measures the date and time according to + /// some external reference. + /// + /// External references may be reset, so this clock is not necessarily + /// monotonic, making it unsuitable for measuring elapsed time. + /// + /// It is intended for reporting the current date and time for humans. + interface wall-clock { + /// A time and date in seconds plus nanoseconds. + record datetime { + seconds: u64, + nanoseconds: u32, + } + + /// Read the current value of the clock. + /// + /// This clock is not monotonic, therefore calling this function repeatedly + /// will not necessarily produce a sequence of non-decreasing values. + /// + /// The returned timestamps represent the number of seconds since + /// 1970-01-01T00:00:00Z, also known as [POSIX's Seconds Since the Epoch], + /// also known as [Unix Time]. + /// + /// The nanoseconds field of the output is always less than 1000000000. + /// + /// [POSIX's Seconds Since the Epoch]: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html#tag_21_04_16 + /// [Unix Time]: https://en.wikipedia.org/wiki/Unix_time + now: func() -> datetime; + + /// Query the resolution of the clock. + /// + /// The nanoseconds field of the output is always less than 1000000000. + resolution: func() -> datetime; + } +} + +package wasi:io@0.2.0 { + interface error { + /// A resource which represents some error information. + /// + /// The only method provided by this resource is `to-debug-string`, + /// which provides some human-readable information about the error. + /// + /// In the `wasi:io` package, this resource is returned through the + /// `wasi:io/streams/stream-error` type. + /// + /// To provide more specific error information, other interfaces may + /// provide functions to further "downcast" this error into more specific + /// error information. For example, `error`s returned in streams derived + /// from filesystem types to be described using the filesystem's own + /// error-code type, using the function + /// `wasi:filesystem/types/filesystem-error-code`, which takes a parameter + /// `borrow` and returns + /// `option`. + /// + /// The set of functions which can "downcast" an `error` into a more + /// concrete type is open. + resource error { + + /// Returns a string that is suitable to assist humans in debugging + /// this error. + /// + /// WARNING: The returned string should not be consumed mechanically! + /// It may change across platforms, hosts, or other implementation + /// details. Parsing this string is a major platform-compatibility + /// hazard. + to-debug-string: func() -> string; + } + } + + /// A poll API intended to let users wait for I/O events on multiple handles + /// at once. + interface poll { + /// `pollable` represents a single I/O event which may be ready, or not. + resource pollable { + + /// `block` returns immediately if the pollable is ready, and otherwise + /// blocks until ready. + /// + /// This function is equivalent to calling `poll.poll` on a list + /// containing only this pollable. + block: func(); + + /// Return the readiness of a pollable. This function never blocks. + /// + /// Returns `true` when the pollable is ready, and `false` otherwise. + ready: func() -> bool; + } + + /// Poll for completion on a set of pollables. + /// + /// This function takes a list of pollables, which identify I/O sources of + /// interest, and waits until one or more of the events is ready for I/O. + /// + /// The result `list` contains one or more indices of handles in the + /// argument list that is ready for I/O. + /// + /// If the list contains more elements than can be indexed with a `u32` + /// value, this function traps. + /// + /// A timeout can be implemented by adding a pollable from the + /// wasi-clocks API to the list. + /// + /// This function does not return a `result`; polling in itself does not + /// do any I/O so it doesn't fail. If any of the I/O sources identified by + /// the pollables has an error, it is indicated by marking the source as + /// being reaedy for I/O. + poll: func(in: list>) -> list; + } + + /// WASI I/O is an I/O abstraction API which is currently focused on providing + /// stream types. + /// + /// In the future, the component model is expected to add built-in stream types; + /// when it does, they are expected to subsume this API. + interface streams { + use error.{error}; + use poll.{pollable}; + + /// An error for input-stream and output-stream operations. + variant stream-error { + /// The last operation (a write or flush) failed before completion. + /// + /// More information is available in the `error` payload. + last-operation-failed(error), + /// The stream is closed: no more input will be accepted by the + /// stream. A closed output-stream will return this error on all + /// future operations. + closed, + } + + /// An input bytestream. + /// + /// `input-stream`s are *non-blocking* to the extent practical on underlying + /// platforms. I/O operations always return promptly; if fewer bytes are + /// promptly available than requested, they return the number of bytes promptly + /// available, which could even be zero. To wait for data to be available, + /// use the `subscribe` function to obtain a `pollable` which can be polled + /// for using `wasi:io/poll`. + resource input-stream { + + /// Read bytes from a stream, after blocking until at least one byte can + /// be read. Except for blocking, behavior is identical to `read`. + blocking-read: func(len: u64) -> result, stream-error>; + + /// Skip bytes from a stream, after blocking until at least one byte + /// can be skipped. Except for blocking behavior, identical to `skip`. + blocking-skip: func(len: u64) -> result; + + /// Perform a non-blocking read from the stream. + /// + /// When the source of a `read` is binary data, the bytes from the source + /// are returned verbatim. When the source of a `read` is known to the + /// implementation to be text, bytes containing the UTF-8 encoding of the + /// text are returned. + /// + /// This function returns a list of bytes containing the read data, + /// when successful. The returned list will contain up to `len` bytes; + /// it may return fewer than requested, but not more. The list is + /// empty when no bytes are available for reading at this time. The + /// pollable given by `subscribe` will be ready when more bytes are + /// available. + /// + /// This function fails with a `stream-error` when the operation + /// encounters an error, giving `last-operation-failed`, or when the + /// stream is closed, giving `closed`. + /// + /// When the caller gives a `len` of 0, it represents a request to + /// read 0 bytes. If the stream is still open, this call should + /// succeed and return an empty list, or otherwise fail with `closed`. + /// + /// The `len` parameter is a `u64`, which could represent a list of u8 which + /// is not possible to allocate in wasm32, or not desirable to allocate as + /// as a return value by the callee. The callee may return a list of bytes + /// less than `len` in size while more bytes are available for reading. + read: func(len: u64) -> result, stream-error>; + + /// Skip bytes from a stream. Returns number of bytes skipped. + /// + /// Behaves identical to `read`, except instead of returning a list + /// of bytes, returns the number of bytes consumed from the stream. + skip: func(len: u64) -> result; + + /// Create a `pollable` which will resolve once either the specified stream + /// has bytes available to read or the other end of the stream has been + /// closed. + /// The created `pollable` is a child resource of the `input-stream`. + /// Implementations may trap if the `input-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + subscribe: func() -> pollable; + } + + /// An output bytestream. + /// + /// `output-stream`s are *non-blocking* to the extent practical on + /// underlying platforms. Except where specified otherwise, I/O operations also + /// always return promptly, after the number of bytes that can be written + /// promptly, which could even be zero. To wait for the stream to be ready to + /// accept data, the `subscribe` function to obtain a `pollable` which can be + /// polled for using `wasi:io/poll`. + resource output-stream { + + /// Request to flush buffered output, and block until flush completes + /// and stream is ready for writing again. + blocking-flush: func() -> result<_, stream-error>; + + /// Read from one stream and write to another, with blocking. + /// + /// This is similar to `splice`, except that it blocks until the + /// `output-stream` is ready for writing, and the `input-stream` + /// is ready for reading, before performing the `splice`. + blocking-splice: func(src: borrow, len: u64) -> result; + + /// Perform a write of up to 4096 bytes, and then flush the stream. Block + /// until all of these operations are complete, or an error occurs. + /// + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write`, and `flush`, and is implemented with the + /// following pseudo-code: + /// + /// ```text + /// let pollable = this.subscribe(); + /// while !contents.is_empty() { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, contents.len()); + /// let (chunk, rest) = contents.split_at(len); + /// this.write(chunk ); // eliding error handling + /// contents = rest; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + blocking-write-and-flush: func(contents: list) -> result<_, stream-error>; + + /// Perform a write of up to 4096 zeroes, and then flush the stream. + /// Block until all of these operations are complete, or an error + /// occurs. + /// + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write-zeroes`, and `flush`, and is implemented with + /// the following pseudo-code: + /// + /// ```text + /// let pollable = this.subscribe(); + /// while num_zeroes != 0 { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, num_zeroes); + /// this.write-zeroes(len); // eliding error handling + /// num_zeroes -= len; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + blocking-write-zeroes-and-flush: func(len: u64) -> result<_, stream-error>; + + /// Check readiness for writing. This function never blocks. + /// + /// Returns the number of bytes permitted for the next call to `write`, + /// or an error. Calling `write` with more bytes than this function has + /// permitted will trap. + /// + /// When this function returns 0 bytes, the `subscribe` pollable will + /// become ready when this function will report at least 1 byte, or an + /// error. + check-write: func() -> result; + + /// Request to flush buffered output. This function never blocks. + /// + /// This tells the output-stream that the caller intends any buffered + /// output to be flushed. the output which is expected to be flushed + /// is all that has been passed to `write` prior to this call. + /// + /// Upon calling this function, the `output-stream` will not accept any + /// writes (`check-write` will return `ok(0)`) until the flush has + /// completed. The `subscribe` pollable will become ready when the + /// flush has completed and the stream can accept more writes. + flush: func() -> result<_, stream-error>; + + /// Read from one stream and write to another. + /// + /// The behavior of splice is equivelant to: + /// 1. calling `check-write` on the `output-stream` + /// 2. calling `read` on the `input-stream` with the smaller of the + /// `check-write` permitted length and the `len` provided to `splice` + /// 3. calling `write` on the `output-stream` with that read data. + /// + /// Any error reported by the call to `check-write`, `read`, or + /// `write` ends the splice and reports that error. + /// + /// This function returns the number of bytes transferred; it may be less + /// than `len`. + splice: func(src: borrow, len: u64) -> result; + + /// Create a `pollable` which will resolve once the output-stream + /// is ready for more writing, or an error has occured. When this + /// pollable is ready, `check-write` will return `ok(n)` with n>0, or an + /// error. + /// + /// If the stream is closed, this pollable is always ready immediately. + /// + /// The created `pollable` is a child resource of the `output-stream`. + /// Implementations may trap if the `output-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + subscribe: func() -> pollable; + + /// Perform a write. This function never blocks. + /// + /// When the destination of a `write` is binary data, the bytes from + /// `contents` are written verbatim. When the destination of a `write` is + /// known to the implementation to be text, the bytes of `contents` are + /// transcoded from UTF-8 into the encoding of the destination and then + /// written. + /// + /// Precondition: check-write gave permit of Ok(n) and contents has a + /// length of less than or equal to n. Otherwise, this function will trap. + /// + /// returns Err(closed) without writing if the stream has closed since + /// the last call to check-write provided a permit. + write: func(contents: list) -> result<_, stream-error>; + + /// Write zeroes to a stream. + /// + /// This should be used precisely like `write` with the exact same + /// preconditions (must use check-write first), but instead of + /// passing a list of bytes, you simply pass the number of zero-bytes + /// that should be written. + write-zeroes: func(len: u64) -> result<_, stream-error>; + } + } +} + +package wasi:random@0.2.0 { + /// The insecure-seed interface for seeding hash-map DoS resistance. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + interface insecure-seed { + /// Return a 128-bit value that may contain a pseudo-random value. + /// + /// The returned value is not required to be computed from a CSPRNG, and may + /// even be entirely deterministic. Host implementations are encouraged to + /// provide pseudo-random values to any program exposed to + /// attacker-controlled content, to enable DoS protection built into many + /// languages' hash-map implementations. + /// + /// This function is intended to only be called once, by a source language + /// to initialize Denial Of Service (DoS) protection in its hash-map + /// implementation. + /// + /// # Expected future evolution + /// + /// This will likely be changed to a value import, to prevent it from being + /// called multiple times and potentially used for purposes other than DoS + /// protection. + insecure-seed: func() -> tuple; + } + + /// The insecure interface for insecure pseudo-random numbers. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + interface insecure { + /// Return `len` insecure pseudo-random bytes. + /// + /// This function is not cryptographically secure. Do not use it for + /// anything related to security. + /// + /// There are no requirements on the values of the returned bytes, however + /// implementations are encouraged to return evenly distributed values with + /// a long period. + get-insecure-random-bytes: func(len: u64) -> list; + + /// Return an insecure pseudo-random `u64` value. + /// + /// This function returns the same type of pseudo-random data as + /// `get-insecure-random-bytes`, represented as a `u64`. + get-insecure-random-u64: func() -> u64; + } + + /// WASI Random is a random data API. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + interface random { + /// Return `len` cryptographically-secure random or pseudo-random bytes. + /// + /// This function must produce data at least as cryptographically secure and + /// fast as an adequately seeded cryptographically-secure pseudo-random + /// number generator (CSPRNG). It must not block, from the perspective of + /// the calling program, under any circumstances, including on the first + /// request and on requests for numbers of bytes. The returned data must + /// always be unpredictable. + /// + /// This function must always return fresh data. Deterministic environments + /// must omit this function, rather than implementing it with deterministic + /// data. + get-random-bytes: func(len: u64) -> list; + + /// Return a cryptographically-secure random or pseudo-random `u64` value. + /// + /// This function returns the same type of data as `get-random-bytes`, + /// represented as a `u64`. + get-random-u64: func() -> u64; + } +} diff --git a/testdata/wasi/cli.wit.json b/testdata/wasi/cli.wit.json index 1e46bcb2..baa274a4 100644 --- a/testdata/wasi/cli.wit.json +++ b/testdata/wasi/cli.wit.json @@ -84,36 +84,14 @@ { "name": "imports", "imports": { - "interface-9": { - "interface": { - "id": 9 - } - }, - "interface-8": { - "interface": { - "id": 8 - } - }, "interface-7": { "interface": { "id": 7 } - } - }, - "exports": {}, - "package": 3 - }, - { - "name": "imports", - "imports": { - "interface-10": { - "interface": { - "id": 10 - } }, - "interface-11": { + "interface-8": { "interface": { - "id": 11 + "id": 8 } }, "interface-1": { @@ -121,14 +99,14 @@ "id": 1 } }, - "interface-15": { + "interface-12": { "interface": { - "id": 15 + "id": 12 } }, - "interface-16": { + "interface-13": { "interface": { - "id": 16 + "id": 13 } }, "interface-0": { @@ -146,19 +124,41 @@ "id": 3 } }, - "interface-13": { + "interface-10": { "interface": { - "id": 13 + "id": 10 } }, - "interface-14": { + "interface-11": { "interface": { - "id": 14 + "id": 11 } }, - "interface-12": { + "interface-9": { "interface": { - "id": 12 + "id": 9 + } + } + }, + "exports": {}, + "package": 3 + }, + { + "name": "imports", + "imports": { + "interface-16": { + "interface": { + "id": 16 + } + }, + "interface-15": { + "interface": { + "id": 15 + } + }, + "interface-14": { + "interface": { + "id": 14 } } }, @@ -253,24 +253,19 @@ "id": 6 } }, - "interface-10": { - "interface": { - "id": 10 - } - }, - "interface-11": { + "interface-7": { "interface": { - "id": 11 + "id": 7 } }, - "interface-15": { + "interface-8": { "interface": { - "id": 15 + "id": 8 } }, - "interface-16": { + "interface-12": { "interface": { - "id": 16 + "id": 12 } }, "interface-13": { @@ -278,14 +273,14 @@ "id": 13 } }, - "interface-14": { + "interface-10": { "interface": { - "id": 14 + "id": 10 } }, - "interface-12": { + "interface-11": { "interface": { - "id": 12 + "id": 11 } }, "interface-9": { @@ -293,14 +288,19 @@ "id": 9 } }, - "interface-8": { + "interface-16": { "interface": { - "id": 8 + "id": 16 } }, - "interface-7": { + "interface-15": { "interface": { - "id": 7 + "id": 15 + } + }, + "interface-14": { + "interface": { + "id": 14 } } }, @@ -395,24 +395,19 @@ "id": 6 } }, - "interface-10": { - "interface": { - "id": 10 - } - }, - "interface-11": { + "interface-7": { "interface": { - "id": 11 + "id": 7 } }, - "interface-15": { + "interface-8": { "interface": { - "id": 15 + "id": 8 } }, - "interface-16": { + "interface-12": { "interface": { - "id": 16 + "id": 12 } }, "interface-13": { @@ -420,14 +415,14 @@ "id": 13 } }, - "interface-14": { + "interface-10": { "interface": { - "id": 14 + "id": 10 } }, - "interface-12": { + "interface-11": { "interface": { - "id": 12 + "id": 11 } }, "interface-9": { @@ -435,14 +430,19 @@ "id": 9 } }, - "interface-8": { + "interface-16": { "interface": { - "id": 8 + "id": 16 } }, - "interface-7": { + "interface-15": { "interface": { - "id": 7 + "id": 15 + } + }, + "interface-14": { + "interface": { + "id": 14 } } }, @@ -1811,131 +1811,26 @@ }, "package": 2 }, - { - "name": "insecure-seed", - "types": {}, - "functions": { - "insecure-seed": { - "name": "insecure-seed", - "kind": "freestanding", - "params": [], - "results": [ - { - "type": 71 - } - ], - "docs": { - "contents": "Return a 128-bit value that may contain a pseudo-random value.\n\nThe returned value is not required to be computed from a CSPRNG, and may\neven be entirely deterministic. Host implementations are encouraged to\nprovide pseudo-random values to any program exposed to\nattacker-controlled content, to enable DoS protection built into many\nlanguages' hash-map implementations.\n\nThis function is intended to only be called once, by a source language\nto initialize Denial Of Service (DoS) protection in its hash-map\nimplementation.\n\n# Expected future evolution\n\nThis will likely be changed to a value import, to prevent it from being\ncalled multiple times and potentially used for purposes other than DoS\nprotection." - } - } - }, - "docs": { - "contents": "The insecure-seed interface for seeding hash-map DoS resistance.\n\nIt is intended to be portable at least between Unix-family platforms and\nWindows." - }, - "package": 3 - }, - { - "name": "insecure", - "types": {}, - "functions": { - "get-insecure-random-bytes": { - "name": "get-insecure-random-bytes", - "kind": "freestanding", - "params": [ - { - "name": "len", - "type": "u64" - } - ], - "results": [ - { - "type": 72 - } - ], - "docs": { - "contents": "Return `len` insecure pseudo-random bytes.\n\nThis function is not cryptographically secure. Do not use it for\nanything related to security.\n\nThere are no requirements on the values of the returned bytes, however\nimplementations are encouraged to return evenly distributed values with\na long period." - } - }, - "get-insecure-random-u64": { - "name": "get-insecure-random-u64", - "kind": "freestanding", - "params": [], - "results": [ - { - "type": "u64" - } - ], - "docs": { - "contents": "Return an insecure pseudo-random `u64` value.\n\nThis function returns the same type of pseudo-random data as\n`get-insecure-random-bytes`, represented as a `u64`." - } - } - }, - "docs": { - "contents": "The insecure interface for insecure pseudo-random numbers.\n\nIt is intended to be portable at least between Unix-family platforms and\nWindows." - }, - "package": 3 - }, - { - "name": "random", - "types": {}, - "functions": { - "get-random-bytes": { - "name": "get-random-bytes", - "kind": "freestanding", - "params": [ - { - "name": "len", - "type": "u64" - } - ], - "results": [ - { - "type": 72 - } - ], - "docs": { - "contents": "Return `len` cryptographically-secure random or pseudo-random bytes.\n\nThis function must produce data at least as cryptographically secure and\nfast as an adequately seeded cryptographically-secure pseudo-random\nnumber generator (CSPRNG). It must not block, from the perspective of\nthe calling program, under any circumstances, including on the first\nrequest and on requests for numbers of bytes. The returned data must\nalways be unpredictable.\n\nThis function must always return fresh data. Deterministic environments\nmust omit this function, rather than implementing it with deterministic\ndata." - } - }, - "get-random-u64": { - "name": "get-random-u64", - "kind": "freestanding", - "params": [], - "results": [ - { - "type": "u64" - } - ], - "docs": { - "contents": "Return a cryptographically-secure random or pseudo-random `u64` value.\n\nThis function returns the same type of data as `get-random-bytes`,\nrepresented as a `u64`." - } - } - }, - "docs": { - "contents": "WASI Random is a random data API.\n\nIt is intended to be portable at least between Unix-family platforms and\nWindows." - }, - "package": 3 - }, { "name": "network", "types": { - "network": 73, - "error-code": 74, - "ip-address-family": 75, - "ipv4-address": 76, - "ipv6-address": 77, - "ip-address": 78, - "ipv4-socket-address": 79, - "ipv6-socket-address": 80, - "ip-socket-address": 81 + "network": 71, + "error-code": 72, + "ip-address-family": 73, + "ipv4-address": 74, + "ipv6-address": 75, + "ip-address": 76, + "ipv4-socket-address": 77, + "ipv6-socket-address": 78, + "ip-socket-address": 79 }, "functions": {}, - "package": 4 + "package": 3 }, { "name": "instance-network", "types": { - "network": 82 + "network": 80 }, "functions": { "instance-network": { @@ -1944,7 +1839,7 @@ "params": [], "results": [ { - "type": 159 + "type": 157 } ], "docs": { @@ -1955,16 +1850,16 @@ "docs": { "contents": "This interface provides a value-export of the default network handle.." }, - "package": 4 + "package": 3 }, { "name": "ip-name-lookup", "types": { - "pollable": 83, - "network": 84, - "error-code": 85, - "ip-address": 86, - "resolve-address-stream": 87 + "pollable": 81, + "network": 82, + "error-code": 83, + "ip-address": 84, + "resolve-address-stream": 85 }, "functions": { "resolve-addresses": { @@ -1973,7 +1868,7 @@ "params": [ { "name": "network", - "type": 88 + "type": 86 }, { "name": "name", @@ -1982,7 +1877,7 @@ ], "results": [ { - "type": 90 + "type": 88 } ], "docs": { @@ -1992,17 +1887,17 @@ "[method]resolve-address-stream.resolve-next-address": { "name": "[method]resolve-address-stream.resolve-next-address", "kind": { - "method": 87 + "method": 85 }, "params": [ { "name": "self", - "type": 91 + "type": 89 } ], "results": [ { - "type": 93 + "type": 91 } ], "docs": { @@ -2012,17 +1907,17 @@ "[method]resolve-address-stream.subscribe": { "name": "[method]resolve-address-stream.subscribe", "kind": { - "method": 87 + "method": 85 }, "params": [ { "name": "self", - "type": 91 + "type": 89 } ], "results": [ { - "type": 160 + "type": 158 } ], "docs": { @@ -2030,45 +1925,45 @@ } } }, - "package": 4 + "package": 3 }, { "name": "tcp", "types": { - "input-stream": 94, - "output-stream": 95, - "pollable": 96, - "duration": 97, - "network": 98, - "error-code": 99, - "ip-socket-address": 100, - "ip-address-family": 101, - "shutdown-type": 102, - "tcp-socket": 103 + "input-stream": 92, + "output-stream": 93, + "pollable": 94, + "duration": 95, + "network": 96, + "error-code": 97, + "ip-socket-address": 98, + "ip-address-family": 99, + "shutdown-type": 100, + "tcp-socket": 101 }, "functions": { "[method]tcp-socket.start-bind": { "name": "[method]tcp-socket.start-bind", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 }, { "name": "network", - "type": 105 + "type": 103 }, { "name": "local-address", - "type": 100 + "type": 98 } ], "results": [ { - "type": 106 + "type": 104 } ], "docs": { @@ -2078,42 +1973,42 @@ "[method]tcp-socket.finish-bind": { "name": "[method]tcp-socket.finish-bind", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 } ], "results": [ { - "type": 106 + "type": 104 } ] }, "[method]tcp-socket.start-connect": { "name": "[method]tcp-socket.start-connect", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 }, { "name": "network", - "type": 105 + "type": 103 }, { "name": "remote-address", - "type": 100 + "type": 98 } ], "results": [ { - "type": 106 + "type": 104 } ], "docs": { @@ -2123,34 +2018,34 @@ "[method]tcp-socket.finish-connect": { "name": "[method]tcp-socket.finish-connect", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 } ], "results": [ { - "type": 110 + "type": 108 } ] }, "[method]tcp-socket.start-listen": { "name": "[method]tcp-socket.start-listen", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 } ], "results": [ { - "type": 106 + "type": 104 } ], "docs": { @@ -2160,34 +2055,34 @@ "[method]tcp-socket.finish-listen": { "name": "[method]tcp-socket.finish-listen", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 } ], "results": [ { - "type": 106 + "type": 104 } ] }, "[method]tcp-socket.accept": { "name": "[method]tcp-socket.accept", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 } ], "results": [ { - "type": 113 + "type": 111 } ], "docs": { @@ -2197,17 +2092,17 @@ "[method]tcp-socket.local-address": { "name": "[method]tcp-socket.local-address", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 } ], "results": [ { - "type": 114 + "type": 112 } ], "docs": { @@ -2217,17 +2112,17 @@ "[method]tcp-socket.remote-address": { "name": "[method]tcp-socket.remote-address", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 } ], "results": [ { - "type": 114 + "type": 112 } ], "docs": { @@ -2237,12 +2132,12 @@ "[method]tcp-socket.is-listening": { "name": "[method]tcp-socket.is-listening", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 } ], "results": [ @@ -2257,17 +2152,17 @@ "[method]tcp-socket.address-family": { "name": "[method]tcp-socket.address-family", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 } ], "results": [ { - "type": 101 + "type": 99 } ], "docs": { @@ -2277,12 +2172,12 @@ "[method]tcp-socket.set-listen-backlog-size": { "name": "[method]tcp-socket.set-listen-backlog-size", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 }, { "name": "value", @@ -2291,7 +2186,7 @@ ], "results": [ { - "type": 106 + "type": 104 } ], "docs": { @@ -2301,17 +2196,17 @@ "[method]tcp-socket.keep-alive-enabled": { "name": "[method]tcp-socket.keep-alive-enabled", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 } ], "results": [ { - "type": 115 + "type": 113 } ], "docs": { @@ -2321,12 +2216,12 @@ "[method]tcp-socket.set-keep-alive-enabled": { "name": "[method]tcp-socket.set-keep-alive-enabled", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 }, { "name": "value", @@ -2335,24 +2230,24 @@ ], "results": [ { - "type": 106 + "type": 104 } ] }, "[method]tcp-socket.keep-alive-idle-time": { "name": "[method]tcp-socket.keep-alive-idle-time", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 } ], "results": [ { - "type": 116 + "type": 114 } ], "docs": { @@ -2362,38 +2257,38 @@ "[method]tcp-socket.set-keep-alive-idle-time": { "name": "[method]tcp-socket.set-keep-alive-idle-time", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 }, { "name": "value", - "type": 97 + "type": 95 } ], "results": [ { - "type": 106 + "type": 104 } ] }, "[method]tcp-socket.keep-alive-interval": { "name": "[method]tcp-socket.keep-alive-interval", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 } ], "results": [ { - "type": 116 + "type": 114 } ], "docs": { @@ -2403,38 +2298,38 @@ "[method]tcp-socket.set-keep-alive-interval": { "name": "[method]tcp-socket.set-keep-alive-interval", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 }, { "name": "value", - "type": 97 + "type": 95 } ], "results": [ { - "type": 106 + "type": 104 } ] }, "[method]tcp-socket.keep-alive-count": { "name": "[method]tcp-socket.keep-alive-count", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 } ], "results": [ { - "type": 117 + "type": 115 } ], "docs": { @@ -2444,12 +2339,12 @@ "[method]tcp-socket.set-keep-alive-count": { "name": "[method]tcp-socket.set-keep-alive-count", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 }, { "name": "value", @@ -2458,24 +2353,24 @@ ], "results": [ { - "type": 106 + "type": 104 } ] }, "[method]tcp-socket.hop-limit": { "name": "[method]tcp-socket.hop-limit", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 } ], "results": [ { - "type": 118 + "type": 116 } ], "docs": { @@ -2485,12 +2380,12 @@ "[method]tcp-socket.set-hop-limit": { "name": "[method]tcp-socket.set-hop-limit", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 }, { "name": "value", @@ -2499,24 +2394,24 @@ ], "results": [ { - "type": 106 + "type": 104 } ] }, "[method]tcp-socket.receive-buffer-size": { "name": "[method]tcp-socket.receive-buffer-size", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 } ], "results": [ { - "type": 119 + "type": 117 } ], "docs": { @@ -2526,12 +2421,12 @@ "[method]tcp-socket.set-receive-buffer-size": { "name": "[method]tcp-socket.set-receive-buffer-size", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 }, { "name": "value", @@ -2540,36 +2435,36 @@ ], "results": [ { - "type": 106 + "type": 104 } ] }, "[method]tcp-socket.send-buffer-size": { "name": "[method]tcp-socket.send-buffer-size", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 } ], "results": [ { - "type": 119 + "type": 117 } ] }, "[method]tcp-socket.set-send-buffer-size": { "name": "[method]tcp-socket.set-send-buffer-size", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 }, { "name": "value", @@ -2578,24 +2473,24 @@ ], "results": [ { - "type": 106 + "type": 104 } ] }, "[method]tcp-socket.subscribe": { "name": "[method]tcp-socket.subscribe", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 } ], "results": [ { - "type": 161 + "type": 159 } ], "docs": { @@ -2605,21 +2500,21 @@ "[method]tcp-socket.shutdown": { "name": "[method]tcp-socket.shutdown", "kind": { - "method": 103 + "method": 101 }, "params": [ { "name": "self", - "type": 104 + "type": 102 }, { "name": "shutdown-type", - "type": 102 + "type": 100 } ], "results": [ { - "type": 106 + "type": 104 } ], "docs": { @@ -2627,15 +2522,15 @@ } } }, - "package": 4 + "package": 3 }, { "name": "tcp-create-socket", "types": { - "network": 120, - "error-code": 121, - "ip-address-family": 122, - "tcp-socket": 123 + "network": 118, + "error-code": 119, + "ip-address-family": 120, + "tcp-socket": 121 }, "functions": { "create-tcp-socket": { @@ -2644,12 +2539,12 @@ "params": [ { "name": "address-family", - "type": 122 + "type": 120 } ], "results": [ { - "type": 125 + "type": 123 } ], "docs": { @@ -2657,45 +2552,45 @@ } } }, - "package": 4 + "package": 3 }, { "name": "udp", "types": { - "pollable": 126, - "network": 127, - "error-code": 128, - "ip-socket-address": 129, - "ip-address-family": 130, - "incoming-datagram": 132, - "outgoing-datagram": 134, - "udp-socket": 135, - "incoming-datagram-stream": 136, - "outgoing-datagram-stream": 137 + "pollable": 124, + "network": 125, + "error-code": 126, + "ip-socket-address": 127, + "ip-address-family": 128, + "incoming-datagram": 130, + "outgoing-datagram": 132, + "udp-socket": 133, + "incoming-datagram-stream": 134, + "outgoing-datagram-stream": 135 }, "functions": { "[method]udp-socket.start-bind": { "name": "[method]udp-socket.start-bind", "kind": { - "method": 135 + "method": 133 }, "params": [ { "name": "self", - "type": 138 + "type": 136 }, { "name": "network", - "type": 139 + "type": 137 }, { "name": "local-address", - "type": 129 + "type": 127 } ], "results": [ { - "type": 140 + "type": 138 } ], "docs": { @@ -2705,38 +2600,38 @@ "[method]udp-socket.finish-bind": { "name": "[method]udp-socket.finish-bind", "kind": { - "method": 135 + "method": 133 }, "params": [ { "name": "self", - "type": 138 + "type": 136 } ], "results": [ { - "type": 140 + "type": 138 } ] }, "[method]udp-socket.stream": { "name": "[method]udp-socket.stream", "kind": { - "method": 135 + "method": 133 }, "params": [ { "name": "self", - "type": 138 + "type": 136 }, { "name": "remote-address", - "type": 133 + "type": 131 } ], "results": [ { - "type": 144 + "type": 142 } ], "docs": { @@ -2746,17 +2641,17 @@ "[method]udp-socket.local-address": { "name": "[method]udp-socket.local-address", "kind": { - "method": 135 + "method": 133 }, "params": [ { "name": "self", - "type": 138 + "type": 136 } ], "results": [ { - "type": 145 + "type": 143 } ], "docs": { @@ -2766,17 +2661,17 @@ "[method]udp-socket.remote-address": { "name": "[method]udp-socket.remote-address", "kind": { - "method": 135 + "method": 133 }, "params": [ { "name": "self", - "type": 138 + "type": 136 } ], "results": [ { - "type": 145 + "type": 143 } ], "docs": { @@ -2786,17 +2681,17 @@ "[method]udp-socket.address-family": { "name": "[method]udp-socket.address-family", "kind": { - "method": 135 + "method": 133 }, "params": [ { "name": "self", - "type": 138 + "type": 136 } ], "results": [ { - "type": 130 + "type": 128 } ], "docs": { @@ -2806,17 +2701,17 @@ "[method]udp-socket.unicast-hop-limit": { "name": "[method]udp-socket.unicast-hop-limit", "kind": { - "method": 135 + "method": 133 }, "params": [ { "name": "self", - "type": 138 + "type": 136 } ], "results": [ { - "type": 146 + "type": 144 } ], "docs": { @@ -2826,12 +2721,12 @@ "[method]udp-socket.set-unicast-hop-limit": { "name": "[method]udp-socket.set-unicast-hop-limit", "kind": { - "method": 135 + "method": 133 }, "params": [ { "name": "self", - "type": 138 + "type": 136 }, { "name": "value", @@ -2840,24 +2735,24 @@ ], "results": [ { - "type": 140 + "type": 138 } ] }, "[method]udp-socket.receive-buffer-size": { "name": "[method]udp-socket.receive-buffer-size", "kind": { - "method": 135 + "method": 133 }, "params": [ { "name": "self", - "type": 138 + "type": 136 } ], "results": [ { - "type": 147 + "type": 145 } ], "docs": { @@ -2867,12 +2762,12 @@ "[method]udp-socket.set-receive-buffer-size": { "name": "[method]udp-socket.set-receive-buffer-size", "kind": { - "method": 135 + "method": 133 }, "params": [ { "name": "self", - "type": 138 + "type": 136 }, { "name": "value", @@ -2881,36 +2776,36 @@ ], "results": [ { - "type": 140 + "type": 138 } ] }, "[method]udp-socket.send-buffer-size": { "name": "[method]udp-socket.send-buffer-size", "kind": { - "method": 135 + "method": 133 }, "params": [ { "name": "self", - "type": 138 + "type": 136 } ], "results": [ { - "type": 147 + "type": 145 } ] }, "[method]udp-socket.set-send-buffer-size": { "name": "[method]udp-socket.set-send-buffer-size", "kind": { - "method": 135 + "method": 133 }, "params": [ { "name": "self", - "type": 138 + "type": 136 }, { "name": "value", @@ -2919,24 +2814,24 @@ ], "results": [ { - "type": 140 + "type": 138 } ] }, "[method]udp-socket.subscribe": { "name": "[method]udp-socket.subscribe", "kind": { - "method": 135 + "method": 133 }, "params": [ { "name": "self", - "type": 138 + "type": 136 } ], "results": [ { - "type": 162 + "type": 160 } ], "docs": { @@ -2946,12 +2841,12 @@ "[method]incoming-datagram-stream.receive": { "name": "[method]incoming-datagram-stream.receive", "kind": { - "method": 136 + "method": 134 }, "params": [ { "name": "self", - "type": 148 + "type": 146 }, { "name": "max-results", @@ -2960,7 +2855,7 @@ ], "results": [ { - "type": 150 + "type": 148 } ], "docs": { @@ -2970,17 +2865,17 @@ "[method]incoming-datagram-stream.subscribe": { "name": "[method]incoming-datagram-stream.subscribe", "kind": { - "method": 136 + "method": 134 }, "params": [ { "name": "self", - "type": 148 + "type": 146 } ], "results": [ { - "type": 162 + "type": 160 } ], "docs": { @@ -2990,17 +2885,17 @@ "[method]outgoing-datagram-stream.check-send": { "name": "[method]outgoing-datagram-stream.check-send", "kind": { - "method": 137 + "method": 135 }, "params": [ { "name": "self", - "type": 151 + "type": 149 } ], "results": [ { - "type": 147 + "type": 145 } ], "docs": { @@ -3010,21 +2905,21 @@ "[method]outgoing-datagram-stream.send": { "name": "[method]outgoing-datagram-stream.send", "kind": { - "method": 137 + "method": 135 }, "params": [ { "name": "self", - "type": 151 + "type": 149 }, { "name": "datagrams", - "type": 152 + "type": 150 } ], "results": [ { - "type": 147 + "type": 145 } ], "docs": { @@ -3034,17 +2929,17 @@ "[method]outgoing-datagram-stream.subscribe": { "name": "[method]outgoing-datagram-stream.subscribe", "kind": { - "method": 137 + "method": 135 }, "params": [ { "name": "self", - "type": 151 + "type": 149 } ], "results": [ { - "type": 162 + "type": 160 } ], "docs": { @@ -3052,15 +2947,15 @@ } } }, - "package": 4 + "package": 3 }, { "name": "udp-create-socket", "types": { - "network": 153, - "error-code": 154, - "ip-address-family": 155, - "udp-socket": 156 + "network": 151, + "error-code": 152, + "ip-address-family": 153, + "udp-socket": 154 }, "functions": { "create-udp-socket": { @@ -3069,12 +2964,12 @@ "params": [ { "name": "address-family", - "type": 155 + "type": 153 } ], "results": [ { - "type": 158 + "type": 156 } ], "docs": { @@ -3082,6 +2977,111 @@ } } }, + "package": 3 + }, + { + "name": "insecure-seed", + "types": {}, + "functions": { + "insecure-seed": { + "name": "insecure-seed", + "kind": "freestanding", + "params": [], + "results": [ + { + "type": 161 + } + ], + "docs": { + "contents": "Return a 128-bit value that may contain a pseudo-random value.\n\nThe returned value is not required to be computed from a CSPRNG, and may\neven be entirely deterministic. Host implementations are encouraged to\nprovide pseudo-random values to any program exposed to\nattacker-controlled content, to enable DoS protection built into many\nlanguages' hash-map implementations.\n\nThis function is intended to only be called once, by a source language\nto initialize Denial Of Service (DoS) protection in its hash-map\nimplementation.\n\n# Expected future evolution\n\nThis will likely be changed to a value import, to prevent it from being\ncalled multiple times and potentially used for purposes other than DoS\nprotection." + } + } + }, + "docs": { + "contents": "The insecure-seed interface for seeding hash-map DoS resistance.\n\nIt is intended to be portable at least between Unix-family platforms and\nWindows." + }, + "package": 4 + }, + { + "name": "insecure", + "types": {}, + "functions": { + "get-insecure-random-bytes": { + "name": "get-insecure-random-bytes", + "kind": "freestanding", + "params": [ + { + "name": "len", + "type": "u64" + } + ], + "results": [ + { + "type": 162 + } + ], + "docs": { + "contents": "Return `len` insecure pseudo-random bytes.\n\nThis function is not cryptographically secure. Do not use it for\nanything related to security.\n\nThere are no requirements on the values of the returned bytes, however\nimplementations are encouraged to return evenly distributed values with\na long period." + } + }, + "get-insecure-random-u64": { + "name": "get-insecure-random-u64", + "kind": "freestanding", + "params": [], + "results": [ + { + "type": "u64" + } + ], + "docs": { + "contents": "Return an insecure pseudo-random `u64` value.\n\nThis function returns the same type of pseudo-random data as\n`get-insecure-random-bytes`, represented as a `u64`." + } + } + }, + "docs": { + "contents": "The insecure interface for insecure pseudo-random numbers.\n\nIt is intended to be portable at least between Unix-family platforms and\nWindows." + }, + "package": 4 + }, + { + "name": "random", + "types": {}, + "functions": { + "get-random-bytes": { + "name": "get-random-bytes", + "kind": "freestanding", + "params": [ + { + "name": "len", + "type": "u64" + } + ], + "results": [ + { + "type": 162 + } + ], + "docs": { + "contents": "Return `len` cryptographically-secure random or pseudo-random bytes.\n\nThis function must produce data at least as cryptographically secure and\nfast as an adequately seeded cryptographically-secure pseudo-random\nnumber generator (CSPRNG). It must not block, from the perspective of\nthe calling program, under any circumstances, including on the first\nrequest and on requests for numbers of bytes. The returned data must\nalways be unpredictable.\n\nThis function must always return fresh data. Deterministic environments\nmust omit this function, rather than implementing it with deterministic\ndata." + } + }, + "get-random-u64": { + "name": "get-random-u64", + "kind": "freestanding", + "params": [], + "results": [ + { + "type": "u64" + } + ], + "docs": { + "contents": "Return a cryptographically-secure random or pseudo-random `u64` value.\n\nThis function returns the same type of data as `get-random-bytes`,\nrepresented as a `u64`." + } + } + }, + "docs": { + "contents": "WASI Random is a random data API.\n\nIt is intended to be portable at least between Unix-family platforms and\nWindows." + }, "package": 4 }, { @@ -4547,30 +4547,11 @@ }, "owner": null }, - { - "name": null, - "kind": { - "tuple": { - "types": [ - "u64", - "u64" - ] - } - }, - "owner": null - }, - { - "name": null, - "kind": { - "list": "u8" - }, - "owner": null - }, { "name": "network", "kind": "resource", "owner": { - "interface": 10 + "interface": 7 }, "docs": { "contents": "An opaque resource that represents access to (a subset of) the network.\nThis enables context-based security for networking.\nThere is no need for this to map 1:1 to a physical network interface." @@ -4711,7 +4692,7 @@ } }, "owner": { - "interface": 10 + "interface": 7 }, "docs": { "contents": "Error codes.\n\nIn theory, every API can return any error code.\nIn practice, API's typically only return the errors documented per API\ncombined with a couple of errors that are always possible:\n- `unknown`\n- `access-denied`\n- `not-supported`\n- `out-of-memory`\n- `concurrency-conflict`\n\nSee each individual API for what the POSIX equivalents are. They sometimes differ per API." @@ -4738,7 +4719,7 @@ } }, "owner": { - "interface": 10 + "interface": 7 } }, { @@ -4754,7 +4735,7 @@ } }, "owner": { - "interface": 10 + "interface": 7 } }, { @@ -4774,7 +4755,7 @@ } }, "owner": { - "interface": 10 + "interface": 7 } }, { @@ -4784,17 +4765,17 @@ "cases": [ { "name": "ipv4", - "type": 76 + "type": 74 }, { "name": "ipv6", - "type": 77 + "type": 75 } ] } }, "owner": { - "interface": 10 + "interface": 7 } }, { @@ -4811,7 +4792,7 @@ }, { "name": "address", - "type": 76, + "type": 74, "docs": { "contents": "sin_addr" } @@ -4820,7 +4801,7 @@ } }, "owner": { - "interface": 10 + "interface": 7 } }, { @@ -4844,7 +4825,7 @@ }, { "name": "address", - "type": 77, + "type": 75, "docs": { "contents": "sin6_addr" } @@ -4860,7 +4841,7 @@ } }, "owner": { - "interface": 10 + "interface": 7 } }, { @@ -4870,26 +4851,26 @@ "cases": [ { "name": "ipv4", - "type": 79 + "type": 77 }, { "name": "ipv6", - "type": 80 + "type": 78 } ] } }, "owner": { - "interface": 10 + "interface": 7 } }, { "name": "network", "kind": { - "type": 73 + "type": 71 }, "owner": { - "interface": 11 + "interface": 8 } }, { @@ -4898,48 +4879,48 @@ "type": 2 }, "owner": { - "interface": 12 + "interface": 9 } }, { "name": "network", "kind": { - "type": 73 + "type": 71 }, "owner": { - "interface": 12 + "interface": 9 } }, { "name": "error-code", "kind": { - "type": 74 + "type": 72 }, "owner": { - "interface": 12 + "interface": 9 } }, { "name": "ip-address", "kind": { - "type": 78 + "type": 76 }, "owner": { - "interface": 12 + "interface": 9 } }, { "name": "resolve-address-stream", "kind": "resource", "owner": { - "interface": 12 + "interface": 9 } }, { "name": null, "kind": { "handle": { - "borrow": 84 + "borrow": 82 } }, "owner": null @@ -4948,7 +4929,7 @@ "name": null, "kind": { "handle": { - "own": 87 + "own": 85 } }, "owner": null @@ -4957,8 +4938,8 @@ "name": null, "kind": { "result": { - "ok": 89, - "err": 85 + "ok": 87, + "err": 83 } }, "owner": null @@ -4967,7 +4948,7 @@ "name": null, "kind": { "handle": { - "borrow": 87 + "borrow": 85 } }, "owner": null @@ -4975,7 +4956,7 @@ { "name": null, "kind": { - "option": 86 + "option": 84 }, "owner": null }, @@ -4983,8 +4964,8 @@ "name": null, "kind": { "result": { - "ok": 92, - "err": 85 + "ok": 90, + "err": 83 } }, "owner": null @@ -4995,7 +4976,7 @@ "type": 10 }, "owner": { - "interface": 13 + "interface": 10 } }, { @@ -5004,7 +4985,7 @@ "type": 11 }, "owner": { - "interface": 13 + "interface": 10 } }, { @@ -5013,7 +4994,7 @@ "type": 2 }, "owner": { - "interface": 13 + "interface": 10 } }, { @@ -5022,43 +5003,43 @@ "type": 21 }, "owner": { - "interface": 13 + "interface": 10 } }, { "name": "network", "kind": { - "type": 73 + "type": 71 }, "owner": { - "interface": 13 + "interface": 10 } }, { "name": "error-code", "kind": { - "type": 74 + "type": 72 }, "owner": { - "interface": 13 + "interface": 10 } }, { "name": "ip-socket-address", "kind": { - "type": 81 + "type": 79 }, "owner": { - "interface": 13 + "interface": 10 } }, { "name": "ip-address-family", "kind": { - "type": 75 + "type": 73 }, "owner": { - "interface": 13 + "interface": 10 } }, { @@ -5088,14 +5069,14 @@ } }, "owner": { - "interface": 13 + "interface": 10 } }, { "name": "tcp-socket", "kind": "resource", "owner": { - "interface": 13 + "interface": 10 }, "docs": { "contents": "A TCP socket resource.\n\nThe socket can be in one of the following states:\n- `unbound`\n- `bind-in-progress`\n- `bound` (See note below)\n- `listen-in-progress`\n- `listening`\n- `connect-in-progress`\n- `connected`\n- `closed`\nSee \nfor a more information.\n\nNote: Except where explicitly mentioned, whenever this documentation uses\nthe term \"bound\" without backticks it actually means: in the `bound` state *or higher*.\n(i.e. `bound`, `listen-in-progress`, `listening`, `connect-in-progress` or `connected`)\n\nIn addition to the general error codes documented on the\n`network::error-code` type, TCP socket methods may always return\n`error(invalid-state)` when in the `closed` state." @@ -5105,7 +5086,7 @@ "name": null, "kind": { "handle": { - "borrow": 103 + "borrow": 101 } }, "owner": null @@ -5114,7 +5095,7 @@ "name": null, "kind": { "handle": { - "borrow": 98 + "borrow": 96 } }, "owner": null @@ -5124,7 +5105,7 @@ "kind": { "result": { "ok": null, - "err": 99 + "err": 97 } }, "owner": null @@ -5133,7 +5114,7 @@ "name": null, "kind": { "handle": { - "own": 94 + "own": 92 } }, "owner": null @@ -5142,7 +5123,7 @@ "name": null, "kind": { "handle": { - "own": 95 + "own": 93 } }, "owner": null @@ -5152,8 +5133,8 @@ "kind": { "tuple": { "types": [ - 107, - 108 + 105, + 106 ] } }, @@ -5163,8 +5144,8 @@ "name": null, "kind": { "result": { - "ok": 109, - "err": 99 + "ok": 107, + "err": 97 } }, "owner": null @@ -5173,7 +5154,7 @@ "name": null, "kind": { "handle": { - "own": 103 + "own": 101 } }, "owner": null @@ -5183,9 +5164,9 @@ "kind": { "tuple": { "types": [ - 111, - 107, - 108 + 109, + 105, + 106 ] } }, @@ -5195,8 +5176,8 @@ "name": null, "kind": { "result": { - "ok": 112, - "err": 99 + "ok": 110, + "err": 97 } }, "owner": null @@ -5205,8 +5186,8 @@ "name": null, "kind": { "result": { - "ok": 100, - "err": 99 + "ok": 98, + "err": 97 } }, "owner": null @@ -5216,7 +5197,7 @@ "kind": { "result": { "ok": "bool", - "err": 99 + "err": 97 } }, "owner": null @@ -5225,8 +5206,8 @@ "name": null, "kind": { "result": { - "ok": 97, - "err": 99 + "ok": 95, + "err": 97 } }, "owner": null @@ -5236,7 +5217,7 @@ "kind": { "result": { "ok": "u32", - "err": 99 + "err": 97 } }, "owner": null @@ -5246,7 +5227,7 @@ "kind": { "result": { "ok": "u8", - "err": 99 + "err": 97 } }, "owner": null @@ -5256,7 +5237,7 @@ "kind": { "result": { "ok": "u64", - "err": 99 + "err": 97 } }, "owner": null @@ -5264,44 +5245,44 @@ { "name": "network", "kind": { - "type": 73 + "type": 71 }, "owner": { - "interface": 14 + "interface": 11 } }, { "name": "error-code", "kind": { - "type": 74 + "type": 72 }, "owner": { - "interface": 14 + "interface": 11 } }, { "name": "ip-address-family", "kind": { - "type": 75 + "type": 73 }, "owner": { - "interface": 14 + "interface": 11 } }, { "name": "tcp-socket", "kind": { - "type": 103 + "type": 101 }, "owner": { - "interface": 14 + "interface": 11 } }, { "name": null, "kind": { "handle": { - "own": 123 + "own": 121 } }, "owner": null @@ -5310,8 +5291,8 @@ "name": null, "kind": { "result": { - "ok": 124, - "err": 121 + "ok": 122, + "err": 119 } }, "owner": null @@ -5322,43 +5303,43 @@ "type": 2 }, "owner": { - "interface": 15 + "interface": 12 } }, { "name": "network", "kind": { - "type": 73 + "type": 71 }, "owner": { - "interface": 15 + "interface": 12 } }, { "name": "error-code", "kind": { - "type": 74 + "type": 72 }, "owner": { - "interface": 15 + "interface": 12 } }, { "name": "ip-socket-address", "kind": { - "type": 81 + "type": 79 }, "owner": { - "interface": 15 + "interface": 12 } }, { "name": "ip-address-family", "kind": { - "type": 75 + "type": 73 }, "owner": { - "interface": 15 + "interface": 12 } }, { @@ -5375,14 +5356,14 @@ "fields": [ { "name": "data", - "type": 131, + "type": 129, "docs": { "contents": "The payload.\n\nTheoretical max size: ~64 KiB. In practice, typically less than 1500 bytes." } }, { "name": "remote-address", - "type": 129, + "type": 127, "docs": { "contents": "The source address.\n\nThis field is guaranteed to match the remote address the stream was initialized with, if any.\n\nEquivalent to the `src_addr` out parameter of `recvfrom`." } @@ -5391,7 +5372,7 @@ } }, "owner": { - "interface": 15 + "interface": 12 }, "docs": { "contents": "A received datagram." @@ -5400,7 +5381,7 @@ { "name": null, "kind": { - "option": 129 + "option": 127 }, "owner": null }, @@ -5411,14 +5392,14 @@ "fields": [ { "name": "data", - "type": 131, + "type": 129, "docs": { "contents": "The payload." } }, { "name": "remote-address", - "type": 133, + "type": 131, "docs": { "contents": "The destination address.\n\nThe requirements on this field depend on how the stream was initialized:\n- with a remote address: this field must be None or match the stream's remote address exactly.\n- without a remote address: this field is required.\n\nIf this value is None, the send operation is equivalent to `send` in POSIX. Otherwise it is equivalent to `sendto`." } @@ -5427,7 +5408,7 @@ } }, "owner": { - "interface": 15 + "interface": 12 }, "docs": { "contents": "A datagram to be sent out." @@ -5437,7 +5418,7 @@ "name": "udp-socket", "kind": "resource", "owner": { - "interface": 15 + "interface": 12 }, "docs": { "contents": "A UDP socket handle." @@ -5447,21 +5428,21 @@ "name": "incoming-datagram-stream", "kind": "resource", "owner": { - "interface": 15 + "interface": 12 } }, { "name": "outgoing-datagram-stream", "kind": "resource", "owner": { - "interface": 15 + "interface": 12 } }, { "name": null, "kind": { "handle": { - "borrow": 135 + "borrow": 133 } }, "owner": null @@ -5470,7 +5451,7 @@ "name": null, "kind": { "handle": { - "borrow": 127 + "borrow": 125 } }, "owner": null @@ -5480,7 +5461,7 @@ "kind": { "result": { "ok": null, - "err": 128 + "err": 126 } }, "owner": null @@ -5489,7 +5470,7 @@ "name": null, "kind": { "handle": { - "own": 136 + "own": 134 } }, "owner": null @@ -5498,7 +5479,7 @@ "name": null, "kind": { "handle": { - "own": 137 + "own": 135 } }, "owner": null @@ -5508,8 +5489,8 @@ "kind": { "tuple": { "types": [ - 141, - 142 + 139, + 140 ] } }, @@ -5519,8 +5500,8 @@ "name": null, "kind": { "result": { - "ok": 143, - "err": 128 + "ok": 141, + "err": 126 } }, "owner": null @@ -5529,8 +5510,8 @@ "name": null, "kind": { "result": { - "ok": 129, - "err": 128 + "ok": 127, + "err": 126 } }, "owner": null @@ -5540,7 +5521,7 @@ "kind": { "result": { "ok": "u8", - "err": 128 + "err": 126 } }, "owner": null @@ -5550,7 +5531,7 @@ "kind": { "result": { "ok": "u64", - "err": 128 + "err": 126 } }, "owner": null @@ -5559,7 +5540,7 @@ "name": null, "kind": { "handle": { - "borrow": 136 + "borrow": 134 } }, "owner": null @@ -5567,7 +5548,7 @@ { "name": null, "kind": { - "list": 132 + "list": 130 }, "owner": null }, @@ -5575,8 +5556,8 @@ "name": null, "kind": { "result": { - "ok": 149, - "err": 128 + "ok": 147, + "err": 126 } }, "owner": null @@ -5585,7 +5566,7 @@ "name": null, "kind": { "handle": { - "borrow": 137 + "borrow": 135 } }, "owner": null @@ -5593,51 +5574,51 @@ { "name": null, "kind": { - "list": 134 + "list": 132 }, "owner": null }, { "name": "network", "kind": { - "type": 73 + "type": 71 }, "owner": { - "interface": 16 + "interface": 13 } }, { "name": "error-code", "kind": { - "type": 74 + "type": 72 }, "owner": { - "interface": 16 + "interface": 13 } }, { "name": "ip-address-family", "kind": { - "type": 75 + "type": 73 }, "owner": { - "interface": 16 + "interface": 13 } }, { "name": "udp-socket", "kind": { - "type": 135 + "type": 133 }, "owner": { - "interface": 16 + "interface": 13 } }, { "name": null, "kind": { "handle": { - "own": 156 + "own": 154 } }, "owner": null @@ -5646,8 +5627,8 @@ "name": null, "kind": { "result": { - "ok": 157, - "err": 154 + "ok": 155, + "err": 152 } }, "owner": null @@ -5656,7 +5637,7 @@ "name": null, "kind": { "handle": { - "own": 82 + "own": 80 } }, "owner": null @@ -5665,7 +5646,7 @@ "name": null, "kind": { "handle": { - "own": 83 + "own": 81 } }, "owner": null @@ -5674,7 +5655,7 @@ "name": null, "kind": { "handle": { - "own": 96 + "own": 94 } }, "owner": null @@ -5683,11 +5664,30 @@ "name": null, "kind": { "handle": { - "own": 126 + "own": 124 + } + }, + "owner": null + }, + { + "name": null, + "kind": { + "tuple": { + "types": [ + "u64", + "u64" + ] } }, "owner": null }, + { + "name": null, + "kind": { + "list": "u8" + }, + "owner": null + }, { "name": null, "kind": { @@ -5914,26 +5914,26 @@ } }, { - "name": "wasi:random@0.2.0", + "name": "wasi:sockets@0.2.0", "interfaces": { - "insecure-seed": 7, - "insecure": 8, - "random": 9 + "network": 7, + "instance-network": 8, + "ip-name-lookup": 9, + "tcp": 10, + "tcp-create-socket": 11, + "udp": 12, + "udp-create-socket": 13 }, "worlds": { "imports": 3 } }, { - "name": "wasi:sockets@0.2.0", + "name": "wasi:random@0.2.0", "interfaces": { - "network": 10, - "instance-network": 11, - "ip-name-lookup": 12, - "tcp": 13, - "tcp-create-socket": 14, - "udp": 15, - "udp-create-socket": 16 + "insecure-seed": 14, + "insecure": 15, + "random": 16 }, "worlds": { "imports": 4 diff --git a/testdata/wasi/cli.wit.json.golden.wit b/testdata/wasi/cli.wit.json.golden.wit index c422676a..df962597 100644 --- a/testdata/wasi/cli.wit.json.golden.wit +++ b/testdata/wasi/cli.wit.json.golden.wit @@ -155,97 +155,6 @@ world command { export run; } -package wasi:clocks@0.2.0 { - /// WASI Monotonic Clock is a clock API intended to let users measure elapsed - /// time. - /// - /// It is intended to be portable at least between Unix-family platforms and - /// Windows. - /// - /// A monotonic clock is a clock which has an unspecified initial value, and - /// successive reads of the clock will produce non-decreasing values. - /// - /// It is intended for measuring elapsed time. - interface monotonic-clock { - use wasi:io/poll@0.2.0.{pollable}; - - /// An instant in time, in nanoseconds. An instant is relative to an - /// unspecified initial value, and can only be compared to instances from - /// the same monotonic-clock. - type instant = u64; - - /// A duration of time, in nanoseconds. - type duration = u64; - - /// Read the current value of the clock. - /// - /// The clock is monotonic, therefore calling this function repeatedly will - /// produce a sequence of non-decreasing values. - now: func() -> instant; - - /// Query the resolution of the clock. Returns the duration of time - /// corresponding to a clock tick. - resolution: func() -> duration; - - /// Create a `pollable` which will resolve once the specified instant - /// occured. - subscribe-instant: func(when: instant) -> pollable; - - /// Create a `pollable` which will resolve once the given duration has - /// elapsed, starting at the time at which this function was called. - /// occured. - subscribe-duration: func(when: duration) -> pollable; - } - - /// WASI Wall Clock is a clock API intended to let users query the current - /// time. The name "wall" makes an analogy to a "clock on the wall", which - /// is not necessarily monotonic as it may be reset. - /// - /// It is intended to be portable at least between Unix-family platforms and - /// Windows. - /// - /// A wall clock is a clock which measures the date and time according to - /// some external reference. - /// - /// External references may be reset, so this clock is not necessarily - /// monotonic, making it unsuitable for measuring elapsed time. - /// - /// It is intended for reporting the current date and time for humans. - interface wall-clock { - /// A time and date in seconds plus nanoseconds. - record datetime { - seconds: u64, - nanoseconds: u32, - } - - /// Read the current value of the clock. - /// - /// This clock is not monotonic, therefore calling this function repeatedly - /// will not necessarily produce a sequence of non-decreasing values. - /// - /// The returned timestamps represent the number of seconds since - /// 1970-01-01T00:00:00Z, also known as [POSIX's Seconds Since the Epoch], - /// also known as [Unix Time]. - /// - /// The nanoseconds field of the output is always less than 1000000000. - /// - /// [POSIX's Seconds Since the Epoch]: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html#tag_21_04_16 - /// [Unix Time]: https://en.wikipedia.org/wiki/Unix_time - now: func() -> datetime; - - /// Query the resolution of the clock. - /// - /// The nanoseconds field of the output is always less than 1000000000. - resolution: func() -> datetime; - } - - world imports { - import wasi:io/poll@0.2.0; - import monotonic-clock; - import wall-clock; - } -} - package wasi:filesystem@0.2.0 { /// WASI filesystem is a filesystem API primarily intended to let users run WASI /// programs that access their files on their existing filesystems, without @@ -813,729 +722,665 @@ package wasi:filesystem@0.2.0 { } } -package wasi:io@0.2.0 { - interface error { - /// A resource which represents some error information. - /// - /// The only method provided by this resource is `to-debug-string`, - /// which provides some human-readable information about the error. - /// - /// In the `wasi:io` package, this resource is returned through the - /// `wasi:io/streams/stream-error` type. +package wasi:sockets@0.2.0 { + interface network { + /// An opaque resource that represents access to (a subset of) the network. + /// This enables context-based security for networking. + /// There is no need for this to map 1:1 to a physical network interface. + resource network; + + /// Error codes. /// - /// To provide more specific error information, other interfaces may - /// provide functions to further "downcast" this error into more specific - /// error information. For example, `error`s returned in streams derived - /// from filesystem types to be described using the filesystem's own - /// error-code type, using the function - /// `wasi:filesystem/types/filesystem-error-code`, which takes a parameter - /// `borrow` and returns - /// `option`. + /// In theory, every API can return any error code. + /// In practice, API's typically only return the errors documented per API + /// combined with a couple of errors that are always possible: + /// - `unknown` + /// - `access-denied` + /// - `not-supported` + /// - `out-of-memory` + /// - `concurrency-conflict` /// - /// The set of functions which can "downcast" an `error` into a more - /// concrete type is open. - resource error { - - /// Returns a string that is suitable to assist humans in debugging - /// this error. + /// See each individual API for what the POSIX equivalents are. They sometimes differ + /// per API. + enum error-code { + /// Unknown error + unknown, + /// Access denied. /// - /// WARNING: The returned string should not be consumed mechanically! - /// It may change across platforms, hosts, or other implementation - /// details. Parsing this string is a major platform-compatibility - /// hazard. - to-debug-string: func() -> string; - } - } - - /// A poll API intended to let users wait for I/O events on multiple handles - /// at once. - interface poll { - /// `pollable` represents a single I/O event which may be ready, or not. - resource pollable { - - /// `block` returns immediately if the pollable is ready, and otherwise - /// blocks until ready. + /// POSIX equivalent: EACCES, EPERM + access-denied, + /// The operation is not supported. /// - /// This function is equivalent to calling `poll.poll` on a list - /// containing only this pollable. - block: func(); - - /// Return the readiness of a pollable. This function never blocks. + /// POSIX equivalent: EOPNOTSUPP + not-supported, + /// One of the arguments is invalid. /// - /// Returns `true` when the pollable is ready, and `false` otherwise. - ready: func() -> bool; - } - - /// Poll for completion on a set of pollables. - /// - /// This function takes a list of pollables, which identify I/O sources of - /// interest, and waits until one or more of the events is ready for I/O. - /// - /// The result `list` contains one or more indices of handles in the - /// argument list that is ready for I/O. - /// - /// If the list contains more elements than can be indexed with a `u32` - /// value, this function traps. - /// - /// A timeout can be implemented by adding a pollable from the - /// wasi-clocks API to the list. - /// - /// This function does not return a `result`; polling in itself does not - /// do any I/O so it doesn't fail. If any of the I/O sources identified by - /// the pollables has an error, it is indicated by marking the source as - /// being reaedy for I/O. - poll: func(in: list>) -> list; - } - - /// WASI I/O is an I/O abstraction API which is currently focused on providing - /// stream types. - /// - /// In the future, the component model is expected to add built-in stream types; - /// when it does, they are expected to subsume this API. - interface streams { - use error.{error}; - use poll.{pollable}; - - /// An error for input-stream and output-stream operations. - variant stream-error { - /// The last operation (a write or flush) failed before completion. + /// POSIX equivalent: EINVAL + invalid-argument, + /// Not enough memory to complete the operation. /// - /// More information is available in the `error` payload. - last-operation-failed(error), - /// The stream is closed: no more input will be accepted by the - /// stream. A closed output-stream will return this error on all - /// future operations. - closed, - } - - /// An input bytestream. - /// - /// `input-stream`s are *non-blocking* to the extent practical on underlying - /// platforms. I/O operations always return promptly; if fewer bytes are - /// promptly available than requested, they return the number of bytes promptly - /// available, which could even be zero. To wait for data to be available, - /// use the `subscribe` function to obtain a `pollable` which can be polled - /// for using `wasi:io/poll`. - resource input-stream { - - /// Read bytes from a stream, after blocking until at least one byte can - /// be read. Except for blocking, behavior is identical to `read`. - blocking-read: func(len: u64) -> result, stream-error>; - - /// Skip bytes from a stream, after blocking until at least one byte - /// can be skipped. Except for blocking behavior, identical to `skip`. - blocking-skip: func(len: u64) -> result; - - /// Perform a non-blocking read from the stream. + /// POSIX equivalent: ENOMEM, ENOBUFS, EAI_MEMORY + out-of-memory, + /// The operation timed out before it could finish completely. + timeout, + /// This operation is incompatible with another asynchronous operation that is already + /// in progress. /// - /// When the source of a `read` is binary data, the bytes from the source - /// are returned verbatim. When the source of a `read` is known to the - /// implementation to be text, bytes containing the UTF-8 encoding of the - /// text are returned. + /// POSIX equivalent: EALREADY + concurrency-conflict, + /// Trying to finish an asynchronous operation that: + /// - has not been started yet, or: + /// - was already finished by a previous `finish-*` call. /// - /// This function returns a list of bytes containing the read data, - /// when successful. The returned list will contain up to `len` bytes; - /// it may return fewer than requested, but not more. The list is - /// empty when no bytes are available for reading at this time. The - /// pollable given by `subscribe` will be ready when more bytes are - /// available. + /// Note: this is scheduled to be removed when `future`s are natively supported. + not-in-progress, + /// The operation has been aborted because it could not be completed immediately. /// - /// This function fails with a `stream-error` when the operation - /// encounters an error, giving `last-operation-failed`, or when the - /// stream is closed, giving `closed`. + /// Note: this is scheduled to be removed when `future`s are natively supported. + would-block, + /// The operation is not valid in the socket's current state. + invalid-state, + /// A new socket resource could not be created because of a system limit. + new-socket-limit, + /// A bind operation failed because the provided address is not an address that the + /// `network` can bind to. + address-not-bindable, + /// A bind operation failed because the provided address is already in use or because + /// there are no ephemeral ports available. + address-in-use, + /// The remote address is not reachable + remote-unreachable, + /// The TCP connection was forcefully rejected + connection-refused, + /// The TCP connection was reset. + connection-reset, + /// A TCP connection was aborted. + connection-aborted, + /// The size of a datagram sent to a UDP socket exceeded the maximum + /// supported size. + datagram-too-large, + /// Name does not exist or has no suitable associated IP addresses. + name-unresolvable, + /// A temporary failure in name resolution occurred. + temporary-resolver-failure, + /// A permanent failure in name resolution occurred. + permanent-resolver-failure + } + enum ip-address-family { + /// Similar to `AF_INET` in POSIX. + ipv4, + /// Similar to `AF_INET6` in POSIX. + ipv6 + } + type ipv4-address = tuple; + type ipv6-address = tuple; + variant ip-address { + ipv4(ipv4-address), + ipv6(ipv6-address), + } + record ipv4-socket-address { + /// sin_port + port: u16, + /// sin_addr + address: ipv4-address, + } + record ipv6-socket-address { + /// sin6_port + port: u16, + /// sin6_flowinfo + flow-info: u32, + /// sin6_addr + address: ipv6-address, + /// sin6_scope_id + scope-id: u32, + } + variant ip-socket-address { + ipv4(ipv4-socket-address), + ipv6(ipv6-socket-address), + } + } + + /// This interface provides a value-export of the default network handle.. + interface instance-network { + use network.{network}; + + /// Get a handle to the default network. + instance-network: func() -> network; + } + + interface ip-name-lookup { + use wasi:io/poll@0.2.0.{pollable}; + use network.{network}; + use network.{error-code}; + use network.{ip-address}; + resource resolve-address-stream { + + /// Returns the next address from the resolver. /// - /// When the caller gives a `len` of 0, it represents a request to - /// read 0 bytes. If the stream is still open, this call should - /// succeed and return an empty list, or otherwise fail with `closed`. + /// This function should be called multiple times. On each call, it will + /// return the next address in connection order preference. If all + /// addresses have been exhausted, this function returns `none`. /// - /// The `len` parameter is a `u64`, which could represent a list of u8 which - /// is not possible to allocate in wasm32, or not desirable to allocate as - /// as a return value by the callee. The callee may return a list of bytes - /// less than `len` in size while more bytes are available for reading. - read: func(len: u64) -> result, stream-error>; - - /// Skip bytes from a stream. Returns number of bytes skipped. + /// This function never returns IPv4-mapped IPv6 addresses. /// - /// Behaves identical to `read`, except instead of returning a list - /// of bytes, returns the number of bytes consumed from the stream. - skip: func(len: u64) -> result; + /// # Typical errors + /// - `name-unresolvable`: Name does not exist or has no suitable associated + /// IP addresses. (EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY) + /// - `temporary-resolver-failure`: A temporary failure in name resolution occurred. + /// (EAI_AGAIN) + /// - `permanent-resolver-failure`: A permanent failure in name resolution occurred. + /// (EAI_FAIL) + /// - `would-block`: A result is not available yet. (EWOULDBLOCK, EAGAIN) + resolve-next-address: func() -> result, error-code>; - /// Create a `pollable` which will resolve once either the specified stream - /// has bytes available to read or the other end of the stream has been - /// closed. - /// The created `pollable` is a child resource of the `input-stream`. - /// Implementations may trap if the `input-stream` is dropped before - /// all derived `pollable`s created with this function are dropped. + /// Create a `pollable` which will resolve once the stream is ready for I/O. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. subscribe: func() -> pollable; } - /// An output bytestream. + /// Resolve an internet host name to a list of IP addresses. /// - /// `output-stream`s are *non-blocking* to the extent practical on - /// underlying platforms. Except where specified otherwise, I/O operations also - /// always return promptly, after the number of bytes that can be written - /// promptly, which could even be zero. To wait for the stream to be ready to - /// accept data, the `subscribe` function to obtain a `pollable` which can be - /// polled for using `wasi:io/poll`. - resource output-stream { + /// Unicode domain names are automatically converted to ASCII using IDNA encoding. + /// If the input is an IP address string, the address is parsed and returned + /// as-is without making any external requests. + /// + /// See the wasi-socket proposal README.md for a comparison with getaddrinfo. + /// + /// This function never blocks. It either immediately fails or immediately + /// returns successfully with a `resolve-address-stream` that can be used + /// to (asynchronously) fetch the results. + /// + /// # Typical errors + /// - `invalid-argument`: `name` is a syntactically invalid domain name or IP address. + /// + /// # References: + /// - + /// - + /// - + /// - + resolve-addresses: func(network: borrow, name: string) -> result; + } - /// Request to flush buffered output, and block until flush completes - /// and stream is ready for writing again. - blocking-flush: func() -> result<_, stream-error>; + interface tcp { + use wasi:io/streams@0.2.0.{input-stream}; + use wasi:io/streams@0.2.0.{output-stream}; + use wasi:io/poll@0.2.0.{pollable}; + use wasi:clocks/monotonic-clock@0.2.0.{duration}; + use network.{network}; + use network.{error-code}; + use network.{ip-socket-address}; + use network.{ip-address-family}; + enum shutdown-type { + /// Similar to `SHUT_RD` in POSIX. + receive, + /// Similar to `SHUT_WR` in POSIX. + send, + /// Similar to `SHUT_RDWR` in POSIX. + both + } - /// Read from one stream and write to another, with blocking. + /// A TCP socket resource. + /// + /// The socket can be in one of the following states: + /// - `unbound` + /// - `bind-in-progress` + /// - `bound` (See note below) + /// - `listen-in-progress` + /// - `listening` + /// - `connect-in-progress` + /// - `connected` + /// - `closed` + /// See + /// for a more information. + /// + /// Note: Except where explicitly mentioned, whenever this documentation uses + /// the term "bound" without backticks it actually means: in the `bound` state *or + /// higher*. + /// (i.e. `bound`, `listen-in-progress`, `listening`, `connect-in-progress` or `connected`) + /// + /// In addition to the general error codes documented on the + /// `network::error-code` type, TCP socket methods may always return + /// `error(invalid-state)` when in the `closed` state. + resource tcp-socket { + + /// Accept a new client socket. /// - /// This is similar to `splice`, except that it blocks until the - /// `output-stream` is ready for writing, and the `input-stream` - /// is ready for reading, before performing the `splice`. - blocking-splice: func(src: borrow, len: u64) -> result; + /// The returned socket is bound and in the `connected` state. The following properties + /// are inherited from the listener socket: + /// - `address-family` + /// - `keep-alive-enabled` + /// - `keep-alive-idle-time` + /// - `keep-alive-interval` + /// - `keep-alive-count` + /// - `hop-limit` + /// - `receive-buffer-size` + /// - `send-buffer-size` + /// + /// On success, this function returns the newly accepted client socket along with + /// a pair of streams that can be used to read & write to the connection. + /// + /// # Typical errors + /// - `invalid-state`: Socket is not in the `listening` state. (EINVAL) + /// - `would-block`: No pending connections at the moment. (EWOULDBLOCK, EAGAIN) + /// - `connection-aborted`: An incoming connection was pending, but was terminated + /// by the client before this listener could accept it. (ECONNABORTED) + /// - `new-socket-limit`: The new socket resource could not be created because of + /// a system limit. (EMFILE, ENFILE) + /// + /// # References + /// - + /// - + /// - + /// - + accept: func() -> result, error-code>; - /// Perform a write of up to 4096 bytes, and then flush the stream. Block - /// until all of these operations are complete, or an error occurs. + /// Whether this is a IPv4 or IPv6 socket. /// - /// This is a convenience wrapper around the use of `check-write`, - /// `subscribe`, `write`, and `flush`, and is implemented with the - /// following pseudo-code: + /// Equivalent to the SO_DOMAIN socket option. + address-family: func() -> ip-address-family; + finish-bind: func() -> result<_, error-code>; + finish-connect: func() -> result, error-code>; + finish-listen: func() -> result<_, error-code>; + + /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. /// - /// ```text - /// let pollable = this.subscribe(); - /// while !contents.is_empty() { - /// // Wait for the stream to become writable - /// pollable.block(); - /// let Ok(n) = this.check-write(); // eliding error handling - /// let len = min(n, contents.len()); - /// let (chunk, rest) = contents.split_at(len); - /// this.write(chunk ); // eliding error handling - /// contents = rest; - /// } - /// this.flush(); - /// // Wait for completion of `flush` - /// pollable.block(); - /// // Check for any errors that arose during `flush` - /// let _ = this.check-write(); // eliding error handling - /// ``` - blocking-write-and-flush: func(contents: list) -> result<_, stream-error>; + /// If the provided value is 0, an `invalid-argument` error is returned. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The TTL value must be 1 or higher. + hop-limit: func() -> result; - /// Perform a write of up to 4096 zeroes, and then flush the stream. - /// Block until all of these operations are complete, or an error - /// occurs. + /// Whether the socket is in the `listening` state. /// - /// This is a convenience wrapper around the use of `check-write`, - /// `subscribe`, `write-zeroes`, and `flush`, and is implemented with - /// the following pseudo-code: + /// Equivalent to the SO_ACCEPTCONN socket option. + is-listening: func() -> bool; + + /// The maximum amount of keepalive packets TCP should send before aborting the connection. /// - /// ```text - /// let pollable = this.subscribe(); - /// while num_zeroes != 0 { - /// // Wait for the stream to become writable - /// pollable.block(); - /// let Ok(n) = this.check-write(); // eliding error handling - /// let len = min(n, num_zeroes); - /// this.write-zeroes(len); // eliding error handling - /// num_zeroes -= len; - /// } - /// this.flush(); - /// // Wait for completion of `flush` - /// pollable.block(); - /// // Check for any errors that arose during `flush` - /// let _ = this.check-write(); // eliding error handling - /// ``` - blocking-write-zeroes-and-flush: func(len: u64) -> result<_, stream-error>; + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// I.e. after setting a value, reading the same setting back may return a different + /// value. + /// + /// Equivalent to the TCP_KEEPCNT socket option. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-count: func() -> result; - /// Check readiness for writing. This function never blocks. + /// Enables or disables keepalive. /// - /// Returns the number of bytes permitted for the next call to `write`, - /// or an error. Calling `write` with more bytes than this function has - /// permitted will trap. + /// The keepalive behavior can be adjusted using: + /// - `keep-alive-idle-time` + /// - `keep-alive-interval` + /// - `keep-alive-count` + /// These properties can be configured while `keep-alive-enabled` is false, but only + /// come into effect when `keep-alive-enabled` is true. /// - /// When this function returns 0 bytes, the `subscribe` pollable will - /// become ready when this function will report at least 1 byte, or an - /// error. - check-write: func() -> result; + /// Equivalent to the SO_KEEPALIVE socket option. + keep-alive-enabled: func() -> result; - /// Request to flush buffered output. This function never blocks. + /// Amount of time the connection has to be idle before TCP starts sending keepalive + /// packets. /// - /// This tells the output-stream that the caller intends any buffered - /// output to be flushed. the output which is expected to be flushed - /// is all that has been passed to `write` prior to this call. + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// I.e. after setting a value, reading the same setting back may return a different + /// value. /// - /// Upon calling this function, the `output-stream` will not accept any - /// writes (`check-write` will return `ok(0)`) until the flush has - /// completed. The `subscribe` pollable will become ready when the - /// flush has completed and the stream can accept more writes. - flush: func() -> result<_, stream-error>; + /// Equivalent to the TCP_KEEPIDLE socket option. (TCP_KEEPALIVE on MacOS) + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-idle-time: func() -> result; - /// Read from one stream and write to another. + /// The time between keepalive packets. /// - /// The behavior of splice is equivelant to: - /// 1. calling `check-write` on the `output-stream` - /// 2. calling `read` on the `input-stream` with the smaller of the - /// `check-write` permitted length and the `len` provided to `splice` - /// 3. calling `write` on the `output-stream` with that read data. + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// I.e. after setting a value, reading the same setting back may return a different + /// value. /// - /// Any error reported by the call to `check-write`, `read`, or - /// `write` ends the splice and reports that error. + /// Equivalent to the TCP_KEEPINTVL socket option. /// - /// This function returns the number of bytes transferred; it may be less - /// than `len`. - splice: func(src: borrow, len: u64) -> result; + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-interval: func() -> result; - /// Create a `pollable` which will resolve once the output-stream - /// is ready for more writing, or an error has occured. When this - /// pollable is ready, `check-write` will return `ok(n)` with n>0, or an - /// error. + /// Get the bound local address. /// - /// If the stream is closed, this pollable is always ready immediately. + /// POSIX mentions: + /// > If the socket has not been bound to a local name, the value + /// > stored in the object pointed to by `address` is unspecified. /// - /// The created `pollable` is a child resource of the `output-stream`. - /// Implementations may trap if the `output-stream` is dropped before - /// all derived `pollable`s created with this function are dropped. - subscribe: func() -> pollable; + /// WASI is stricter and requires `local-address` to return `invalid-state` when the + /// socket hasn't been bound yet. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. + /// + /// # References + /// - + /// - + /// - + /// - + local-address: func() -> result; - /// Perform a write. This function never blocks. + /// The kernel buffer space reserved for sends/receives on this socket. /// - /// When the destination of a `write` is binary data, the bytes from - /// `contents` are written verbatim. When the destination of a `write` is - /// known to the implementation to be text, the bytes of `contents` are - /// transcoded from UTF-8 into the encoding of the destination and then - /// written. + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// I.e. after setting a value, reading the same setting back may return a different + /// value. /// - /// Precondition: check-write gave permit of Ok(n) and contents has a - /// length of less than or equal to n. Otherwise, this function will trap. + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. /// - /// returns Err(closed) without writing if the stream has closed since - /// the last call to check-write provided a permit. - write: func(contents: list) -> result<_, stream-error>; + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + receive-buffer-size: func() -> result; - /// Write zeroes to a stream. + /// Get the remote address. /// - /// This should be used precisely like `write` with the exact same - /// preconditions (must use check-write first), but instead of - /// passing a list of bytes, you simply pass the number of zero-bytes - /// that should be written. - write-zeroes: func(len: u64) -> result<_, stream-error>; - } - } - - world imports { - import error; - import poll; - import streams; - } -} - -package wasi:random@0.2.0 { - /// The insecure-seed interface for seeding hash-map DoS resistance. - /// - /// It is intended to be portable at least between Unix-family platforms and - /// Windows. - interface insecure-seed { - /// Return a 128-bit value that may contain a pseudo-random value. - /// - /// The returned value is not required to be computed from a CSPRNG, and may - /// even be entirely deterministic. Host implementations are encouraged to - /// provide pseudo-random values to any program exposed to - /// attacker-controlled content, to enable DoS protection built into many - /// languages' hash-map implementations. - /// - /// This function is intended to only be called once, by a source language - /// to initialize Denial Of Service (DoS) protection in its hash-map - /// implementation. - /// - /// # Expected future evolution - /// - /// This will likely be changed to a value import, to prevent it from being - /// called multiple times and potentially used for purposes other than DoS - /// protection. - insecure-seed: func() -> tuple; - } - - /// The insecure interface for insecure pseudo-random numbers. - /// - /// It is intended to be portable at least between Unix-family platforms and - /// Windows. - interface insecure { - /// Return `len` insecure pseudo-random bytes. - /// - /// This function is not cryptographically secure. Do not use it for - /// anything related to security. - /// - /// There are no requirements on the values of the returned bytes, however - /// implementations are encouraged to return evenly distributed values with - /// a long period. - get-insecure-random-bytes: func(len: u64) -> list; - - /// Return an insecure pseudo-random `u64` value. - /// - /// This function returns the same type of pseudo-random data as - /// `get-insecure-random-bytes`, represented as a `u64`. - get-insecure-random-u64: func() -> u64; - } - - /// WASI Random is a random data API. - /// - /// It is intended to be portable at least between Unix-family platforms and - /// Windows. - interface random { - /// Return `len` cryptographically-secure random or pseudo-random bytes. - /// - /// This function must produce data at least as cryptographically secure and - /// fast as an adequately seeded cryptographically-secure pseudo-random - /// number generator (CSPRNG). It must not block, from the perspective of - /// the calling program, under any circumstances, including on the first - /// request and on requests for numbers of bytes. The returned data must - /// always be unpredictable. - /// - /// This function must always return fresh data. Deterministic environments - /// must omit this function, rather than implementing it with deterministic - /// data. - get-random-bytes: func(len: u64) -> list; - - /// Return a cryptographically-secure random or pseudo-random `u64` value. - /// - /// This function returns the same type of data as `get-random-bytes`, - /// represented as a `u64`. - get-random-u64: func() -> u64; - } - - world imports { - import random; - import insecure; - import insecure-seed; - } -} + /// # Typical errors + /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + remote-address: func() -> result; + send-buffer-size: func() -> result; + set-hop-limit: func(value: u8) -> result<_, error-code>; + set-keep-alive-count: func(value: u32) -> result<_, error-code>; + set-keep-alive-enabled: func(value: bool) -> result<_, error-code>; + set-keep-alive-idle-time: func(value: duration) -> result<_, error-code>; + set-keep-alive-interval: func(value: duration) -> result<_, error-code>; -package wasi:sockets@0.2.0 { - interface network { - /// An opaque resource that represents access to (a subset of) the network. - /// This enables context-based security for networking. - /// There is no need for this to map 1:1 to a physical network interface. - resource network; + /// Hints the desired listen queue size. Implementations are free to ignore this. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// + /// # Typical errors + /// - `not-supported`: (set) The platform does not support changing the backlog + /// size after the initial listen. + /// - `invalid-argument`: (set) The provided value was 0. + /// - `invalid-state`: (set) The socket is in the `connect-in-progress` or + /// `connected` state. + set-listen-backlog-size: func(value: u64) -> result<_, error-code>; + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + set-send-buffer-size: func(value: u64) -> result<_, error-code>; - /// Error codes. - /// - /// In theory, every API can return any error code. - /// In practice, API's typically only return the errors documented per API - /// combined with a couple of errors that are always possible: - /// - `unknown` - /// - `access-denied` - /// - `not-supported` - /// - `out-of-memory` - /// - `concurrency-conflict` - /// - /// See each individual API for what the POSIX equivalents are. They sometimes differ - /// per API. - enum error-code { - /// Unknown error - unknown, - /// Access denied. + /// Initiate a graceful shutdown. /// - /// POSIX equivalent: EACCES, EPERM - access-denied, - /// The operation is not supported. + /// - `receive`: The socket is not expecting to receive any data from + /// the peer. The `input-stream` associated with this socket will be + /// closed. Any data still in the receive queue at time of calling + /// this method will be discarded. + /// - `send`: The socket has no more data to send to the peer. The `output-stream` + /// associated with this socket will be closed and a FIN packet will be sent. + /// - `both`: Same effect as `receive` & `send` combined. + /// + /// This function is idempotent. Shutting a down a direction more than once + /// has no effect and returns `ok`. + /// + /// The shutdown function does not close (drop) the socket. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) /// - /// POSIX equivalent: EOPNOTSUPP - not-supported, - /// One of the arguments is invalid. + /// # References + /// - + /// - + /// - + /// - + shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code>; + + /// Bind the socket to a specific network on the provided IP address and port. /// - /// POSIX equivalent: EINVAL - invalid-argument, - /// Not enough memory to complete the operation. + /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the + /// implementation to decide which + /// network interface(s) to bind to. + /// If the TCP/UDP port is zero, the socket will be bound to a random free port. /// - /// POSIX equivalent: ENOMEM, ENOBUFS, EAI_MEMORY - out-of-memory, - /// The operation timed out before it could finish completely. - timeout, - /// This operation is incompatible with another asynchronous operation that is already - /// in progress. + /// Bind can be attempted multiple times on the same socket, even with + /// different arguments on each iteration. But never concurrently and + /// only as long as the previous bind failed. Once a bind succeeds, the + /// binding can't be changed anymore. /// - /// POSIX equivalent: EALREADY - concurrency-conflict, - /// Trying to finish an asynchronous operation that: - /// - has not been started yet, or: - /// - was already finished by a previous `finish-*` call. + /// # Typical errors + /// - `invalid-argument`: The `local-address` has the wrong address family. + /// (EAFNOSUPPORT, EFAULT on Windows) + /// - `invalid-argument`: `local-address` is not a unicast address. (EINVAL) + /// - `invalid-argument`: `local-address` is an IPv4-mapped IPv6 address. + /// (EINVAL) + /// - `invalid-state`: The socket is already bound. (EINVAL) + /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS + /// on Windows) + /// - `address-in-use`: Address is already in use. (EADDRINUSE) + /// - `address-not-bindable`: `local-address` is not an address that the `network` + /// can bind to. (EADDRNOTAVAIL) + /// - `not-in-progress`: A `bind` operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. + /// (EWOULDBLOCK, EAGAIN) /// - /// Note: this is scheduled to be removed when `future`s are natively supported. - not-in-progress, - /// The operation has been aborted because it could not be completed immediately. + /// # Implementors note + /// When binding to a non-zero port, this bind operation shouldn't be affected by + /// the TIME_WAIT + /// state of a recently closed socket on the same local address. In practice this + /// means that the SO_REUSEADDR + /// socket option should be set implicitly on all platforms, except on Windows where + /// this is the default behavior + /// and SO_REUSEADDR performs something different entirely. /// - /// Note: this is scheduled to be removed when `future`s are natively supported. - would-block, - /// The operation is not valid in the socket's current state. - invalid-state, - /// A new socket resource could not be created because of a system limit. - new-socket-limit, - /// A bind operation failed because the provided address is not an address that the - /// `network` can bind to. - address-not-bindable, - /// A bind operation failed because the provided address is already in use or because - /// there are no ephemeral ports available. - address-in-use, - /// The remote address is not reachable - remote-unreachable, - /// The TCP connection was forcefully rejected - connection-refused, - /// The TCP connection was reset. - connection-reset, - /// A TCP connection was aborted. - connection-aborted, - /// The size of a datagram sent to a UDP socket exceeded the maximum - /// supported size. - datagram-too-large, - /// Name does not exist or has no suitable associated IP addresses. - name-unresolvable, - /// A temporary failure in name resolution occurred. - temporary-resolver-failure, - /// A permanent failure in name resolution occurred. - permanent-resolver-failure - } - enum ip-address-family { - /// Similar to `AF_INET` in POSIX. - ipv4, - /// Similar to `AF_INET6` in POSIX. - ipv6 - } - type ipv4-address = tuple; - type ipv6-address = tuple; - variant ip-address { - ipv4(ipv4-address), - ipv6(ipv6-address), - } - record ipv4-socket-address { - /// sin_port - port: u16, - /// sin_addr - address: ipv4-address, - } - record ipv6-socket-address { - /// sin6_port - port: u16, - /// sin6_flowinfo - flow-info: u32, - /// sin6_addr - address: ipv6-address, - /// sin6_scope_id - scope-id: u32, - } - variant ip-socket-address { - ipv4(ipv4-socket-address), - ipv6(ipv6-socket-address), - } - } - - /// This interface provides a value-export of the default network handle.. - interface instance-network { - use network.{network}; - - /// Get a handle to the default network. - instance-network: func() -> network; - } + /// Unlike in POSIX, in WASI the bind operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `bind` as part of either `start-bind` or `finish-bind`. + /// + /// # References + /// - + /// - + /// - + /// - + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; - interface ip-name-lookup { - use wasi:io/poll@0.2.0.{pollable}; - use network.{network}; - use network.{error-code}; - use network.{ip-address}; - resource resolve-address-stream { + /// Connect to a remote endpoint. + /// + /// On success: + /// - the socket is transitioned into the `connection` state. + /// - a pair of streams is returned that can be used to read & write to the connection + /// + /// After a failed connection attempt, the socket will be in the `closed` + /// state and the only valid action left is to `drop` the socket. A single + /// socket can not be used to connect more than once. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. + /// (EAFNOSUPPORT) + /// - `invalid-argument`: `remote-address` is not a unicast address. (EINVAL, + /// ENETUNREACH on Linux, EAFNOSUPPORT on MacOS) + /// - `invalid-argument`: `remote-address` is an IPv4-mapped IPv6 address. + /// (EINVAL, EADDRNOTAVAIL on Illumos) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY + /// (`0.0.0.0` / `::`). (EADDRNOTAVAIL on Windows) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EADDRNOTAVAIL + /// on Windows) + /// - `invalid-argument`: The socket is already attached to a different network. + /// The `network` passed to `connect` must be identical to the one passed to `bind`. + /// - `invalid-state`: The socket is already in the `connected` state. + /// (EISCONN) + /// - `invalid-state`: The socket is already in the `listening` state. + /// (EOPNOTSUPP, EINVAL on Windows) + /// - `timeout`: Connection timed out. (ETIMEDOUT) + /// - `connection-refused`: The connection was forcefully rejected. (ECONNREFUSED) + /// - `connection-reset`: The connection was reset. (ECONNRESET) + /// - `connection-aborted`: The connection was aborted. (ECONNABORTED) + /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, + /// EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `address-in-use`: Tried to perform an implicit bind, but there were + /// no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// - `not-in-progress`: A connect operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. + /// (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// The POSIX equivalent of `start-connect` is the regular `connect` syscall. + /// Because all WASI sockets are non-blocking this is expected to return + /// EINPROGRESS, which should be translated to `ok()` in WASI. + /// + /// The POSIX equivalent of `finish-connect` is a `poll` for event `POLLOUT` + /// with a timeout of 0 on the socket descriptor. Followed by a check for + /// the `SO_ERROR` socket option, in case the poll signaled readiness. + /// + /// # References + /// - + /// - + /// - + /// - + start-connect: func(network: borrow, remote-address: ip-socket-address) -> result<_, error-code>; - /// Returns the next address from the resolver. + /// Start listening for new connections. /// - /// This function should be called multiple times. On each call, it will - /// return the next address in connection order preference. If all - /// addresses have been exhausted, this function returns `none`. + /// Transitions the socket into the `listening` state. /// - /// This function never returns IPv4-mapped IPv6 addresses. + /// Unlike POSIX, the socket must already be explicitly bound. /// /// # Typical errors - /// - `name-unresolvable`: Name does not exist or has no suitable associated - /// IP addresses. (EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY) - /// - `temporary-resolver-failure`: A temporary failure in name resolution occurred. - /// (EAI_AGAIN) - /// - `permanent-resolver-failure`: A permanent failure in name resolution occurred. - /// (EAI_FAIL) - /// - `would-block`: A result is not available yet. (EWOULDBLOCK, EAGAIN) - resolve-next-address: func() -> result, error-code>; + /// - `invalid-state`: The socket is not bound to any local address. (EDESTADDRREQ) + /// - `invalid-state`: The socket is already in the `connected` state. + /// (EISCONN, EINVAL on BSD) + /// - `invalid-state`: The socket is already in the `listening` state. + /// - `address-in-use`: Tried to perform an implicit bind, but there were + /// no ephemeral ports available. (EADDRINUSE) + /// - `not-in-progress`: A listen operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. + /// (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// Unlike in POSIX, in WASI the listen operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `listen` as part of either `start-listen` or `finish-listen`. + /// + /// # References + /// - + /// - + /// - + /// - + start-listen: func() -> result<_, error-code>; - /// Create a `pollable` which will resolve once the stream is ready for I/O. + /// Create a `pollable` which can be used to poll for, or block on, + /// completion of any of the asynchronous operations of this socket. + /// + /// When `finish-bind`, `finish-listen`, `finish-connect` or `accept` + /// return `error(would-block)`, this pollable can be used to wait for + /// their success or failure, after which the method can be retried. + /// + /// The pollable is not limited to the async operation that happens to be + /// in progress at the time of calling `subscribe` (if any). Theoretically, + /// `subscribe` only has to be called once per socket and can then be + /// (re)used for the remainder of the socket's lifetime. + /// + /// See + /// for a more information. /// /// Note: this function is here for WASI Preview2 only. /// It's planned to be removed when `future` is natively supported in Preview3. subscribe: func() -> pollable; } + } - /// Resolve an internet host name to a list of IP addresses. + interface tcp-create-socket { + use network.{network}; + use network.{error-code}; + use network.{ip-address-family}; + use tcp.{tcp-socket}; + + /// Create a new TCP socket. /// - /// Unicode domain names are automatically converted to ASCII using IDNA encoding. - /// If the input is an IP address string, the address is parsed and returned - /// as-is without making any external requests. + /// Similar to `socket(AF_INET or AF_INET6, SOCK_STREAM, IPPROTO_TCP)` in POSIX. + /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. /// - /// See the wasi-socket proposal README.md for a comparison with getaddrinfo. + /// This function does not require a network capability handle. This is considered + /// to be safe because + /// at time of creation, the socket is not bound to any `network` yet. Up to the moment + /// `bind`/`connect` + /// is called, the socket is effectively an in-memory configuration object, unable + /// to communicate with the outside world. /// - /// This function never blocks. It either immediately fails or immediately - /// returns successfully with a `resolve-address-stream` that can be used - /// to (asynchronously) fetch the results. + /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous + /// operations. /// /// # Typical errors - /// - `invalid-argument`: `name` is a syntactically invalid domain name or IP address. + /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) + /// - `new-socket-limit`: The new socket resource could not be created because of + /// a system limit. (EMFILE, ENFILE) /// - /// # References: - /// - - /// - - /// - - /// - - resolve-addresses: func(network: borrow, name: string) -> result; + /// # References + /// - + /// - + /// - + /// - + create-tcp-socket: func(address-family: ip-address-family) -> result; } - interface tcp { - use wasi:io/streams@0.2.0.{input-stream}; - use wasi:io/streams@0.2.0.{output-stream}; + interface udp { use wasi:io/poll@0.2.0.{pollable}; - use wasi:clocks/monotonic-clock@0.2.0.{duration}; use network.{network}; use network.{error-code}; use network.{ip-socket-address}; use network.{ip-address-family}; - enum shutdown-type { - /// Similar to `SHUT_RD` in POSIX. - receive, - /// Similar to `SHUT_WR` in POSIX. - send, - /// Similar to `SHUT_RDWR` in POSIX. - both - } - - /// A TCP socket resource. - /// - /// The socket can be in one of the following states: - /// - `unbound` - /// - `bind-in-progress` - /// - `bound` (See note below) - /// - `listen-in-progress` - /// - `listening` - /// - `connect-in-progress` - /// - `connected` - /// - `closed` - /// See - /// for a more information. - /// - /// Note: Except where explicitly mentioned, whenever this documentation uses - /// the term "bound" without backticks it actually means: in the `bound` state *or - /// higher*. - /// (i.e. `bound`, `listen-in-progress`, `listening`, `connect-in-progress` or `connected`) - /// - /// In addition to the general error codes documented on the - /// `network::error-code` type, TCP socket methods may always return - /// `error(invalid-state)` when in the `closed` state. - resource tcp-socket { - /// Accept a new client socket. + /// A received datagram. + record incoming-datagram { + /// The payload. /// - /// The returned socket is bound and in the `connected` state. The following properties - /// are inherited from the listener socket: - /// - `address-family` - /// - `keep-alive-enabled` - /// - `keep-alive-idle-time` - /// - `keep-alive-interval` - /// - `keep-alive-count` - /// - `hop-limit` - /// - `receive-buffer-size` - /// - `send-buffer-size` + /// Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes. + data: list, + /// The source address. /// - /// On success, this function returns the newly accepted client socket along with - /// a pair of streams that can be used to read & write to the connection. + /// This field is guaranteed to match the remote address the stream was initialized + /// with, if any. /// - /// # Typical errors - /// - `invalid-state`: Socket is not in the `listening` state. (EINVAL) - /// - `would-block`: No pending connections at the moment. (EWOULDBLOCK, EAGAIN) - /// - `connection-aborted`: An incoming connection was pending, but was terminated - /// by the client before this listener could accept it. (ECONNABORTED) - /// - `new-socket-limit`: The new socket resource could not be created because of - /// a system limit. (EMFILE, ENFILE) + /// Equivalent to the `src_addr` out parameter of `recvfrom`. + remote-address: ip-socket-address, + } + + /// A datagram to be sent out. + record outgoing-datagram { + /// The payload. + data: list, + /// The destination address. /// - /// # References - /// - - /// - - /// - - /// - - accept: func() -> result, error-code>; + /// The requirements on this field depend on how the stream was initialized: + /// - with a remote address: this field must be None or match the stream's remote + /// address exactly. + /// - without a remote address: this field is required. + /// + /// If this value is None, the send operation is equivalent to `send` in POSIX. Otherwise + /// it is equivalent to `sendto`. + remote-address: option, + } + + /// A UDP socket handle. + resource udp-socket { /// Whether this is a IPv4 or IPv6 socket. /// /// Equivalent to the SO_DOMAIN socket option. address-family: func() -> ip-address-family; finish-bind: func() -> result<_, error-code>; - finish-connect: func() -> result, error-code>; - finish-listen: func() -> result<_, error-code>; - - /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The TTL value must be 1 or higher. - hop-limit: func() -> result; - - /// Whether the socket is in the `listening` state. - /// - /// Equivalent to the SO_ACCEPTCONN socket option. - is-listening: func() -> bool; - - /// The maximum amount of keepalive packets TCP should send before aborting the connection. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or - /// rounded. - /// I.e. after setting a value, reading the same setting back may return a different - /// value. - /// - /// Equivalent to the TCP_KEEPCNT socket option. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The provided value was 0. - keep-alive-count: func() -> result; - - /// Enables or disables keepalive. - /// - /// The keepalive behavior can be adjusted using: - /// - `keep-alive-idle-time` - /// - `keep-alive-interval` - /// - `keep-alive-count` - /// These properties can be configured while `keep-alive-enabled` is false, but only - /// come into effect when `keep-alive-enabled` is true. - /// - /// Equivalent to the SO_KEEPALIVE socket option. - keep-alive-enabled: func() -> result; - - /// Amount of time the connection has to be idle before TCP starts sending keepalive - /// packets. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or - /// rounded. - /// I.e. after setting a value, reading the same setting back may return a different - /// value. - /// - /// Equivalent to the TCP_KEEPIDLE socket option. (TCP_KEEPALIVE on MacOS) - /// - /// # Typical errors - /// - `invalid-argument`: (set) The provided value was 0. - keep-alive-idle-time: func() -> result; - - /// The time between keepalive packets. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or - /// rounded. - /// I.e. after setting a value, reading the same setting back may return a different - /// value. - /// - /// Equivalent to the TCP_KEEPINTVL socket option. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The provided value was 0. - keep-alive-interval: func() -> result; - /// Get the bound local address. + /// Get the current bound address. /// /// POSIX mentions: /// > If the socket has not been bound to a local name, the value @@ -1550,101 +1395,50 @@ package wasi:sockets@0.2.0 { /// # References /// - /// - - /// - - /// - - local-address: func() -> result; - - /// The kernel buffer space reserved for sends/receives on this socket. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or - /// rounded. - /// I.e. after setting a value, reading the same setting back may return a different - /// value. - /// - /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The provided value was 0. - receive-buffer-size: func() -> result; - - /// Get the remote address. - /// - /// # Typical errors - /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) - /// - /// # References - /// - - /// - - /// - - /// - - remote-address: func() -> result; - send-buffer-size: func() -> result; - set-hop-limit: func(value: u8) -> result<_, error-code>; - set-keep-alive-count: func(value: u32) -> result<_, error-code>; - set-keep-alive-enabled: func(value: bool) -> result<_, error-code>; - set-keep-alive-idle-time: func(value: duration) -> result<_, error-code>; - set-keep-alive-interval: func(value: duration) -> result<_, error-code>; - - /// Hints the desired listen queue size. Implementations are free to ignore this. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or - /// rounded. - /// - /// # Typical errors - /// - `not-supported`: (set) The platform does not support changing the backlog - /// size after the initial listen. - /// - `invalid-argument`: (set) The provided value was 0. - /// - `invalid-state`: (set) The socket is in the `connect-in-progress` or - /// `connected` state. - set-listen-backlog-size: func(value: u64) -> result<_, error-code>; - set-receive-buffer-size: func(value: u64) -> result<_, error-code>; - set-send-buffer-size: func(value: u64) -> result<_, error-code>; + /// - + /// - + local-address: func() -> result; - /// Initiate a graceful shutdown. + /// The kernel buffer space reserved for sends/receives on this socket. /// - /// - `receive`: The socket is not expecting to receive any data from - /// the peer. The `input-stream` associated with this socket will be - /// closed. Any data still in the receive queue at time of calling - /// this method will be discarded. - /// - `send`: The socket has no more data to send to the peer. The `output-stream` - /// associated with this socket will be closed and a FIN packet will be sent. - /// - `both`: Same effect as `receive` & `send` combined. + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// I.e. after setting a value, reading the same setting back may return a different + /// value. /// - /// This function is idempotent. Shutting a down a direction more than once - /// has no effect and returns `ok`. + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. /// - /// The shutdown function does not close (drop) the socket. + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + receive-buffer-size: func() -> result; + + /// Get the address the socket is currently streaming to. /// /// # Typical errors - /// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) + /// - `invalid-state`: The socket is not streaming to a specific remote address. (ENOTCONN) /// /// # References - /// - - /// - - /// - - /// - - shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code>; + /// - + /// - + /// - + /// - + remote-address: func() -> result; + send-buffer-size: func() -> result; + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; /// Bind the socket to a specific network on the provided IP address and port. /// /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the /// implementation to decide which /// network interface(s) to bind to. - /// If the TCP/UDP port is zero, the socket will be bound to a random free port. - /// - /// Bind can be attempted multiple times on the same socket, even with - /// different arguments on each iteration. But never concurrently and - /// only as long as the previous bind failed. Once a bind succeeds, the - /// binding can't be changed anymore. + /// If the port is zero, the socket will be bound to a random free port. /// /// # Typical errors /// - `invalid-argument`: The `local-address` has the wrong address family. /// (EAFNOSUPPORT, EFAULT on Windows) - /// - `invalid-argument`: `local-address` is not a unicast address. (EINVAL) - /// - `invalid-argument`: `local-address` is an IPv4-mapped IPv6 address. - /// (EINVAL) /// - `invalid-state`: The socket is already bound. (EINVAL) /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS /// on Windows) @@ -1656,14 +1450,6 @@ package wasi:sockets@0.2.0 { /// (EWOULDBLOCK, EAGAIN) /// /// # Implementors note - /// When binding to a non-zero port, this bind operation shouldn't be affected by - /// the TIME_WAIT - /// state of a recently closed socket on the same local address. In practice this - /// means that the SO_REUSEADDR - /// socket option should be set implicitly on all platforms, except on Windows where - /// this is the default behavior - /// and SO_REUSEADDR performs something different entirely. - /// /// Unlike in POSIX, in WASI the bind operation is async. This enables /// interactive WASI hosts to inject permission prompts. Runtimes that /// don't want to make use of this ability can simply call the native @@ -1676,105 +1462,174 @@ package wasi:sockets@0.2.0 { /// - start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; - /// Connect to a remote endpoint. + /// Set up inbound & outbound communication channels, optionally to a specific peer. /// - /// On success: - /// - the socket is transitioned into the `connection` state. - /// - a pair of streams is returned that can be used to read & write to the connection + /// This function only changes the local socket configuration and does not generate + /// any network traffic. + /// On success, the `remote-address` of the socket is updated. The `local-address` + /// may be updated as well, + /// based on the best network path to `remote-address`. /// - /// After a failed connection attempt, the socket will be in the `closed` - /// state and the only valid action left is to `drop` the socket. A single - /// socket can not be used to connect more than once. + /// When a `remote-address` is provided, the returned streams are limited to communicating + /// with that specific peer: + /// - `send` can only be used to send to this destination. + /// - `receive` will only return datagrams sent from the provided `remote-address`. + /// + /// This method may be called multiple times on the same socket to change its association, + /// but + /// only the most recently returned pair of streams will be operational. Implementations + /// may trap if + /// the streams returned by a previous invocation haven't been dropped yet before + /// calling `stream` again. + /// + /// The POSIX equivalent in pseudo-code is: + /// ```text + /// if (was previously connected) { + /// connect(s, AF_UNSPEC) + /// } + /// if (remote_address is Some) { + /// connect(s, remote_address) + /// } + /// ``` + /// + /// Unlike in POSIX, the socket must already be explicitly bound. /// /// # Typical errors /// - `invalid-argument`: The `remote-address` has the wrong address family. /// (EAFNOSUPPORT) - /// - `invalid-argument`: `remote-address` is not a unicast address. (EINVAL, - /// ENETUNREACH on Linux, EAFNOSUPPORT on MacOS) - /// - `invalid-argument`: `remote-address` is an IPv4-mapped IPv6 address. - /// (EINVAL, EADDRNOTAVAIL on Illumos) /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY - /// (`0.0.0.0` / `::`). (EADDRNOTAVAIL on Windows) - /// - `invalid-argument`: The port in `remote-address` is set to 0. (EADDRNOTAVAIL - /// on Windows) - /// - `invalid-argument`: The socket is already attached to a different network. - /// The `network` passed to `connect` must be identical to the one passed to `bind`. - /// - `invalid-state`: The socket is already in the `connected` state. - /// (EISCONN) - /// - `invalid-state`: The socket is already in the `listening` state. - /// (EOPNOTSUPP, EINVAL on Windows) - /// - `timeout`: Connection timed out. (ETIMEDOUT) - /// - `connection-refused`: The connection was forcefully rejected. (ECONNREFUSED) - /// - `connection-reset`: The connection was reset. (ECONNRESET) - /// - `connection-aborted`: The connection was aborted. (ECONNABORTED) - /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, - /// EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, + /// EADDRNOTAVAIL) + /// - `invalid-state`: The socket is not bound. /// - `address-in-use`: Tried to perform an implicit bind, but there were /// no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) - /// - `not-in-progress`: A connect operation is not in progress. - /// - `would-block`: Can't finish the operation, it is still in progress. - /// (EWOULDBLOCK, EAGAIN) - /// - /// # Implementors note - /// The POSIX equivalent of `start-connect` is the regular `connect` syscall. - /// Because all WASI sockets are non-blocking this is expected to return - /// EINPROGRESS, which should be translated to `ok()` in WASI. - /// - /// The POSIX equivalent of `finish-connect` is a `poll` for event `POLLOUT` - /// with a timeout of 0 on the socket descriptor. Followed by a check for - /// the `SO_ERROR` socket option, in case the poll signaled readiness. + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, + /// ENETRESET, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) /// /// # References /// - /// - /// - /// - - start-connect: func(network: borrow, remote-address: ip-socket-address) -> result<_, error-code>; + %stream: func(remote-address: option) -> result, error-code>; - /// Start listening for new connections. + /// Create a `pollable` which will resolve once the socket is ready for I/O. /// - /// Transitions the socket into the `listening` state. + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + + /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. /// - /// Unlike POSIX, the socket must already be explicitly bound. + /// If the provided value is 0, an `invalid-argument` error is returned. /// /// # Typical errors - /// - `invalid-state`: The socket is not bound to any local address. (EDESTADDRREQ) - /// - `invalid-state`: The socket is already in the `connected` state. - /// (EISCONN, EINVAL on BSD) - /// - `invalid-state`: The socket is already in the `listening` state. - /// - `address-in-use`: Tried to perform an implicit bind, but there were - /// no ephemeral ports available. (EADDRINUSE) - /// - `not-in-progress`: A listen operation is not in progress. - /// - `would-block`: Can't finish the operation, it is still in progress. - /// (EWOULDBLOCK, EAGAIN) + /// - `invalid-argument`: (set) The TTL value must be 1 or higher. + unicast-hop-limit: func() -> result; + } + resource incoming-datagram-stream { + + /// Receive messages on the socket. /// - /// # Implementors note - /// Unlike in POSIX, in WASI the listen operation is async. This enables - /// interactive WASI hosts to inject permission prompts. Runtimes that - /// don't want to make use of this ability can simply call the native - /// `listen` as part of either `start-listen` or `finish-listen`. + /// This function attempts to receive up to `max-results` datagrams on the socket + /// without blocking. + /// The returned list may contain fewer elements than requested, but never more. + /// + /// This function returns successfully with an empty list when either: + /// - `max-results` is 0, or: + /// - `max-results` is greater than 0, but no results are immediately available. + /// This function never returns `error(would-block)`. + /// + /// # Typical errors + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET + /// on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) /// /// # References - /// - - /// - - /// - - /// - - start-listen: func() -> result<_, error-code>; + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + receive: func(max-results: u64) -> result, error-code>; - /// Create a `pollable` which can be used to poll for, or block on, - /// completion of any of the asynchronous operations of this socket. + /// Create a `pollable` which will resolve once the stream is ready to receive again. /// - /// When `finish-bind`, `finish-listen`, `finish-connect` or `accept` - /// return `error(would-block)`, this pollable can be used to wait for - /// their success or failure, after which the method can be retried. + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } + resource outgoing-datagram-stream { + + /// Check readiness for sending. This function never blocks. /// - /// The pollable is not limited to the async operation that happens to be - /// in progress at the time of calling `subscribe` (if any). Theoretically, - /// `subscribe` only has to be called once per socket and can then be - /// (re)used for the remainder of the socket's lifetime. + /// Returns the number of datagrams permitted for the next call to `send`, + /// or an error. Calling `send` with more datagrams than this function has + /// permitted will trap. + /// + /// When this function returns ok(0), the `subscribe` pollable will + /// become ready when this function will report at least ok(1), or an + /// error. + /// + /// Never returns `would-block`. + check-send: func() -> result; + + /// Send messages on the socket. + /// + /// This function attempts to send all provided `datagrams` on the socket without + /// blocking and + /// returns how many messages were actually sent (or queued for sending). This function + /// never + /// returns `error(would-block)`. If none of the datagrams were able to be sent, `ok(0)` + /// is returned. + /// + /// This function semantically behaves the same as iterating the `datagrams` list + /// and sequentially + /// sending each individual datagram until either the end of the list has been reached + /// or the first error occurred. + /// If at least one datagram has been sent successfully, this function never returns + /// an error. + /// + /// If the input list is empty, the function returns `ok(0)`. + /// + /// Each call to `send` must be permitted by a preceding `check-send`. Implementations + /// must trap if + /// either `check-send` was not called or `datagrams` contains more items than `check-send` + /// permitted. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. + /// (EAFNOSUPPORT) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY + /// (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, + /// EADDRNOTAVAIL) + /// - `invalid-argument`: The socket is in "connected" mode and `remote-address` + /// is `some` value that does not match the address passed to `stream`. (EISCONN) + /// - `invalid-argument`: The socket is not "connected" and no value for `remote-address` + /// was provided. (EDESTADDRREQ) + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, + /// ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// - `datagram-too-large`: The datagram is too large. (EMSGSIZE) /// - /// See - /// for a more information. + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + send: func(datagrams: list) -> result; + + /// Create a `pollable` which will resolve once the stream is ready to send again. /// /// Note: this function is here for WASI Preview2 only. /// It's planned to be removed when `future` is natively supported in Preview3. @@ -1782,23 +1637,23 @@ package wasi:sockets@0.2.0 { } } - interface tcp-create-socket { + interface udp-create-socket { use network.{network}; use network.{error-code}; use network.{ip-address-family}; - use tcp.{tcp-socket}; + use udp.{udp-socket}; - /// Create a new TCP socket. + /// Create a new UDP socket. /// - /// Similar to `socket(AF_INET or AF_INET6, SOCK_STREAM, IPPROTO_TCP)` in POSIX. + /// Similar to `socket(AF_INET or AF_INET6, SOCK_DGRAM, IPPROTO_UDP)` in POSIX. /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. /// /// This function does not require a network capability handle. This is considered /// to be safe because /// at time of creation, the socket is not bound to any `network` yet. Up to the moment - /// `bind`/`connect` - /// is called, the socket is effectively an in-memory configuration object, unable - /// to communicate with the outside world. + /// `bind` is called, + /// the socket is effectively an in-memory configuration object, unable to communicate + /// with the outside world. /// /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous /// operations. @@ -1808,363 +1663,508 @@ package wasi:sockets@0.2.0 { /// - `new-socket-limit`: The new socket resource could not be created because of /// a system limit. (EMFILE, ENFILE) /// - /// # References + /// # References: /// - /// - /// - /// - - create-tcp-socket: func(address-family: ip-address-family) -> result; + create-udp-socket: func(address-family: ip-address-family) -> result; } - interface udp { + world imports { + import network; + import instance-network; + import wasi:io/poll@0.2.0; + import udp; + import udp-create-socket; + import wasi:io/error@0.2.0; + import wasi:io/streams@0.2.0; + import wasi:clocks/monotonic-clock@0.2.0; + import tcp; + import tcp-create-socket; + import ip-name-lookup; + } +} + +package wasi:clocks@0.2.0 { + /// WASI Monotonic Clock is a clock API intended to let users measure elapsed + /// time. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + /// + /// A monotonic clock is a clock which has an unspecified initial value, and + /// successive reads of the clock will produce non-decreasing values. + /// + /// It is intended for measuring elapsed time. + interface monotonic-clock { use wasi:io/poll@0.2.0.{pollable}; - use network.{network}; - use network.{error-code}; - use network.{ip-socket-address}; - use network.{ip-address-family}; - /// A received datagram. - record incoming-datagram { - /// The payload. - /// - /// Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes. - data: list, - /// The source address. - /// - /// This field is guaranteed to match the remote address the stream was initialized - /// with, if any. - /// - /// Equivalent to the `src_addr` out parameter of `recvfrom`. - remote-address: ip-socket-address, - } + /// An instant in time, in nanoseconds. An instant is relative to an + /// unspecified initial value, and can only be compared to instances from + /// the same monotonic-clock. + type instant = u64; - /// A datagram to be sent out. - record outgoing-datagram { - /// The payload. - data: list, - /// The destination address. - /// - /// The requirements on this field depend on how the stream was initialized: - /// - with a remote address: this field must be None or match the stream's remote - /// address exactly. - /// - without a remote address: this field is required. - /// - /// If this value is None, the send operation is equivalent to `send` in POSIX. Otherwise - /// it is equivalent to `sendto`. - remote-address: option, - } + /// A duration of time, in nanoseconds. + type duration = u64; - /// A UDP socket handle. - resource udp-socket { + /// Read the current value of the clock. + /// + /// The clock is monotonic, therefore calling this function repeatedly will + /// produce a sequence of non-decreasing values. + now: func() -> instant; - /// Whether this is a IPv4 or IPv6 socket. - /// - /// Equivalent to the SO_DOMAIN socket option. - address-family: func() -> ip-address-family; - finish-bind: func() -> result<_, error-code>; + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + resolution: func() -> duration; - /// Get the current bound address. - /// - /// POSIX mentions: - /// > If the socket has not been bound to a local name, the value - /// > stored in the object pointed to by `address` is unspecified. - /// - /// WASI is stricter and requires `local-address` to return `invalid-state` when the - /// socket hasn't been bound yet. - /// - /// # Typical errors - /// - `invalid-state`: The socket is not bound to any local address. - /// - /// # References - /// - - /// - - /// - - /// - - local-address: func() -> result; + /// Create a `pollable` which will resolve once the specified instant + /// occured. + subscribe-instant: func(when: instant) -> pollable; - /// The kernel buffer space reserved for sends/receives on this socket. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or - /// rounded. - /// I.e. after setting a value, reading the same setting back may return a different - /// value. - /// - /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The provided value was 0. - receive-buffer-size: func() -> result; + /// Create a `pollable` which will resolve once the given duration has + /// elapsed, starting at the time at which this function was called. + /// occured. + subscribe-duration: func(when: duration) -> pollable; + } - /// Get the address the socket is currently streaming to. - /// - /// # Typical errors - /// - `invalid-state`: The socket is not streaming to a specific remote address. (ENOTCONN) - /// - /// # References - /// - - /// - - /// - - /// - - remote-address: func() -> result; - send-buffer-size: func() -> result; - set-receive-buffer-size: func(value: u64) -> result<_, error-code>; - set-send-buffer-size: func(value: u64) -> result<_, error-code>; - set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; + /// WASI Wall Clock is a clock API intended to let users query the current + /// time. The name "wall" makes an analogy to a "clock on the wall", which + /// is not necessarily monotonic as it may be reset. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + /// + /// A wall clock is a clock which measures the date and time according to + /// some external reference. + /// + /// External references may be reset, so this clock is not necessarily + /// monotonic, making it unsuitable for measuring elapsed time. + /// + /// It is intended for reporting the current date and time for humans. + interface wall-clock { + /// A time and date in seconds plus nanoseconds. + record datetime { + seconds: u64, + nanoseconds: u32, + } - /// Bind the socket to a specific network on the provided IP address and port. - /// - /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the - /// implementation to decide which - /// network interface(s) to bind to. - /// If the port is zero, the socket will be bound to a random free port. - /// - /// # Typical errors - /// - `invalid-argument`: The `local-address` has the wrong address family. - /// (EAFNOSUPPORT, EFAULT on Windows) - /// - `invalid-state`: The socket is already bound. (EINVAL) - /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS - /// on Windows) - /// - `address-in-use`: Address is already in use. (EADDRINUSE) - /// - `address-not-bindable`: `local-address` is not an address that the `network` - /// can bind to. (EADDRNOTAVAIL) - /// - `not-in-progress`: A `bind` operation is not in progress. - /// - `would-block`: Can't finish the operation, it is still in progress. - /// (EWOULDBLOCK, EAGAIN) + /// Read the current value of the clock. + /// + /// This clock is not monotonic, therefore calling this function repeatedly + /// will not necessarily produce a sequence of non-decreasing values. + /// + /// The returned timestamps represent the number of seconds since + /// 1970-01-01T00:00:00Z, also known as [POSIX's Seconds Since the Epoch], + /// also known as [Unix Time]. + /// + /// The nanoseconds field of the output is always less than 1000000000. + /// + /// [POSIX's Seconds Since the Epoch]: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html#tag_21_04_16 + /// [Unix Time]: https://en.wikipedia.org/wiki/Unix_time + now: func() -> datetime; + + /// Query the resolution of the clock. + /// + /// The nanoseconds field of the output is always less than 1000000000. + resolution: func() -> datetime; + } + + world imports { + import wasi:io/poll@0.2.0; + import monotonic-clock; + import wall-clock; + } +} + +package wasi:io@0.2.0 { + interface error { + /// A resource which represents some error information. + /// + /// The only method provided by this resource is `to-debug-string`, + /// which provides some human-readable information about the error. + /// + /// In the `wasi:io` package, this resource is returned through the + /// `wasi:io/streams/stream-error` type. + /// + /// To provide more specific error information, other interfaces may + /// provide functions to further "downcast" this error into more specific + /// error information. For example, `error`s returned in streams derived + /// from filesystem types to be described using the filesystem's own + /// error-code type, using the function + /// `wasi:filesystem/types/filesystem-error-code`, which takes a parameter + /// `borrow` and returns + /// `option`. + /// + /// The set of functions which can "downcast" an `error` into a more + /// concrete type is open. + resource error { + + /// Returns a string that is suitable to assist humans in debugging + /// this error. /// - /// # Implementors note - /// Unlike in POSIX, in WASI the bind operation is async. This enables - /// interactive WASI hosts to inject permission prompts. Runtimes that - /// don't want to make use of this ability can simply call the native - /// `bind` as part of either `start-bind` or `finish-bind`. + /// WARNING: The returned string should not be consumed mechanically! + /// It may change across platforms, hosts, or other implementation + /// details. Parsing this string is a major platform-compatibility + /// hazard. + to-debug-string: func() -> string; + } + } + + /// A poll API intended to let users wait for I/O events on multiple handles + /// at once. + interface poll { + /// `pollable` represents a single I/O event which may be ready, or not. + resource pollable { + + /// `block` returns immediately if the pollable is ready, and otherwise + /// blocks until ready. /// - /// # References - /// - - /// - - /// - - /// - - start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + /// This function is equivalent to calling `poll.poll` on a list + /// containing only this pollable. + block: func(); - /// Set up inbound & outbound communication channels, optionally to a specific peer. + /// Return the readiness of a pollable. This function never blocks. /// - /// This function only changes the local socket configuration and does not generate - /// any network traffic. - /// On success, the `remote-address` of the socket is updated. The `local-address` - /// may be updated as well, - /// based on the best network path to `remote-address`. + /// Returns `true` when the pollable is ready, and `false` otherwise. + ready: func() -> bool; + } + + /// Poll for completion on a set of pollables. + /// + /// This function takes a list of pollables, which identify I/O sources of + /// interest, and waits until one or more of the events is ready for I/O. + /// + /// The result `list` contains one or more indices of handles in the + /// argument list that is ready for I/O. + /// + /// If the list contains more elements than can be indexed with a `u32` + /// value, this function traps. + /// + /// A timeout can be implemented by adding a pollable from the + /// wasi-clocks API to the list. + /// + /// This function does not return a `result`; polling in itself does not + /// do any I/O so it doesn't fail. If any of the I/O sources identified by + /// the pollables has an error, it is indicated by marking the source as + /// being reaedy for I/O. + poll: func(in: list>) -> list; + } + + /// WASI I/O is an I/O abstraction API which is currently focused on providing + /// stream types. + /// + /// In the future, the component model is expected to add built-in stream types; + /// when it does, they are expected to subsume this API. + interface streams { + use error.{error}; + use poll.{pollable}; + + /// An error for input-stream and output-stream operations. + variant stream-error { + /// The last operation (a write or flush) failed before completion. /// - /// When a `remote-address` is provided, the returned streams are limited to communicating - /// with that specific peer: - /// - `send` can only be used to send to this destination. - /// - `receive` will only return datagrams sent from the provided `remote-address`. + /// More information is available in the `error` payload. + last-operation-failed(error), + /// The stream is closed: no more input will be accepted by the + /// stream. A closed output-stream will return this error on all + /// future operations. + closed, + } + + /// An input bytestream. + /// + /// `input-stream`s are *non-blocking* to the extent practical on underlying + /// platforms. I/O operations always return promptly; if fewer bytes are + /// promptly available than requested, they return the number of bytes promptly + /// available, which could even be zero. To wait for data to be available, + /// use the `subscribe` function to obtain a `pollable` which can be polled + /// for using `wasi:io/poll`. + resource input-stream { + + /// Read bytes from a stream, after blocking until at least one byte can + /// be read. Except for blocking, behavior is identical to `read`. + blocking-read: func(len: u64) -> result, stream-error>; + + /// Skip bytes from a stream, after blocking until at least one byte + /// can be skipped. Except for blocking behavior, identical to `skip`. + blocking-skip: func(len: u64) -> result; + + /// Perform a non-blocking read from the stream. /// - /// This method may be called multiple times on the same socket to change its association, - /// but - /// only the most recently returned pair of streams will be operational. Implementations - /// may trap if - /// the streams returned by a previous invocation haven't been dropped yet before - /// calling `stream` again. + /// When the source of a `read` is binary data, the bytes from the source + /// are returned verbatim. When the source of a `read` is known to the + /// implementation to be text, bytes containing the UTF-8 encoding of the + /// text are returned. /// - /// The POSIX equivalent in pseudo-code is: - /// ```text - /// if (was previously connected) { - /// connect(s, AF_UNSPEC) - /// } - /// if (remote_address is Some) { - /// connect(s, remote_address) - /// } - /// ``` + /// This function returns a list of bytes containing the read data, + /// when successful. The returned list will contain up to `len` bytes; + /// it may return fewer than requested, but not more. The list is + /// empty when no bytes are available for reading at this time. The + /// pollable given by `subscribe` will be ready when more bytes are + /// available. /// - /// Unlike in POSIX, the socket must already be explicitly bound. + /// This function fails with a `stream-error` when the operation + /// encounters an error, giving `last-operation-failed`, or when the + /// stream is closed, giving `closed`. /// - /// # Typical errors - /// - `invalid-argument`: The `remote-address` has the wrong address family. - /// (EAFNOSUPPORT) - /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY - /// (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) - /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, - /// EADDRNOTAVAIL) - /// - `invalid-state`: The socket is not bound. - /// - `address-in-use`: Tried to perform an implicit bind, but there were - /// no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) - /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, - /// ENETRESET, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) - /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// When the caller gives a `len` of 0, it represents a request to + /// read 0 bytes. If the stream is still open, this call should + /// succeed and return an empty list, or otherwise fail with `closed`. /// - /// # References - /// - - /// - - /// - - /// - - %stream: func(remote-address: option) -> result, error-code>; + /// The `len` parameter is a `u64`, which could represent a list of u8 which + /// is not possible to allocate in wasm32, or not desirable to allocate as + /// as a return value by the callee. The callee may return a list of bytes + /// less than `len` in size while more bytes are available for reading. + read: func(len: u64) -> result, stream-error>; - /// Create a `pollable` which will resolve once the socket is ready for I/O. + /// Skip bytes from a stream. Returns number of bytes skipped. /// - /// Note: this function is here for WASI Preview2 only. - /// It's planned to be removed when `future` is natively supported in Preview3. - subscribe: func() -> pollable; + /// Behaves identical to `read`, except instead of returning a list + /// of bytes, returns the number of bytes consumed from the stream. + skip: func(len: u64) -> result; - /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The TTL value must be 1 or higher. - unicast-hop-limit: func() -> result; + /// Create a `pollable` which will resolve once either the specified stream + /// has bytes available to read or the other end of the stream has been + /// closed. + /// The created `pollable` is a child resource of the `input-stream`. + /// Implementations may trap if the `input-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + subscribe: func() -> pollable; } - resource incoming-datagram-stream { - /// Receive messages on the socket. - /// - /// This function attempts to receive up to `max-results` datagrams on the socket - /// without blocking. - /// The returned list may contain fewer elements than requested, but never more. + /// An output bytestream. + /// + /// `output-stream`s are *non-blocking* to the extent practical on + /// underlying platforms. Except where specified otherwise, I/O operations also + /// always return promptly, after the number of bytes that can be written + /// promptly, which could even be zero. To wait for the stream to be ready to + /// accept data, the `subscribe` function to obtain a `pollable` which can be + /// polled for using `wasi:io/poll`. + resource output-stream { + + /// Request to flush buffered output, and block until flush completes + /// and stream is ready for writing again. + blocking-flush: func() -> result<_, stream-error>; + + /// Read from one stream and write to another, with blocking. /// - /// This function returns successfully with an empty list when either: - /// - `max-results` is 0, or: - /// - `max-results` is greater than 0, but no results are immediately available. - /// This function never returns `error(would-block)`. + /// This is similar to `splice`, except that it blocks until the + /// `output-stream` is ready for writing, and the `input-stream` + /// is ready for reading, before performing the `splice`. + blocking-splice: func(src: borrow, len: u64) -> result; + + /// Perform a write of up to 4096 bytes, and then flush the stream. Block + /// until all of these operations are complete, or an error occurs. /// - /// # Typical errors - /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET - /// on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) - /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write`, and `flush`, and is implemented with the + /// following pseudo-code: /// - /// # References - /// - - /// - - /// - - /// - - /// - - /// - - /// - - /// - - receive: func(max-results: u64) -> result, error-code>; + /// ```text + /// let pollable = this.subscribe(); + /// while !contents.is_empty() { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, contents.len()); + /// let (chunk, rest) = contents.split_at(len); + /// this.write(chunk ); // eliding error handling + /// contents = rest; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + blocking-write-and-flush: func(contents: list) -> result<_, stream-error>; - /// Create a `pollable` which will resolve once the stream is ready to receive again. + /// Perform a write of up to 4096 zeroes, and then flush the stream. + /// Block until all of these operations are complete, or an error + /// occurs. /// - /// Note: this function is here for WASI Preview2 only. - /// It's planned to be removed when `future` is natively supported in Preview3. - subscribe: func() -> pollable; - } - resource outgoing-datagram-stream { + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write-zeroes`, and `flush`, and is implemented with + /// the following pseudo-code: + /// + /// ```text + /// let pollable = this.subscribe(); + /// while num_zeroes != 0 { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, num_zeroes); + /// this.write-zeroes(len); // eliding error handling + /// num_zeroes -= len; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + blocking-write-zeroes-and-flush: func(len: u64) -> result<_, stream-error>; - /// Check readiness for sending. This function never blocks. + /// Check readiness for writing. This function never blocks. /// - /// Returns the number of datagrams permitted for the next call to `send`, - /// or an error. Calling `send` with more datagrams than this function has + /// Returns the number of bytes permitted for the next call to `write`, + /// or an error. Calling `write` with more bytes than this function has /// permitted will trap. /// - /// When this function returns ok(0), the `subscribe` pollable will - /// become ready when this function will report at least ok(1), or an + /// When this function returns 0 bytes, the `subscribe` pollable will + /// become ready when this function will report at least 1 byte, or an /// error. + check-write: func() -> result; + + /// Request to flush buffered output. This function never blocks. /// - /// Never returns `would-block`. - check-send: func() -> result; + /// This tells the output-stream that the caller intends any buffered + /// output to be flushed. the output which is expected to be flushed + /// is all that has been passed to `write` prior to this call. + /// + /// Upon calling this function, the `output-stream` will not accept any + /// writes (`check-write` will return `ok(0)`) until the flush has + /// completed. The `subscribe` pollable will become ready when the + /// flush has completed and the stream can accept more writes. + flush: func() -> result<_, stream-error>; - /// Send messages on the socket. + /// Read from one stream and write to another. /// - /// This function attempts to send all provided `datagrams` on the socket without - /// blocking and - /// returns how many messages were actually sent (or queued for sending). This function - /// never - /// returns `error(would-block)`. If none of the datagrams were able to be sent, `ok(0)` - /// is returned. + /// The behavior of splice is equivelant to: + /// 1. calling `check-write` on the `output-stream` + /// 2. calling `read` on the `input-stream` with the smaller of the + /// `check-write` permitted length and the `len` provided to `splice` + /// 3. calling `write` on the `output-stream` with that read data. /// - /// This function semantically behaves the same as iterating the `datagrams` list - /// and sequentially - /// sending each individual datagram until either the end of the list has been reached - /// or the first error occurred. - /// If at least one datagram has been sent successfully, this function never returns - /// an error. + /// Any error reported by the call to `check-write`, `read`, or + /// `write` ends the splice and reports that error. /// - /// If the input list is empty, the function returns `ok(0)`. + /// This function returns the number of bytes transferred; it may be less + /// than `len`. + splice: func(src: borrow, len: u64) -> result; + + /// Create a `pollable` which will resolve once the output-stream + /// is ready for more writing, or an error has occured. When this + /// pollable is ready, `check-write` will return `ok(n)` with n>0, or an + /// error. /// - /// Each call to `send` must be permitted by a preceding `check-send`. Implementations - /// must trap if - /// either `check-send` was not called or `datagrams` contains more items than `check-send` - /// permitted. + /// If the stream is closed, this pollable is always ready immediately. /// - /// # Typical errors - /// - `invalid-argument`: The `remote-address` has the wrong address family. - /// (EAFNOSUPPORT) - /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY - /// (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) - /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, - /// EADDRNOTAVAIL) - /// - `invalid-argument`: The socket is in "connected" mode and `remote-address` - /// is `some` value that does not match the address passed to `stream`. (EISCONN) - /// - `invalid-argument`: The socket is not "connected" and no value for `remote-address` - /// was provided. (EDESTADDRREQ) - /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, - /// ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) - /// - `connection-refused`: The connection was refused. (ECONNREFUSED) - /// - `datagram-too-large`: The datagram is too large. (EMSGSIZE) + /// The created `pollable` is a child resource of the `output-stream`. + /// Implementations may trap if the `output-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + subscribe: func() -> pollable; + + /// Perform a write. This function never blocks. /// - /// # References - /// - - /// - - /// - - /// - - /// - - /// - - /// - - /// - - send: func(datagrams: list) -> result; + /// When the destination of a `write` is binary data, the bytes from + /// `contents` are written verbatim. When the destination of a `write` is + /// known to the implementation to be text, the bytes of `contents` are + /// transcoded from UTF-8 into the encoding of the destination and then + /// written. + /// + /// Precondition: check-write gave permit of Ok(n) and contents has a + /// length of less than or equal to n. Otherwise, this function will trap. + /// + /// returns Err(closed) without writing if the stream has closed since + /// the last call to check-write provided a permit. + write: func(contents: list) -> result<_, stream-error>; - /// Create a `pollable` which will resolve once the stream is ready to send again. + /// Write zeroes to a stream. /// - /// Note: this function is here for WASI Preview2 only. - /// It's planned to be removed when `future` is natively supported in Preview3. - subscribe: func() -> pollable; + /// This should be used precisely like `write` with the exact same + /// preconditions (must use check-write first), but instead of + /// passing a list of bytes, you simply pass the number of zero-bytes + /// that should be written. + write-zeroes: func(len: u64) -> result<_, stream-error>; } } - interface udp-create-socket { - use network.{network}; - use network.{error-code}; - use network.{ip-address-family}; - use udp.{udp-socket}; + world imports { + import error; + import poll; + import streams; + } +} - /// Create a new UDP socket. +package wasi:random@0.2.0 { + /// The insecure-seed interface for seeding hash-map DoS resistance. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + interface insecure-seed { + /// Return a 128-bit value that may contain a pseudo-random value. /// - /// Similar to `socket(AF_INET or AF_INET6, SOCK_DGRAM, IPPROTO_UDP)` in POSIX. - /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. + /// The returned value is not required to be computed from a CSPRNG, and may + /// even be entirely deterministic. Host implementations are encouraged to + /// provide pseudo-random values to any program exposed to + /// attacker-controlled content, to enable DoS protection built into many + /// languages' hash-map implementations. /// - /// This function does not require a network capability handle. This is considered - /// to be safe because - /// at time of creation, the socket is not bound to any `network` yet. Up to the moment - /// `bind` is called, - /// the socket is effectively an in-memory configuration object, unable to communicate - /// with the outside world. + /// This function is intended to only be called once, by a source language + /// to initialize Denial Of Service (DoS) protection in its hash-map + /// implementation. /// - /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous - /// operations. + /// # Expected future evolution /// - /// # Typical errors - /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) - /// - `new-socket-limit`: The new socket resource could not be created because of - /// a system limit. (EMFILE, ENFILE) + /// This will likely be changed to a value import, to prevent it from being + /// called multiple times and potentially used for purposes other than DoS + /// protection. + insecure-seed: func() -> tuple; + } + + /// The insecure interface for insecure pseudo-random numbers. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + interface insecure { + /// Return `len` insecure pseudo-random bytes. /// - /// # References: - /// - - /// - - /// - - /// - - create-udp-socket: func(address-family: ip-address-family) -> result; + /// This function is not cryptographically secure. Do not use it for + /// anything related to security. + /// + /// There are no requirements on the values of the returned bytes, however + /// implementations are encouraged to return evenly distributed values with + /// a long period. + get-insecure-random-bytes: func(len: u64) -> list; + + /// Return an insecure pseudo-random `u64` value. + /// + /// This function returns the same type of pseudo-random data as + /// `get-insecure-random-bytes`, represented as a `u64`. + get-insecure-random-u64: func() -> u64; + } + + /// WASI Random is a random data API. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + interface random { + /// Return `len` cryptographically-secure random or pseudo-random bytes. + /// + /// This function must produce data at least as cryptographically secure and + /// fast as an adequately seeded cryptographically-secure pseudo-random + /// number generator (CSPRNG). It must not block, from the perspective of + /// the calling program, under any circumstances, including on the first + /// request and on requests for numbers of bytes. The returned data must + /// always be unpredictable. + /// + /// This function must always return fresh data. Deterministic environments + /// must omit this function, rather than implementing it with deterministic + /// data. + get-random-bytes: func(len: u64) -> list; + + /// Return a cryptographically-secure random or pseudo-random `u64` value. + /// + /// This function returns the same type of data as `get-random-bytes`, + /// represented as a `u64`. + get-random-u64: func() -> u64; } world imports { - import network; - import instance-network; - import wasi:io/poll@0.2.0; - import udp; - import udp-create-socket; - import wasi:io/error@0.2.0; - import wasi:io/streams@0.2.0; - import wasi:clocks/monotonic-clock@0.2.0; - import tcp; - import tcp-create-socket; - import ip-name-lookup; + import random; + import insecure; + import insecure-seed; } } diff --git a/testdata/wasi/http-minimal.wit b/testdata/wasi/http-minimal.wit index e6449f5e..b3eb45fd 100644 --- a/testdata/wasi/http-minimal.wit +++ b/testdata/wasi/http-minimal.wit @@ -1,18 +1,671 @@ -package wasi:cli@0.2.0; +package wasi:http@0.2.0; -interface stdin { +/// This interface defines all of the types and methods for implementing +/// HTTP Requests and Responses, both incoming and outgoing, as well as +/// their headers, trailers, and bodies. +interface types { + use wasi:clocks/monotonic-clock@0.2.0.{duration}; use wasi:io/streams@0.2.0.{input-stream}; - get-stdin: func() -> input-stream; + use wasi:io/streams@0.2.0.{output-stream}; + use wasi:io/error@0.2.0.{error as io-error}; + use wasi:io/poll@0.2.0.{pollable}; + + /// This type corresponds to HTTP standard Methods. + variant method { + get, + head, + post, + put, + delete, + connect, + options, + trace, + patch, + other(string), + } + + /// This type corresponds to HTTP standard Related Schemes. + variant scheme { HTTP, HTTPS, other(string) } + + /// Defines the case payload type for `DNS-error` above: + record DNS-error-payload { + rcode: option, + info-code: option, + } + + /// Defines the case payload type for `TLS-alert-received` above: + record TLS-alert-received-payload { + alert-id: option, + alert-message: option, + } + + /// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: + record field-size-payload { + field-name: option, + field-size: option, + } + + /// These cases are inspired by the IANA HTTP Proxy Error Types: + /// https://www.iana.org/assignments/http-proxy-status/http-proxy-status.xhtml#table-http-proxy-error-types + variant error-code { + DNS-timeout, + DNS-error(DNS-error-payload), + destination-not-found, + destination-unavailable, + destination-IP-prohibited, + destination-IP-unroutable, + connection-refused, + connection-terminated, + connection-timeout, + connection-read-timeout, + connection-write-timeout, + connection-limit-reached, + TLS-protocol-error, + TLS-certificate-error, + TLS-alert-received(TLS-alert-received-payload), + HTTP-request-denied, + HTTP-request-length-required, + HTTP-request-body-size(option), + HTTP-request-method-invalid, + HTTP-request-URI-invalid, + HTTP-request-URI-too-long, + HTTP-request-header-section-size(option), + HTTP-request-header-size(option), + HTTP-request-trailer-section-size(option), + HTTP-request-trailer-size(field-size-payload), + HTTP-response-incomplete, + HTTP-response-header-section-size(option), + HTTP-response-header-size(field-size-payload), + HTTP-response-body-size(option), + HTTP-response-trailer-section-size(option), + HTTP-response-trailer-size(field-size-payload), + HTTP-response-transfer-coding(option), + HTTP-response-content-coding(option), + HTTP-response-timeout, + HTTP-upgrade-failed, + HTTP-protocol-error, + loop-detected, + configuration-error, + /// This is a catch-all error for anything that doesn't fit cleanly into a + /// more specific case. It also includes an optional string for an + /// unstructured description of the error. Users should not depend on the + /// string for diagnosing errors, as it's not required to be consistent + /// between implementations. + internal-error(option), + } + + /// This type enumerates the different kinds of errors that may occur when + /// setting or appending to a `fields` resource. + variant header-error { + /// This error indicates that a `field-key` or `field-value` was + /// syntactically invalid when used with an operation that sets headers in a + /// `fields`. + invalid-syntax, + /// This error indicates that a forbidden `field-key` was used when trying + /// to set a header in a `fields`. + forbidden, + /// This error indicates that the operation on the `fields` was not + /// permitted because the fields are immutable. + immutable, + } + + /// Field keys are always strings. + type field-key = string; + + /// Field values should always be ASCII strings. However, in + /// reality, HTTP implementations often have to interpret malformed values, + /// so they are provided as a list of bytes. + type field-value = list; + + /// This following block defines the `fields` resource which corresponds to + /// HTTP standard Fields. Fields are a common representation used for both + /// Headers and Trailers. + /// + /// A `fields` may be mutable or immutable. A `fields` created using the + /// constructor, `from-list`, or `clone` will be mutable, but a `fields` + /// resource given by other means (including, but not limited to, + /// `incoming-request.headers`, `outgoing-request.headers`) might be be + /// immutable. In an immutable fields, the `set`, `append`, and `delete` + /// operations will fail with `header-error.immutable`. + resource fields { + /// Construct an empty HTTP Fields. + /// + /// The resulting `fields` is mutable. + constructor(); + + /// Append a value for a key. Does not change or delete any existing + /// values for that key. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-key` or + /// `field-value` are syntactically invalid. + append: func(name: field-key, value: field-value) -> result<_, header-error>; + + /// Make a deep copy of the Fields. Equivelant in behavior to calling the + /// `fields` constructor on the return value of `entries`. The resulting + /// `fields` is mutable. + clone: func() -> fields; + + /// Delete all values for a key. Does nothing if no values for the key + /// exist. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-key` is + /// syntactically invalid. + delete: func(name: field-key) -> result<_, header-error>; + + /// Retrieve the full set of keys and values in the Fields. Like the + /// constructor, the list represents each key-value pair. + /// + /// The outer list represents each key-value pair in the Fields. Keys + /// which have multiple values are represented by multiple entries in this + /// list with the same key. + entries: func() -> list>; + + /// Get all of the values corresponding to a key. If the key is not present + /// in this `fields` or is syntactically invalid, an empty list is returned. + /// However, if the key is present but empty, this is represented by a list + /// with one or more empty field-values present. + get: func(name: field-key) -> list; + + /// Returns `true` when the key is present in this `fields`. If the key is + /// syntactically invalid, `false` is returned. + has: func(name: field-key) -> bool; + + /// Set all of the values for a key. Clears any existing values for that + /// key, if they have been set. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-key` or any of + /// the `field-value`s are syntactically invalid. + set: func(name: field-key, value: list) -> result<_, header-error>; + + /// Construct an HTTP Fields. + /// + /// The resulting `fields` is mutable. + /// + /// The list represents each key-value pair in the Fields. Keys + /// which have multiple values are represented by multiple entries in this + /// list with the same key. + /// + /// The tuple is a pair of the field key, represented as a string, and + /// Value, represented as a list of bytes. + /// + /// An error result will be returned if any `field-key` or `field-value` is + /// syntactically invalid, or if a field is forbidden. + from-list: static func(entries: list>) -> result; + } + + /// Headers is an alias for Fields. + type headers = fields; + + /// Trailers is an alias for Fields. + type trailers = fields; + + /// Represents an incoming HTTP Request. + resource incoming-request { + + /// Returns the authority from the request, if it was present. + authority: func() -> option; + + /// Gives the `incoming-body` associated with this request. Will only + /// return success at most once, and subsequent calls will return error. + consume: func() -> result; + + /// Get the `headers` associated with the request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// The `headers` returned are a child resource: it must be dropped before + /// the parent `incoming-request` is dropped. Dropping this + /// `incoming-request` before all children are dropped will trap. + headers: func() -> headers; + + /// Returns the method of the incoming request. + method: func() -> method; + + /// Returns the path with query parameters from the request, as a string. + path-with-query: func() -> option; + + /// Returns the protocol scheme from the request. + scheme: func() -> option; + } + + /// Represents an outgoing HTTP Request. + resource outgoing-request { + /// Construct a new `outgoing-request` with a default `method` of `GET`, and + /// `none` values for `path-with-query`, `scheme`, and `authority`. + /// + /// * `headers` is the HTTP Headers for the Request. + /// + /// It is possible to construct, or manipulate with the accessor functions + /// below, an `outgoing-request` with an invalid combination of `scheme` + /// and `authority`, or `headers` which are not permitted to be sent. + /// It is the obligation of the `outgoing-handler.handle` implementation + /// to reject invalid constructions of `outgoing-request`. + constructor(headers: headers); + + /// Get the HTTP Authority for the Request. A value of `none` may be used + /// with Related Schemes which do not require an Authority. The HTTP and + /// HTTPS schemes always require an authority. + authority: func() -> option; + + /// Returns the resource corresponding to the outgoing Body for this + /// Request. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-request` can be retrieved at most once. Subsequent + /// calls will return error. + body: func() -> result; + + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transfered to + /// another component by e.g. `outgoing-handler.handle`. + headers: func() -> headers; + + /// Get the Method for the Request. + method: func() -> method; + + /// Get the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. + path-with-query: func() -> option; + + /// Get the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. + scheme: func() -> option; + + /// Set the HTTP Authority for the Request. A value of `none` may be used + /// with Related Schemes which do not require an Authority. The HTTP and + /// HTTPS schemes always require an authority. Fails if the string given is + /// not a syntactically valid uri authority. + set-authority: func(authority: option) -> result; + + /// Set the Method for the Request. Fails if the string present in a + /// `method.other` argument is not a syntactically valid method. + set-method: func(method: method) -> result; + + /// Set the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. Fails is the + /// string given is not a syntactically valid path and query uri component. + set-path-with-query: func(path-with-query: option) -> result; + + /// Set the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. Fails if the + /// string given is not a syntactically valid uri scheme. + set-scheme: func(scheme: option) -> result; + } + + /// Parameters for making an HTTP Request. Each of these parameters is + /// currently an optional timeout applicable to the transport layer of the + /// HTTP protocol. + /// + /// These timeouts are separate from any the user may use to bound a + /// blocking call to `wasi:io/poll.poll`. + resource request-options { + /// Construct a default `request-options` value. + constructor(); + + /// The timeout for receiving subsequent chunks of bytes in the Response + /// body stream. + between-bytes-timeout: func() -> option; + + /// The timeout for the initial connect to the HTTP Server. + connect-timeout: func() -> option; + + /// The timeout for receiving the first byte of the Response body. + first-byte-timeout: func() -> option; + + /// Set the timeout for receiving subsequent chunks of bytes in the Response + /// body stream. An error return value indicates that this timeout is not + /// supported. + set-between-bytes-timeout: func(duration: option) -> result; + + /// Set the timeout for the initial connect to the HTTP Server. An error + /// return value indicates that this timeout is not supported. + set-connect-timeout: func(duration: option) -> result; + + /// Set the timeout for receiving the first byte of the Response body. An + /// error return value indicates that this timeout is not supported. + set-first-byte-timeout: func(duration: option) -> result; + } + + /// Represents the ability to send an HTTP Response. + /// + /// This resource is used by the `wasi:http/incoming-handler` interface to + /// allow a Response to be sent corresponding to the Request provided as the + /// other argument to `incoming-handler.handle`. + resource response-outparam { + + /// Set the value of the `response-outparam` to either send a response, + /// or indicate an error. + /// + /// This method consumes the `response-outparam` to ensure that it is + /// called at most once. If it is never called, the implementation + /// will respond with an error. + /// + /// The user may provide an `error` to `response` to allow the + /// implementation determine how to respond with an HTTP error response. + set: static func(param: response-outparam, response: result); + } + + /// This type corresponds to the HTTP standard Status Code. + type status-code = u16; + + /// Represents an incoming HTTP Response. + resource incoming-response { + + /// Returns the incoming body. May be called at most once. Returns error + /// if called additional times. + consume: func() -> result; + + /// Returns the headers from the incoming response. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `incoming-response` is dropped. + headers: func() -> headers; + + /// Returns the status code from the incoming response. + status: func() -> status-code; + } + + /// Represents an incoming HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, indicating that the full contents of the + /// body have been received. This resource represents the contents as + /// an `input-stream` and the delivery of trailers as a `future-trailers`, + /// and ensures that the user of this interface may only be consuming either + /// the body contents or waiting on trailers at any given time. + resource incoming-body { + + /// Returns the contents of the body, as a stream of bytes. + /// + /// Returns success on first call: the stream representing the contents + /// can be retrieved at most once. Subsequent calls will return error. + /// + /// The returned `input-stream` resource is a child: it must be dropped + /// before the parent `incoming-body` is dropped, or consumed by + /// `incoming-body.finish`. + /// + /// This invariant ensures that the implementation can determine whether + /// the user is consuming the contents of the body, waiting on the + /// `future-trailers` to be ready, or neither. This allows for network + /// backpressure is to be applied when the user is consuming the body, + /// and for that backpressure to not inhibit delivery of the trailers if + /// the user does not read the entire body. + %stream: func() -> result; + + /// Takes ownership of `incoming-body`, and returns a `future-trailers`. + /// This function will trap if the `input-stream` child is still alive. + finish: static func(this: incoming-body) -> future-trailers; + } + + /// Represents a future which may eventaully return trailers, or an error. + /// + /// In the case that the incoming HTTP Request or Response did not have any + /// trailers, this future will resolve to the empty set of trailers once the + /// complete Request or Response body has been received. + resource future-trailers { + + /// Returns the contents of the trailers, or an error which occured, + /// once the future is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the trailers or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the HTTP Request or Response + /// body, as well as any trailers, were received successfully, or that an + /// error occured receiving them. The optional `trailers` indicates whether + /// or not trailers were present in the body. + /// + /// When some `trailers` are returned by this method, the `trailers` + /// resource is immutable, and a child. Use of the `set`, `append`, or + /// `delete` methods will return an error, and the resource must be + /// dropped before the parent `future-trailers` is dropped. + get: func() -> option, error-code>>>; + + /// Returns a pollable which becomes ready when either the trailers have + /// been received, or an error has occured. When this pollable is ready, + /// the `get` method will return `some`. + subscribe: func() -> pollable; + } + + /// Represents an outgoing HTTP Response. + resource outgoing-response { + /// Construct an `outgoing-response`, with a default `status-code` of `200`. + /// If a different `status-code` is needed, it must be set via the + /// `set-status-code` method. + /// + /// * `headers` is the HTTP Headers for the Response. + constructor(headers: headers); + + /// Returns the resource corresponding to the outgoing Body for this Response. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-response` can be retrieved at most once. Subsequent + /// calls will return error. + body: func() -> result; + + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transfered to + /// another component by e.g. `outgoing-handler.handle`. + headers: func() -> headers; + + /// Set the HTTP Status Code for the Response. Fails if the status-code + /// given is not a valid http status code. + set-status-code: func(status-code: status-code) -> result; + + /// Get the HTTP Status Code for the Response. + status-code: func() -> status-code; + } + + /// Represents an outgoing HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, inducating the full contents of the body + /// have been sent. This resource represents the contents as an + /// `output-stream` child resource, and the completion of the body (with + /// optional trailers) with a static function that consumes the + /// `outgoing-body` resource, and ensures that the user of this interface + /// may not write to the body contents after the body has been finished. + /// + /// If the user code drops this resource, as opposed to calling the static + /// method `finish`, the implementation should treat the body as incomplete, + /// and that an error has occured. The implementation should propogate this + /// error to the HTTP protocol by whatever means it has available, + /// including: corrupting the body on the wire, aborting the associated + /// Request, or sending a late status code for the Response. + resource outgoing-body { + + /// Returns a stream for writing the body contents. + /// + /// The returned `output-stream` is a child resource: it must be dropped + /// before the parent `outgoing-body` resource is dropped (or finished), + /// otherwise the `outgoing-body` drop or `finish` will trap. + /// + /// Returns success on the first call: the `output-stream` resource for + /// this `outgoing-body` may be retrieved at most once. Subsequent calls + /// will return error. + write: func() -> result; + + /// Finalize an outgoing body, optionally providing trailers. This must be + /// called to signal that the response is complete. If the `outgoing-body` + /// is dropped without calling `outgoing-body.finalize`, the implementation + /// should treat the body as corrupted. + /// + /// Fails if the body's `outgoing-request` or `outgoing-response` was + /// constructed with a Content-Length header, and the contents written + /// to the body (via `write`) does not match the value given in the + /// Content-Length. + finish: static func(this: outgoing-body, trailers: option) -> result<_, error-code>; + } + + /// Represents a future which may eventaully return an incoming HTTP + /// Response, or an error. + /// + /// This resource is returned by the `wasi:http/outgoing-handler` interface to + /// provide the HTTP Response corresponding to the sent Request. + resource future-incoming-response { + + /// Returns the incoming HTTP Response, or an error, once one is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the response or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the incoming HTTP Response + /// status and headers have recieved successfully, or that an error + /// occured. Errors may also occur while consuming the response body, + /// but those will be reported by the `incoming-body` and its + /// `output-stream` child. + get: func() -> option>>; + + /// Returns a pollable which becomes ready when either the Response has + /// been received, or an error has occured. When this pollable is ready, + /// the `get` method will return `some`. + subscribe: func() -> pollable; + } + + /// Attempts to extract a http-related `error` from the wasi:io `error` + /// provided. + /// + /// Stream operations which return + /// `wasi:io/stream/stream-error::last-operation-failed` have a payload of + /// type `wasi:io/error/error` with more information about the operation + /// that failed. This payload can be passed through to this function to see + /// if there's http-related information about the error to return. + /// + /// Note that this function is fallible because not all io-errors are + /// http-related errors. + http-error-code: func(err: borrow) -> option; } -interface stdout { - use wasi:io/streams@0.2.0.{output-stream}; - get-stdout: func() -> output-stream; +/// This interface defines a handler of incoming HTTP Requests. It should +/// be exported by components which can respond to HTTP Requests. +interface incoming-handler { + use types.{incoming-request}; + use types.{response-outparam}; + + /// This function is invoked with an incoming HTTP Request, and a resource + /// `response-outparam` which provides the capability to reply with an HTTP + /// Response. The response is sent by calling the `response-outparam.set` + /// method, which allows execution to continue after the response has been + /// sent. This enables both streaming to the response body, and performing other + /// work. + /// + /// The implementor of this function must write a response to the + /// `response-outparam` before returning, or else the caller will respond + /// with an error on its behalf. + handle: func(request: incoming-request, response-out: response-outparam); } -interface stderr { - use wasi:io/streams@0.2.0.{output-stream}; - get-stderr: func() -> output-stream; +/// This interface defines a handler of outgoing HTTP Requests. It should be +/// imported by components which wish to make HTTP Requests. +interface outgoing-handler { + use types.{outgoing-request}; + use types.{request-options}; + use types.{future-incoming-response}; + use types.{error-code}; + + /// This function is invoked with an outgoing HTTP Request, and it returns + /// a resource `future-incoming-response` which represents an HTTP Response + /// which may arrive in the future. + /// + /// The `options` argument accepts optional parameters for the HTTP + /// protocol's transport layer. + /// + /// This function may return an error if the `outgoing-request` is invalid + /// or not allowed to be made. Otherwise, protocol errors are reported + /// through the `future-incoming-response`. + handle: func(request: outgoing-request, options: option) -> result; +} + +/// The `wasi:http/proxy` world captures a widely-implementable intersection of +/// hosts that includes HTTP forward and reverse proxies. Components targeting +/// this world may concurrently stream in and out any number of incoming and +/// outgoing HTTP requests. +world proxy { + import wasi:io/poll@0.2.0; + import wasi:clocks/monotonic-clock@0.2.0; + import wasi:io/error@0.2.0; + import wasi:io/streams@0.2.0; + import types; + import wasi:random/random@0.2.0; + import wasi:cli/stdout@0.2.0; + import wasi:cli/stderr@0.2.0; + import wasi:cli/stdin@0.2.0; + import outgoing-handler; + import wasi:clocks/wall-clock@0.2.0; + export incoming-handler; +} + +package wasi:cli@0.2.0 { + interface stdin { + use wasi:io/streams@0.2.0.{input-stream}; + get-stdin: func() -> input-stream; + } + + interface stdout { + use wasi:io/streams@0.2.0.{output-stream}; + get-stdout: func() -> output-stream; + } + + interface stderr { + use wasi:io/streams@0.2.0.{output-stream}; + get-stderr: func() -> output-stream; + } +} + +package wasi:random@0.2.0 { + /// WASI Random is a random data API. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + interface random { + /// Return `len` cryptographically-secure random or pseudo-random bytes. + /// + /// This function must produce data at least as cryptographically secure and + /// fast as an adequately seeded cryptographically-secure pseudo-random + /// number generator (CSPRNG). It must not block, from the perspective of + /// the calling program, under any circumstances, including on the first + /// request and on requests for numbers of bytes. The returned data must + /// always be unpredictable. + /// + /// This function must always return fresh data. Deterministic environments + /// must omit this function, rather than implementing it with deterministic + /// data. + get-random-bytes: func(len: u64) -> list; + + /// Return a cryptographically-secure random or pseudo-random `u64` value. + /// + /// This function returns the same type of data as `get-random-bytes`, + /// represented as a `u64`. + get-random-u64: func() -> u64; + } } package wasi:clocks@0.2.0 { @@ -100,631 +753,6 @@ package wasi:clocks@0.2.0 { } } -package wasi:http@0.2.0 { - /// This interface defines all of the types and methods for implementing - /// HTTP Requests and Responses, both incoming and outgoing, as well as - /// their headers, trailers, and bodies. - interface types { - use wasi:clocks/monotonic-clock@0.2.0.{duration}; - use wasi:io/streams@0.2.0.{input-stream}; - use wasi:io/streams@0.2.0.{output-stream}; - use wasi:io/error@0.2.0.{error as io-error}; - use wasi:io/poll@0.2.0.{pollable}; - - /// This type corresponds to HTTP standard Methods. - variant method { - get, - head, - post, - put, - delete, - connect, - options, - trace, - patch, - other(string), - } - - /// This type corresponds to HTTP standard Related Schemes. - variant scheme { HTTP, HTTPS, other(string) } - - /// Defines the case payload type for `DNS-error` above: - record DNS-error-payload { - rcode: option, - info-code: option, - } - - /// Defines the case payload type for `TLS-alert-received` above: - record TLS-alert-received-payload { - alert-id: option, - alert-message: option, - } - - /// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: - record field-size-payload { - field-name: option, - field-size: option, - } - - /// These cases are inspired by the IANA HTTP Proxy Error Types: - /// https://www.iana.org/assignments/http-proxy-status/http-proxy-status.xhtml#table-http-proxy-error-types - variant error-code { - DNS-timeout, - DNS-error(DNS-error-payload), - destination-not-found, - destination-unavailable, - destination-IP-prohibited, - destination-IP-unroutable, - connection-refused, - connection-terminated, - connection-timeout, - connection-read-timeout, - connection-write-timeout, - connection-limit-reached, - TLS-protocol-error, - TLS-certificate-error, - TLS-alert-received(TLS-alert-received-payload), - HTTP-request-denied, - HTTP-request-length-required, - HTTP-request-body-size(option), - HTTP-request-method-invalid, - HTTP-request-URI-invalid, - HTTP-request-URI-too-long, - HTTP-request-header-section-size(option), - HTTP-request-header-size(option), - HTTP-request-trailer-section-size(option), - HTTP-request-trailer-size(field-size-payload), - HTTP-response-incomplete, - HTTP-response-header-section-size(option), - HTTP-response-header-size(field-size-payload), - HTTP-response-body-size(option), - HTTP-response-trailer-section-size(option), - HTTP-response-trailer-size(field-size-payload), - HTTP-response-transfer-coding(option), - HTTP-response-content-coding(option), - HTTP-response-timeout, - HTTP-upgrade-failed, - HTTP-protocol-error, - loop-detected, - configuration-error, - /// This is a catch-all error for anything that doesn't fit cleanly into a - /// more specific case. It also includes an optional string for an - /// unstructured description of the error. Users should not depend on the - /// string for diagnosing errors, as it's not required to be consistent - /// between implementations. - internal-error(option), - } - - /// This type enumerates the different kinds of errors that may occur when - /// setting or appending to a `fields` resource. - variant header-error { - /// This error indicates that a `field-key` or `field-value` was - /// syntactically invalid when used with an operation that sets headers in a - /// `fields`. - invalid-syntax, - /// This error indicates that a forbidden `field-key` was used when trying - /// to set a header in a `fields`. - forbidden, - /// This error indicates that the operation on the `fields` was not - /// permitted because the fields are immutable. - immutable, - } - - /// Field keys are always strings. - type field-key = string; - - /// Field values should always be ASCII strings. However, in - /// reality, HTTP implementations often have to interpret malformed values, - /// so they are provided as a list of bytes. - type field-value = list; - - /// This following block defines the `fields` resource which corresponds to - /// HTTP standard Fields. Fields are a common representation used for both - /// Headers and Trailers. - /// - /// A `fields` may be mutable or immutable. A `fields` created using the - /// constructor, `from-list`, or `clone` will be mutable, but a `fields` - /// resource given by other means (including, but not limited to, - /// `incoming-request.headers`, `outgoing-request.headers`) might be be - /// immutable. In an immutable fields, the `set`, `append`, and `delete` - /// operations will fail with `header-error.immutable`. - resource fields { - /// Construct an empty HTTP Fields. - /// - /// The resulting `fields` is mutable. - constructor(); - - /// Append a value for a key. Does not change or delete any existing - /// values for that key. - /// - /// Fails with `header-error.immutable` if the `fields` are immutable. - /// - /// Fails with `header-error.invalid-syntax` if the `field-key` or - /// `field-value` are syntactically invalid. - append: func(name: field-key, value: field-value) -> result<_, header-error>; - - /// Make a deep copy of the Fields. Equivelant in behavior to calling the - /// `fields` constructor on the return value of `entries`. The resulting - /// `fields` is mutable. - clone: func() -> fields; - - /// Delete all values for a key. Does nothing if no values for the key - /// exist. - /// - /// Fails with `header-error.immutable` if the `fields` are immutable. - /// - /// Fails with `header-error.invalid-syntax` if the `field-key` is - /// syntactically invalid. - delete: func(name: field-key) -> result<_, header-error>; - - /// Retrieve the full set of keys and values in the Fields. Like the - /// constructor, the list represents each key-value pair. - /// - /// The outer list represents each key-value pair in the Fields. Keys - /// which have multiple values are represented by multiple entries in this - /// list with the same key. - entries: func() -> list>; - - /// Get all of the values corresponding to a key. If the key is not present - /// in this `fields` or is syntactically invalid, an empty list is returned. - /// However, if the key is present but empty, this is represented by a list - /// with one or more empty field-values present. - get: func(name: field-key) -> list; - - /// Returns `true` when the key is present in this `fields`. If the key is - /// syntactically invalid, `false` is returned. - has: func(name: field-key) -> bool; - - /// Set all of the values for a key. Clears any existing values for that - /// key, if they have been set. - /// - /// Fails with `header-error.immutable` if the `fields` are immutable. - /// - /// Fails with `header-error.invalid-syntax` if the `field-key` or any of - /// the `field-value`s are syntactically invalid. - set: func(name: field-key, value: list) -> result<_, header-error>; - - /// Construct an HTTP Fields. - /// - /// The resulting `fields` is mutable. - /// - /// The list represents each key-value pair in the Fields. Keys - /// which have multiple values are represented by multiple entries in this - /// list with the same key. - /// - /// The tuple is a pair of the field key, represented as a string, and - /// Value, represented as a list of bytes. - /// - /// An error result will be returned if any `field-key` or `field-value` is - /// syntactically invalid, or if a field is forbidden. - from-list: static func(entries: list>) -> result; - } - - /// Headers is an alias for Fields. - type headers = fields; - - /// Trailers is an alias for Fields. - type trailers = fields; - - /// Represents an incoming HTTP Request. - resource incoming-request { - - /// Returns the authority from the request, if it was present. - authority: func() -> option; - - /// Gives the `incoming-body` associated with this request. Will only - /// return success at most once, and subsequent calls will return error. - consume: func() -> result; - - /// Get the `headers` associated with the request. - /// - /// The returned `headers` resource is immutable: `set`, `append`, and - /// `delete` operations will fail with `header-error.immutable`. - /// - /// The `headers` returned are a child resource: it must be dropped before - /// the parent `incoming-request` is dropped. Dropping this - /// `incoming-request` before all children are dropped will trap. - headers: func() -> headers; - - /// Returns the method of the incoming request. - method: func() -> method; - - /// Returns the path with query parameters from the request, as a string. - path-with-query: func() -> option; - - /// Returns the protocol scheme from the request. - scheme: func() -> option; - } - - /// Represents an outgoing HTTP Request. - resource outgoing-request { - /// Construct a new `outgoing-request` with a default `method` of `GET`, and - /// `none` values for `path-with-query`, `scheme`, and `authority`. - /// - /// * `headers` is the HTTP Headers for the Request. - /// - /// It is possible to construct, or manipulate with the accessor functions - /// below, an `outgoing-request` with an invalid combination of `scheme` - /// and `authority`, or `headers` which are not permitted to be sent. - /// It is the obligation of the `outgoing-handler.handle` implementation - /// to reject invalid constructions of `outgoing-request`. - constructor(headers: headers); - - /// Get the HTTP Authority for the Request. A value of `none` may be used - /// with Related Schemes which do not require an Authority. The HTTP and - /// HTTPS schemes always require an authority. - authority: func() -> option; - - /// Returns the resource corresponding to the outgoing Body for this - /// Request. - /// - /// Returns success on the first call: the `outgoing-body` resource for - /// this `outgoing-request` can be retrieved at most once. Subsequent - /// calls will return error. - body: func() -> result; - - /// Get the headers associated with the Request. - /// - /// The returned `headers` resource is immutable: `set`, `append`, and - /// `delete` operations will fail with `header-error.immutable`. - /// - /// This headers resource is a child: it must be dropped before the parent - /// `outgoing-request` is dropped, or its ownership is transfered to - /// another component by e.g. `outgoing-handler.handle`. - headers: func() -> headers; - - /// Get the Method for the Request. - method: func() -> method; - - /// Get the combination of the HTTP Path and Query for the Request. - /// When `none`, this represents an empty Path and empty Query. - path-with-query: func() -> option; - - /// Get the HTTP Related Scheme for the Request. When `none`, the - /// implementation may choose an appropriate default scheme. - scheme: func() -> option; - - /// Set the HTTP Authority for the Request. A value of `none` may be used - /// with Related Schemes which do not require an Authority. The HTTP and - /// HTTPS schemes always require an authority. Fails if the string given is - /// not a syntactically valid uri authority. - set-authority: func(authority: option) -> result; - - /// Set the Method for the Request. Fails if the string present in a - /// `method.other` argument is not a syntactically valid method. - set-method: func(method: method) -> result; - - /// Set the combination of the HTTP Path and Query for the Request. - /// When `none`, this represents an empty Path and empty Query. Fails is the - /// string given is not a syntactically valid path and query uri component. - set-path-with-query: func(path-with-query: option) -> result; - - /// Set the HTTP Related Scheme for the Request. When `none`, the - /// implementation may choose an appropriate default scheme. Fails if the - /// string given is not a syntactically valid uri scheme. - set-scheme: func(scheme: option) -> result; - } - - /// Parameters for making an HTTP Request. Each of these parameters is - /// currently an optional timeout applicable to the transport layer of the - /// HTTP protocol. - /// - /// These timeouts are separate from any the user may use to bound a - /// blocking call to `wasi:io/poll.poll`. - resource request-options { - /// Construct a default `request-options` value. - constructor(); - - /// The timeout for receiving subsequent chunks of bytes in the Response - /// body stream. - between-bytes-timeout: func() -> option; - - /// The timeout for the initial connect to the HTTP Server. - connect-timeout: func() -> option; - - /// The timeout for receiving the first byte of the Response body. - first-byte-timeout: func() -> option; - - /// Set the timeout for receiving subsequent chunks of bytes in the Response - /// body stream. An error return value indicates that this timeout is not - /// supported. - set-between-bytes-timeout: func(duration: option) -> result; - - /// Set the timeout for the initial connect to the HTTP Server. An error - /// return value indicates that this timeout is not supported. - set-connect-timeout: func(duration: option) -> result; - - /// Set the timeout for receiving the first byte of the Response body. An - /// error return value indicates that this timeout is not supported. - set-first-byte-timeout: func(duration: option) -> result; - } - - /// Represents the ability to send an HTTP Response. - /// - /// This resource is used by the `wasi:http/incoming-handler` interface to - /// allow a Response to be sent corresponding to the Request provided as the - /// other argument to `incoming-handler.handle`. - resource response-outparam { - - /// Set the value of the `response-outparam` to either send a response, - /// or indicate an error. - /// - /// This method consumes the `response-outparam` to ensure that it is - /// called at most once. If it is never called, the implementation - /// will respond with an error. - /// - /// The user may provide an `error` to `response` to allow the - /// implementation determine how to respond with an HTTP error response. - set: static func(param: response-outparam, response: result); - } - - /// This type corresponds to the HTTP standard Status Code. - type status-code = u16; - - /// Represents an incoming HTTP Response. - resource incoming-response { - - /// Returns the incoming body. May be called at most once. Returns error - /// if called additional times. - consume: func() -> result; - - /// Returns the headers from the incoming response. - /// - /// The returned `headers` resource is immutable: `set`, `append`, and - /// `delete` operations will fail with `header-error.immutable`. - /// - /// This headers resource is a child: it must be dropped before the parent - /// `incoming-response` is dropped. - headers: func() -> headers; - - /// Returns the status code from the incoming response. - status: func() -> status-code; - } - - /// Represents an incoming HTTP Request or Response's Body. - /// - /// A body has both its contents - a stream of bytes - and a (possibly - /// empty) set of trailers, indicating that the full contents of the - /// body have been received. This resource represents the contents as - /// an `input-stream` and the delivery of trailers as a `future-trailers`, - /// and ensures that the user of this interface may only be consuming either - /// the body contents or waiting on trailers at any given time. - resource incoming-body { - - /// Returns the contents of the body, as a stream of bytes. - /// - /// Returns success on first call: the stream representing the contents - /// can be retrieved at most once. Subsequent calls will return error. - /// - /// The returned `input-stream` resource is a child: it must be dropped - /// before the parent `incoming-body` is dropped, or consumed by - /// `incoming-body.finish`. - /// - /// This invariant ensures that the implementation can determine whether - /// the user is consuming the contents of the body, waiting on the - /// `future-trailers` to be ready, or neither. This allows for network - /// backpressure is to be applied when the user is consuming the body, - /// and for that backpressure to not inhibit delivery of the trailers if - /// the user does not read the entire body. - %stream: func() -> result; - - /// Takes ownership of `incoming-body`, and returns a `future-trailers`. - /// This function will trap if the `input-stream` child is still alive. - finish: static func(this: incoming-body) -> future-trailers; - } - - /// Represents a future which may eventaully return trailers, or an error. - /// - /// In the case that the incoming HTTP Request or Response did not have any - /// trailers, this future will resolve to the empty set of trailers once the - /// complete Request or Response body has been received. - resource future-trailers { - - /// Returns the contents of the trailers, or an error which occured, - /// once the future is ready. - /// - /// The outer `option` represents future readiness. Users can wait on this - /// `option` to become `some` using the `subscribe` method. - /// - /// The outer `result` is used to retrieve the trailers or error at most - /// once. It will be success on the first call in which the outer option - /// is `some`, and error on subsequent calls. - /// - /// The inner `result` represents that either the HTTP Request or Response - /// body, as well as any trailers, were received successfully, or that an - /// error occured receiving them. The optional `trailers` indicates whether - /// or not trailers were present in the body. - /// - /// When some `trailers` are returned by this method, the `trailers` - /// resource is immutable, and a child. Use of the `set`, `append`, or - /// `delete` methods will return an error, and the resource must be - /// dropped before the parent `future-trailers` is dropped. - get: func() -> option, error-code>>>; - - /// Returns a pollable which becomes ready when either the trailers have - /// been received, or an error has occured. When this pollable is ready, - /// the `get` method will return `some`. - subscribe: func() -> pollable; - } - - /// Represents an outgoing HTTP Response. - resource outgoing-response { - /// Construct an `outgoing-response`, with a default `status-code` of `200`. - /// If a different `status-code` is needed, it must be set via the - /// `set-status-code` method. - /// - /// * `headers` is the HTTP Headers for the Response. - constructor(headers: headers); - - /// Returns the resource corresponding to the outgoing Body for this Response. - /// - /// Returns success on the first call: the `outgoing-body` resource for - /// this `outgoing-response` can be retrieved at most once. Subsequent - /// calls will return error. - body: func() -> result; - - /// Get the headers associated with the Request. - /// - /// The returned `headers` resource is immutable: `set`, `append`, and - /// `delete` operations will fail with `header-error.immutable`. - /// - /// This headers resource is a child: it must be dropped before the parent - /// `outgoing-request` is dropped, or its ownership is transfered to - /// another component by e.g. `outgoing-handler.handle`. - headers: func() -> headers; - - /// Set the HTTP Status Code for the Response. Fails if the status-code - /// given is not a valid http status code. - set-status-code: func(status-code: status-code) -> result; - - /// Get the HTTP Status Code for the Response. - status-code: func() -> status-code; - } - - /// Represents an outgoing HTTP Request or Response's Body. - /// - /// A body has both its contents - a stream of bytes - and a (possibly - /// empty) set of trailers, inducating the full contents of the body - /// have been sent. This resource represents the contents as an - /// `output-stream` child resource, and the completion of the body (with - /// optional trailers) with a static function that consumes the - /// `outgoing-body` resource, and ensures that the user of this interface - /// may not write to the body contents after the body has been finished. - /// - /// If the user code drops this resource, as opposed to calling the static - /// method `finish`, the implementation should treat the body as incomplete, - /// and that an error has occured. The implementation should propogate this - /// error to the HTTP protocol by whatever means it has available, - /// including: corrupting the body on the wire, aborting the associated - /// Request, or sending a late status code for the Response. - resource outgoing-body { - - /// Returns a stream for writing the body contents. - /// - /// The returned `output-stream` is a child resource: it must be dropped - /// before the parent `outgoing-body` resource is dropped (or finished), - /// otherwise the `outgoing-body` drop or `finish` will trap. - /// - /// Returns success on the first call: the `output-stream` resource for - /// this `outgoing-body` may be retrieved at most once. Subsequent calls - /// will return error. - write: func() -> result; - - /// Finalize an outgoing body, optionally providing trailers. This must be - /// called to signal that the response is complete. If the `outgoing-body` - /// is dropped without calling `outgoing-body.finalize`, the implementation - /// should treat the body as corrupted. - /// - /// Fails if the body's `outgoing-request` or `outgoing-response` was - /// constructed with a Content-Length header, and the contents written - /// to the body (via `write`) does not match the value given in the - /// Content-Length. - finish: static func(this: outgoing-body, trailers: option) -> result<_, error-code>; - } - - /// Represents a future which may eventaully return an incoming HTTP - /// Response, or an error. - /// - /// This resource is returned by the `wasi:http/outgoing-handler` interface to - /// provide the HTTP Response corresponding to the sent Request. - resource future-incoming-response { - - /// Returns the incoming HTTP Response, or an error, once one is ready. - /// - /// The outer `option` represents future readiness. Users can wait on this - /// `option` to become `some` using the `subscribe` method. - /// - /// The outer `result` is used to retrieve the response or error at most - /// once. It will be success on the first call in which the outer option - /// is `some`, and error on subsequent calls. - /// - /// The inner `result` represents that either the incoming HTTP Response - /// status and headers have recieved successfully, or that an error - /// occured. Errors may also occur while consuming the response body, - /// but those will be reported by the `incoming-body` and its - /// `output-stream` child. - get: func() -> option>>; - - /// Returns a pollable which becomes ready when either the Response has - /// been received, or an error has occured. When this pollable is ready, - /// the `get` method will return `some`. - subscribe: func() -> pollable; - } - - /// Attempts to extract a http-related `error` from the wasi:io `error` - /// provided. - /// - /// Stream operations which return - /// `wasi:io/stream/stream-error::last-operation-failed` have a payload of - /// type `wasi:io/error/error` with more information about the operation - /// that failed. This payload can be passed through to this function to see - /// if there's http-related information about the error to return. - /// - /// Note that this function is fallible because not all io-errors are - /// http-related errors. - http-error-code: func(err: borrow) -> option; - } - - /// This interface defines a handler of incoming HTTP Requests. It should - /// be exported by components which can respond to HTTP Requests. - interface incoming-handler { - use types.{incoming-request}; - use types.{response-outparam}; - - /// This function is invoked with an incoming HTTP Request, and a resource - /// `response-outparam` which provides the capability to reply with an HTTP - /// Response. The response is sent by calling the `response-outparam.set` - /// method, which allows execution to continue after the response has been - /// sent. This enables both streaming to the response body, and performing other - /// work. - /// - /// The implementor of this function must write a response to the - /// `response-outparam` before returning, or else the caller will respond - /// with an error on its behalf. - handle: func(request: incoming-request, response-out: response-outparam); - } - - /// This interface defines a handler of outgoing HTTP Requests. It should be - /// imported by components which wish to make HTTP Requests. - interface outgoing-handler { - use types.{outgoing-request}; - use types.{request-options}; - use types.{future-incoming-response}; - use types.{error-code}; - - /// This function is invoked with an outgoing HTTP Request, and it returns - /// a resource `future-incoming-response` which represents an HTTP Response - /// which may arrive in the future. - /// - /// The `options` argument accepts optional parameters for the HTTP - /// protocol's transport layer. - /// - /// This function may return an error if the `outgoing-request` is invalid - /// or not allowed to be made. Otherwise, protocol errors are reported - /// through the `future-incoming-response`. - handle: func(request: outgoing-request, options: option) -> result; - } - - /// The `wasi:http/proxy` world captures a widely-implementable intersection of - /// hosts that includes HTTP forward and reverse proxies. Components targeting - /// this world may concurrently stream in and out any number of incoming and - /// outgoing HTTP requests. - world proxy { - import wasi:io/poll@0.2.0; - import wasi:clocks/monotonic-clock@0.2.0; - import wasi:io/error@0.2.0; - import wasi:io/streams@0.2.0; - import types; - import wasi:random/random@0.2.0; - import wasi:cli/stdout@0.2.0; - import wasi:cli/stderr@0.2.0; - import wasi:cli/stdin@0.2.0; - import outgoing-handler; - import wasi:clocks/wall-clock@0.2.0; - export incoming-handler; - } -} - package wasi:io@0.2.0 { interface error { /// A resource which represents some error information. @@ -1029,31 +1057,3 @@ package wasi:io@0.2.0 { } } } - -package wasi:random@0.2.0 { - /// WASI Random is a random data API. - /// - /// It is intended to be portable at least between Unix-family platforms and - /// Windows. - interface random { - /// Return `len` cryptographically-secure random or pseudo-random bytes. - /// - /// This function must produce data at least as cryptographically secure and - /// fast as an adequately seeded cryptographically-secure pseudo-random - /// number generator (CSPRNG). It must not block, from the perspective of - /// the calling program, under any circumstances, including on the first - /// request and on requests for numbers of bytes. The returned data must - /// always be unpredictable. - /// - /// This function must always return fresh data. Deterministic environments - /// must omit this function, rather than implementing it with deterministic - /// data. - get-random-bytes: func(len: u64) -> list; - - /// Return a cryptographically-secure random or pseudo-random `u64` value. - /// - /// This function returns the same type of data as `get-random-bytes`, - /// represented as a `u64`. - get-random-u64: func() -> u64; - } -} diff --git a/testdata/wasi/http-minimal.wit.json.golden.wit b/testdata/wasi/http-minimal.wit.json.golden.wit index e6449f5e..12a174b5 100644 --- a/testdata/wasi/http-minimal.wit.json.golden.wit +++ b/testdata/wasi/http-minimal.wit.json.golden.wit @@ -1,18 +1,643 @@ -package wasi:cli@0.2.0; +package wasi:http@0.2.0; -interface stdin { +/// This interface defines all of the types and methods for implementing +/// HTTP Requests and Responses, both incoming and outgoing, as well as +/// their headers, trailers, and bodies. +interface types { + use wasi:clocks/monotonic-clock@0.2.0.{duration}; use wasi:io/streams@0.2.0.{input-stream}; - get-stdin: func() -> input-stream; + use wasi:io/streams@0.2.0.{output-stream}; + use wasi:io/error@0.2.0.{error as io-error}; + use wasi:io/poll@0.2.0.{pollable}; + + /// This type corresponds to HTTP standard Methods. + variant method { + get, + head, + post, + put, + delete, + connect, + options, + trace, + patch, + other(string), + } + + /// This type corresponds to HTTP standard Related Schemes. + variant scheme { HTTP, HTTPS, other(string) } + + /// Defines the case payload type for `DNS-error` above: + record DNS-error-payload { + rcode: option, + info-code: option, + } + + /// Defines the case payload type for `TLS-alert-received` above: + record TLS-alert-received-payload { + alert-id: option, + alert-message: option, + } + + /// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: + record field-size-payload { + field-name: option, + field-size: option, + } + + /// These cases are inspired by the IANA HTTP Proxy Error Types: + /// https://www.iana.org/assignments/http-proxy-status/http-proxy-status.xhtml#table-http-proxy-error-types + variant error-code { + DNS-timeout, + DNS-error(DNS-error-payload), + destination-not-found, + destination-unavailable, + destination-IP-prohibited, + destination-IP-unroutable, + connection-refused, + connection-terminated, + connection-timeout, + connection-read-timeout, + connection-write-timeout, + connection-limit-reached, + TLS-protocol-error, + TLS-certificate-error, + TLS-alert-received(TLS-alert-received-payload), + HTTP-request-denied, + HTTP-request-length-required, + HTTP-request-body-size(option), + HTTP-request-method-invalid, + HTTP-request-URI-invalid, + HTTP-request-URI-too-long, + HTTP-request-header-section-size(option), + HTTP-request-header-size(option), + HTTP-request-trailer-section-size(option), + HTTP-request-trailer-size(field-size-payload), + HTTP-response-incomplete, + HTTP-response-header-section-size(option), + HTTP-response-header-size(field-size-payload), + HTTP-response-body-size(option), + HTTP-response-trailer-section-size(option), + HTTP-response-trailer-size(field-size-payload), + HTTP-response-transfer-coding(option), + HTTP-response-content-coding(option), + HTTP-response-timeout, + HTTP-upgrade-failed, + HTTP-protocol-error, + loop-detected, + configuration-error, + /// This is a catch-all error for anything that doesn't fit cleanly into a + /// more specific case. It also includes an optional string for an + /// unstructured description of the error. Users should not depend on the + /// string for diagnosing errors, as it's not required to be consistent + /// between implementations. + internal-error(option), + } + + /// This type enumerates the different kinds of errors that may occur when + /// setting or appending to a `fields` resource. + variant header-error { + /// This error indicates that a `field-key` or `field-value` was + /// syntactically invalid when used with an operation that sets headers in a + /// `fields`. + invalid-syntax, + /// This error indicates that a forbidden `field-key` was used when trying + /// to set a header in a `fields`. + forbidden, + /// This error indicates that the operation on the `fields` was not + /// permitted because the fields are immutable. + immutable, + } + + /// Field keys are always strings. + type field-key = string; + + /// Field values should always be ASCII strings. However, in + /// reality, HTTP implementations often have to interpret malformed values, + /// so they are provided as a list of bytes. + type field-value = list; + + /// This following block defines the `fields` resource which corresponds to + /// HTTP standard Fields. Fields are a common representation used for both + /// Headers and Trailers. + /// + /// A `fields` may be mutable or immutable. A `fields` created using the + /// constructor, `from-list`, or `clone` will be mutable, but a `fields` + /// resource given by other means (including, but not limited to, + /// `incoming-request.headers`, `outgoing-request.headers`) might be be + /// immutable. In an immutable fields, the `set`, `append`, and `delete` + /// operations will fail with `header-error.immutable`. + resource fields { + /// Construct an empty HTTP Fields. + /// + /// The resulting `fields` is mutable. + constructor(); + + /// Append a value for a key. Does not change or delete any existing + /// values for that key. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-key` or + /// `field-value` are syntactically invalid. + append: func(name: field-key, value: field-value) -> result<_, header-error>; + + /// Make a deep copy of the Fields. Equivelant in behavior to calling the + /// `fields` constructor on the return value of `entries`. The resulting + /// `fields` is mutable. + clone: func() -> fields; + + /// Delete all values for a key. Does nothing if no values for the key + /// exist. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-key` is + /// syntactically invalid. + delete: func(name: field-key) -> result<_, header-error>; + + /// Retrieve the full set of keys and values in the Fields. Like the + /// constructor, the list represents each key-value pair. + /// + /// The outer list represents each key-value pair in the Fields. Keys + /// which have multiple values are represented by multiple entries in this + /// list with the same key. + entries: func() -> list>; + + /// Get all of the values corresponding to a key. If the key is not present + /// in this `fields` or is syntactically invalid, an empty list is returned. + /// However, if the key is present but empty, this is represented by a list + /// with one or more empty field-values present. + get: func(name: field-key) -> list; + + /// Returns `true` when the key is present in this `fields`. If the key is + /// syntactically invalid, `false` is returned. + has: func(name: field-key) -> bool; + + /// Set all of the values for a key. Clears any existing values for that + /// key, if they have been set. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-key` or any of + /// the `field-value`s are syntactically invalid. + set: func(name: field-key, value: list) -> result<_, header-error>; + + /// Construct an HTTP Fields. + /// + /// The resulting `fields` is mutable. + /// + /// The list represents each key-value pair in the Fields. Keys + /// which have multiple values are represented by multiple entries in this + /// list with the same key. + /// + /// The tuple is a pair of the field key, represented as a string, and + /// Value, represented as a list of bytes. + /// + /// An error result will be returned if any `field-key` or `field-value` is + /// syntactically invalid, or if a field is forbidden. + from-list: static func(entries: list>) -> result; + } + + /// Headers is an alias for Fields. + type headers = fields; + + /// Trailers is an alias for Fields. + type trailers = fields; + + /// Represents an incoming HTTP Request. + resource incoming-request { + + /// Returns the authority from the request, if it was present. + authority: func() -> option; + + /// Gives the `incoming-body` associated with this request. Will only + /// return success at most once, and subsequent calls will return error. + consume: func() -> result; + + /// Get the `headers` associated with the request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// The `headers` returned are a child resource: it must be dropped before + /// the parent `incoming-request` is dropped. Dropping this + /// `incoming-request` before all children are dropped will trap. + headers: func() -> headers; + + /// Returns the method of the incoming request. + method: func() -> method; + + /// Returns the path with query parameters from the request, as a string. + path-with-query: func() -> option; + + /// Returns the protocol scheme from the request. + scheme: func() -> option; + } + + /// Represents an outgoing HTTP Request. + resource outgoing-request { + /// Construct a new `outgoing-request` with a default `method` of `GET`, and + /// `none` values for `path-with-query`, `scheme`, and `authority`. + /// + /// * `headers` is the HTTP Headers for the Request. + /// + /// It is possible to construct, or manipulate with the accessor functions + /// below, an `outgoing-request` with an invalid combination of `scheme` + /// and `authority`, or `headers` which are not permitted to be sent. + /// It is the obligation of the `outgoing-handler.handle` implementation + /// to reject invalid constructions of `outgoing-request`. + constructor(headers: headers); + + /// Get the HTTP Authority for the Request. A value of `none` may be used + /// with Related Schemes which do not require an Authority. The HTTP and + /// HTTPS schemes always require an authority. + authority: func() -> option; + + /// Returns the resource corresponding to the outgoing Body for this + /// Request. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-request` can be retrieved at most once. Subsequent + /// calls will return error. + body: func() -> result; + + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transfered to + /// another component by e.g. `outgoing-handler.handle`. + headers: func() -> headers; + + /// Get the Method for the Request. + method: func() -> method; + + /// Get the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. + path-with-query: func() -> option; + + /// Get the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. + scheme: func() -> option; + + /// Set the HTTP Authority for the Request. A value of `none` may be used + /// with Related Schemes which do not require an Authority. The HTTP and + /// HTTPS schemes always require an authority. Fails if the string given is + /// not a syntactically valid uri authority. + set-authority: func(authority: option) -> result; + + /// Set the Method for the Request. Fails if the string present in a + /// `method.other` argument is not a syntactically valid method. + set-method: func(method: method) -> result; + + /// Set the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. Fails is the + /// string given is not a syntactically valid path and query uri component. + set-path-with-query: func(path-with-query: option) -> result; + + /// Set the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. Fails if the + /// string given is not a syntactically valid uri scheme. + set-scheme: func(scheme: option) -> result; + } + + /// Parameters for making an HTTP Request. Each of these parameters is + /// currently an optional timeout applicable to the transport layer of the + /// HTTP protocol. + /// + /// These timeouts are separate from any the user may use to bound a + /// blocking call to `wasi:io/poll.poll`. + resource request-options { + /// Construct a default `request-options` value. + constructor(); + + /// The timeout for receiving subsequent chunks of bytes in the Response + /// body stream. + between-bytes-timeout: func() -> option; + + /// The timeout for the initial connect to the HTTP Server. + connect-timeout: func() -> option; + + /// The timeout for receiving the first byte of the Response body. + first-byte-timeout: func() -> option; + + /// Set the timeout for receiving subsequent chunks of bytes in the Response + /// body stream. An error return value indicates that this timeout is not + /// supported. + set-between-bytes-timeout: func(duration: option) -> result; + + /// Set the timeout for the initial connect to the HTTP Server. An error + /// return value indicates that this timeout is not supported. + set-connect-timeout: func(duration: option) -> result; + + /// Set the timeout for receiving the first byte of the Response body. An + /// error return value indicates that this timeout is not supported. + set-first-byte-timeout: func(duration: option) -> result; + } + + /// Represents the ability to send an HTTP Response. + /// + /// This resource is used by the `wasi:http/incoming-handler` interface to + /// allow a Response to be sent corresponding to the Request provided as the + /// other argument to `incoming-handler.handle`. + resource response-outparam { + + /// Set the value of the `response-outparam` to either send a response, + /// or indicate an error. + /// + /// This method consumes the `response-outparam` to ensure that it is + /// called at most once. If it is never called, the implementation + /// will respond with an error. + /// + /// The user may provide an `error` to `response` to allow the + /// implementation determine how to respond with an HTTP error response. + set: static func(param: response-outparam, response: result); + } + + /// This type corresponds to the HTTP standard Status Code. + type status-code = u16; + + /// Represents an incoming HTTP Response. + resource incoming-response { + + /// Returns the incoming body. May be called at most once. Returns error + /// if called additional times. + consume: func() -> result; + + /// Returns the headers from the incoming response. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `incoming-response` is dropped. + headers: func() -> headers; + + /// Returns the status code from the incoming response. + status: func() -> status-code; + } + + /// Represents an incoming HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, indicating that the full contents of the + /// body have been received. This resource represents the contents as + /// an `input-stream` and the delivery of trailers as a `future-trailers`, + /// and ensures that the user of this interface may only be consuming either + /// the body contents or waiting on trailers at any given time. + resource incoming-body { + + /// Returns the contents of the body, as a stream of bytes. + /// + /// Returns success on first call: the stream representing the contents + /// can be retrieved at most once. Subsequent calls will return error. + /// + /// The returned `input-stream` resource is a child: it must be dropped + /// before the parent `incoming-body` is dropped, or consumed by + /// `incoming-body.finish`. + /// + /// This invariant ensures that the implementation can determine whether + /// the user is consuming the contents of the body, waiting on the + /// `future-trailers` to be ready, or neither. This allows for network + /// backpressure is to be applied when the user is consuming the body, + /// and for that backpressure to not inhibit delivery of the trailers if + /// the user does not read the entire body. + %stream: func() -> result; + + /// Takes ownership of `incoming-body`, and returns a `future-trailers`. + /// This function will trap if the `input-stream` child is still alive. + finish: static func(this: incoming-body) -> future-trailers; + } + + /// Represents a future which may eventaully return trailers, or an error. + /// + /// In the case that the incoming HTTP Request or Response did not have any + /// trailers, this future will resolve to the empty set of trailers once the + /// complete Request or Response body has been received. + resource future-trailers { + + /// Returns the contents of the trailers, or an error which occured, + /// once the future is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the trailers or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the HTTP Request or Response + /// body, as well as any trailers, were received successfully, or that an + /// error occured receiving them. The optional `trailers` indicates whether + /// or not trailers were present in the body. + /// + /// When some `trailers` are returned by this method, the `trailers` + /// resource is immutable, and a child. Use of the `set`, `append`, or + /// `delete` methods will return an error, and the resource must be + /// dropped before the parent `future-trailers` is dropped. + get: func() -> option, error-code>>>; + + /// Returns a pollable which becomes ready when either the trailers have + /// been received, or an error has occured. When this pollable is ready, + /// the `get` method will return `some`. + subscribe: func() -> pollable; + } + + /// Represents an outgoing HTTP Response. + resource outgoing-response { + /// Construct an `outgoing-response`, with a default `status-code` of `200`. + /// If a different `status-code` is needed, it must be set via the + /// `set-status-code` method. + /// + /// * `headers` is the HTTP Headers for the Response. + constructor(headers: headers); + + /// Returns the resource corresponding to the outgoing Body for this Response. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-response` can be retrieved at most once. Subsequent + /// calls will return error. + body: func() -> result; + + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transfered to + /// another component by e.g. `outgoing-handler.handle`. + headers: func() -> headers; + + /// Set the HTTP Status Code for the Response. Fails if the status-code + /// given is not a valid http status code. + set-status-code: func(status-code: status-code) -> result; + + /// Get the HTTP Status Code for the Response. + status-code: func() -> status-code; + } + + /// Represents an outgoing HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, inducating the full contents of the body + /// have been sent. This resource represents the contents as an + /// `output-stream` child resource, and the completion of the body (with + /// optional trailers) with a static function that consumes the + /// `outgoing-body` resource, and ensures that the user of this interface + /// may not write to the body contents after the body has been finished. + /// + /// If the user code drops this resource, as opposed to calling the static + /// method `finish`, the implementation should treat the body as incomplete, + /// and that an error has occured. The implementation should propogate this + /// error to the HTTP protocol by whatever means it has available, + /// including: corrupting the body on the wire, aborting the associated + /// Request, or sending a late status code for the Response. + resource outgoing-body { + + /// Returns a stream for writing the body contents. + /// + /// The returned `output-stream` is a child resource: it must be dropped + /// before the parent `outgoing-body` resource is dropped (or finished), + /// otherwise the `outgoing-body` drop or `finish` will trap. + /// + /// Returns success on the first call: the `output-stream` resource for + /// this `outgoing-body` may be retrieved at most once. Subsequent calls + /// will return error. + write: func() -> result; + + /// Finalize an outgoing body, optionally providing trailers. This must be + /// called to signal that the response is complete. If the `outgoing-body` + /// is dropped without calling `outgoing-body.finalize`, the implementation + /// should treat the body as corrupted. + /// + /// Fails if the body's `outgoing-request` or `outgoing-response` was + /// constructed with a Content-Length header, and the contents written + /// to the body (via `write`) does not match the value given in the + /// Content-Length. + finish: static func(this: outgoing-body, trailers: option) -> result<_, error-code>; + } + + /// Represents a future which may eventaully return an incoming HTTP + /// Response, or an error. + /// + /// This resource is returned by the `wasi:http/outgoing-handler` interface to + /// provide the HTTP Response corresponding to the sent Request. + resource future-incoming-response { + + /// Returns the incoming HTTP Response, or an error, once one is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the response or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the incoming HTTP Response + /// status and headers have recieved successfully, or that an error + /// occured. Errors may also occur while consuming the response body, + /// but those will be reported by the `incoming-body` and its + /// `output-stream` child. + get: func() -> option>>; + + /// Returns a pollable which becomes ready when either the Response has + /// been received, or an error has occured. When this pollable is ready, + /// the `get` method will return `some`. + subscribe: func() -> pollable; + } + + /// Attempts to extract a http-related `error` from the wasi:io `error` + /// provided. + /// + /// Stream operations which return + /// `wasi:io/stream/stream-error::last-operation-failed` have a payload of + /// type `wasi:io/error/error` with more information about the operation + /// that failed. This payload can be passed through to this function to see + /// if there's http-related information about the error to return. + /// + /// Note that this function is fallible because not all io-errors are + /// http-related errors. + http-error-code: func(err: borrow) -> option; } -interface stdout { - use wasi:io/streams@0.2.0.{output-stream}; - get-stdout: func() -> output-stream; +/// This interface defines a handler of incoming HTTP Requests. It should +/// be exported by components which can respond to HTTP Requests. +interface incoming-handler { + use types.{incoming-request}; + use types.{response-outparam}; + + /// This function is invoked with an incoming HTTP Request, and a resource + /// `response-outparam` which provides the capability to reply with an HTTP + /// Response. The response is sent by calling the `response-outparam.set` + /// method, which allows execution to continue after the response has been + /// sent. This enables both streaming to the response body, and performing other + /// work. + /// + /// The implementor of this function must write a response to the + /// `response-outparam` before returning, or else the caller will respond + /// with an error on its behalf. + handle: func(request: incoming-request, response-out: response-outparam); } -interface stderr { - use wasi:io/streams@0.2.0.{output-stream}; - get-stderr: func() -> output-stream; +/// This interface defines a handler of outgoing HTTP Requests. It should be +/// imported by components which wish to make HTTP Requests. +interface outgoing-handler { + use types.{outgoing-request}; + use types.{request-options}; + use types.{future-incoming-response}; + use types.{error-code}; + + /// This function is invoked with an outgoing HTTP Request, and it returns + /// a resource `future-incoming-response` which represents an HTTP Response + /// which may arrive in the future. + /// + /// The `options` argument accepts optional parameters for the HTTP + /// protocol's transport layer. + /// + /// This function may return an error if the `outgoing-request` is invalid + /// or not allowed to be made. Otherwise, protocol errors are reported + /// through the `future-incoming-response`. + handle: func(request: outgoing-request, options: option) -> result; +} + +/// The `wasi:http/proxy` world captures a widely-implementable intersection of +/// hosts that includes HTTP forward and reverse proxies. Components targeting +/// this world may concurrently stream in and out any number of incoming and +/// outgoing HTTP requests. +world proxy { + import wasi:io/poll@0.2.0; + import wasi:clocks/monotonic-clock@0.2.0; + import wasi:io/error@0.2.0; + import wasi:io/streams@0.2.0; + import types; + import wasi:random/random@0.2.0; + import wasi:cli/stdout@0.2.0; + import wasi:cli/stderr@0.2.0; + import wasi:cli/stdin@0.2.0; + import outgoing-handler; + import wasi:clocks/wall-clock@0.2.0; + export incoming-handler; +} + +package wasi:cli@0.2.0 { + interface stdin { + use wasi:io/streams@0.2.0.{input-stream}; + get-stdin: func() -> input-stream; + } + + interface stdout { + use wasi:io/streams@0.2.0.{output-stream}; + get-stdout: func() -> output-stream; + } + + interface stderr { + use wasi:io/streams@0.2.0.{output-stream}; + get-stderr: func() -> output-stream; + } } package wasi:clocks@0.2.0 { @@ -100,631 +725,6 @@ package wasi:clocks@0.2.0 { } } -package wasi:http@0.2.0 { - /// This interface defines all of the types and methods for implementing - /// HTTP Requests and Responses, both incoming and outgoing, as well as - /// their headers, trailers, and bodies. - interface types { - use wasi:clocks/monotonic-clock@0.2.0.{duration}; - use wasi:io/streams@0.2.0.{input-stream}; - use wasi:io/streams@0.2.0.{output-stream}; - use wasi:io/error@0.2.0.{error as io-error}; - use wasi:io/poll@0.2.0.{pollable}; - - /// This type corresponds to HTTP standard Methods. - variant method { - get, - head, - post, - put, - delete, - connect, - options, - trace, - patch, - other(string), - } - - /// This type corresponds to HTTP standard Related Schemes. - variant scheme { HTTP, HTTPS, other(string) } - - /// Defines the case payload type for `DNS-error` above: - record DNS-error-payload { - rcode: option, - info-code: option, - } - - /// Defines the case payload type for `TLS-alert-received` above: - record TLS-alert-received-payload { - alert-id: option, - alert-message: option, - } - - /// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: - record field-size-payload { - field-name: option, - field-size: option, - } - - /// These cases are inspired by the IANA HTTP Proxy Error Types: - /// https://www.iana.org/assignments/http-proxy-status/http-proxy-status.xhtml#table-http-proxy-error-types - variant error-code { - DNS-timeout, - DNS-error(DNS-error-payload), - destination-not-found, - destination-unavailable, - destination-IP-prohibited, - destination-IP-unroutable, - connection-refused, - connection-terminated, - connection-timeout, - connection-read-timeout, - connection-write-timeout, - connection-limit-reached, - TLS-protocol-error, - TLS-certificate-error, - TLS-alert-received(TLS-alert-received-payload), - HTTP-request-denied, - HTTP-request-length-required, - HTTP-request-body-size(option), - HTTP-request-method-invalid, - HTTP-request-URI-invalid, - HTTP-request-URI-too-long, - HTTP-request-header-section-size(option), - HTTP-request-header-size(option), - HTTP-request-trailer-section-size(option), - HTTP-request-trailer-size(field-size-payload), - HTTP-response-incomplete, - HTTP-response-header-section-size(option), - HTTP-response-header-size(field-size-payload), - HTTP-response-body-size(option), - HTTP-response-trailer-section-size(option), - HTTP-response-trailer-size(field-size-payload), - HTTP-response-transfer-coding(option), - HTTP-response-content-coding(option), - HTTP-response-timeout, - HTTP-upgrade-failed, - HTTP-protocol-error, - loop-detected, - configuration-error, - /// This is a catch-all error for anything that doesn't fit cleanly into a - /// more specific case. It also includes an optional string for an - /// unstructured description of the error. Users should not depend on the - /// string for diagnosing errors, as it's not required to be consistent - /// between implementations. - internal-error(option), - } - - /// This type enumerates the different kinds of errors that may occur when - /// setting or appending to a `fields` resource. - variant header-error { - /// This error indicates that a `field-key` or `field-value` was - /// syntactically invalid when used with an operation that sets headers in a - /// `fields`. - invalid-syntax, - /// This error indicates that a forbidden `field-key` was used when trying - /// to set a header in a `fields`. - forbidden, - /// This error indicates that the operation on the `fields` was not - /// permitted because the fields are immutable. - immutable, - } - - /// Field keys are always strings. - type field-key = string; - - /// Field values should always be ASCII strings. However, in - /// reality, HTTP implementations often have to interpret malformed values, - /// so they are provided as a list of bytes. - type field-value = list; - - /// This following block defines the `fields` resource which corresponds to - /// HTTP standard Fields. Fields are a common representation used for both - /// Headers and Trailers. - /// - /// A `fields` may be mutable or immutable. A `fields` created using the - /// constructor, `from-list`, or `clone` will be mutable, but a `fields` - /// resource given by other means (including, but not limited to, - /// `incoming-request.headers`, `outgoing-request.headers`) might be be - /// immutable. In an immutable fields, the `set`, `append`, and `delete` - /// operations will fail with `header-error.immutable`. - resource fields { - /// Construct an empty HTTP Fields. - /// - /// The resulting `fields` is mutable. - constructor(); - - /// Append a value for a key. Does not change or delete any existing - /// values for that key. - /// - /// Fails with `header-error.immutable` if the `fields` are immutable. - /// - /// Fails with `header-error.invalid-syntax` if the `field-key` or - /// `field-value` are syntactically invalid. - append: func(name: field-key, value: field-value) -> result<_, header-error>; - - /// Make a deep copy of the Fields. Equivelant in behavior to calling the - /// `fields` constructor on the return value of `entries`. The resulting - /// `fields` is mutable. - clone: func() -> fields; - - /// Delete all values for a key. Does nothing if no values for the key - /// exist. - /// - /// Fails with `header-error.immutable` if the `fields` are immutable. - /// - /// Fails with `header-error.invalid-syntax` if the `field-key` is - /// syntactically invalid. - delete: func(name: field-key) -> result<_, header-error>; - - /// Retrieve the full set of keys and values in the Fields. Like the - /// constructor, the list represents each key-value pair. - /// - /// The outer list represents each key-value pair in the Fields. Keys - /// which have multiple values are represented by multiple entries in this - /// list with the same key. - entries: func() -> list>; - - /// Get all of the values corresponding to a key. If the key is not present - /// in this `fields` or is syntactically invalid, an empty list is returned. - /// However, if the key is present but empty, this is represented by a list - /// with one or more empty field-values present. - get: func(name: field-key) -> list; - - /// Returns `true` when the key is present in this `fields`. If the key is - /// syntactically invalid, `false` is returned. - has: func(name: field-key) -> bool; - - /// Set all of the values for a key. Clears any existing values for that - /// key, if they have been set. - /// - /// Fails with `header-error.immutable` if the `fields` are immutable. - /// - /// Fails with `header-error.invalid-syntax` if the `field-key` or any of - /// the `field-value`s are syntactically invalid. - set: func(name: field-key, value: list) -> result<_, header-error>; - - /// Construct an HTTP Fields. - /// - /// The resulting `fields` is mutable. - /// - /// The list represents each key-value pair in the Fields. Keys - /// which have multiple values are represented by multiple entries in this - /// list with the same key. - /// - /// The tuple is a pair of the field key, represented as a string, and - /// Value, represented as a list of bytes. - /// - /// An error result will be returned if any `field-key` or `field-value` is - /// syntactically invalid, or if a field is forbidden. - from-list: static func(entries: list>) -> result; - } - - /// Headers is an alias for Fields. - type headers = fields; - - /// Trailers is an alias for Fields. - type trailers = fields; - - /// Represents an incoming HTTP Request. - resource incoming-request { - - /// Returns the authority from the request, if it was present. - authority: func() -> option; - - /// Gives the `incoming-body` associated with this request. Will only - /// return success at most once, and subsequent calls will return error. - consume: func() -> result; - - /// Get the `headers` associated with the request. - /// - /// The returned `headers` resource is immutable: `set`, `append`, and - /// `delete` operations will fail with `header-error.immutable`. - /// - /// The `headers` returned are a child resource: it must be dropped before - /// the parent `incoming-request` is dropped. Dropping this - /// `incoming-request` before all children are dropped will trap. - headers: func() -> headers; - - /// Returns the method of the incoming request. - method: func() -> method; - - /// Returns the path with query parameters from the request, as a string. - path-with-query: func() -> option; - - /// Returns the protocol scheme from the request. - scheme: func() -> option; - } - - /// Represents an outgoing HTTP Request. - resource outgoing-request { - /// Construct a new `outgoing-request` with a default `method` of `GET`, and - /// `none` values for `path-with-query`, `scheme`, and `authority`. - /// - /// * `headers` is the HTTP Headers for the Request. - /// - /// It is possible to construct, or manipulate with the accessor functions - /// below, an `outgoing-request` with an invalid combination of `scheme` - /// and `authority`, or `headers` which are not permitted to be sent. - /// It is the obligation of the `outgoing-handler.handle` implementation - /// to reject invalid constructions of `outgoing-request`. - constructor(headers: headers); - - /// Get the HTTP Authority for the Request. A value of `none` may be used - /// with Related Schemes which do not require an Authority. The HTTP and - /// HTTPS schemes always require an authority. - authority: func() -> option; - - /// Returns the resource corresponding to the outgoing Body for this - /// Request. - /// - /// Returns success on the first call: the `outgoing-body` resource for - /// this `outgoing-request` can be retrieved at most once. Subsequent - /// calls will return error. - body: func() -> result; - - /// Get the headers associated with the Request. - /// - /// The returned `headers` resource is immutable: `set`, `append`, and - /// `delete` operations will fail with `header-error.immutable`. - /// - /// This headers resource is a child: it must be dropped before the parent - /// `outgoing-request` is dropped, or its ownership is transfered to - /// another component by e.g. `outgoing-handler.handle`. - headers: func() -> headers; - - /// Get the Method for the Request. - method: func() -> method; - - /// Get the combination of the HTTP Path and Query for the Request. - /// When `none`, this represents an empty Path and empty Query. - path-with-query: func() -> option; - - /// Get the HTTP Related Scheme for the Request. When `none`, the - /// implementation may choose an appropriate default scheme. - scheme: func() -> option; - - /// Set the HTTP Authority for the Request. A value of `none` may be used - /// with Related Schemes which do not require an Authority. The HTTP and - /// HTTPS schemes always require an authority. Fails if the string given is - /// not a syntactically valid uri authority. - set-authority: func(authority: option) -> result; - - /// Set the Method for the Request. Fails if the string present in a - /// `method.other` argument is not a syntactically valid method. - set-method: func(method: method) -> result; - - /// Set the combination of the HTTP Path and Query for the Request. - /// When `none`, this represents an empty Path and empty Query. Fails is the - /// string given is not a syntactically valid path and query uri component. - set-path-with-query: func(path-with-query: option) -> result; - - /// Set the HTTP Related Scheme for the Request. When `none`, the - /// implementation may choose an appropriate default scheme. Fails if the - /// string given is not a syntactically valid uri scheme. - set-scheme: func(scheme: option) -> result; - } - - /// Parameters for making an HTTP Request. Each of these parameters is - /// currently an optional timeout applicable to the transport layer of the - /// HTTP protocol. - /// - /// These timeouts are separate from any the user may use to bound a - /// blocking call to `wasi:io/poll.poll`. - resource request-options { - /// Construct a default `request-options` value. - constructor(); - - /// The timeout for receiving subsequent chunks of bytes in the Response - /// body stream. - between-bytes-timeout: func() -> option; - - /// The timeout for the initial connect to the HTTP Server. - connect-timeout: func() -> option; - - /// The timeout for receiving the first byte of the Response body. - first-byte-timeout: func() -> option; - - /// Set the timeout for receiving subsequent chunks of bytes in the Response - /// body stream. An error return value indicates that this timeout is not - /// supported. - set-between-bytes-timeout: func(duration: option) -> result; - - /// Set the timeout for the initial connect to the HTTP Server. An error - /// return value indicates that this timeout is not supported. - set-connect-timeout: func(duration: option) -> result; - - /// Set the timeout for receiving the first byte of the Response body. An - /// error return value indicates that this timeout is not supported. - set-first-byte-timeout: func(duration: option) -> result; - } - - /// Represents the ability to send an HTTP Response. - /// - /// This resource is used by the `wasi:http/incoming-handler` interface to - /// allow a Response to be sent corresponding to the Request provided as the - /// other argument to `incoming-handler.handle`. - resource response-outparam { - - /// Set the value of the `response-outparam` to either send a response, - /// or indicate an error. - /// - /// This method consumes the `response-outparam` to ensure that it is - /// called at most once. If it is never called, the implementation - /// will respond with an error. - /// - /// The user may provide an `error` to `response` to allow the - /// implementation determine how to respond with an HTTP error response. - set: static func(param: response-outparam, response: result); - } - - /// This type corresponds to the HTTP standard Status Code. - type status-code = u16; - - /// Represents an incoming HTTP Response. - resource incoming-response { - - /// Returns the incoming body. May be called at most once. Returns error - /// if called additional times. - consume: func() -> result; - - /// Returns the headers from the incoming response. - /// - /// The returned `headers` resource is immutable: `set`, `append`, and - /// `delete` operations will fail with `header-error.immutable`. - /// - /// This headers resource is a child: it must be dropped before the parent - /// `incoming-response` is dropped. - headers: func() -> headers; - - /// Returns the status code from the incoming response. - status: func() -> status-code; - } - - /// Represents an incoming HTTP Request or Response's Body. - /// - /// A body has both its contents - a stream of bytes - and a (possibly - /// empty) set of trailers, indicating that the full contents of the - /// body have been received. This resource represents the contents as - /// an `input-stream` and the delivery of trailers as a `future-trailers`, - /// and ensures that the user of this interface may only be consuming either - /// the body contents or waiting on trailers at any given time. - resource incoming-body { - - /// Returns the contents of the body, as a stream of bytes. - /// - /// Returns success on first call: the stream representing the contents - /// can be retrieved at most once. Subsequent calls will return error. - /// - /// The returned `input-stream` resource is a child: it must be dropped - /// before the parent `incoming-body` is dropped, or consumed by - /// `incoming-body.finish`. - /// - /// This invariant ensures that the implementation can determine whether - /// the user is consuming the contents of the body, waiting on the - /// `future-trailers` to be ready, or neither. This allows for network - /// backpressure is to be applied when the user is consuming the body, - /// and for that backpressure to not inhibit delivery of the trailers if - /// the user does not read the entire body. - %stream: func() -> result; - - /// Takes ownership of `incoming-body`, and returns a `future-trailers`. - /// This function will trap if the `input-stream` child is still alive. - finish: static func(this: incoming-body) -> future-trailers; - } - - /// Represents a future which may eventaully return trailers, or an error. - /// - /// In the case that the incoming HTTP Request or Response did not have any - /// trailers, this future will resolve to the empty set of trailers once the - /// complete Request or Response body has been received. - resource future-trailers { - - /// Returns the contents of the trailers, or an error which occured, - /// once the future is ready. - /// - /// The outer `option` represents future readiness. Users can wait on this - /// `option` to become `some` using the `subscribe` method. - /// - /// The outer `result` is used to retrieve the trailers or error at most - /// once. It will be success on the first call in which the outer option - /// is `some`, and error on subsequent calls. - /// - /// The inner `result` represents that either the HTTP Request or Response - /// body, as well as any trailers, were received successfully, or that an - /// error occured receiving them. The optional `trailers` indicates whether - /// or not trailers were present in the body. - /// - /// When some `trailers` are returned by this method, the `trailers` - /// resource is immutable, and a child. Use of the `set`, `append`, or - /// `delete` methods will return an error, and the resource must be - /// dropped before the parent `future-trailers` is dropped. - get: func() -> option, error-code>>>; - - /// Returns a pollable which becomes ready when either the trailers have - /// been received, or an error has occured. When this pollable is ready, - /// the `get` method will return `some`. - subscribe: func() -> pollable; - } - - /// Represents an outgoing HTTP Response. - resource outgoing-response { - /// Construct an `outgoing-response`, with a default `status-code` of `200`. - /// If a different `status-code` is needed, it must be set via the - /// `set-status-code` method. - /// - /// * `headers` is the HTTP Headers for the Response. - constructor(headers: headers); - - /// Returns the resource corresponding to the outgoing Body for this Response. - /// - /// Returns success on the first call: the `outgoing-body` resource for - /// this `outgoing-response` can be retrieved at most once. Subsequent - /// calls will return error. - body: func() -> result; - - /// Get the headers associated with the Request. - /// - /// The returned `headers` resource is immutable: `set`, `append`, and - /// `delete` operations will fail with `header-error.immutable`. - /// - /// This headers resource is a child: it must be dropped before the parent - /// `outgoing-request` is dropped, or its ownership is transfered to - /// another component by e.g. `outgoing-handler.handle`. - headers: func() -> headers; - - /// Set the HTTP Status Code for the Response. Fails if the status-code - /// given is not a valid http status code. - set-status-code: func(status-code: status-code) -> result; - - /// Get the HTTP Status Code for the Response. - status-code: func() -> status-code; - } - - /// Represents an outgoing HTTP Request or Response's Body. - /// - /// A body has both its contents - a stream of bytes - and a (possibly - /// empty) set of trailers, inducating the full contents of the body - /// have been sent. This resource represents the contents as an - /// `output-stream` child resource, and the completion of the body (with - /// optional trailers) with a static function that consumes the - /// `outgoing-body` resource, and ensures that the user of this interface - /// may not write to the body contents after the body has been finished. - /// - /// If the user code drops this resource, as opposed to calling the static - /// method `finish`, the implementation should treat the body as incomplete, - /// and that an error has occured. The implementation should propogate this - /// error to the HTTP protocol by whatever means it has available, - /// including: corrupting the body on the wire, aborting the associated - /// Request, or sending a late status code for the Response. - resource outgoing-body { - - /// Returns a stream for writing the body contents. - /// - /// The returned `output-stream` is a child resource: it must be dropped - /// before the parent `outgoing-body` resource is dropped (or finished), - /// otherwise the `outgoing-body` drop or `finish` will trap. - /// - /// Returns success on the first call: the `output-stream` resource for - /// this `outgoing-body` may be retrieved at most once. Subsequent calls - /// will return error. - write: func() -> result; - - /// Finalize an outgoing body, optionally providing trailers. This must be - /// called to signal that the response is complete. If the `outgoing-body` - /// is dropped without calling `outgoing-body.finalize`, the implementation - /// should treat the body as corrupted. - /// - /// Fails if the body's `outgoing-request` or `outgoing-response` was - /// constructed with a Content-Length header, and the contents written - /// to the body (via `write`) does not match the value given in the - /// Content-Length. - finish: static func(this: outgoing-body, trailers: option) -> result<_, error-code>; - } - - /// Represents a future which may eventaully return an incoming HTTP - /// Response, or an error. - /// - /// This resource is returned by the `wasi:http/outgoing-handler` interface to - /// provide the HTTP Response corresponding to the sent Request. - resource future-incoming-response { - - /// Returns the incoming HTTP Response, or an error, once one is ready. - /// - /// The outer `option` represents future readiness. Users can wait on this - /// `option` to become `some` using the `subscribe` method. - /// - /// The outer `result` is used to retrieve the response or error at most - /// once. It will be success on the first call in which the outer option - /// is `some`, and error on subsequent calls. - /// - /// The inner `result` represents that either the incoming HTTP Response - /// status and headers have recieved successfully, or that an error - /// occured. Errors may also occur while consuming the response body, - /// but those will be reported by the `incoming-body` and its - /// `output-stream` child. - get: func() -> option>>; - - /// Returns a pollable which becomes ready when either the Response has - /// been received, or an error has occured. When this pollable is ready, - /// the `get` method will return `some`. - subscribe: func() -> pollable; - } - - /// Attempts to extract a http-related `error` from the wasi:io `error` - /// provided. - /// - /// Stream operations which return - /// `wasi:io/stream/stream-error::last-operation-failed` have a payload of - /// type `wasi:io/error/error` with more information about the operation - /// that failed. This payload can be passed through to this function to see - /// if there's http-related information about the error to return. - /// - /// Note that this function is fallible because not all io-errors are - /// http-related errors. - http-error-code: func(err: borrow) -> option; - } - - /// This interface defines a handler of incoming HTTP Requests. It should - /// be exported by components which can respond to HTTP Requests. - interface incoming-handler { - use types.{incoming-request}; - use types.{response-outparam}; - - /// This function is invoked with an incoming HTTP Request, and a resource - /// `response-outparam` which provides the capability to reply with an HTTP - /// Response. The response is sent by calling the `response-outparam.set` - /// method, which allows execution to continue after the response has been - /// sent. This enables both streaming to the response body, and performing other - /// work. - /// - /// The implementor of this function must write a response to the - /// `response-outparam` before returning, or else the caller will respond - /// with an error on its behalf. - handle: func(request: incoming-request, response-out: response-outparam); - } - - /// This interface defines a handler of outgoing HTTP Requests. It should be - /// imported by components which wish to make HTTP Requests. - interface outgoing-handler { - use types.{outgoing-request}; - use types.{request-options}; - use types.{future-incoming-response}; - use types.{error-code}; - - /// This function is invoked with an outgoing HTTP Request, and it returns - /// a resource `future-incoming-response` which represents an HTTP Response - /// which may arrive in the future. - /// - /// The `options` argument accepts optional parameters for the HTTP - /// protocol's transport layer. - /// - /// This function may return an error if the `outgoing-request` is invalid - /// or not allowed to be made. Otherwise, protocol errors are reported - /// through the `future-incoming-response`. - handle: func(request: outgoing-request, options: option) -> result; - } - - /// The `wasi:http/proxy` world captures a widely-implementable intersection of - /// hosts that includes HTTP forward and reverse proxies. Components targeting - /// this world may concurrently stream in and out any number of incoming and - /// outgoing HTTP requests. - world proxy { - import wasi:io/poll@0.2.0; - import wasi:clocks/monotonic-clock@0.2.0; - import wasi:io/error@0.2.0; - import wasi:io/streams@0.2.0; - import types; - import wasi:random/random@0.2.0; - import wasi:cli/stdout@0.2.0; - import wasi:cli/stderr@0.2.0; - import wasi:cli/stdin@0.2.0; - import outgoing-handler; - import wasi:clocks/wall-clock@0.2.0; - export incoming-handler; - } -} - package wasi:io@0.2.0 { interface error { /// A resource which represents some error information. diff --git a/testdata/wasi/http.wit.json.golden.wit b/testdata/wasi/http.wit.json.golden.wit index ec478e6f..f3c7e5d6 100644 --- a/testdata/wasi/http.wit.json.golden.wit +++ b/testdata/wasi/http.wit.json.golden.wit @@ -155,97 +155,6 @@ world command { export run; } -package wasi:clocks@0.2.0 { - /// WASI Monotonic Clock is a clock API intended to let users measure elapsed - /// time. - /// - /// It is intended to be portable at least between Unix-family platforms and - /// Windows. - /// - /// A monotonic clock is a clock which has an unspecified initial value, and - /// successive reads of the clock will produce non-decreasing values. - /// - /// It is intended for measuring elapsed time. - interface monotonic-clock { - use wasi:io/poll@0.2.0.{pollable}; - - /// An instant in time, in nanoseconds. An instant is relative to an - /// unspecified initial value, and can only be compared to instances from - /// the same monotonic-clock. - type instant = u64; - - /// A duration of time, in nanoseconds. - type duration = u64; - - /// Read the current value of the clock. - /// - /// The clock is monotonic, therefore calling this function repeatedly will - /// produce a sequence of non-decreasing values. - now: func() -> instant; - - /// Query the resolution of the clock. Returns the duration of time - /// corresponding to a clock tick. - resolution: func() -> duration; - - /// Create a `pollable` which will resolve once the specified instant - /// occured. - subscribe-instant: func(when: instant) -> pollable; - - /// Create a `pollable` which will resolve once the given duration has - /// elapsed, starting at the time at which this function was called. - /// occured. - subscribe-duration: func(when: duration) -> pollable; - } - - /// WASI Wall Clock is a clock API intended to let users query the current - /// time. The name "wall" makes an analogy to a "clock on the wall", which - /// is not necessarily monotonic as it may be reset. - /// - /// It is intended to be portable at least between Unix-family platforms and - /// Windows. - /// - /// A wall clock is a clock which measures the date and time according to - /// some external reference. - /// - /// External references may be reset, so this clock is not necessarily - /// monotonic, making it unsuitable for measuring elapsed time. - /// - /// It is intended for reporting the current date and time for humans. - interface wall-clock { - /// A time and date in seconds plus nanoseconds. - record datetime { - seconds: u64, - nanoseconds: u32, - } - - /// Read the current value of the clock. - /// - /// This clock is not monotonic, therefore calling this function repeatedly - /// will not necessarily produce a sequence of non-decreasing values. - /// - /// The returned timestamps represent the number of seconds since - /// 1970-01-01T00:00:00Z, also known as [POSIX's Seconds Since the Epoch], - /// also known as [Unix Time]. - /// - /// The nanoseconds field of the output is always less than 1000000000. - /// - /// [POSIX's Seconds Since the Epoch]: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html#tag_21_04_16 - /// [Unix Time]: https://en.wikipedia.org/wiki/Unix_time - now: func() -> datetime; - - /// Query the resolution of the clock. - /// - /// The nanoseconds field of the output is always less than 1000000000. - resolution: func() -> datetime; - } - - world imports { - import wasi:io/poll@0.2.0; - import monotonic-clock; - import wall-clock; - } -} - package wasi:filesystem@0.2.0 { /// WASI filesystem is a filesystem API primarily intended to let users run WASI /// programs that access their files on their existing filesystems, without @@ -1454,729 +1363,665 @@ package wasi:http@0.2.0 { } } -package wasi:io@0.2.0 { - interface error { - /// A resource which represents some error information. - /// - /// The only method provided by this resource is `to-debug-string`, - /// which provides some human-readable information about the error. - /// - /// In the `wasi:io` package, this resource is returned through the - /// `wasi:io/streams/stream-error` type. +package wasi:sockets@0.2.0 { + interface network { + /// An opaque resource that represents access to (a subset of) the network. + /// This enables context-based security for networking. + /// There is no need for this to map 1:1 to a physical network interface. + resource network; + + /// Error codes. /// - /// To provide more specific error information, other interfaces may - /// provide functions to further "downcast" this error into more specific - /// error information. For example, `error`s returned in streams derived - /// from filesystem types to be described using the filesystem's own - /// error-code type, using the function - /// `wasi:filesystem/types/filesystem-error-code`, which takes a parameter - /// `borrow` and returns - /// `option`. + /// In theory, every API can return any error code. + /// In practice, API's typically only return the errors documented per API + /// combined with a couple of errors that are always possible: + /// - `unknown` + /// - `access-denied` + /// - `not-supported` + /// - `out-of-memory` + /// - `concurrency-conflict` /// - /// The set of functions which can "downcast" an `error` into a more - /// concrete type is open. - resource error { - - /// Returns a string that is suitable to assist humans in debugging - /// this error. + /// See each individual API for what the POSIX equivalents are. They sometimes differ + /// per API. + enum error-code { + /// Unknown error + unknown, + /// Access denied. /// - /// WARNING: The returned string should not be consumed mechanically! - /// It may change across platforms, hosts, or other implementation - /// details. Parsing this string is a major platform-compatibility - /// hazard. - to-debug-string: func() -> string; - } - } - - /// A poll API intended to let users wait for I/O events on multiple handles - /// at once. - interface poll { - /// `pollable` represents a single I/O event which may be ready, or not. - resource pollable { - - /// `block` returns immediately if the pollable is ready, and otherwise - /// blocks until ready. + /// POSIX equivalent: EACCES, EPERM + access-denied, + /// The operation is not supported. /// - /// This function is equivalent to calling `poll.poll` on a list - /// containing only this pollable. - block: func(); - - /// Return the readiness of a pollable. This function never blocks. + /// POSIX equivalent: EOPNOTSUPP + not-supported, + /// One of the arguments is invalid. /// - /// Returns `true` when the pollable is ready, and `false` otherwise. - ready: func() -> bool; - } - - /// Poll for completion on a set of pollables. - /// - /// This function takes a list of pollables, which identify I/O sources of - /// interest, and waits until one or more of the events is ready for I/O. - /// - /// The result `list` contains one or more indices of handles in the - /// argument list that is ready for I/O. - /// - /// If the list contains more elements than can be indexed with a `u32` - /// value, this function traps. - /// - /// A timeout can be implemented by adding a pollable from the - /// wasi-clocks API to the list. - /// - /// This function does not return a `result`; polling in itself does not - /// do any I/O so it doesn't fail. If any of the I/O sources identified by - /// the pollables has an error, it is indicated by marking the source as - /// being reaedy for I/O. - poll: func(in: list>) -> list; - } - - /// WASI I/O is an I/O abstraction API which is currently focused on providing - /// stream types. - /// - /// In the future, the component model is expected to add built-in stream types; - /// when it does, they are expected to subsume this API. - interface streams { - use error.{error}; - use poll.{pollable}; - - /// An error for input-stream and output-stream operations. - variant stream-error { - /// The last operation (a write or flush) failed before completion. + /// POSIX equivalent: EINVAL + invalid-argument, + /// Not enough memory to complete the operation. /// - /// More information is available in the `error` payload. - last-operation-failed(error), - /// The stream is closed: no more input will be accepted by the - /// stream. A closed output-stream will return this error on all - /// future operations. - closed, - } - - /// An input bytestream. - /// - /// `input-stream`s are *non-blocking* to the extent practical on underlying - /// platforms. I/O operations always return promptly; if fewer bytes are - /// promptly available than requested, they return the number of bytes promptly - /// available, which could even be zero. To wait for data to be available, - /// use the `subscribe` function to obtain a `pollable` which can be polled - /// for using `wasi:io/poll`. - resource input-stream { - - /// Read bytes from a stream, after blocking until at least one byte can - /// be read. Except for blocking, behavior is identical to `read`. - blocking-read: func(len: u64) -> result, stream-error>; - - /// Skip bytes from a stream, after blocking until at least one byte - /// can be skipped. Except for blocking behavior, identical to `skip`. - blocking-skip: func(len: u64) -> result; - - /// Perform a non-blocking read from the stream. + /// POSIX equivalent: ENOMEM, ENOBUFS, EAI_MEMORY + out-of-memory, + /// The operation timed out before it could finish completely. + timeout, + /// This operation is incompatible with another asynchronous operation that is already + /// in progress. /// - /// When the source of a `read` is binary data, the bytes from the source - /// are returned verbatim. When the source of a `read` is known to the - /// implementation to be text, bytes containing the UTF-8 encoding of the - /// text are returned. + /// POSIX equivalent: EALREADY + concurrency-conflict, + /// Trying to finish an asynchronous operation that: + /// - has not been started yet, or: + /// - was already finished by a previous `finish-*` call. /// - /// This function returns a list of bytes containing the read data, - /// when successful. The returned list will contain up to `len` bytes; - /// it may return fewer than requested, but not more. The list is - /// empty when no bytes are available for reading at this time. The - /// pollable given by `subscribe` will be ready when more bytes are - /// available. + /// Note: this is scheduled to be removed when `future`s are natively supported. + not-in-progress, + /// The operation has been aborted because it could not be completed immediately. /// - /// This function fails with a `stream-error` when the operation - /// encounters an error, giving `last-operation-failed`, or when the - /// stream is closed, giving `closed`. + /// Note: this is scheduled to be removed when `future`s are natively supported. + would-block, + /// The operation is not valid in the socket's current state. + invalid-state, + /// A new socket resource could not be created because of a system limit. + new-socket-limit, + /// A bind operation failed because the provided address is not an address that the + /// `network` can bind to. + address-not-bindable, + /// A bind operation failed because the provided address is already in use or because + /// there are no ephemeral ports available. + address-in-use, + /// The remote address is not reachable + remote-unreachable, + /// The TCP connection was forcefully rejected + connection-refused, + /// The TCP connection was reset. + connection-reset, + /// A TCP connection was aborted. + connection-aborted, + /// The size of a datagram sent to a UDP socket exceeded the maximum + /// supported size. + datagram-too-large, + /// Name does not exist or has no suitable associated IP addresses. + name-unresolvable, + /// A temporary failure in name resolution occurred. + temporary-resolver-failure, + /// A permanent failure in name resolution occurred. + permanent-resolver-failure + } + enum ip-address-family { + /// Similar to `AF_INET` in POSIX. + ipv4, + /// Similar to `AF_INET6` in POSIX. + ipv6 + } + type ipv4-address = tuple; + type ipv6-address = tuple; + variant ip-address { + ipv4(ipv4-address), + ipv6(ipv6-address), + } + record ipv4-socket-address { + /// sin_port + port: u16, + /// sin_addr + address: ipv4-address, + } + record ipv6-socket-address { + /// sin6_port + port: u16, + /// sin6_flowinfo + flow-info: u32, + /// sin6_addr + address: ipv6-address, + /// sin6_scope_id + scope-id: u32, + } + variant ip-socket-address { + ipv4(ipv4-socket-address), + ipv6(ipv6-socket-address), + } + } + + /// This interface provides a value-export of the default network handle.. + interface instance-network { + use network.{network}; + + /// Get a handle to the default network. + instance-network: func() -> network; + } + + interface ip-name-lookup { + use wasi:io/poll@0.2.0.{pollable}; + use network.{network}; + use network.{error-code}; + use network.{ip-address}; + resource resolve-address-stream { + + /// Returns the next address from the resolver. /// - /// When the caller gives a `len` of 0, it represents a request to - /// read 0 bytes. If the stream is still open, this call should - /// succeed and return an empty list, or otherwise fail with `closed`. + /// This function should be called multiple times. On each call, it will + /// return the next address in connection order preference. If all + /// addresses have been exhausted, this function returns `none`. /// - /// The `len` parameter is a `u64`, which could represent a list of u8 which - /// is not possible to allocate in wasm32, or not desirable to allocate as - /// as a return value by the callee. The callee may return a list of bytes - /// less than `len` in size while more bytes are available for reading. - read: func(len: u64) -> result, stream-error>; - - /// Skip bytes from a stream. Returns number of bytes skipped. + /// This function never returns IPv4-mapped IPv6 addresses. /// - /// Behaves identical to `read`, except instead of returning a list - /// of bytes, returns the number of bytes consumed from the stream. - skip: func(len: u64) -> result; + /// # Typical errors + /// - `name-unresolvable`: Name does not exist or has no suitable associated + /// IP addresses. (EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY) + /// - `temporary-resolver-failure`: A temporary failure in name resolution occurred. + /// (EAI_AGAIN) + /// - `permanent-resolver-failure`: A permanent failure in name resolution occurred. + /// (EAI_FAIL) + /// - `would-block`: A result is not available yet. (EWOULDBLOCK, EAGAIN) + resolve-next-address: func() -> result, error-code>; - /// Create a `pollable` which will resolve once either the specified stream - /// has bytes available to read or the other end of the stream has been - /// closed. - /// The created `pollable` is a child resource of the `input-stream`. - /// Implementations may trap if the `input-stream` is dropped before - /// all derived `pollable`s created with this function are dropped. + /// Create a `pollable` which will resolve once the stream is ready for I/O. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. subscribe: func() -> pollable; } - /// An output bytestream. + /// Resolve an internet host name to a list of IP addresses. /// - /// `output-stream`s are *non-blocking* to the extent practical on - /// underlying platforms. Except where specified otherwise, I/O operations also - /// always return promptly, after the number of bytes that can be written - /// promptly, which could even be zero. To wait for the stream to be ready to - /// accept data, the `subscribe` function to obtain a `pollable` which can be - /// polled for using `wasi:io/poll`. - resource output-stream { + /// Unicode domain names are automatically converted to ASCII using IDNA encoding. + /// If the input is an IP address string, the address is parsed and returned + /// as-is without making any external requests. + /// + /// See the wasi-socket proposal README.md for a comparison with getaddrinfo. + /// + /// This function never blocks. It either immediately fails or immediately + /// returns successfully with a `resolve-address-stream` that can be used + /// to (asynchronously) fetch the results. + /// + /// # Typical errors + /// - `invalid-argument`: `name` is a syntactically invalid domain name or IP address. + /// + /// # References: + /// - + /// - + /// - + /// - + resolve-addresses: func(network: borrow, name: string) -> result; + } - /// Request to flush buffered output, and block until flush completes - /// and stream is ready for writing again. - blocking-flush: func() -> result<_, stream-error>; + interface tcp { + use wasi:io/streams@0.2.0.{input-stream}; + use wasi:io/streams@0.2.0.{output-stream}; + use wasi:io/poll@0.2.0.{pollable}; + use wasi:clocks/monotonic-clock@0.2.0.{duration}; + use network.{network}; + use network.{error-code}; + use network.{ip-socket-address}; + use network.{ip-address-family}; + enum shutdown-type { + /// Similar to `SHUT_RD` in POSIX. + receive, + /// Similar to `SHUT_WR` in POSIX. + send, + /// Similar to `SHUT_RDWR` in POSIX. + both + } - /// Read from one stream and write to another, with blocking. + /// A TCP socket resource. + /// + /// The socket can be in one of the following states: + /// - `unbound` + /// - `bind-in-progress` + /// - `bound` (See note below) + /// - `listen-in-progress` + /// - `listening` + /// - `connect-in-progress` + /// - `connected` + /// - `closed` + /// See + /// for a more information. + /// + /// Note: Except where explicitly mentioned, whenever this documentation uses + /// the term "bound" without backticks it actually means: in the `bound` state *or + /// higher*. + /// (i.e. `bound`, `listen-in-progress`, `listening`, `connect-in-progress` or `connected`) + /// + /// In addition to the general error codes documented on the + /// `network::error-code` type, TCP socket methods may always return + /// `error(invalid-state)` when in the `closed` state. + resource tcp-socket { + + /// Accept a new client socket. /// - /// This is similar to `splice`, except that it blocks until the - /// `output-stream` is ready for writing, and the `input-stream` - /// is ready for reading, before performing the `splice`. - blocking-splice: func(src: borrow, len: u64) -> result; + /// The returned socket is bound and in the `connected` state. The following properties + /// are inherited from the listener socket: + /// - `address-family` + /// - `keep-alive-enabled` + /// - `keep-alive-idle-time` + /// - `keep-alive-interval` + /// - `keep-alive-count` + /// - `hop-limit` + /// - `receive-buffer-size` + /// - `send-buffer-size` + /// + /// On success, this function returns the newly accepted client socket along with + /// a pair of streams that can be used to read & write to the connection. + /// + /// # Typical errors + /// - `invalid-state`: Socket is not in the `listening` state. (EINVAL) + /// - `would-block`: No pending connections at the moment. (EWOULDBLOCK, EAGAIN) + /// - `connection-aborted`: An incoming connection was pending, but was terminated + /// by the client before this listener could accept it. (ECONNABORTED) + /// - `new-socket-limit`: The new socket resource could not be created because of + /// a system limit. (EMFILE, ENFILE) + /// + /// # References + /// - + /// - + /// - + /// - + accept: func() -> result, error-code>; - /// Perform a write of up to 4096 bytes, and then flush the stream. Block - /// until all of these operations are complete, or an error occurs. + /// Whether this is a IPv4 or IPv6 socket. /// - /// This is a convenience wrapper around the use of `check-write`, - /// `subscribe`, `write`, and `flush`, and is implemented with the - /// following pseudo-code: + /// Equivalent to the SO_DOMAIN socket option. + address-family: func() -> ip-address-family; + finish-bind: func() -> result<_, error-code>; + finish-connect: func() -> result, error-code>; + finish-listen: func() -> result<_, error-code>; + + /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. /// - /// ```text - /// let pollable = this.subscribe(); - /// while !contents.is_empty() { - /// // Wait for the stream to become writable - /// pollable.block(); - /// let Ok(n) = this.check-write(); // eliding error handling - /// let len = min(n, contents.len()); - /// let (chunk, rest) = contents.split_at(len); - /// this.write(chunk ); // eliding error handling - /// contents = rest; - /// } - /// this.flush(); - /// // Wait for completion of `flush` - /// pollable.block(); - /// // Check for any errors that arose during `flush` - /// let _ = this.check-write(); // eliding error handling - /// ``` - blocking-write-and-flush: func(contents: list) -> result<_, stream-error>; + /// If the provided value is 0, an `invalid-argument` error is returned. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The TTL value must be 1 or higher. + hop-limit: func() -> result; - /// Perform a write of up to 4096 zeroes, and then flush the stream. - /// Block until all of these operations are complete, or an error - /// occurs. + /// Whether the socket is in the `listening` state. /// - /// This is a convenience wrapper around the use of `check-write`, - /// `subscribe`, `write-zeroes`, and `flush`, and is implemented with - /// the following pseudo-code: + /// Equivalent to the SO_ACCEPTCONN socket option. + is-listening: func() -> bool; + + /// The maximum amount of keepalive packets TCP should send before aborting the connection. /// - /// ```text - /// let pollable = this.subscribe(); - /// while num_zeroes != 0 { - /// // Wait for the stream to become writable - /// pollable.block(); - /// let Ok(n) = this.check-write(); // eliding error handling - /// let len = min(n, num_zeroes); - /// this.write-zeroes(len); // eliding error handling - /// num_zeroes -= len; - /// } - /// this.flush(); - /// // Wait for completion of `flush` - /// pollable.block(); - /// // Check for any errors that arose during `flush` - /// let _ = this.check-write(); // eliding error handling - /// ``` - blocking-write-zeroes-and-flush: func(len: u64) -> result<_, stream-error>; + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// I.e. after setting a value, reading the same setting back may return a different + /// value. + /// + /// Equivalent to the TCP_KEEPCNT socket option. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-count: func() -> result; - /// Check readiness for writing. This function never blocks. + /// Enables or disables keepalive. /// - /// Returns the number of bytes permitted for the next call to `write`, - /// or an error. Calling `write` with more bytes than this function has - /// permitted will trap. + /// The keepalive behavior can be adjusted using: + /// - `keep-alive-idle-time` + /// - `keep-alive-interval` + /// - `keep-alive-count` + /// These properties can be configured while `keep-alive-enabled` is false, but only + /// come into effect when `keep-alive-enabled` is true. /// - /// When this function returns 0 bytes, the `subscribe` pollable will - /// become ready when this function will report at least 1 byte, or an - /// error. - check-write: func() -> result; + /// Equivalent to the SO_KEEPALIVE socket option. + keep-alive-enabled: func() -> result; - /// Request to flush buffered output. This function never blocks. + /// Amount of time the connection has to be idle before TCP starts sending keepalive + /// packets. /// - /// This tells the output-stream that the caller intends any buffered - /// output to be flushed. the output which is expected to be flushed - /// is all that has been passed to `write` prior to this call. + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// I.e. after setting a value, reading the same setting back may return a different + /// value. /// - /// Upon calling this function, the `output-stream` will not accept any - /// writes (`check-write` will return `ok(0)`) until the flush has - /// completed. The `subscribe` pollable will become ready when the - /// flush has completed and the stream can accept more writes. - flush: func() -> result<_, stream-error>; + /// Equivalent to the TCP_KEEPIDLE socket option. (TCP_KEEPALIVE on MacOS) + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-idle-time: func() -> result; - /// Read from one stream and write to another. + /// The time between keepalive packets. /// - /// The behavior of splice is equivelant to: - /// 1. calling `check-write` on the `output-stream` - /// 2. calling `read` on the `input-stream` with the smaller of the - /// `check-write` permitted length and the `len` provided to `splice` - /// 3. calling `write` on the `output-stream` with that read data. + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// I.e. after setting a value, reading the same setting back may return a different + /// value. /// - /// Any error reported by the call to `check-write`, `read`, or - /// `write` ends the splice and reports that error. + /// Equivalent to the TCP_KEEPINTVL socket option. /// - /// This function returns the number of bytes transferred; it may be less - /// than `len`. - splice: func(src: borrow, len: u64) -> result; + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-interval: func() -> result; - /// Create a `pollable` which will resolve once the output-stream - /// is ready for more writing, or an error has occured. When this - /// pollable is ready, `check-write` will return `ok(n)` with n>0, or an - /// error. + /// Get the bound local address. /// - /// If the stream is closed, this pollable is always ready immediately. + /// POSIX mentions: + /// > If the socket has not been bound to a local name, the value + /// > stored in the object pointed to by `address` is unspecified. /// - /// The created `pollable` is a child resource of the `output-stream`. - /// Implementations may trap if the `output-stream` is dropped before - /// all derived `pollable`s created with this function are dropped. - subscribe: func() -> pollable; + /// WASI is stricter and requires `local-address` to return `invalid-state` when the + /// socket hasn't been bound yet. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. + /// + /// # References + /// - + /// - + /// - + /// - + local-address: func() -> result; - /// Perform a write. This function never blocks. + /// The kernel buffer space reserved for sends/receives on this socket. /// - /// When the destination of a `write` is binary data, the bytes from - /// `contents` are written verbatim. When the destination of a `write` is - /// known to the implementation to be text, the bytes of `contents` are - /// transcoded from UTF-8 into the encoding of the destination and then - /// written. + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// I.e. after setting a value, reading the same setting back may return a different + /// value. /// - /// Precondition: check-write gave permit of Ok(n) and contents has a - /// length of less than or equal to n. Otherwise, this function will trap. + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. /// - /// returns Err(closed) without writing if the stream has closed since - /// the last call to check-write provided a permit. - write: func(contents: list) -> result<_, stream-error>; + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + receive-buffer-size: func() -> result; - /// Write zeroes to a stream. + /// Get the remote address. /// - /// This should be used precisely like `write` with the exact same - /// preconditions (must use check-write first), but instead of - /// passing a list of bytes, you simply pass the number of zero-bytes - /// that should be written. - write-zeroes: func(len: u64) -> result<_, stream-error>; - } - } - - world imports { - import error; - import poll; - import streams; - } -} - -package wasi:random@0.2.0 { - /// The insecure-seed interface for seeding hash-map DoS resistance. - /// - /// It is intended to be portable at least between Unix-family platforms and - /// Windows. - interface insecure-seed { - /// Return a 128-bit value that may contain a pseudo-random value. - /// - /// The returned value is not required to be computed from a CSPRNG, and may - /// even be entirely deterministic. Host implementations are encouraged to - /// provide pseudo-random values to any program exposed to - /// attacker-controlled content, to enable DoS protection built into many - /// languages' hash-map implementations. - /// - /// This function is intended to only be called once, by a source language - /// to initialize Denial Of Service (DoS) protection in its hash-map - /// implementation. - /// - /// # Expected future evolution - /// - /// This will likely be changed to a value import, to prevent it from being - /// called multiple times and potentially used for purposes other than DoS - /// protection. - insecure-seed: func() -> tuple; - } - - /// The insecure interface for insecure pseudo-random numbers. - /// - /// It is intended to be portable at least between Unix-family platforms and - /// Windows. - interface insecure { - /// Return `len` insecure pseudo-random bytes. - /// - /// This function is not cryptographically secure. Do not use it for - /// anything related to security. - /// - /// There are no requirements on the values of the returned bytes, however - /// implementations are encouraged to return evenly distributed values with - /// a long period. - get-insecure-random-bytes: func(len: u64) -> list; - - /// Return an insecure pseudo-random `u64` value. - /// - /// This function returns the same type of pseudo-random data as - /// `get-insecure-random-bytes`, represented as a `u64`. - get-insecure-random-u64: func() -> u64; - } - - /// WASI Random is a random data API. - /// - /// It is intended to be portable at least between Unix-family platforms and - /// Windows. - interface random { - /// Return `len` cryptographically-secure random or pseudo-random bytes. - /// - /// This function must produce data at least as cryptographically secure and - /// fast as an adequately seeded cryptographically-secure pseudo-random - /// number generator (CSPRNG). It must not block, from the perspective of - /// the calling program, under any circumstances, including on the first - /// request and on requests for numbers of bytes. The returned data must - /// always be unpredictable. - /// - /// This function must always return fresh data. Deterministic environments - /// must omit this function, rather than implementing it with deterministic - /// data. - get-random-bytes: func(len: u64) -> list; - - /// Return a cryptographically-secure random or pseudo-random `u64` value. - /// - /// This function returns the same type of data as `get-random-bytes`, - /// represented as a `u64`. - get-random-u64: func() -> u64; - } - - world imports { - import random; - import insecure; - import insecure-seed; - } -} + /// # Typical errors + /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + remote-address: func() -> result; + send-buffer-size: func() -> result; + set-hop-limit: func(value: u8) -> result<_, error-code>; + set-keep-alive-count: func(value: u32) -> result<_, error-code>; + set-keep-alive-enabled: func(value: bool) -> result<_, error-code>; + set-keep-alive-idle-time: func(value: duration) -> result<_, error-code>; + set-keep-alive-interval: func(value: duration) -> result<_, error-code>; -package wasi:sockets@0.2.0 { - interface network { - /// An opaque resource that represents access to (a subset of) the network. - /// This enables context-based security for networking. - /// There is no need for this to map 1:1 to a physical network interface. - resource network; + /// Hints the desired listen queue size. Implementations are free to ignore this. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// + /// # Typical errors + /// - `not-supported`: (set) The platform does not support changing the backlog + /// size after the initial listen. + /// - `invalid-argument`: (set) The provided value was 0. + /// - `invalid-state`: (set) The socket is in the `connect-in-progress` or + /// `connected` state. + set-listen-backlog-size: func(value: u64) -> result<_, error-code>; + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + set-send-buffer-size: func(value: u64) -> result<_, error-code>; - /// Error codes. - /// - /// In theory, every API can return any error code. - /// In practice, API's typically only return the errors documented per API - /// combined with a couple of errors that are always possible: - /// - `unknown` - /// - `access-denied` - /// - `not-supported` - /// - `out-of-memory` - /// - `concurrency-conflict` - /// - /// See each individual API for what the POSIX equivalents are. They sometimes differ - /// per API. - enum error-code { - /// Unknown error - unknown, - /// Access denied. + /// Initiate a graceful shutdown. /// - /// POSIX equivalent: EACCES, EPERM - access-denied, - /// The operation is not supported. + /// - `receive`: The socket is not expecting to receive any data from + /// the peer. The `input-stream` associated with this socket will be + /// closed. Any data still in the receive queue at time of calling + /// this method will be discarded. + /// - `send`: The socket has no more data to send to the peer. The `output-stream` + /// associated with this socket will be closed and a FIN packet will be sent. + /// - `both`: Same effect as `receive` & `send` combined. + /// + /// This function is idempotent. Shutting a down a direction more than once + /// has no effect and returns `ok`. + /// + /// The shutdown function does not close (drop) the socket. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) /// - /// POSIX equivalent: EOPNOTSUPP - not-supported, - /// One of the arguments is invalid. + /// # References + /// - + /// - + /// - + /// - + shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code>; + + /// Bind the socket to a specific network on the provided IP address and port. /// - /// POSIX equivalent: EINVAL - invalid-argument, - /// Not enough memory to complete the operation. + /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the + /// implementation to decide which + /// network interface(s) to bind to. + /// If the TCP/UDP port is zero, the socket will be bound to a random free port. /// - /// POSIX equivalent: ENOMEM, ENOBUFS, EAI_MEMORY - out-of-memory, - /// The operation timed out before it could finish completely. - timeout, - /// This operation is incompatible with another asynchronous operation that is already - /// in progress. + /// Bind can be attempted multiple times on the same socket, even with + /// different arguments on each iteration. But never concurrently and + /// only as long as the previous bind failed. Once a bind succeeds, the + /// binding can't be changed anymore. /// - /// POSIX equivalent: EALREADY - concurrency-conflict, - /// Trying to finish an asynchronous operation that: - /// - has not been started yet, or: - /// - was already finished by a previous `finish-*` call. + /// # Typical errors + /// - `invalid-argument`: The `local-address` has the wrong address family. + /// (EAFNOSUPPORT, EFAULT on Windows) + /// - `invalid-argument`: `local-address` is not a unicast address. (EINVAL) + /// - `invalid-argument`: `local-address` is an IPv4-mapped IPv6 address. + /// (EINVAL) + /// - `invalid-state`: The socket is already bound. (EINVAL) + /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS + /// on Windows) + /// - `address-in-use`: Address is already in use. (EADDRINUSE) + /// - `address-not-bindable`: `local-address` is not an address that the `network` + /// can bind to. (EADDRNOTAVAIL) + /// - `not-in-progress`: A `bind` operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. + /// (EWOULDBLOCK, EAGAIN) /// - /// Note: this is scheduled to be removed when `future`s are natively supported. - not-in-progress, - /// The operation has been aborted because it could not be completed immediately. + /// # Implementors note + /// When binding to a non-zero port, this bind operation shouldn't be affected by + /// the TIME_WAIT + /// state of a recently closed socket on the same local address. In practice this + /// means that the SO_REUSEADDR + /// socket option should be set implicitly on all platforms, except on Windows where + /// this is the default behavior + /// and SO_REUSEADDR performs something different entirely. /// - /// Note: this is scheduled to be removed when `future`s are natively supported. - would-block, - /// The operation is not valid in the socket's current state. - invalid-state, - /// A new socket resource could not be created because of a system limit. - new-socket-limit, - /// A bind operation failed because the provided address is not an address that the - /// `network` can bind to. - address-not-bindable, - /// A bind operation failed because the provided address is already in use or because - /// there are no ephemeral ports available. - address-in-use, - /// The remote address is not reachable - remote-unreachable, - /// The TCP connection was forcefully rejected - connection-refused, - /// The TCP connection was reset. - connection-reset, - /// A TCP connection was aborted. - connection-aborted, - /// The size of a datagram sent to a UDP socket exceeded the maximum - /// supported size. - datagram-too-large, - /// Name does not exist or has no suitable associated IP addresses. - name-unresolvable, - /// A temporary failure in name resolution occurred. - temporary-resolver-failure, - /// A permanent failure in name resolution occurred. - permanent-resolver-failure - } - enum ip-address-family { - /// Similar to `AF_INET` in POSIX. - ipv4, - /// Similar to `AF_INET6` in POSIX. - ipv6 - } - type ipv4-address = tuple; - type ipv6-address = tuple; - variant ip-address { - ipv4(ipv4-address), - ipv6(ipv6-address), - } - record ipv4-socket-address { - /// sin_port - port: u16, - /// sin_addr - address: ipv4-address, - } - record ipv6-socket-address { - /// sin6_port - port: u16, - /// sin6_flowinfo - flow-info: u32, - /// sin6_addr - address: ipv6-address, - /// sin6_scope_id - scope-id: u32, - } - variant ip-socket-address { - ipv4(ipv4-socket-address), - ipv6(ipv6-socket-address), - } - } - - /// This interface provides a value-export of the default network handle.. - interface instance-network { - use network.{network}; - - /// Get a handle to the default network. - instance-network: func() -> network; - } + /// Unlike in POSIX, in WASI the bind operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `bind` as part of either `start-bind` or `finish-bind`. + /// + /// # References + /// - + /// - + /// - + /// - + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; - interface ip-name-lookup { - use wasi:io/poll@0.2.0.{pollable}; - use network.{network}; - use network.{error-code}; - use network.{ip-address}; - resource resolve-address-stream { + /// Connect to a remote endpoint. + /// + /// On success: + /// - the socket is transitioned into the `connection` state. + /// - a pair of streams is returned that can be used to read & write to the connection + /// + /// After a failed connection attempt, the socket will be in the `closed` + /// state and the only valid action left is to `drop` the socket. A single + /// socket can not be used to connect more than once. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. + /// (EAFNOSUPPORT) + /// - `invalid-argument`: `remote-address` is not a unicast address. (EINVAL, + /// ENETUNREACH on Linux, EAFNOSUPPORT on MacOS) + /// - `invalid-argument`: `remote-address` is an IPv4-mapped IPv6 address. + /// (EINVAL, EADDRNOTAVAIL on Illumos) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY + /// (`0.0.0.0` / `::`). (EADDRNOTAVAIL on Windows) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EADDRNOTAVAIL + /// on Windows) + /// - `invalid-argument`: The socket is already attached to a different network. + /// The `network` passed to `connect` must be identical to the one passed to `bind`. + /// - `invalid-state`: The socket is already in the `connected` state. + /// (EISCONN) + /// - `invalid-state`: The socket is already in the `listening` state. + /// (EOPNOTSUPP, EINVAL on Windows) + /// - `timeout`: Connection timed out. (ETIMEDOUT) + /// - `connection-refused`: The connection was forcefully rejected. (ECONNREFUSED) + /// - `connection-reset`: The connection was reset. (ECONNRESET) + /// - `connection-aborted`: The connection was aborted. (ECONNABORTED) + /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, + /// EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `address-in-use`: Tried to perform an implicit bind, but there were + /// no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// - `not-in-progress`: A connect operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. + /// (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// The POSIX equivalent of `start-connect` is the regular `connect` syscall. + /// Because all WASI sockets are non-blocking this is expected to return + /// EINPROGRESS, which should be translated to `ok()` in WASI. + /// + /// The POSIX equivalent of `finish-connect` is a `poll` for event `POLLOUT` + /// with a timeout of 0 on the socket descriptor. Followed by a check for + /// the `SO_ERROR` socket option, in case the poll signaled readiness. + /// + /// # References + /// - + /// - + /// - + /// - + start-connect: func(network: borrow, remote-address: ip-socket-address) -> result<_, error-code>; - /// Returns the next address from the resolver. + /// Start listening for new connections. /// - /// This function should be called multiple times. On each call, it will - /// return the next address in connection order preference. If all - /// addresses have been exhausted, this function returns `none`. + /// Transitions the socket into the `listening` state. /// - /// This function never returns IPv4-mapped IPv6 addresses. + /// Unlike POSIX, the socket must already be explicitly bound. /// /// # Typical errors - /// - `name-unresolvable`: Name does not exist or has no suitable associated - /// IP addresses. (EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY) - /// - `temporary-resolver-failure`: A temporary failure in name resolution occurred. - /// (EAI_AGAIN) - /// - `permanent-resolver-failure`: A permanent failure in name resolution occurred. - /// (EAI_FAIL) - /// - `would-block`: A result is not available yet. (EWOULDBLOCK, EAGAIN) - resolve-next-address: func() -> result, error-code>; + /// - `invalid-state`: The socket is not bound to any local address. (EDESTADDRREQ) + /// - `invalid-state`: The socket is already in the `connected` state. + /// (EISCONN, EINVAL on BSD) + /// - `invalid-state`: The socket is already in the `listening` state. + /// - `address-in-use`: Tried to perform an implicit bind, but there were + /// no ephemeral ports available. (EADDRINUSE) + /// - `not-in-progress`: A listen operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. + /// (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// Unlike in POSIX, in WASI the listen operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `listen` as part of either `start-listen` or `finish-listen`. + /// + /// # References + /// - + /// - + /// - + /// - + start-listen: func() -> result<_, error-code>; - /// Create a `pollable` which will resolve once the stream is ready for I/O. + /// Create a `pollable` which can be used to poll for, or block on, + /// completion of any of the asynchronous operations of this socket. + /// + /// When `finish-bind`, `finish-listen`, `finish-connect` or `accept` + /// return `error(would-block)`, this pollable can be used to wait for + /// their success or failure, after which the method can be retried. + /// + /// The pollable is not limited to the async operation that happens to be + /// in progress at the time of calling `subscribe` (if any). Theoretically, + /// `subscribe` only has to be called once per socket and can then be + /// (re)used for the remainder of the socket's lifetime. + /// + /// See + /// for a more information. /// /// Note: this function is here for WASI Preview2 only. /// It's planned to be removed when `future` is natively supported in Preview3. subscribe: func() -> pollable; } + } - /// Resolve an internet host name to a list of IP addresses. + interface tcp-create-socket { + use network.{network}; + use network.{error-code}; + use network.{ip-address-family}; + use tcp.{tcp-socket}; + + /// Create a new TCP socket. /// - /// Unicode domain names are automatically converted to ASCII using IDNA encoding. - /// If the input is an IP address string, the address is parsed and returned - /// as-is without making any external requests. + /// Similar to `socket(AF_INET or AF_INET6, SOCK_STREAM, IPPROTO_TCP)` in POSIX. + /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. /// - /// See the wasi-socket proposal README.md for a comparison with getaddrinfo. + /// This function does not require a network capability handle. This is considered + /// to be safe because + /// at time of creation, the socket is not bound to any `network` yet. Up to the moment + /// `bind`/`connect` + /// is called, the socket is effectively an in-memory configuration object, unable + /// to communicate with the outside world. /// - /// This function never blocks. It either immediately fails or immediately - /// returns successfully with a `resolve-address-stream` that can be used - /// to (asynchronously) fetch the results. + /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous + /// operations. /// /// # Typical errors - /// - `invalid-argument`: `name` is a syntactically invalid domain name or IP address. + /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) + /// - `new-socket-limit`: The new socket resource could not be created because of + /// a system limit. (EMFILE, ENFILE) /// - /// # References: - /// - - /// - - /// - - /// - - resolve-addresses: func(network: borrow, name: string) -> result; + /// # References + /// - + /// - + /// - + /// - + create-tcp-socket: func(address-family: ip-address-family) -> result; } - interface tcp { - use wasi:io/streams@0.2.0.{input-stream}; - use wasi:io/streams@0.2.0.{output-stream}; + interface udp { use wasi:io/poll@0.2.0.{pollable}; - use wasi:clocks/monotonic-clock@0.2.0.{duration}; use network.{network}; use network.{error-code}; use network.{ip-socket-address}; use network.{ip-address-family}; - enum shutdown-type { - /// Similar to `SHUT_RD` in POSIX. - receive, - /// Similar to `SHUT_WR` in POSIX. - send, - /// Similar to `SHUT_RDWR` in POSIX. - both - } - - /// A TCP socket resource. - /// - /// The socket can be in one of the following states: - /// - `unbound` - /// - `bind-in-progress` - /// - `bound` (See note below) - /// - `listen-in-progress` - /// - `listening` - /// - `connect-in-progress` - /// - `connected` - /// - `closed` - /// See - /// for a more information. - /// - /// Note: Except where explicitly mentioned, whenever this documentation uses - /// the term "bound" without backticks it actually means: in the `bound` state *or - /// higher*. - /// (i.e. `bound`, `listen-in-progress`, `listening`, `connect-in-progress` or `connected`) - /// - /// In addition to the general error codes documented on the - /// `network::error-code` type, TCP socket methods may always return - /// `error(invalid-state)` when in the `closed` state. - resource tcp-socket { - /// Accept a new client socket. + /// A received datagram. + record incoming-datagram { + /// The payload. /// - /// The returned socket is bound and in the `connected` state. The following properties - /// are inherited from the listener socket: - /// - `address-family` - /// - `keep-alive-enabled` - /// - `keep-alive-idle-time` - /// - `keep-alive-interval` - /// - `keep-alive-count` - /// - `hop-limit` - /// - `receive-buffer-size` - /// - `send-buffer-size` + /// Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes. + data: list, + /// The source address. /// - /// On success, this function returns the newly accepted client socket along with - /// a pair of streams that can be used to read & write to the connection. + /// This field is guaranteed to match the remote address the stream was initialized + /// with, if any. /// - /// # Typical errors - /// - `invalid-state`: Socket is not in the `listening` state. (EINVAL) - /// - `would-block`: No pending connections at the moment. (EWOULDBLOCK, EAGAIN) - /// - `connection-aborted`: An incoming connection was pending, but was terminated - /// by the client before this listener could accept it. (ECONNABORTED) - /// - `new-socket-limit`: The new socket resource could not be created because of - /// a system limit. (EMFILE, ENFILE) + /// Equivalent to the `src_addr` out parameter of `recvfrom`. + remote-address: ip-socket-address, + } + + /// A datagram to be sent out. + record outgoing-datagram { + /// The payload. + data: list, + /// The destination address. /// - /// # References - /// - - /// - - /// - - /// - - accept: func() -> result, error-code>; + /// The requirements on this field depend on how the stream was initialized: + /// - with a remote address: this field must be None or match the stream's remote + /// address exactly. + /// - without a remote address: this field is required. + /// + /// If this value is None, the send operation is equivalent to `send` in POSIX. Otherwise + /// it is equivalent to `sendto`. + remote-address: option, + } + + /// A UDP socket handle. + resource udp-socket { /// Whether this is a IPv4 or IPv6 socket. /// /// Equivalent to the SO_DOMAIN socket option. address-family: func() -> ip-address-family; finish-bind: func() -> result<_, error-code>; - finish-connect: func() -> result, error-code>; - finish-listen: func() -> result<_, error-code>; - - /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The TTL value must be 1 or higher. - hop-limit: func() -> result; - - /// Whether the socket is in the `listening` state. - /// - /// Equivalent to the SO_ACCEPTCONN socket option. - is-listening: func() -> bool; - - /// The maximum amount of keepalive packets TCP should send before aborting the connection. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or - /// rounded. - /// I.e. after setting a value, reading the same setting back may return a different - /// value. - /// - /// Equivalent to the TCP_KEEPCNT socket option. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The provided value was 0. - keep-alive-count: func() -> result; - - /// Enables or disables keepalive. - /// - /// The keepalive behavior can be adjusted using: - /// - `keep-alive-idle-time` - /// - `keep-alive-interval` - /// - `keep-alive-count` - /// These properties can be configured while `keep-alive-enabled` is false, but only - /// come into effect when `keep-alive-enabled` is true. - /// - /// Equivalent to the SO_KEEPALIVE socket option. - keep-alive-enabled: func() -> result; - - /// Amount of time the connection has to be idle before TCP starts sending keepalive - /// packets. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or - /// rounded. - /// I.e. after setting a value, reading the same setting back may return a different - /// value. - /// - /// Equivalent to the TCP_KEEPIDLE socket option. (TCP_KEEPALIVE on MacOS) - /// - /// # Typical errors - /// - `invalid-argument`: (set) The provided value was 0. - keep-alive-idle-time: func() -> result; - - /// The time between keepalive packets. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or - /// rounded. - /// I.e. after setting a value, reading the same setting back may return a different - /// value. - /// - /// Equivalent to the TCP_KEEPINTVL socket option. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The provided value was 0. - keep-alive-interval: func() -> result; - /// Get the bound local address. + /// Get the current bound address. /// /// POSIX mentions: /// > If the socket has not been bound to a local name, the value @@ -2191,101 +2036,50 @@ package wasi:sockets@0.2.0 { /// # References /// - /// - - /// - - /// - - local-address: func() -> result; - - /// The kernel buffer space reserved for sends/receives on this socket. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or - /// rounded. - /// I.e. after setting a value, reading the same setting back may return a different - /// value. - /// - /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The provided value was 0. - receive-buffer-size: func() -> result; - - /// Get the remote address. - /// - /// # Typical errors - /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) - /// - /// # References - /// - - /// - - /// - - /// - - remote-address: func() -> result; - send-buffer-size: func() -> result; - set-hop-limit: func(value: u8) -> result<_, error-code>; - set-keep-alive-count: func(value: u32) -> result<_, error-code>; - set-keep-alive-enabled: func(value: bool) -> result<_, error-code>; - set-keep-alive-idle-time: func(value: duration) -> result<_, error-code>; - set-keep-alive-interval: func(value: duration) -> result<_, error-code>; - - /// Hints the desired listen queue size. Implementations are free to ignore this. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or - /// rounded. - /// - /// # Typical errors - /// - `not-supported`: (set) The platform does not support changing the backlog - /// size after the initial listen. - /// - `invalid-argument`: (set) The provided value was 0. - /// - `invalid-state`: (set) The socket is in the `connect-in-progress` or - /// `connected` state. - set-listen-backlog-size: func(value: u64) -> result<_, error-code>; - set-receive-buffer-size: func(value: u64) -> result<_, error-code>; - set-send-buffer-size: func(value: u64) -> result<_, error-code>; + /// - + /// - + local-address: func() -> result; - /// Initiate a graceful shutdown. + /// The kernel buffer space reserved for sends/receives on this socket. /// - /// - `receive`: The socket is not expecting to receive any data from - /// the peer. The `input-stream` associated with this socket will be - /// closed. Any data still in the receive queue at time of calling - /// this method will be discarded. - /// - `send`: The socket has no more data to send to the peer. The `output-stream` - /// associated with this socket will be closed and a FIN packet will be sent. - /// - `both`: Same effect as `receive` & `send` combined. + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or + /// rounded. + /// I.e. after setting a value, reading the same setting back may return a different + /// value. /// - /// This function is idempotent. Shutting a down a direction more than once - /// has no effect and returns `ok`. + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. /// - /// The shutdown function does not close (drop) the socket. + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + receive-buffer-size: func() -> result; + + /// Get the address the socket is currently streaming to. /// /// # Typical errors - /// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) + /// - `invalid-state`: The socket is not streaming to a specific remote address. (ENOTCONN) /// /// # References - /// - - /// - - /// - - /// - - shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code>; + /// - + /// - + /// - + /// - + remote-address: func() -> result; + send-buffer-size: func() -> result; + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; /// Bind the socket to a specific network on the provided IP address and port. /// /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the /// implementation to decide which /// network interface(s) to bind to. - /// If the TCP/UDP port is zero, the socket will be bound to a random free port. - /// - /// Bind can be attempted multiple times on the same socket, even with - /// different arguments on each iteration. But never concurrently and - /// only as long as the previous bind failed. Once a bind succeeds, the - /// binding can't be changed anymore. + /// If the port is zero, the socket will be bound to a random free port. /// /// # Typical errors /// - `invalid-argument`: The `local-address` has the wrong address family. /// (EAFNOSUPPORT, EFAULT on Windows) - /// - `invalid-argument`: `local-address` is not a unicast address. (EINVAL) - /// - `invalid-argument`: `local-address` is an IPv4-mapped IPv6 address. - /// (EINVAL) /// - `invalid-state`: The socket is already bound. (EINVAL) /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS /// on Windows) @@ -2297,14 +2091,6 @@ package wasi:sockets@0.2.0 { /// (EWOULDBLOCK, EAGAIN) /// /// # Implementors note - /// When binding to a non-zero port, this bind operation shouldn't be affected by - /// the TIME_WAIT - /// state of a recently closed socket on the same local address. In practice this - /// means that the SO_REUSEADDR - /// socket option should be set implicitly on all platforms, except on Windows where - /// this is the default behavior - /// and SO_REUSEADDR performs something different entirely. - /// /// Unlike in POSIX, in WASI the bind operation is async. This enables /// interactive WASI hosts to inject permission prompts. Runtimes that /// don't want to make use of this ability can simply call the native @@ -2317,105 +2103,174 @@ package wasi:sockets@0.2.0 { /// - start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; - /// Connect to a remote endpoint. + /// Set up inbound & outbound communication channels, optionally to a specific peer. /// - /// On success: - /// - the socket is transitioned into the `connection` state. - /// - a pair of streams is returned that can be used to read & write to the connection + /// This function only changes the local socket configuration and does not generate + /// any network traffic. + /// On success, the `remote-address` of the socket is updated. The `local-address` + /// may be updated as well, + /// based on the best network path to `remote-address`. /// - /// After a failed connection attempt, the socket will be in the `closed` - /// state and the only valid action left is to `drop` the socket. A single - /// socket can not be used to connect more than once. + /// When a `remote-address` is provided, the returned streams are limited to communicating + /// with that specific peer: + /// - `send` can only be used to send to this destination. + /// - `receive` will only return datagrams sent from the provided `remote-address`. + /// + /// This method may be called multiple times on the same socket to change its association, + /// but + /// only the most recently returned pair of streams will be operational. Implementations + /// may trap if + /// the streams returned by a previous invocation haven't been dropped yet before + /// calling `stream` again. + /// + /// The POSIX equivalent in pseudo-code is: + /// ```text + /// if (was previously connected) { + /// connect(s, AF_UNSPEC) + /// } + /// if (remote_address is Some) { + /// connect(s, remote_address) + /// } + /// ``` + /// + /// Unlike in POSIX, the socket must already be explicitly bound. /// /// # Typical errors /// - `invalid-argument`: The `remote-address` has the wrong address family. /// (EAFNOSUPPORT) - /// - `invalid-argument`: `remote-address` is not a unicast address. (EINVAL, - /// ENETUNREACH on Linux, EAFNOSUPPORT on MacOS) - /// - `invalid-argument`: `remote-address` is an IPv4-mapped IPv6 address. - /// (EINVAL, EADDRNOTAVAIL on Illumos) /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY - /// (`0.0.0.0` / `::`). (EADDRNOTAVAIL on Windows) - /// - `invalid-argument`: The port in `remote-address` is set to 0. (EADDRNOTAVAIL - /// on Windows) - /// - `invalid-argument`: The socket is already attached to a different network. - /// The `network` passed to `connect` must be identical to the one passed to `bind`. - /// - `invalid-state`: The socket is already in the `connected` state. - /// (EISCONN) - /// - `invalid-state`: The socket is already in the `listening` state. - /// (EOPNOTSUPP, EINVAL on Windows) - /// - `timeout`: Connection timed out. (ETIMEDOUT) - /// - `connection-refused`: The connection was forcefully rejected. (ECONNREFUSED) - /// - `connection-reset`: The connection was reset. (ECONNRESET) - /// - `connection-aborted`: The connection was aborted. (ECONNABORTED) - /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, - /// EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, + /// EADDRNOTAVAIL) + /// - `invalid-state`: The socket is not bound. /// - `address-in-use`: Tried to perform an implicit bind, but there were /// no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) - /// - `not-in-progress`: A connect operation is not in progress. - /// - `would-block`: Can't finish the operation, it is still in progress. - /// (EWOULDBLOCK, EAGAIN) - /// - /// # Implementors note - /// The POSIX equivalent of `start-connect` is the regular `connect` syscall. - /// Because all WASI sockets are non-blocking this is expected to return - /// EINPROGRESS, which should be translated to `ok()` in WASI. - /// - /// The POSIX equivalent of `finish-connect` is a `poll` for event `POLLOUT` - /// with a timeout of 0 on the socket descriptor. Followed by a check for - /// the `SO_ERROR` socket option, in case the poll signaled readiness. + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, + /// ENETRESET, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) /// /// # References /// - /// - /// - /// - - start-connect: func(network: borrow, remote-address: ip-socket-address) -> result<_, error-code>; + %stream: func(remote-address: option) -> result, error-code>; - /// Start listening for new connections. + /// Create a `pollable` which will resolve once the socket is ready for I/O. /// - /// Transitions the socket into the `listening` state. + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + + /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. /// - /// Unlike POSIX, the socket must already be explicitly bound. + /// If the provided value is 0, an `invalid-argument` error is returned. /// /// # Typical errors - /// - `invalid-state`: The socket is not bound to any local address. (EDESTADDRREQ) - /// - `invalid-state`: The socket is already in the `connected` state. - /// (EISCONN, EINVAL on BSD) - /// - `invalid-state`: The socket is already in the `listening` state. - /// - `address-in-use`: Tried to perform an implicit bind, but there were - /// no ephemeral ports available. (EADDRINUSE) - /// - `not-in-progress`: A listen operation is not in progress. - /// - `would-block`: Can't finish the operation, it is still in progress. - /// (EWOULDBLOCK, EAGAIN) + /// - `invalid-argument`: (set) The TTL value must be 1 or higher. + unicast-hop-limit: func() -> result; + } + resource incoming-datagram-stream { + + /// Receive messages on the socket. /// - /// # Implementors note - /// Unlike in POSIX, in WASI the listen operation is async. This enables - /// interactive WASI hosts to inject permission prompts. Runtimes that - /// don't want to make use of this ability can simply call the native - /// `listen` as part of either `start-listen` or `finish-listen`. + /// This function attempts to receive up to `max-results` datagrams on the socket + /// without blocking. + /// The returned list may contain fewer elements than requested, but never more. + /// + /// This function returns successfully with an empty list when either: + /// - `max-results` is 0, or: + /// - `max-results` is greater than 0, but no results are immediately available. + /// This function never returns `error(would-block)`. + /// + /// # Typical errors + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET + /// on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) /// /// # References - /// - - /// - - /// - - /// - - start-listen: func() -> result<_, error-code>; + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + receive: func(max-results: u64) -> result, error-code>; - /// Create a `pollable` which can be used to poll for, or block on, - /// completion of any of the asynchronous operations of this socket. + /// Create a `pollable` which will resolve once the stream is ready to receive again. /// - /// When `finish-bind`, `finish-listen`, `finish-connect` or `accept` - /// return `error(would-block)`, this pollable can be used to wait for - /// their success or failure, after which the method can be retried. + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } + resource outgoing-datagram-stream { + + /// Check readiness for sending. This function never blocks. /// - /// The pollable is not limited to the async operation that happens to be - /// in progress at the time of calling `subscribe` (if any). Theoretically, - /// `subscribe` only has to be called once per socket and can then be - /// (re)used for the remainder of the socket's lifetime. + /// Returns the number of datagrams permitted for the next call to `send`, + /// or an error. Calling `send` with more datagrams than this function has + /// permitted will trap. + /// + /// When this function returns ok(0), the `subscribe` pollable will + /// become ready when this function will report at least ok(1), or an + /// error. + /// + /// Never returns `would-block`. + check-send: func() -> result; + + /// Send messages on the socket. + /// + /// This function attempts to send all provided `datagrams` on the socket without + /// blocking and + /// returns how many messages were actually sent (or queued for sending). This function + /// never + /// returns `error(would-block)`. If none of the datagrams were able to be sent, `ok(0)` + /// is returned. + /// + /// This function semantically behaves the same as iterating the `datagrams` list + /// and sequentially + /// sending each individual datagram until either the end of the list has been reached + /// or the first error occurred. + /// If at least one datagram has been sent successfully, this function never returns + /// an error. + /// + /// If the input list is empty, the function returns `ok(0)`. + /// + /// Each call to `send` must be permitted by a preceding `check-send`. Implementations + /// must trap if + /// either `check-send` was not called or `datagrams` contains more items than `check-send` + /// permitted. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. + /// (EAFNOSUPPORT) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY + /// (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, + /// EADDRNOTAVAIL) + /// - `invalid-argument`: The socket is in "connected" mode and `remote-address` + /// is `some` value that does not match the address passed to `stream`. (EISCONN) + /// - `invalid-argument`: The socket is not "connected" and no value for `remote-address` + /// was provided. (EDESTADDRREQ) + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, + /// ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// - `datagram-too-large`: The datagram is too large. (EMSGSIZE) /// - /// See - /// for a more information. + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + send: func(datagrams: list) -> result; + + /// Create a `pollable` which will resolve once the stream is ready to send again. /// /// Note: this function is here for WASI Preview2 only. /// It's planned to be removed when `future` is natively supported in Preview3. @@ -2423,23 +2278,23 @@ package wasi:sockets@0.2.0 { } } - interface tcp-create-socket { + interface udp-create-socket { use network.{network}; use network.{error-code}; use network.{ip-address-family}; - use tcp.{tcp-socket}; + use udp.{udp-socket}; - /// Create a new TCP socket. + /// Create a new UDP socket. /// - /// Similar to `socket(AF_INET or AF_INET6, SOCK_STREAM, IPPROTO_TCP)` in POSIX. + /// Similar to `socket(AF_INET or AF_INET6, SOCK_DGRAM, IPPROTO_UDP)` in POSIX. /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. /// /// This function does not require a network capability handle. This is considered /// to be safe because /// at time of creation, the socket is not bound to any `network` yet. Up to the moment - /// `bind`/`connect` - /// is called, the socket is effectively an in-memory configuration object, unable - /// to communicate with the outside world. + /// `bind` is called, + /// the socket is effectively an in-memory configuration object, unable to communicate + /// with the outside world. /// /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous /// operations. @@ -2449,363 +2304,508 @@ package wasi:sockets@0.2.0 { /// - `new-socket-limit`: The new socket resource could not be created because of /// a system limit. (EMFILE, ENFILE) /// - /// # References + /// # References: /// - /// - /// - /// - - create-tcp-socket: func(address-family: ip-address-family) -> result; + create-udp-socket: func(address-family: ip-address-family) -> result; } - interface udp { + world imports { + import network; + import instance-network; + import wasi:io/poll@0.2.0; + import udp; + import udp-create-socket; + import wasi:io/error@0.2.0; + import wasi:io/streams@0.2.0; + import wasi:clocks/monotonic-clock@0.2.0; + import tcp; + import tcp-create-socket; + import ip-name-lookup; + } +} + +package wasi:clocks@0.2.0 { + /// WASI Monotonic Clock is a clock API intended to let users measure elapsed + /// time. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + /// + /// A monotonic clock is a clock which has an unspecified initial value, and + /// successive reads of the clock will produce non-decreasing values. + /// + /// It is intended for measuring elapsed time. + interface monotonic-clock { use wasi:io/poll@0.2.0.{pollable}; - use network.{network}; - use network.{error-code}; - use network.{ip-socket-address}; - use network.{ip-address-family}; - /// A received datagram. - record incoming-datagram { - /// The payload. - /// - /// Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes. - data: list, - /// The source address. - /// - /// This field is guaranteed to match the remote address the stream was initialized - /// with, if any. - /// - /// Equivalent to the `src_addr` out parameter of `recvfrom`. - remote-address: ip-socket-address, - } + /// An instant in time, in nanoseconds. An instant is relative to an + /// unspecified initial value, and can only be compared to instances from + /// the same monotonic-clock. + type instant = u64; - /// A datagram to be sent out. - record outgoing-datagram { - /// The payload. - data: list, - /// The destination address. - /// - /// The requirements on this field depend on how the stream was initialized: - /// - with a remote address: this field must be None or match the stream's remote - /// address exactly. - /// - without a remote address: this field is required. - /// - /// If this value is None, the send operation is equivalent to `send` in POSIX. Otherwise - /// it is equivalent to `sendto`. - remote-address: option, - } + /// A duration of time, in nanoseconds. + type duration = u64; - /// A UDP socket handle. - resource udp-socket { + /// Read the current value of the clock. + /// + /// The clock is monotonic, therefore calling this function repeatedly will + /// produce a sequence of non-decreasing values. + now: func() -> instant; - /// Whether this is a IPv4 or IPv6 socket. - /// - /// Equivalent to the SO_DOMAIN socket option. - address-family: func() -> ip-address-family; - finish-bind: func() -> result<_, error-code>; + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + resolution: func() -> duration; - /// Get the current bound address. - /// - /// POSIX mentions: - /// > If the socket has not been bound to a local name, the value - /// > stored in the object pointed to by `address` is unspecified. - /// - /// WASI is stricter and requires `local-address` to return `invalid-state` when the - /// socket hasn't been bound yet. - /// - /// # Typical errors - /// - `invalid-state`: The socket is not bound to any local address. - /// - /// # References - /// - - /// - - /// - - /// - - local-address: func() -> result; + /// Create a `pollable` which will resolve once the specified instant + /// occured. + subscribe-instant: func(when: instant) -> pollable; - /// The kernel buffer space reserved for sends/receives on this socket. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or - /// rounded. - /// I.e. after setting a value, reading the same setting back may return a different - /// value. - /// - /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The provided value was 0. - receive-buffer-size: func() -> result; + /// Create a `pollable` which will resolve once the given duration has + /// elapsed, starting at the time at which this function was called. + /// occured. + subscribe-duration: func(when: duration) -> pollable; + } - /// Get the address the socket is currently streaming to. - /// - /// # Typical errors - /// - `invalid-state`: The socket is not streaming to a specific remote address. (ENOTCONN) - /// - /// # References - /// - - /// - - /// - - /// - - remote-address: func() -> result; - send-buffer-size: func() -> result; - set-receive-buffer-size: func(value: u64) -> result<_, error-code>; - set-send-buffer-size: func(value: u64) -> result<_, error-code>; - set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; + /// WASI Wall Clock is a clock API intended to let users query the current + /// time. The name "wall" makes an analogy to a "clock on the wall", which + /// is not necessarily monotonic as it may be reset. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + /// + /// A wall clock is a clock which measures the date and time according to + /// some external reference. + /// + /// External references may be reset, so this clock is not necessarily + /// monotonic, making it unsuitable for measuring elapsed time. + /// + /// It is intended for reporting the current date and time for humans. + interface wall-clock { + /// A time and date in seconds plus nanoseconds. + record datetime { + seconds: u64, + nanoseconds: u32, + } - /// Bind the socket to a specific network on the provided IP address and port. - /// - /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the - /// implementation to decide which - /// network interface(s) to bind to. - /// If the port is zero, the socket will be bound to a random free port. - /// - /// # Typical errors - /// - `invalid-argument`: The `local-address` has the wrong address family. - /// (EAFNOSUPPORT, EFAULT on Windows) - /// - `invalid-state`: The socket is already bound. (EINVAL) - /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS - /// on Windows) - /// - `address-in-use`: Address is already in use. (EADDRINUSE) - /// - `address-not-bindable`: `local-address` is not an address that the `network` - /// can bind to. (EADDRNOTAVAIL) - /// - `not-in-progress`: A `bind` operation is not in progress. - /// - `would-block`: Can't finish the operation, it is still in progress. - /// (EWOULDBLOCK, EAGAIN) + /// Read the current value of the clock. + /// + /// This clock is not monotonic, therefore calling this function repeatedly + /// will not necessarily produce a sequence of non-decreasing values. + /// + /// The returned timestamps represent the number of seconds since + /// 1970-01-01T00:00:00Z, also known as [POSIX's Seconds Since the Epoch], + /// also known as [Unix Time]. + /// + /// The nanoseconds field of the output is always less than 1000000000. + /// + /// [POSIX's Seconds Since the Epoch]: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html#tag_21_04_16 + /// [Unix Time]: https://en.wikipedia.org/wiki/Unix_time + now: func() -> datetime; + + /// Query the resolution of the clock. + /// + /// The nanoseconds field of the output is always less than 1000000000. + resolution: func() -> datetime; + } + + world imports { + import wasi:io/poll@0.2.0; + import monotonic-clock; + import wall-clock; + } +} + +package wasi:io@0.2.0 { + interface error { + /// A resource which represents some error information. + /// + /// The only method provided by this resource is `to-debug-string`, + /// which provides some human-readable information about the error. + /// + /// In the `wasi:io` package, this resource is returned through the + /// `wasi:io/streams/stream-error` type. + /// + /// To provide more specific error information, other interfaces may + /// provide functions to further "downcast" this error into more specific + /// error information. For example, `error`s returned in streams derived + /// from filesystem types to be described using the filesystem's own + /// error-code type, using the function + /// `wasi:filesystem/types/filesystem-error-code`, which takes a parameter + /// `borrow` and returns + /// `option`. + /// + /// The set of functions which can "downcast" an `error` into a more + /// concrete type is open. + resource error { + + /// Returns a string that is suitable to assist humans in debugging + /// this error. /// - /// # Implementors note - /// Unlike in POSIX, in WASI the bind operation is async. This enables - /// interactive WASI hosts to inject permission prompts. Runtimes that - /// don't want to make use of this ability can simply call the native - /// `bind` as part of either `start-bind` or `finish-bind`. + /// WARNING: The returned string should not be consumed mechanically! + /// It may change across platforms, hosts, or other implementation + /// details. Parsing this string is a major platform-compatibility + /// hazard. + to-debug-string: func() -> string; + } + } + + /// A poll API intended to let users wait for I/O events on multiple handles + /// at once. + interface poll { + /// `pollable` represents a single I/O event which may be ready, or not. + resource pollable { + + /// `block` returns immediately if the pollable is ready, and otherwise + /// blocks until ready. /// - /// # References - /// - - /// - - /// - - /// - - start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + /// This function is equivalent to calling `poll.poll` on a list + /// containing only this pollable. + block: func(); - /// Set up inbound & outbound communication channels, optionally to a specific peer. + /// Return the readiness of a pollable. This function never blocks. /// - /// This function only changes the local socket configuration and does not generate - /// any network traffic. - /// On success, the `remote-address` of the socket is updated. The `local-address` - /// may be updated as well, - /// based on the best network path to `remote-address`. + /// Returns `true` when the pollable is ready, and `false` otherwise. + ready: func() -> bool; + } + + /// Poll for completion on a set of pollables. + /// + /// This function takes a list of pollables, which identify I/O sources of + /// interest, and waits until one or more of the events is ready for I/O. + /// + /// The result `list` contains one or more indices of handles in the + /// argument list that is ready for I/O. + /// + /// If the list contains more elements than can be indexed with a `u32` + /// value, this function traps. + /// + /// A timeout can be implemented by adding a pollable from the + /// wasi-clocks API to the list. + /// + /// This function does not return a `result`; polling in itself does not + /// do any I/O so it doesn't fail. If any of the I/O sources identified by + /// the pollables has an error, it is indicated by marking the source as + /// being reaedy for I/O. + poll: func(in: list>) -> list; + } + + /// WASI I/O is an I/O abstraction API which is currently focused on providing + /// stream types. + /// + /// In the future, the component model is expected to add built-in stream types; + /// when it does, they are expected to subsume this API. + interface streams { + use error.{error}; + use poll.{pollable}; + + /// An error for input-stream and output-stream operations. + variant stream-error { + /// The last operation (a write or flush) failed before completion. /// - /// When a `remote-address` is provided, the returned streams are limited to communicating - /// with that specific peer: - /// - `send` can only be used to send to this destination. - /// - `receive` will only return datagrams sent from the provided `remote-address`. + /// More information is available in the `error` payload. + last-operation-failed(error), + /// The stream is closed: no more input will be accepted by the + /// stream. A closed output-stream will return this error on all + /// future operations. + closed, + } + + /// An input bytestream. + /// + /// `input-stream`s are *non-blocking* to the extent practical on underlying + /// platforms. I/O operations always return promptly; if fewer bytes are + /// promptly available than requested, they return the number of bytes promptly + /// available, which could even be zero. To wait for data to be available, + /// use the `subscribe` function to obtain a `pollable` which can be polled + /// for using `wasi:io/poll`. + resource input-stream { + + /// Read bytes from a stream, after blocking until at least one byte can + /// be read. Except for blocking, behavior is identical to `read`. + blocking-read: func(len: u64) -> result, stream-error>; + + /// Skip bytes from a stream, after blocking until at least one byte + /// can be skipped. Except for blocking behavior, identical to `skip`. + blocking-skip: func(len: u64) -> result; + + /// Perform a non-blocking read from the stream. /// - /// This method may be called multiple times on the same socket to change its association, - /// but - /// only the most recently returned pair of streams will be operational. Implementations - /// may trap if - /// the streams returned by a previous invocation haven't been dropped yet before - /// calling `stream` again. + /// When the source of a `read` is binary data, the bytes from the source + /// are returned verbatim. When the source of a `read` is known to the + /// implementation to be text, bytes containing the UTF-8 encoding of the + /// text are returned. /// - /// The POSIX equivalent in pseudo-code is: - /// ```text - /// if (was previously connected) { - /// connect(s, AF_UNSPEC) - /// } - /// if (remote_address is Some) { - /// connect(s, remote_address) - /// } - /// ``` + /// This function returns a list of bytes containing the read data, + /// when successful. The returned list will contain up to `len` bytes; + /// it may return fewer than requested, but not more. The list is + /// empty when no bytes are available for reading at this time. The + /// pollable given by `subscribe` will be ready when more bytes are + /// available. /// - /// Unlike in POSIX, the socket must already be explicitly bound. + /// This function fails with a `stream-error` when the operation + /// encounters an error, giving `last-operation-failed`, or when the + /// stream is closed, giving `closed`. /// - /// # Typical errors - /// - `invalid-argument`: The `remote-address` has the wrong address family. - /// (EAFNOSUPPORT) - /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY - /// (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) - /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, - /// EADDRNOTAVAIL) - /// - `invalid-state`: The socket is not bound. - /// - `address-in-use`: Tried to perform an implicit bind, but there were - /// no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) - /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, - /// ENETRESET, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) - /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// When the caller gives a `len` of 0, it represents a request to + /// read 0 bytes. If the stream is still open, this call should + /// succeed and return an empty list, or otherwise fail with `closed`. /// - /// # References - /// - - /// - - /// - - /// - - %stream: func(remote-address: option) -> result, error-code>; + /// The `len` parameter is a `u64`, which could represent a list of u8 which + /// is not possible to allocate in wasm32, or not desirable to allocate as + /// as a return value by the callee. The callee may return a list of bytes + /// less than `len` in size while more bytes are available for reading. + read: func(len: u64) -> result, stream-error>; - /// Create a `pollable` which will resolve once the socket is ready for I/O. + /// Skip bytes from a stream. Returns number of bytes skipped. /// - /// Note: this function is here for WASI Preview2 only. - /// It's planned to be removed when `future` is natively supported in Preview3. - subscribe: func() -> pollable; + /// Behaves identical to `read`, except instead of returning a list + /// of bytes, returns the number of bytes consumed from the stream. + skip: func(len: u64) -> result; - /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The TTL value must be 1 or higher. - unicast-hop-limit: func() -> result; + /// Create a `pollable` which will resolve once either the specified stream + /// has bytes available to read or the other end of the stream has been + /// closed. + /// The created `pollable` is a child resource of the `input-stream`. + /// Implementations may trap if the `input-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + subscribe: func() -> pollable; } - resource incoming-datagram-stream { - /// Receive messages on the socket. - /// - /// This function attempts to receive up to `max-results` datagrams on the socket - /// without blocking. - /// The returned list may contain fewer elements than requested, but never more. + /// An output bytestream. + /// + /// `output-stream`s are *non-blocking* to the extent practical on + /// underlying platforms. Except where specified otherwise, I/O operations also + /// always return promptly, after the number of bytes that can be written + /// promptly, which could even be zero. To wait for the stream to be ready to + /// accept data, the `subscribe` function to obtain a `pollable` which can be + /// polled for using `wasi:io/poll`. + resource output-stream { + + /// Request to flush buffered output, and block until flush completes + /// and stream is ready for writing again. + blocking-flush: func() -> result<_, stream-error>; + + /// Read from one stream and write to another, with blocking. /// - /// This function returns successfully with an empty list when either: - /// - `max-results` is 0, or: - /// - `max-results` is greater than 0, but no results are immediately available. - /// This function never returns `error(would-block)`. + /// This is similar to `splice`, except that it blocks until the + /// `output-stream` is ready for writing, and the `input-stream` + /// is ready for reading, before performing the `splice`. + blocking-splice: func(src: borrow, len: u64) -> result; + + /// Perform a write of up to 4096 bytes, and then flush the stream. Block + /// until all of these operations are complete, or an error occurs. /// - /// # Typical errors - /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET - /// on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) - /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write`, and `flush`, and is implemented with the + /// following pseudo-code: /// - /// # References - /// - - /// - - /// - - /// - - /// - - /// - - /// - - /// - - receive: func(max-results: u64) -> result, error-code>; + /// ```text + /// let pollable = this.subscribe(); + /// while !contents.is_empty() { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, contents.len()); + /// let (chunk, rest) = contents.split_at(len); + /// this.write(chunk ); // eliding error handling + /// contents = rest; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + blocking-write-and-flush: func(contents: list) -> result<_, stream-error>; - /// Create a `pollable` which will resolve once the stream is ready to receive again. + /// Perform a write of up to 4096 zeroes, and then flush the stream. + /// Block until all of these operations are complete, or an error + /// occurs. /// - /// Note: this function is here for WASI Preview2 only. - /// It's planned to be removed when `future` is natively supported in Preview3. - subscribe: func() -> pollable; - } - resource outgoing-datagram-stream { + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write-zeroes`, and `flush`, and is implemented with + /// the following pseudo-code: + /// + /// ```text + /// let pollable = this.subscribe(); + /// while num_zeroes != 0 { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, num_zeroes); + /// this.write-zeroes(len); // eliding error handling + /// num_zeroes -= len; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + blocking-write-zeroes-and-flush: func(len: u64) -> result<_, stream-error>; - /// Check readiness for sending. This function never blocks. + /// Check readiness for writing. This function never blocks. /// - /// Returns the number of datagrams permitted for the next call to `send`, - /// or an error. Calling `send` with more datagrams than this function has + /// Returns the number of bytes permitted for the next call to `write`, + /// or an error. Calling `write` with more bytes than this function has /// permitted will trap. /// - /// When this function returns ok(0), the `subscribe` pollable will - /// become ready when this function will report at least ok(1), or an + /// When this function returns 0 bytes, the `subscribe` pollable will + /// become ready when this function will report at least 1 byte, or an /// error. + check-write: func() -> result; + + /// Request to flush buffered output. This function never blocks. /// - /// Never returns `would-block`. - check-send: func() -> result; + /// This tells the output-stream that the caller intends any buffered + /// output to be flushed. the output which is expected to be flushed + /// is all that has been passed to `write` prior to this call. + /// + /// Upon calling this function, the `output-stream` will not accept any + /// writes (`check-write` will return `ok(0)`) until the flush has + /// completed. The `subscribe` pollable will become ready when the + /// flush has completed and the stream can accept more writes. + flush: func() -> result<_, stream-error>; - /// Send messages on the socket. + /// Read from one stream and write to another. /// - /// This function attempts to send all provided `datagrams` on the socket without - /// blocking and - /// returns how many messages were actually sent (or queued for sending). This function - /// never - /// returns `error(would-block)`. If none of the datagrams were able to be sent, `ok(0)` - /// is returned. + /// The behavior of splice is equivelant to: + /// 1. calling `check-write` on the `output-stream` + /// 2. calling `read` on the `input-stream` with the smaller of the + /// `check-write` permitted length and the `len` provided to `splice` + /// 3. calling `write` on the `output-stream` with that read data. /// - /// This function semantically behaves the same as iterating the `datagrams` list - /// and sequentially - /// sending each individual datagram until either the end of the list has been reached - /// or the first error occurred. - /// If at least one datagram has been sent successfully, this function never returns - /// an error. + /// Any error reported by the call to `check-write`, `read`, or + /// `write` ends the splice and reports that error. /// - /// If the input list is empty, the function returns `ok(0)`. + /// This function returns the number of bytes transferred; it may be less + /// than `len`. + splice: func(src: borrow, len: u64) -> result; + + /// Create a `pollable` which will resolve once the output-stream + /// is ready for more writing, or an error has occured. When this + /// pollable is ready, `check-write` will return `ok(n)` with n>0, or an + /// error. /// - /// Each call to `send` must be permitted by a preceding `check-send`. Implementations - /// must trap if - /// either `check-send` was not called or `datagrams` contains more items than `check-send` - /// permitted. + /// If the stream is closed, this pollable is always ready immediately. /// - /// # Typical errors - /// - `invalid-argument`: The `remote-address` has the wrong address family. - /// (EAFNOSUPPORT) - /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY - /// (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) - /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, - /// EADDRNOTAVAIL) - /// - `invalid-argument`: The socket is in "connected" mode and `remote-address` - /// is `some` value that does not match the address passed to `stream`. (EISCONN) - /// - `invalid-argument`: The socket is not "connected" and no value for `remote-address` - /// was provided. (EDESTADDRREQ) - /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, - /// ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) - /// - `connection-refused`: The connection was refused. (ECONNREFUSED) - /// - `datagram-too-large`: The datagram is too large. (EMSGSIZE) + /// The created `pollable` is a child resource of the `output-stream`. + /// Implementations may trap if the `output-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + subscribe: func() -> pollable; + + /// Perform a write. This function never blocks. /// - /// # References - /// - - /// - - /// - - /// - - /// - - /// - - /// - - /// - - send: func(datagrams: list) -> result; + /// When the destination of a `write` is binary data, the bytes from + /// `contents` are written verbatim. When the destination of a `write` is + /// known to the implementation to be text, the bytes of `contents` are + /// transcoded from UTF-8 into the encoding of the destination and then + /// written. + /// + /// Precondition: check-write gave permit of Ok(n) and contents has a + /// length of less than or equal to n. Otherwise, this function will trap. + /// + /// returns Err(closed) without writing if the stream has closed since + /// the last call to check-write provided a permit. + write: func(contents: list) -> result<_, stream-error>; - /// Create a `pollable` which will resolve once the stream is ready to send again. + /// Write zeroes to a stream. /// - /// Note: this function is here for WASI Preview2 only. - /// It's planned to be removed when `future` is natively supported in Preview3. - subscribe: func() -> pollable; + /// This should be used precisely like `write` with the exact same + /// preconditions (must use check-write first), but instead of + /// passing a list of bytes, you simply pass the number of zero-bytes + /// that should be written. + write-zeroes: func(len: u64) -> result<_, stream-error>; } } - interface udp-create-socket { - use network.{network}; - use network.{error-code}; - use network.{ip-address-family}; - use udp.{udp-socket}; + world imports { + import error; + import poll; + import streams; + } +} - /// Create a new UDP socket. +package wasi:random@0.2.0 { + /// The insecure-seed interface for seeding hash-map DoS resistance. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + interface insecure-seed { + /// Return a 128-bit value that may contain a pseudo-random value. /// - /// Similar to `socket(AF_INET or AF_INET6, SOCK_DGRAM, IPPROTO_UDP)` in POSIX. - /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. + /// The returned value is not required to be computed from a CSPRNG, and may + /// even be entirely deterministic. Host implementations are encouraged to + /// provide pseudo-random values to any program exposed to + /// attacker-controlled content, to enable DoS protection built into many + /// languages' hash-map implementations. /// - /// This function does not require a network capability handle. This is considered - /// to be safe because - /// at time of creation, the socket is not bound to any `network` yet. Up to the moment - /// `bind` is called, - /// the socket is effectively an in-memory configuration object, unable to communicate - /// with the outside world. + /// This function is intended to only be called once, by a source language + /// to initialize Denial Of Service (DoS) protection in its hash-map + /// implementation. /// - /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous - /// operations. + /// # Expected future evolution /// - /// # Typical errors - /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) - /// - `new-socket-limit`: The new socket resource could not be created because of - /// a system limit. (EMFILE, ENFILE) + /// This will likely be changed to a value import, to prevent it from being + /// called multiple times and potentially used for purposes other than DoS + /// protection. + insecure-seed: func() -> tuple; + } + + /// The insecure interface for insecure pseudo-random numbers. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + interface insecure { + /// Return `len` insecure pseudo-random bytes. /// - /// # References: - /// - - /// - - /// - - /// - - create-udp-socket: func(address-family: ip-address-family) -> result; + /// This function is not cryptographically secure. Do not use it for + /// anything related to security. + /// + /// There are no requirements on the values of the returned bytes, however + /// implementations are encouraged to return evenly distributed values with + /// a long period. + get-insecure-random-bytes: func(len: u64) -> list; + + /// Return an insecure pseudo-random `u64` value. + /// + /// This function returns the same type of pseudo-random data as + /// `get-insecure-random-bytes`, represented as a `u64`. + get-insecure-random-u64: func() -> u64; + } + + /// WASI Random is a random data API. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + interface random { + /// Return `len` cryptographically-secure random or pseudo-random bytes. + /// + /// This function must produce data at least as cryptographically secure and + /// fast as an adequately seeded cryptographically-secure pseudo-random + /// number generator (CSPRNG). It must not block, from the perspective of + /// the calling program, under any circumstances, including on the first + /// request and on requests for numbers of bytes. The returned data must + /// always be unpredictable. + /// + /// This function must always return fresh data. Deterministic environments + /// must omit this function, rather than implementing it with deterministic + /// data. + get-random-bytes: func(len: u64) -> list; + + /// Return a cryptographically-secure random or pseudo-random `u64` value. + /// + /// This function returns the same type of data as `get-random-bytes`, + /// represented as a `u64`. + get-random-u64: func() -> u64; } world imports { - import network; - import instance-network; - import wasi:io/poll@0.2.0; - import udp; - import udp-create-socket; - import wasi:io/error@0.2.0; - import wasi:io/streams@0.2.0; - import wasi:clocks/monotonic-clock@0.2.0; - import tcp; - import tcp-create-socket; - import ip-name-lookup; + import random; + import insecure; + import insecure-seed; } } diff --git a/testdata/wit-parser/complex-include.wit.json.golden.wit b/testdata/wit-parser/complex-include.wit.json.golden.wit index c1b91887..0f5cb40e 100644 --- a/testdata/wit-parser/complex-include.wit.json.golden.wit +++ b/testdata/wit-parser/complex-include.wit.json.golden.wit @@ -1,51 +1,51 @@ -package foo:bar; +package foo:root; -interface a {} +interface ai {} -interface b {} +interface bi {} -world bar-a { - import a; - import b; +world a { + import ai; + import bi; } -package foo:baz { +world b { + import foo:bar/a; + import foo:bar/b; +} + +world c { + import foo:bar/a; + import foo:bar/b; +} + +world union-world { + import ai; + import bi; + import foo:bar/a; + import foo:bar/b; + import foo:baz/a; + import foo:baz/b; +} + +package foo:bar { interface a {} interface b {} - world baz-a { + world bar-a { import a; import b; } } -package foo:root { - interface ai {} - - interface bi {} - - world a { - import ai; - import bi; - } - - world b { - import foo:bar/a; - import foo:bar/b; - } +package foo:baz { + interface a {} - world c { - import foo:bar/a; - import foo:bar/b; - } + interface b {} - world union-world { - import ai; - import bi; - import foo:bar/a; - import foo:bar/b; - import foo:baz/a; - import foo:baz/b; + world baz-a { + import a; + import b; } } diff --git a/testdata/wit-parser/diamond1.wit.json.golden.wit b/testdata/wit-parser/diamond1.wit.json.golden.wit index 4f55e731..f936a37e 100644 --- a/testdata/wit-parser/diamond1.wit.json.golden.wit +++ b/testdata/wit-parser/diamond1.wit.json.golden.wit @@ -1,14 +1,14 @@ -package foo:dep1; +package foo:foo; -interface types {} +world foo { + import foo:dep1/types; + import foo:dep2/types; +} -package foo:dep2 { +package foo:dep1 { interface types {} } -package foo:foo { - world foo { - import foo:dep1/types; - import foo:dep2/types; - } +package foo:dep2 { + interface types {} } diff --git a/testdata/wit-parser/foreign-deps-union.wit.json.golden.wit b/testdata/wit-parser/foreign-deps-union.wit.json.golden.wit index 5bff9991..414a775f 100644 --- a/testdata/wit-parser/foreign-deps-union.wit.json.golden.wit +++ b/testdata/wit-parser/foreign-deps-union.wit.json.golden.wit @@ -10,12 +10,6 @@ package foo:different-pkg { interface i {} } -package foo:foreign-pkg { - interface the-default { - type some-type = u32; - } -} - package foo:root { interface foo { use foo:wasi/clocks.{timestamp}; @@ -62,6 +56,12 @@ package foo:root { } } +package foo:foreign-pkg { + interface the-default { + type some-type = u32; + } +} + package foo:some-pkg { interface the-default { type from-default = string; diff --git a/testdata/wit-parser/foreign-deps.wit.json.golden.wit b/testdata/wit-parser/foreign-deps.wit.json.golden.wit index a9037382..0503a6ac 100644 --- a/testdata/wit-parser/foreign-deps.wit.json.golden.wit +++ b/testdata/wit-parser/foreign-deps.wit.json.golden.wit @@ -10,12 +10,6 @@ package foo:different-pkg { interface i {} } -package foo:foreign-pkg { - interface the-default { - type some-type = u32; - } -} - package foo:root { interface foo { use foo:wasi/clocks.{timestamp}; @@ -55,6 +49,12 @@ package foo:root { } } +package foo:foreign-pkg { + interface the-default { + type some-type = u32; + } +} + package foo:some-pkg { interface the-default { type from-default = string; diff --git a/testdata/wit-parser/ignore-files-deps.wit.json.golden.wit b/testdata/wit-parser/ignore-files-deps.wit.json.golden.wit index dd58f80f..10e775ee 100644 --- a/testdata/wit-parser/ignore-files-deps.wit.json.golden.wit +++ b/testdata/wit-parser/ignore-files-deps.wit.json.golden.wit @@ -1,9 +1,9 @@ -package foo:bar; +package foo:foo; -interface types {} +world foo { + import foo:bar/types; +} -package foo:foo { - world foo { - import foo:bar/types; - } +package foo:bar { + interface types {} } diff --git a/testdata/wit-parser/multi-package-shared-deps.wit.json.golden.wit b/testdata/wit-parser/multi-package-shared-deps.wit.json.golden.wit index 27a7c7f6..9aae55c0 100644 --- a/testdata/wit-parser/multi-package-shared-deps.wit.json.golden.wit +++ b/testdata/wit-parser/multi-package-shared-deps.wit.json.golden.wit @@ -5,6 +5,13 @@ world w-bar { import foo:dep2/types; } +package foo:qux { + world w-qux { + import foo:dep1/types; + import foo:dep2/types; + } +} + package foo:dep1 { interface types {} } @@ -12,10 +19,3 @@ package foo:dep1 { package foo:dep2 { interface types {} } - -package foo:qux { - world w-qux { - import foo:dep1/types; - import foo:dep2/types; - } -} diff --git a/testdata/wit-parser/multi-package-transitive-deps.wit.json.golden.wit b/testdata/wit-parser/multi-package-transitive-deps.wit.json.golden.wit index 3788d564..d4e125ee 100644 --- a/testdata/wit-parser/multi-package-transitive-deps.wit.json.golden.wit +++ b/testdata/wit-parser/multi-package-transitive-deps.wit.json.golden.wit @@ -12,14 +12,14 @@ package foo:dep1 { } } -package foo:dep2 { - interface types { - resource a; - } -} - package foo:qux { world w-qux { import foo:dep2/types; } } + +package foo:dep2 { + interface types { + resource a; + } +} diff --git a/testdata/wit-parser/versions.wit.json.golden.wit b/testdata/wit-parser/versions.wit.json.golden.wit index 82572c64..b7717594 100644 --- a/testdata/wit-parser/versions.wit.json.golden.wit +++ b/testdata/wit-parser/versions.wit.json.golden.wit @@ -1,18 +1,18 @@ -package a:a@1.0.0; +package foo:versions; interface foo { - type t = u32; + use a:a/foo@1.0.0.{t}; + use a:a/foo@2.0.0.{t as t2}; } -package a:a@2.0.0 { +package a:a@1.0.0 { interface foo { type t = u32; } } -package foo:versions { +package a:a@2.0.0 { interface foo { - use a:a/foo@1.0.0.{t}; - use a:a/foo@2.0.0.{t as t2}; + type t = u32; } } diff --git a/wit/resolve.go b/wit/resolve.go index 209ad58a..905a1bbf 100644 --- a/wit/resolve.go +++ b/wit/resolve.go @@ -1,7 +1,6 @@ package wit import ( - "cmp" "fmt" "slices" "strconv" @@ -62,7 +61,19 @@ type World struct { Docs Docs } -// WITPackage returns the [Package] this [World] belongs to. +func (w *World) dependsOn(pkg *Package) bool { + if w.Package == pkg { + return true + } + var done bool + w.AllItems()(func(_ string, i WorldItem) bool { + done = DependsOn(i, pkg) + return !done + }) + return done +} + +// WITPackage returns the [Package] that [World] w belongs to. func (w *World) WITPackage() *Package { return w.Package } @@ -98,7 +109,7 @@ func (w *World) HasInterface(i *Interface) bool { // [sequence]: https://github.com/golang/go/issues/61897 func (w *World) AllInterfaces() iterate.Seq2[string, *Interface] { return func(yield func(string, *Interface) bool) { - w.AllImportsAndExports()(func(name string, i WorldItem) bool { + w.AllItems()(func(name string, i WorldItem) bool { if ref, ok := i.(*InterfaceRef); ok { return yield(name, ref.Interface) } @@ -107,13 +118,28 @@ func (w *World) AllInterfaces() iterate.Seq2[string, *Interface] { } } +// AllTypeDefs returns a [sequence] that yields each [TypeDef] in a [World]. +// The sequence stops if yield returns false. +// +// [sequence]: https://github.com/golang/go/issues/61897 +func (w *World) AllTypeDefs() iterate.Seq2[string, *TypeDef] { + return func(yield func(string, *TypeDef) bool) { + w.AllItems()(func(name string, i WorldItem) bool { + if t, ok := i.(*TypeDef); ok { + return yield(name, t) + } + return true + }) + } +} + // AllFunctions returns a [sequence] that yields each [Function] in a [World]. // The sequence stops if yield returns false. // // [sequence]: https://github.com/golang/go/issues/61897 func (w *World) AllFunctions() iterate.Seq[*Function] { return func(yield func(*Function) bool) { - w.AllImportsAndExports()(func(_ string, i WorldItem) bool { + w.AllItems()(func(_ string, i WorldItem) bool { if f, ok := i.(*Function); ok { return yield(f) } @@ -122,11 +148,11 @@ func (w *World) AllFunctions() iterate.Seq[*Function] { } } -// AllImportsAndExports returns a [sequence] that yields each [WorldItem] in a [World]. +// AllItems returns a [sequence] that yields each [WorldItem] in a [World]. // The sequence stops if yield returns false. // // [sequence]: https://github.com/golang/go/issues/61897 -func (w *World) AllImportsAndExports() iterate.Seq2[string, WorldItem] { +func (w *World) AllItems() iterate.Seq2[string, WorldItem] { return func(yield func(string, WorldItem) bool) { var done bool yield = iterate.Done2(iterate.Once2(yield), func() { done = true }) @@ -163,6 +189,10 @@ type InterfaceRef struct { Stability Stability } +func (ref *InterfaceRef) dependsOn(pkg *Package) bool { + return DependsOn(ref.Interface, pkg) +} + // An Interface represents a [collection of types and functions], which are imported into // or exported from a [WebAssembly component]. // It implements the [Node], and [TypeOwner] interfaces. @@ -180,6 +210,25 @@ type Interface struct { Docs Docs } +func (i *Interface) dependsOn(pkg *Package) bool { + if i.Package == pkg { + return true + } + var done bool + i.TypeDefs.All()(func(_ string, t *TypeDef) bool { + done = DependsOn(t, pkg) + return !done + }) + if done { + return true + } + i.Functions.All()(func(_ string, f *Function) bool { + done = DependsOn(f, pkg) + return !done + }) + return done +} + // WITPackage returns the [Package] this [Interface] belongs to. func (i *Interface) WITPackage() *Package { return i.Package @@ -271,9 +320,7 @@ func (t *TypeDef) StaticFunctions() []*Function { } return true }) - slices.SortFunc(statics, func(a, b *Function) int { - return cmp.Compare(a.Name, b.Name) - }) + slices.SortFunc(statics, compareFunctions) return statics } @@ -287,12 +334,14 @@ func (t *TypeDef) Methods() []*Function { } return true }) - slices.SortFunc(methods, func(a, b *Function) int { - return cmp.Compare(a.Name, b.Name) - }) + slices.SortFunc(methods, compareFunctions) return methods } +func compareFunctions(a, b *Function) int { + return strings.Compare(a.Name, b.Name) +} + // Size returns the byte size for values of type t. func (t *TypeDef) Size() uintptr { return t.Kind.Size() @@ -310,6 +359,13 @@ func (t *TypeDef) Flat() []Type { return t.Kind.Flat() } +func (t *TypeDef) dependsOn(pkg *Package) bool { + if t.Owner != nil && t.Owner.WITPackage() == pkg { + return true + } + return DependsOn(t.Kind, pkg) +} + func (t *TypeDef) hasPointer() bool { return HasPointer(t.Kind) } func (t *TypeDef) hasBorrow() bool { return HasBorrow(t.Kind) } func (t *TypeDef) hasResource() bool { return HasResource(t.Kind) } @@ -368,10 +424,10 @@ func (*Pointer) Align() uintptr { return 4 } // [flattened]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#flattening func (p *Pointer) Flat() []Type { return []Type{PointerTo(p.Type)} } -// hasPointer always returns true. -func (*Pointer) hasPointer() bool { return true } -func (p *Pointer) hasBorrow() bool { return HasBorrow(p.Type) } -func (p *Pointer) hasResource() bool { return HasResource(p.Type) } +func (p *Pointer) dependsOn(pkg *Package) bool { return DependsOn(p.Type, pkg) } +func (*Pointer) hasPointer() bool { return true } +func (p *Pointer) hasBorrow() bool { return HasBorrow(p.Type) } +func (p *Pointer) hasResource() bool { return HasResource(p.Type) } // Record represents a WIT [record type], akin to a struct. // It implements the [Node], [ABI], and [TypeDefKind] interfaces. @@ -416,6 +472,15 @@ func (r *Record) Flat() []Type { return flat } +func (r *Record) dependsOn(pkg *Package) bool { + for _, f := range r.Fields { + if DependsOn(f.Type, pkg) { + return true + } + } + return false +} + func (r *Record) hasPointer() bool { for _, f := range r.Fields { if HasPointer(f.Type) { @@ -517,7 +582,8 @@ type Own struct { Type *TypeDef } -func (o *Own) hasResource() bool { return HasResource(o.Type) } +func (o *Own) dependsOn(pkg *Package) bool { return DependsOn(o.Type, pkg) } +func (o *Own) hasResource() bool { return HasResource(o.Type) } // Borrow represents a WIT [borrowed handle]. // It implements the [Handle], [Node], [ABI], and [TypeDefKind] interfaces. @@ -528,8 +594,9 @@ type Borrow struct { Type *TypeDef } -func (b *Borrow) hasBorrow() bool { return true } -func (b *Borrow) hasResource() bool { return HasResource(b.Type) } +func (b *Borrow) dependsOn(pkg *Package) bool { return DependsOn(b.Type, pkg) } +func (b *Borrow) hasBorrow() bool { return true } +func (b *Borrow) hasResource() bool { return HasResource(b.Type) } // Flags represents a WIT [flags type], stored as a bitfield. // It implements the [Node], [ABI], and [TypeDefKind] interfaces. @@ -760,6 +827,15 @@ func (v *Variant) maxCaseAlign() uintptr { return a } +func (v *Variant) dependsOn(pkg *Package) bool { + for _, t := range v.Types() { + if DependsOn(t, pkg) { + return true + } + } + return false +} + func (v *Variant) hasPointer() bool { for _, t := range v.Types() { if HasPointer(t) { @@ -795,6 +871,10 @@ type Case struct { Docs Docs } +func (c *Case) dependsOn(pkg *Package) bool { + return DependsOn(c.Type, pkg) +} + // Enum represents a WIT [enum type], which is a [Variant] without associated data. // The equivalent in Go is a set of const identifiers declared with iota. // It implements the [Node], [ABI], and [TypeDefKind] interfaces. @@ -988,9 +1068,10 @@ func (*List) Align() uintptr { return 8 } // [2]int32 // [flattened]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#flattening func (l *List) Flat() []Type { return []Type{PointerTo(l.Type), U32{}} } -func (*List) hasPointer() bool { return true } -func (l *List) hasBorrow() bool { return HasBorrow(l.Type) } -func (l *List) hasResource() bool { return HasResource(l.Type) } +func (l *List) dependsOn(p *Package) bool { return DependsOn(l.Type, p) } +func (*List) hasPointer() bool { return true } +func (l *List) hasBorrow() bool { return HasBorrow(l.Type) } +func (l *List) hasResource() bool { return HasResource(l.Type) } // Future represents a WIT [future type], expected to be part of [WASI Preview 3]. // It implements the [Node], [ABI], and [TypeDefKind] interfaces. @@ -1020,9 +1101,10 @@ func (*Future) Align() uintptr { return 0 } // [flattened]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#flattening func (*Future) Flat() []Type { return nil } -func (f *Future) hasPointer() bool { return HasPointer(f.Type) } -func (f *Future) hasBorrow() bool { return HasBorrow(f.Type) } -func (f *Future) hasResource() bool { return HasResource(f.Type) } +func (f *Future) dependsOn(p *Package) bool { return DependsOn(f.Type, p) } +func (f *Future) hasPointer() bool { return HasPointer(f.Type) } +func (f *Future) hasBorrow() bool { return HasBorrow(f.Type) } +func (f *Future) hasResource() bool { return HasResource(f.Type) } // Stream represents a WIT [stream type], expected to be part of [WASI Preview 3]. // It implements the [Node], [ABI], and [TypeDefKind] interfaces. @@ -1053,9 +1135,10 @@ func (*Stream) Align() uintptr { return 0 } // [flattened]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md#flattening func (*Stream) Flat() []Type { return nil } -func (s *Stream) hasPointer() bool { return HasPointer(s.Element) || HasPointer(s.End) } -func (s *Stream) hasBorrow() bool { return HasBorrow(s.Element) || HasBorrow(s.End) } -func (s *Stream) hasResource() bool { return HasResource(s.Element) || HasResource(s.End) } +func (s *Stream) dependsOn(p *Package) bool { return DependsOn(s.Element, p) || DependsOn(s.End, p) } +func (s *Stream) hasPointer() bool { return HasPointer(s.Element) || HasPointer(s.End) } +func (s *Stream) hasBorrow() bool { return HasBorrow(s.Element) || HasBorrow(s.End) } +func (s *Stream) hasResource() bool { return HasResource(s.Element) || HasResource(s.End) } // TypeOwner is the interface implemented by any type that can own a TypeDef, // currently [World] and [Interface]. @@ -1329,6 +1412,20 @@ type Function struct { Docs Docs } +func (f *Function) dependsOn(pkg *Package) bool { + for _, p := range f.Params { + if DependsOn(p.Type, pkg) { + return true + } + } + for _, r := range f.Results { + if DependsOn(r.Type, pkg) { + return true + } + } + return false +} + // BaseName returns the base name of [Function] f. // For static functions, this returns the function name unchanged. // For constructors, this removes the [constructor] and type prefix. @@ -1487,6 +1584,58 @@ type Package struct { Docs Docs } +func (p *Package) dependsOn(pkg *Package) bool { + if pkg == p { + return true + } + var done bool + p.Interfaces.All()(func(_ string, i *Interface) bool { + done = DependsOn(i, pkg) + return !done + }) + if done { + return true + } + p.Worlds.All()(func(_ string, w *World) bool { + done = DependsOn(w, pkg) + return !done + }) + return done +} + +// DependsOn returns true if [Node] node depends on [Package] p. +// Because a package implicitly depends on itself, this returns true if node == p. +func DependsOn(node Node, p *Package) bool { + if node == nil { + return false + } + if node == p { + return true + } + if k, ok := node.(TypeDefKind); ok { + node = Despecialize(k) + } + if d, ok := node.(interface{ dependsOn(*Package) bool }); ok { + return d.dependsOn(p) + } + return false +} + +func comparePackages(a, b *Package) int { + switch { + case a == b: + return 0 + case DependsOn(b, a): + // println(b.Name.String() + " depends on " + a.Name.String()) + return 1 + case DependsOn(a, b): + // println(a.Name.String() + " depends on " + b.Name.String()) + return -1 + } + // println(a.Name.String() + " does not depend on " + b.Name.String()) + return strings.Compare(a.Name.String(), b.Name.String()) +} + // Stability represents the version or feature-gated stability of a given feature. type Stability interface { Node diff --git a/wit/testdata_test.go b/wit/testdata_test.go index 79d614f6..83132b32 100644 --- a/wit/testdata_test.go +++ b/wit/testdata_test.go @@ -15,7 +15,10 @@ import ( "github.com/sergi/go-diff/diffmatchpatch" ) -var update = flag.Bool("update", false, "update golden files") +var ( + update = flag.Bool("update", false, "update golden files") + debug = flag.Bool("debug", false, "debug errors by writing files") +) func compareOrWrite(t *testing.T, path, golden, data string) { if *update { @@ -105,6 +108,9 @@ func TestGoldenWITRoundTrip(t *testing.T) { // Convert back to WIT. data2 := res2.WIT(nil, "") if string(data2) != data { + if *debug { + os.WriteFile(path+".fail.wit", []byte(data2), os.ModePerm) + } dmp := diffmatchpatch.New() dmp.PatchMargin = 3 diffs := dmp.DiffMain(data, data2, false) diff --git a/wit/wit.go b/wit/wit.go index 1e8ca38f..988b2a2c 100644 --- a/wit/wit.go +++ b/wit/wit.go @@ -54,10 +54,10 @@ func (*Resolve) WITKind() string { return "resolve" } // // [WIT]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/WIT.md func (r *Resolve) WIT(ctx Node, _ string) string { + // Sort packages topologically by dependency packages := slices.Clone(r.Packages) - slices.SortFunc(packages, func(a, b *Package) int { - return strings.Compare(a.Name.String(), b.Name.String()) - }) + slices.SortFunc(packages, comparePackages) + var b strings.Builder var hasContent bool for i, p := range packages { @@ -392,7 +392,7 @@ func (t *TypeDef) WIT(ctx Node, name string) string { b.WriteRune('\n') n++ } - slices.SortFunc(methods, functionCompare) + slices.SortFunc(methods, compareFunctions) for _, f := range methods { if f.Docs.Contents != "" { b.WriteRune('\n') @@ -401,7 +401,7 @@ func (t *TypeDef) WIT(ctx Node, name string) string { b.WriteRune('\n') n++ } - slices.SortFunc(statics, functionCompare) + slices.SortFunc(statics, compareFunctions) for _, f := range statics { if f.Docs.Contents != "" { b.WriteRune('\n') @@ -424,10 +424,6 @@ func (t *TypeDef) WIT(ctx Node, name string) string { return t.Kind.WIT(ctx, name) } -func functionCompare(a, b *Function) int { - return strings.Compare(a.Name, b.Name) -} - func escape(name string) string { if witKeywords[name] { return "%" + name