diff --git a/.gitignore b/.gitignore index 917660a34..28b58e27d 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -*.wasm \ No newline at end of file +*.wasm +tmp/ diff --git a/proposals/cli/LICENSE.md b/proposals/cli/LICENSE.md new file mode 100644 index 000000000..c1c3b9443 --- /dev/null +++ b/proposals/cli/LICENSE.md @@ -0,0 +1,8 @@ +Copyright © 2019-2024 the Contributors to the WASI Specification, published +by the [WebAssembly Community Group][cg] under the +[W3C Community Contributor License Agreement (CLA)][cla]. A human-readable +[summary][summary] is available. + +[cg]: https://www.w3.org/community/webassembly/ +[cla]: https://www.w3.org/community/about/agreements/cla/ +[summary]: https://www.w3.org/community/about/agreements/cla-deed/ diff --git a/proposals/cli/README.md b/proposals/cli/README.md new file mode 100644 index 000000000..7df15996a --- /dev/null +++ b/proposals/cli/README.md @@ -0,0 +1,119 @@ +# WASI CLI World + +A proposed [WebAssembly System Interface](https://github.com/WebAssembly/WASI) API. + +### Current Phase + +wasi-cli is currently in [Phase 3]. + +[Phase 3]: https://github.com/WebAssembly/WASI/blob/main/Proposals.md#phase-3---implementation-phase-cg--wg + +### Champions + +- Dan Gohman + +### Portability Criteria + +WASI CLI must have host implementations which can pass the testsuite +on at least Windows, macOS, and Linux. + +WASI CLI must have at least two complete independent implementations. + +## Table of Contents + +- [Introduction](#introduction) +- [Goals [or Motivating Use Cases, or Scenarios]](#goals-or-motivating-use-cases-or-scenarios) +- [Non-goals](#non-goals) +- [API walk-through](#api-walk-through) + - [Use case 1](#use-case-1) + - [Use case 2](#use-case-2) +- [Detailed design discussion](#detailed-design-discussion) + - [Should stdout be an `output-stream`?](#should-stdout-be-an-output-stream) + - [Should stderr be an `output-stream`?](#should-stderr-be-an-output-stream) + - [Should environment variables be arguments to `command`?](#should-environment-variables-be-arguments-to-command) +- [Stakeholder Interest & Feedback](#stakeholder-interest--feedback) +- [References & acknowledgements](#references--acknowledgements) + +### Introduction + +Wasi-cli a [World] proposal for a Command-Line Interface (CLI) environment. It provides APIs commonly available in such environments, such as filesystems and sockets, and also provides command-line facilities such as command-line arguments, environment variables, and stdio. + +[World]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/WIT.md#wit-worlds + +### Goals + +Wasi-cli aims to be useful for: + + - Interactive command-line argument programs. + + - Servers that use filesystems, sockets, and related APIs and expect to be started with + a CLI-style command-line. + + - Stream filters that read from standard input and write to standard output. + +### Non-goals + +Wasi-cli is not aiming to significantly re-imagine the concept of command-line interface programs. While WASI as a whole is exploring ideas such as [Typed Main], wasi-cli sticks to the traditional list-of-strings style command-line arguments. + +[Typed Main]: https://sunfishcode.github.io/typed-main-wasi-presentation/ + +### API walk-through + +The full API documentation can be found [here](command.md). + +TODO [Walk through of how someone would use this API.] + +#### [Use case 1] + +[Provide example code snippets and diagrams explaining how the API would be used to solve the given problem] + +#### [Use case 2] + +[etc.] + +### Detailed design discussion + +#### Should stdout be an `output-stream`? + +For server use cases, standard output (stdout) is typically used as a log, +where it's typically not meaningfully blocking, async, or fallible. It's just +a place for the program to send messages to and forget about them. One option +would be to give such use cases a dedicated API, which would have a single +function to allow printing strings that doesn't return a `result`, meaning it +never fails. + +However, it'd only be a minor simplification in practice, and dedicated cloud +or edge use cases should ideally migrate to more specialized worlds than the +wasi-cli world anyway, as they can result in much greater simplifications, so +this doesn't seem worthwhile. + +#### Should stderr be an `output-stream`? + +This is similar to the question for stdout, but for standard error (stderr), +it's a little more tempting to do something like this because stderr is used +in this logging style by many kinds of applications. + +However, it seems better overall to keep stderr consistent with stdout, and +focus our desires for simplification toward other worlds, which can achieve +even greater simplifications. + +#### Should environment variables be arguments to `command`? + +Environment variables are useful in some non-cli use cases, so leaving them +as separate imports means they can be used from worlds that don't have a +`command` entrypoint. + +### Stakeholder Interest & Feedback + +TODO before entering Phase 3. + +[This should include a list of implementers who have expressed interest in implementing the proposal] + +### References & acknowledgements + +The concept of wasi-cli has been in development for over a year since the proposal is +posted here, and many people have contributed ideas that have influenced. Many thanks +for valuable feedback and advice in particular from: + +- Luke Wagner +- Pat Hickey diff --git a/proposals/cli/command.md b/proposals/cli/command.md new file mode 100644 index 000000000..34c1c9290 --- /dev/null +++ b/proposals/cli/command.md @@ -0,0 +1,3144 @@ +

World command

+ +

Import interface wasi:cli/environment@0.2.8

+
+

Functions

+

get-environment: func

+

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.

+
Return values
+ +

get-arguments: func

+

Get the POSIX-style arguments to the program.

+
Return values
+ +

initial-cwd: func

+

Return a path that programs should use as their initial current working +directory, interpreting . as shorthand for this.

+
Return values
+ +

Import interface wasi:cli/exit@0.2.8

+
+

Functions

+

exit: func

+

Exit the current instance and any linked instances.

+
Params
+ +

exit-with-code: func

+

Exit the current instance and any linked instances, reporting the +specified status code to the host.

+

The meaning of the code depends on the context, with 0 usually meaning +"success", and other values indicating various types of failure.

+

This function does not return; the effect is analogous to a trap, but +without the connotation that something bad has happened.

+
Params
+ +

Import interface wasi:io/error@0.2.8

+
+

Types

+

resource 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 +offer functions to "downcast" this error into more specific types. For example, +errors returned from streams derived from filesystem types can be described using +the filesystem's own error-code type. This is done using the function +wasi:filesystem/types/filesystem-error-code, which takes a borrow<error> +parameter and returns an option<wasi:filesystem/types/error-code>.

+

The set of functions which can "downcast" an error into a more +concrete type is open.

+

Functions

+

[method]error.to-debug-string: func

+

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.

+
Params
+ +
Return values
+ +

Import interface wasi:io/poll@0.2.8

+

A poll API intended to let users wait for I/O events on multiple handles +at once.

+
+

Types

+

resource pollable

+

pollable represents a single I/O event which may be ready, or not.

+

Functions

+

[method]pollable.ready: func

+

Return the readiness of a pollable. This function never blocks.

+

Returns true when the pollable is ready, and false otherwise.

+
Params
+ +
Return values
+ +

[method]pollable.block: func

+

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.

+
Params
+ +

poll: func

+

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<u32> contains one or more indices of handles in the +argument list that is ready for I/O.

+

This function traps if either:

+ +

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 ready for I/O.

+
Params
+ +
Return values
+ +

Import interface wasi:io/streams@0.2.8

+

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.

+
+

Types

+

type error

+

error

+

+

type pollable

+

pollable

+

+

variant stream-error

+

An error for input-stream and output-stream operations.

+
Variant Cases
+ +

resource input-stream

+

An input bytestream.

+

input-streams 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 output-stream

+

An output bytestream.

+

output-streams 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.

+

Dropping an output-stream while there's still an active write in +progress may result in the data being lost. Before dropping the stream, +be sure to fully flush your writes.

+

Functions

+

[method]input-stream.read: func

+

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.

+
Params
+ +
Return values
+ +

[method]input-stream.blocking-read: func

+

Read bytes from a stream, after blocking until at least one byte can +be read. Except for blocking, behavior is identical to read.

+
Params
+ +
Return values
+ +

[method]input-stream.skip: func

+

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.

+
Params
+ +
Return values
+ +

[method]input-stream.blocking-skip: func

+

Skip bytes from a stream, after blocking until at least one byte +can be skipped. Except for blocking behavior, identical to skip.

+
Params
+ +
Return values
+ +

[method]input-stream.subscribe: func

+

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 pollables created with this function are dropped.

+
Params
+ +
Return values
+ +

[method]output-stream.check-write: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.write: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-write-and-flush: func

+

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.

+

Returns success when all of the contents written are successfully +flushed to output. If an error occurs at any point before all +contents are successfully flushed, that error is returned as soon as +possible. If writing and flushing the complete contents causes the +stream to become closed, this call should return success, and +subsequent calls to check-write or other interfaces should return +stream-error::closed.

+
Params
+ +
Return values
+ +

[method]output-stream.flush: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-flush: func

+

Request to flush buffered output, and block until flush completes +and stream is ready for writing again.

+
Params
+ +
Return values
+ +

[method]output-stream.subscribe: func

+

Create a pollable which will resolve once the output-stream +is ready for more writing, or an error has occurred. 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 pollables created with this function are dropped.

+
Params
+ +
Return values
+ +

[method]output-stream.write-zeroes: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-write-zeroes-and-flush: func

+

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.

+

Functionality is equivelant to blocking-write-and-flush with +contents given as a list of len containing only zeroes.

+
Params
+ +
Return values
+ +

[method]output-stream.splice: func

+

Read from one stream and write to another.

+

The behavior of splice is equivalent to:

+
    +
  1. calling check-write on the output-stream
  2. +
  3. calling read on the input-stream with the smaller of the +check-write permitted length and the len provided to splice
  4. +
  5. calling write on the output-stream with that read data.
  6. +
+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-splice: func

+

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.

+
Params
+ +
Return values
+ +

Import interface wasi:cli/stdin@0.2.8

+
+

Types

+

type input-stream

+

input-stream

+

+


+

Functions

+

get-stdin: func

+
Return values
+ +

Import interface wasi:cli/stdout@0.2.8

+
+

Types

+

type output-stream

+

output-stream

+

+


+

Functions

+

get-stdout: func

+
Return values
+ +

Import interface wasi:cli/stderr@0.2.8

+
+

Types

+

type output-stream

+

output-stream

+

+


+

Functions

+

get-stderr: func

+
Return values
+ +

Import interface wasi:cli/terminal-input@0.2.8

+

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.

+
+

Types

+

resource terminal-input

+

The input side of a terminal.

+

Import interface wasi:cli/terminal-output@0.2.8

+

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.

+
+

Types

+

resource terminal-output

+

The output side of a terminal.

+

Import interface wasi:cli/terminal-stdin@0.2.8

+

An interface providing an optional terminal-input for stdin as a +link-time authority.

+
+

Types

+

type terminal-input

+

terminal-input

+

+


+

Functions

+

get-terminal-stdin: func

+

If stdin is connected to a terminal, return a terminal-input handle +allowing further interaction with it.

+
Return values
+ +

Import interface wasi:cli/terminal-stdout@0.2.8

+

An interface providing an optional terminal-output for stdout as a +link-time authority.

+
+

Types

+

type terminal-output

+

terminal-output

+

+


+

Functions

+

get-terminal-stdout: func

+

If stdout is connected to a terminal, return a terminal-output handle +allowing further interaction with it.

+
Return values
+ +

Import interface wasi:cli/terminal-stderr@0.2.8

+

An interface providing an optional terminal-output for stderr as a +link-time authority.

+
+

Types

+

type terminal-output

+

terminal-output

+

+


+

Functions

+

get-terminal-stderr: func

+

If stderr is connected to a terminal, return a terminal-output handle +allowing further interaction with it.

+
Return values
+ +

Import interface wasi:clocks/monotonic-clock@0.2.8

+

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.

+
+

Types

+

type pollable

+

pollable

+

+

type instant

+

u64

+

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 duration

+

u64

+

A duration of time, in nanoseconds. +


+

Functions

+

now: func

+

Read the current value of the clock.

+

The clock is monotonic, therefore calling this function repeatedly will +produce a sequence of non-decreasing values.

+

For completeness, this function traps if it's not possible to represent +the value of the clock in an instant. Consequently, implementations +should ensure that the starting time is low enough to avoid the +possibility of overflow in practice.

+
Return values
+ +

resolution: func

+

Query the resolution of the clock. Returns the duration of time +corresponding to a clock tick.

+
Return values
+ +

subscribe-instant: func

+

Create a pollable which will resolve once the specified instant +has occurred.

+
Params
+ +
Return values
+ +

subscribe-duration: func

+

Create a pollable that will resolve after the specified duration has +elapsed from the time this function is invoked.

+
Params
+ +
Return values
+ +

Import interface wasi:clocks/wall-clock@0.2.8

+

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.

+
+

Types

+

record datetime

+

A time and date in seconds plus nanoseconds.

+
Record Fields
+ +
+

Functions

+

now: func

+

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.

+
Return values
+ +

resolution: func

+

Query the resolution of the clock.

+

The nanoseconds field of the output is always less than 1000000000.

+
Return values
+ +

Import interface wasi:clocks/timezone@0.2.8

+
+

Types

+

type datetime

+

datetime

+

+

record timezone-display

+

Information useful for displaying the timezone of a specific datetime.

+

This information may vary within a single timezone to reflect daylight +saving time adjustments.

+
Record Fields
+ +
+

Functions

+

display: func

+

Return information needed to display the given datetime. This includes +the UTC offset, the time zone name, and a flag indicating whether +daylight saving time is active.

+

If the timezone cannot be determined for the given datetime, return a +timezone-display for UTC with a utc-offset of 0 and no daylight +saving time.

+
Params
+ +
Return values
+ +

utc-offset: func

+

The same as display, but only return the UTC offset.

+
Params
+ +
Return values
+ +

Import interface wasi:filesystem/types@0.2.8

+

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 strings, 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.

+
+

Types

+

type input-stream

+

input-stream

+

+

type output-stream

+

output-stream

+

+

type error

+

error

+

+

type datetime

+

datetime

+

+

type filesize

+

u64

+

File size or length of a region within a file. +

enum descriptor-type

+

The type of a filesystem object referenced by a descriptor.

+

Note: This was called filetype in earlier versions of WASI.

+
Enum Cases
+ +

flags descriptor-flags

+

Descriptor flags.

+

Note: This was called fdflags in earlier versions of WASI.

+
Flags members
+ +

flags path-flags

+

Flags determining the method of how paths are resolved.

+
Flags members
+ +

flags open-flags

+

Open flags used by open-at.

+
Flags members
+ +

type link-count

+

u64

+

Number of hard links to an inode. +

record descriptor-stat

+

File attributes.

+

Note: This was called filestat in earlier versions of WASI.

+
Record Fields
+ +

variant new-timestamp

+

When setting a timestamp, this gives the value to set it to.

+
Variant Cases
+ +

record directory-entry

+

A directory entry.

+
Record Fields
+ +

enum error-code

+

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 Cases
+ +

enum advice

+

File or memory access pattern advisory information.

+
Enum Cases
+ +

record metadata-hash-value

+

A 128-bit hash value, split into parts because wasm doesn't have a +128-bit integer type.

+
Record Fields
+ +

resource descriptor

+

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 directory-entry-stream

+

A stream of directory entries.

+

Functions

+

[method]descriptor.read-via-stream: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.write-via-stream: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.append-via-stream: func

+

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 POSIX.

+
Params
+ +
Return values
+ +

[method]descriptor.advise: func

+

Provide file advisory information on a descriptor.

+

This is similar to posix_fadvise in POSIX.

+
Params
+ +
Return values
+ +

[method]descriptor.sync-data: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.get-flags: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.get-type: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.set-size: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.set-times: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.read: func

+

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<u8, error-code>.

+

Note: This is similar to pread in POSIX.

+
Params
+ +
Return values
+ +

[method]descriptor.write: func

+

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<u8, error-code>.

+

Note: This is similar to pwrite in POSIX.

+
Params
+ +
Return values
+ +

[method]descriptor.read-directory: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.sync: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.create-directory-at: func

+

Create a directory.

+

Note: This is similar to mkdirat in POSIX.

+
Params
+ +
Return values
+ +

[method]descriptor.stat: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.stat-at: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.set-times-at: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.link-at: func

+

Create a hard link.

+

Fails with error-code::no-entry if the old path does not exist, +with error-code::exist if the new path already exists, and +error-code::not-permitted if the old path is not a file.

+

Note: This is similar to linkat in POSIX.

+
Params
+ +
Return values
+ +

[method]descriptor.open-at: func

+

Open a file or directory.

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.readlink-at: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.remove-directory-at: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.rename-at: func

+

Rename a filesystem object.

+

Note: This is similar to renameat in POSIX.

+
Params
+ +
Return values
+ +

[method]descriptor.symlink-at: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.unlink-file-at: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.is-same-object: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.metadata-hash: func

+

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 encouraged to provide the following properties:

+ +

However, none of these is required.

+
Params
+ +
Return values
+ +

[method]descriptor.metadata-hash-at: func

+

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.

+
Params
+ +
Return values
+ +

[method]directory-entry-stream.read-directory-entry: func

+

Read a single directory entry from a directory-entry-stream.

+
Params
+ +
Return values
+ +

filesystem-error-code: func

+

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.

+
Params
+ +
Return values
+ +

Import interface wasi:filesystem/preopens@0.2.8

+
+

Types

+

type descriptor

+

descriptor

+

+


+

Functions

+

get-directories: func

+

Return the set of preopened directories, and their paths.

+
Return values
+ +

Import interface wasi:sockets/network@0.2.8

+
+

Types

+

type error

+

error

+

+

resource 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.

+

enum 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:

+ +

See each individual API for what the POSIX equivalents are. They sometimes differ per API.

+
Enum Cases
+ +

enum ip-address-family

+
Enum Cases
+ +

tuple ipv4-address

+
Tuple Fields
+ +

tuple ipv6-address

+
Tuple Fields
+ +

variant ip-address

+
Variant Cases
+ +

record ipv4-socket-address

+
Record Fields
+ +

record ipv6-socket-address

+
Record Fields
+ +

variant ip-socket-address

+
Variant Cases
+ +
+

Functions

+

network-error-code: func

+

Attempts to extract a network-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 +network-related information about the error to return.

+

Note that this function is fallible because not all stream-related +errors are network-related errors.

+
Params
+ +
Return values
+ +

Import interface wasi:sockets/instance-network@0.2.8

+

This interface provides a value-export of the default network handle..

+
+

Types

+

type network

+

network

+

+


+

Functions

+

instance-network: func

+

Get a handle to the default network.

+
Return values
+ +

Import interface wasi:sockets/udp@0.2.8

+
+

Types

+

type pollable

+

pollable

+

+

type network

+

network

+

+

type error-code

+

error-code

+

+

type ip-socket-address

+

ip-socket-address

+

+

type ip-address-family

+

ip-address-family

+

+

record incoming-datagram

+

A received datagram.

+
Record Fields
+ +

record outgoing-datagram

+

A datagram to be sent out.

+
Record Fields
+ +

resource udp-socket

+

A UDP socket handle.

+

resource incoming-datagram-stream

+

resource outgoing-datagram-stream

+
+

Functions

+

[method]udp-socket.start-bind: func

+

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

+ +

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

+ +
Params
+ +
Return values
+ +

[method]udp-socket.finish-bind: func

+
Params
+ +
Return values
+ +

[method]udp-socket.stream: func

+

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:

+ +

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:

+
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

+ +

References

+ +
Params
+ +
Return values
+ +

[method]udp-socket.local-address: func

+

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

+ +

References

+ +
Params
+ +
Return values
+ +

[method]udp-socket.remote-address: func

+

Get the address the socket is currently streaming to.

+

Typical errors

+ +

References

+ +
Params
+ +
Return values
+ +

[method]udp-socket.address-family: func

+

Whether this is a IPv4 or IPv6 socket.

+

Equivalent to the SO_DOMAIN socket option.

+
Params
+ +
Return values
+ +

[method]udp-socket.unicast-hop-limit: func

+

Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options.

+

If the provided value is 0, an invalid-argument error is returned.

+

Typical errors

+ +
Params
+ +
Return values
+ +

[method]udp-socket.set-unicast-hop-limit: func

+
Params
+ +
Return values
+ +

[method]udp-socket.receive-buffer-size: func

+

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

+ +
Params
+ +
Return values
+ +

[method]udp-socket.set-receive-buffer-size: func

+
Params
+ +
Return values
+ +

[method]udp-socket.send-buffer-size: func

+
Params
+ +
Return values
+ +

[method]udp-socket.set-send-buffer-size: func

+
Params
+ +
Return values
+ +

[method]udp-socket.subscribe: func

+

Create a pollable which will resolve once the socket is ready for I/O.

+

Note: this function is here for WASI 0.2 only. +It's planned to be removed when future is natively supported in Preview3.

+
Params
+ +
Return values
+ +

[method]incoming-datagram-stream.receive: func

+

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:

+ +

Typical errors

+ +

References

+ +
Params
+ +
Return values
+ +

[method]incoming-datagram-stream.subscribe: func

+

Create a pollable which will resolve once the stream is ready to receive again.

+

Note: this function is here for WASI 0.2 only. +It's planned to be removed when future is natively supported in Preview3.

+
Params
+ +
Return values
+ +

[method]outgoing-datagram-stream.check-send: func

+

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.

+
Params
+ +
Return values
+ +

[method]outgoing-datagram-stream.send: func

+

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

+ +

References

+ +
Params
+ +
Return values
+ +

[method]outgoing-datagram-stream.subscribe: func

+

Create a pollable which will resolve once the stream is ready to send again.

+

Note: this function is here for WASI 0.2 only. +It's planned to be removed when future is natively supported in Preview3.

+
Params
+ +
Return values
+ +

Import interface wasi:sockets/udp-create-socket@0.2.8

+
+

Types

+

type network

+

network

+

+

type error-code

+

error-code

+

+

type ip-address-family

+

ip-address-family

+

+

type udp-socket

+

udp-socket

+

+


+

Functions

+

create-udp-socket: func

+

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

+ +

References:

+ +
Params
+ +
Return values
+ +

Import interface wasi:sockets/tcp@0.2.8

+
+

Types

+

type input-stream

+

input-stream

+

+

type output-stream

+

output-stream

+

+

type pollable

+

pollable

+

+

type duration

+

duration

+

+

type network

+

network

+

+

type error-code

+

error-code

+

+

type ip-socket-address

+

ip-socket-address

+

+

type ip-address-family

+

ip-address-family

+

+

enum shutdown-type

+
Enum Cases
+ +

resource tcp-socket

+

A TCP socket resource.

+

The socket can be in one of the following states:

+ +

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.

+

Functions

+

[method]tcp-socket.start-bind: func

+

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

+ +

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

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.finish-bind: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.start-connect: func

+

Connect to a remote endpoint.

+

On success:

+ +

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

+ +

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

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.finish-connect: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.start-listen: func

+

Start listening for new connections.

+

Transitions the socket into the listening state.

+

Unlike POSIX, the socket must already be explicitly bound.

+

Typical errors

+ +

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

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.finish-listen: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.accept: func

+

Accept a new client socket.

+

The returned socket is bound and in the connected state. The following properties are inherited from the listener socket:

+ +

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

+ +

References

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.local-address: func

+

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

+ +

References

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.remote-address: func

+

Get the remote address.

+

Typical errors

+ +

References

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.is-listening: func

+

Whether the socket is in the listening state.

+

Equivalent to the SO_ACCEPTCONN socket option.

+
Params
+ +
Return values
+ +

[method]tcp-socket.address-family: func

+

Whether this is a IPv4 or IPv6 socket.

+

Equivalent to the SO_DOMAIN socket option.

+
Params
+ +
Return values
+ +

[method]tcp-socket.set-listen-backlog-size: func

+

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

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.keep-alive-enabled: func

+

Enables or disables keepalive.

+

The keepalive behavior can be adjusted using:

+ +

Equivalent to the SO_KEEPALIVE socket option.

+
Params
+ +
Return values
+ +

[method]tcp-socket.set-keep-alive-enabled: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.keep-alive-idle-time: func

+

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

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.set-keep-alive-idle-time: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.keep-alive-interval: func

+

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

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.set-keep-alive-interval: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.keep-alive-count: func

+

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

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.set-keep-alive-count: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.hop-limit: func

+

Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options.

+

If the provided value is 0, an invalid-argument error is returned.

+

Typical errors

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.set-hop-limit: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.receive-buffer-size: func

+

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

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.set-receive-buffer-size: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.send-buffer-size: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.set-send-buffer-size: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.subscribe: func

+

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 https://github.com/WebAssembly/wasi-sockets/blob/main/TcpSocketOperationalSemantics.md#pollable-readiness +for more information.

+

Note: this function is here for WASI 0.2 only. +It's planned to be removed when future is natively supported in Preview3.

+
Params
+ +
Return values
+ +

[method]tcp-socket.shutdown: func

+

Initiate a graceful shutdown.

+ +

This function is idempotent; shutting down a direction more than once +has no effect and returns ok.

+

The shutdown function does not close (drop) the socket.

+

Typical errors

+ +

References

+ +
Params
+ +
Return values
+ +

Import interface wasi:sockets/tcp-create-socket@0.2.8

+
+

Types

+

type network

+

network

+

+

type error-code

+

error-code

+

+

type ip-address-family

+

ip-address-family

+

+

type tcp-socket

+

tcp-socket

+

+


+

Functions

+

create-tcp-socket: func

+

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

+ +

References

+ +
Params
+ +
Return values
+ +

Import interface wasi:sockets/ip-name-lookup@0.2.8

+
+

Types

+

type pollable

+

pollable

+

+

type network

+

network

+

+

type error-code

+

error-code

+

+

type ip-address

+

ip-address

+

+

resource resolve-address-stream

+
+

Functions

+

resolve-addresses: func

+

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

+ +

References:

+ +
Params
+ +
Return values
+ +

[method]resolve-address-stream.resolve-next-address: func

+

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

+ +
Params
+ +
Return values
+ +

[method]resolve-address-stream.subscribe: func

+

Create a pollable which will resolve once the stream is ready for I/O.

+

Note: this function is here for WASI 0.2 only. +It's planned to be removed when future is natively supported in Preview3.

+
Params
+ +
Return values
+ +

Import interface wasi:random/random@0.2.8

+

WASI Random is a random data API.

+

It is intended to be portable at least between Unix-family platforms and +Windows.

+
+

Functions

+

get-random-bytes: func

+

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.

+
Params
+ +
Return values
+ +

get-random-u64: func

+

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.

+
Return values
+ +

Import interface wasi:random/insecure@0.2.8

+

The insecure interface for insecure pseudo-random numbers.

+

It is intended to be portable at least between Unix-family platforms and +Windows.

+
+

Functions

+

get-insecure-random-bytes: func

+

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.

+
Params
+ +
Return values
+ +

get-insecure-random-u64: func

+

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.

+
Return values
+ +

Import interface wasi:random/insecure-seed@0.2.8

+

The insecure-seed interface for seeding hash-map DoS resistance.

+

It is intended to be portable at least between Unix-family platforms and +Windows.

+
+

Functions

+

insecure-seed: func

+

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.

+
Return values
+ +

Export interface wasi:cli/run@0.2.8

+
+

Functions

+

run: func

+

Run the program.

+
Return values
+ diff --git a/proposals/cli/imports.md b/proposals/cli/imports.md new file mode 100644 index 000000000..b23b099bb --- /dev/null +++ b/proposals/cli/imports.md @@ -0,0 +1,3130 @@ +

World imports

+ +

Import interface wasi:cli/environment@0.2.8

+
+

Functions

+

get-environment: func

+

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.

+
Return values
+ +

get-arguments: func

+

Get the POSIX-style arguments to the program.

+
Return values
+ +

initial-cwd: func

+

Return a path that programs should use as their initial current working +directory, interpreting . as shorthand for this.

+
Return values
+ +

Import interface wasi:cli/exit@0.2.8

+
+

Functions

+

exit: func

+

Exit the current instance and any linked instances.

+
Params
+ +

exit-with-code: func

+

Exit the current instance and any linked instances, reporting the +specified status code to the host.

+

The meaning of the code depends on the context, with 0 usually meaning +"success", and other values indicating various types of failure.

+

This function does not return; the effect is analogous to a trap, but +without the connotation that something bad has happened.

+
Params
+ +

Import interface wasi:io/error@0.2.8

+
+

Types

+

resource 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 +offer functions to "downcast" this error into more specific types. For example, +errors returned from streams derived from filesystem types can be described using +the filesystem's own error-code type. This is done using the function +wasi:filesystem/types/filesystem-error-code, which takes a borrow<error> +parameter and returns an option<wasi:filesystem/types/error-code>.

+

The set of functions which can "downcast" an error into a more +concrete type is open.

+

Functions

+

[method]error.to-debug-string: func

+

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.

+
Params
+ +
Return values
+ +

Import interface wasi:io/poll@0.2.8

+

A poll API intended to let users wait for I/O events on multiple handles +at once.

+
+

Types

+

resource pollable

+

pollable represents a single I/O event which may be ready, or not.

+

Functions

+

[method]pollable.ready: func

+

Return the readiness of a pollable. This function never blocks.

+

Returns true when the pollable is ready, and false otherwise.

+
Params
+ +
Return values
+ +

[method]pollable.block: func

+

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.

+
Params
+ +

poll: func

+

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<u32> contains one or more indices of handles in the +argument list that is ready for I/O.

+

This function traps if either:

+ +

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 ready for I/O.

+
Params
+ +
Return values
+ +

Import interface wasi:io/streams@0.2.8

+

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.

+
+

Types

+

type error

+

error

+

+

type pollable

+

pollable

+

+

variant stream-error

+

An error for input-stream and output-stream operations.

+
Variant Cases
+ +

resource input-stream

+

An input bytestream.

+

input-streams 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 output-stream

+

An output bytestream.

+

output-streams 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.

+

Dropping an output-stream while there's still an active write in +progress may result in the data being lost. Before dropping the stream, +be sure to fully flush your writes.

+

Functions

+

[method]input-stream.read: func

+

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.

+
Params
+ +
Return values
+ +

[method]input-stream.blocking-read: func

+

Read bytes from a stream, after blocking until at least one byte can +be read. Except for blocking, behavior is identical to read.

+
Params
+ +
Return values
+ +

[method]input-stream.skip: func

+

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.

+
Params
+ +
Return values
+ +

[method]input-stream.blocking-skip: func

+

Skip bytes from a stream, after blocking until at least one byte +can be skipped. Except for blocking behavior, identical to skip.

+
Params
+ +
Return values
+ +

[method]input-stream.subscribe: func

+

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 pollables created with this function are dropped.

+
Params
+ +
Return values
+ +

[method]output-stream.check-write: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.write: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-write-and-flush: func

+

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.

+

Returns success when all of the contents written are successfully +flushed to output. If an error occurs at any point before all +contents are successfully flushed, that error is returned as soon as +possible. If writing and flushing the complete contents causes the +stream to become closed, this call should return success, and +subsequent calls to check-write or other interfaces should return +stream-error::closed.

+
Params
+ +
Return values
+ +

[method]output-stream.flush: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-flush: func

+

Request to flush buffered output, and block until flush completes +and stream is ready for writing again.

+
Params
+ +
Return values
+ +

[method]output-stream.subscribe: func

+

Create a pollable which will resolve once the output-stream +is ready for more writing, or an error has occurred. 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 pollables created with this function are dropped.

+
Params
+ +
Return values
+ +

[method]output-stream.write-zeroes: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-write-zeroes-and-flush: func

+

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.

+

Functionality is equivelant to blocking-write-and-flush with +contents given as a list of len containing only zeroes.

+
Params
+ +
Return values
+ +

[method]output-stream.splice: func

+

Read from one stream and write to another.

+

The behavior of splice is equivalent to:

+
    +
  1. calling check-write on the output-stream
  2. +
  3. calling read on the input-stream with the smaller of the +check-write permitted length and the len provided to splice
  4. +
  5. calling write on the output-stream with that read data.
  6. +
+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-splice: func

+

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.

+
Params
+ +
Return values
+ +

Import interface wasi:cli/stdin@0.2.8

+
+

Types

+

type input-stream

+

input-stream

+

+


+

Functions

+

get-stdin: func

+
Return values
+ +

Import interface wasi:cli/stdout@0.2.8

+
+

Types

+

type output-stream

+

output-stream

+

+


+

Functions

+

get-stdout: func

+
Return values
+ +

Import interface wasi:cli/stderr@0.2.8

+
+

Types

+

type output-stream

+

output-stream

+

+


+

Functions

+

get-stderr: func

+
Return values
+ +

Import interface wasi:cli/terminal-input@0.2.8

+

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.

+
+

Types

+

resource terminal-input

+

The input side of a terminal.

+

Import interface wasi:cli/terminal-output@0.2.8

+

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.

+
+

Types

+

resource terminal-output

+

The output side of a terminal.

+

Import interface wasi:cli/terminal-stdin@0.2.8

+

An interface providing an optional terminal-input for stdin as a +link-time authority.

+
+

Types

+

type terminal-input

+

terminal-input

+

+


+

Functions

+

get-terminal-stdin: func

+

If stdin is connected to a terminal, return a terminal-input handle +allowing further interaction with it.

+
Return values
+ +

Import interface wasi:cli/terminal-stdout@0.2.8

+

An interface providing an optional terminal-output for stdout as a +link-time authority.

+
+

Types

+

type terminal-output

+

terminal-output

+

+


+

Functions

+

get-terminal-stdout: func

+

If stdout is connected to a terminal, return a terminal-output handle +allowing further interaction with it.

+
Return values
+ +

Import interface wasi:cli/terminal-stderr@0.2.8

+

An interface providing an optional terminal-output for stderr as a +link-time authority.

+
+

Types

+

type terminal-output

+

terminal-output

+

+


+

Functions

+

get-terminal-stderr: func

+

If stderr is connected to a terminal, return a terminal-output handle +allowing further interaction with it.

+
Return values
+ +

Import interface wasi:clocks/monotonic-clock@0.2.8

+

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.

+
+

Types

+

type pollable

+

pollable

+

+

type instant

+

u64

+

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 duration

+

u64

+

A duration of time, in nanoseconds. +


+

Functions

+

now: func

+

Read the current value of the clock.

+

The clock is monotonic, therefore calling this function repeatedly will +produce a sequence of non-decreasing values.

+

For completeness, this function traps if it's not possible to represent +the value of the clock in an instant. Consequently, implementations +should ensure that the starting time is low enough to avoid the +possibility of overflow in practice.

+
Return values
+ +

resolution: func

+

Query the resolution of the clock. Returns the duration of time +corresponding to a clock tick.

+
Return values
+ +

subscribe-instant: func

+

Create a pollable which will resolve once the specified instant +has occurred.

+
Params
+ +
Return values
+ +

subscribe-duration: func

+

Create a pollable that will resolve after the specified duration has +elapsed from the time this function is invoked.

+
Params
+ +
Return values
+ +

Import interface wasi:clocks/wall-clock@0.2.8

+

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.

+
+

Types

+

record datetime

+

A time and date in seconds plus nanoseconds.

+
Record Fields
+ +
+

Functions

+

now: func

+

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.

+
Return values
+ +

resolution: func

+

Query the resolution of the clock.

+

The nanoseconds field of the output is always less than 1000000000.

+
Return values
+ +

Import interface wasi:clocks/timezone@0.2.8

+
+

Types

+

type datetime

+

datetime

+

+

record timezone-display

+

Information useful for displaying the timezone of a specific datetime.

+

This information may vary within a single timezone to reflect daylight +saving time adjustments.

+
Record Fields
+ +
+

Functions

+

display: func

+

Return information needed to display the given datetime. This includes +the UTC offset, the time zone name, and a flag indicating whether +daylight saving time is active.

+

If the timezone cannot be determined for the given datetime, return a +timezone-display for UTC with a utc-offset of 0 and no daylight +saving time.

+
Params
+ +
Return values
+ +

utc-offset: func

+

The same as display, but only return the UTC offset.

+
Params
+ +
Return values
+ +

Import interface wasi:filesystem/types@0.2.8

+

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 strings, 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.

+
+

Types

+

type input-stream

+

input-stream

+

+

type output-stream

+

output-stream

+

+

type error

+

error

+

+

type datetime

+

datetime

+

+

type filesize

+

u64

+

File size or length of a region within a file. +

enum descriptor-type

+

The type of a filesystem object referenced by a descriptor.

+

Note: This was called filetype in earlier versions of WASI.

+
Enum Cases
+ +

flags descriptor-flags

+

Descriptor flags.

+

Note: This was called fdflags in earlier versions of WASI.

+
Flags members
+ +

flags path-flags

+

Flags determining the method of how paths are resolved.

+
Flags members
+ +

flags open-flags

+

Open flags used by open-at.

+
Flags members
+ +

type link-count

+

u64

+

Number of hard links to an inode. +

record descriptor-stat

+

File attributes.

+

Note: This was called filestat in earlier versions of WASI.

+
Record Fields
+ +

variant new-timestamp

+

When setting a timestamp, this gives the value to set it to.

+
Variant Cases
+ +

record directory-entry

+

A directory entry.

+
Record Fields
+ +

enum error-code

+

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 Cases
+ +

enum advice

+

File or memory access pattern advisory information.

+
Enum Cases
+ +

record metadata-hash-value

+

A 128-bit hash value, split into parts because wasm doesn't have a +128-bit integer type.

+
Record Fields
+ +

resource descriptor

+

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 directory-entry-stream

+

A stream of directory entries.

+

Functions

+

[method]descriptor.read-via-stream: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.write-via-stream: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.append-via-stream: func

+

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 POSIX.

+
Params
+ +
Return values
+ +

[method]descriptor.advise: func

+

Provide file advisory information on a descriptor.

+

This is similar to posix_fadvise in POSIX.

+
Params
+ +
Return values
+ +

[method]descriptor.sync-data: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.get-flags: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.get-type: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.set-size: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.set-times: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.read: func

+

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<u8, error-code>.

+

Note: This is similar to pread in POSIX.

+
Params
+ +
Return values
+ +

[method]descriptor.write: func

+

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<u8, error-code>.

+

Note: This is similar to pwrite in POSIX.

+
Params
+ +
Return values
+ +

[method]descriptor.read-directory: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.sync: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.create-directory-at: func

+

Create a directory.

+

Note: This is similar to mkdirat in POSIX.

+
Params
+ +
Return values
+ +

[method]descriptor.stat: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.stat-at: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.set-times-at: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.link-at: func

+

Create a hard link.

+

Fails with error-code::no-entry if the old path does not exist, +with error-code::exist if the new path already exists, and +error-code::not-permitted if the old path is not a file.

+

Note: This is similar to linkat in POSIX.

+
Params
+ +
Return values
+ +

[method]descriptor.open-at: func

+

Open a file or directory.

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.readlink-at: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.remove-directory-at: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.rename-at: func

+

Rename a filesystem object.

+

Note: This is similar to renameat in POSIX.

+
Params
+ +
Return values
+ +

[method]descriptor.symlink-at: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.unlink-file-at: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.is-same-object: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.metadata-hash: func

+

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 encouraged to provide the following properties:

+ +

However, none of these is required.

+
Params
+ +
Return values
+ +

[method]descriptor.metadata-hash-at: func

+

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.

+
Params
+ +
Return values
+ +

[method]directory-entry-stream.read-directory-entry: func

+

Read a single directory entry from a directory-entry-stream.

+
Params
+ +
Return values
+ +

filesystem-error-code: func

+

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.

+
Params
+ +
Return values
+ +

Import interface wasi:filesystem/preopens@0.2.8

+
+

Types

+

type descriptor

+

descriptor

+

+


+

Functions

+

get-directories: func

+

Return the set of preopened directories, and their paths.

+
Return values
+ +

Import interface wasi:sockets/network@0.2.8

+
+

Types

+

type error

+

error

+

+

resource 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.

+

enum 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:

+ +

See each individual API for what the POSIX equivalents are. They sometimes differ per API.

+
Enum Cases
+ +

enum ip-address-family

+
Enum Cases
+ +

tuple ipv4-address

+
Tuple Fields
+ +

tuple ipv6-address

+
Tuple Fields
+ +

variant ip-address

+
Variant Cases
+ +

record ipv4-socket-address

+
Record Fields
+ +

record ipv6-socket-address

+
Record Fields
+ +

variant ip-socket-address

+
Variant Cases
+ +
+

Functions

+

network-error-code: func

+

Attempts to extract a network-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 +network-related information about the error to return.

+

Note that this function is fallible because not all stream-related +errors are network-related errors.

+
Params
+ +
Return values
+ +

Import interface wasi:sockets/instance-network@0.2.8

+

This interface provides a value-export of the default network handle..

+
+

Types

+

type network

+

network

+

+


+

Functions

+

instance-network: func

+

Get a handle to the default network.

+
Return values
+ +

Import interface wasi:sockets/udp@0.2.8

+
+

Types

+

type pollable

+

pollable

+

+

type network

+

network

+

+

type error-code

+

error-code

+

+

type ip-socket-address

+

ip-socket-address

+

+

type ip-address-family

+

ip-address-family

+

+

record incoming-datagram

+

A received datagram.

+
Record Fields
+ +

record outgoing-datagram

+

A datagram to be sent out.

+
Record Fields
+ +

resource udp-socket

+

A UDP socket handle.

+

resource incoming-datagram-stream

+

resource outgoing-datagram-stream

+
+

Functions

+

[method]udp-socket.start-bind: func

+

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

+ +

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

+ +
Params
+ +
Return values
+ +

[method]udp-socket.finish-bind: func

+
Params
+ +
Return values
+ +

[method]udp-socket.stream: func

+

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:

+ +

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:

+
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

+ +

References

+ +
Params
+ +
Return values
+ +

[method]udp-socket.local-address: func

+

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

+ +

References

+ +
Params
+ +
Return values
+ +

[method]udp-socket.remote-address: func

+

Get the address the socket is currently streaming to.

+

Typical errors

+ +

References

+ +
Params
+ +
Return values
+ +

[method]udp-socket.address-family: func

+

Whether this is a IPv4 or IPv6 socket.

+

Equivalent to the SO_DOMAIN socket option.

+
Params
+ +
Return values
+ +

[method]udp-socket.unicast-hop-limit: func

+

Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options.

+

If the provided value is 0, an invalid-argument error is returned.

+

Typical errors

+ +
Params
+ +
Return values
+ +

[method]udp-socket.set-unicast-hop-limit: func

+
Params
+ +
Return values
+ +

[method]udp-socket.receive-buffer-size: func

+

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

+ +
Params
+ +
Return values
+ +

[method]udp-socket.set-receive-buffer-size: func

+
Params
+ +
Return values
+ +

[method]udp-socket.send-buffer-size: func

+
Params
+ +
Return values
+ +

[method]udp-socket.set-send-buffer-size: func

+
Params
+ +
Return values
+ +

[method]udp-socket.subscribe: func

+

Create a pollable which will resolve once the socket is ready for I/O.

+

Note: this function is here for WASI 0.2 only. +It's planned to be removed when future is natively supported in Preview3.

+
Params
+ +
Return values
+ +

[method]incoming-datagram-stream.receive: func

+

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:

+ +

Typical errors

+ +

References

+ +
Params
+ +
Return values
+ +

[method]incoming-datagram-stream.subscribe: func

+

Create a pollable which will resolve once the stream is ready to receive again.

+

Note: this function is here for WASI 0.2 only. +It's planned to be removed when future is natively supported in Preview3.

+
Params
+ +
Return values
+ +

[method]outgoing-datagram-stream.check-send: func

+

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.

+
Params
+ +
Return values
+ +

[method]outgoing-datagram-stream.send: func

+

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

+ +

References

+ +
Params
+ +
Return values
+ +

[method]outgoing-datagram-stream.subscribe: func

+

Create a pollable which will resolve once the stream is ready to send again.

+

Note: this function is here for WASI 0.2 only. +It's planned to be removed when future is natively supported in Preview3.

+
Params
+ +
Return values
+ +

Import interface wasi:sockets/udp-create-socket@0.2.8

+
+

Types

+

type network

+

network

+

+

type error-code

+

error-code

+

+

type ip-address-family

+

ip-address-family

+

+

type udp-socket

+

udp-socket

+

+


+

Functions

+

create-udp-socket: func

+

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

+ +

References:

+ +
Params
+ +
Return values
+ +

Import interface wasi:sockets/tcp@0.2.8

+
+

Types

+

type input-stream

+

input-stream

+

+

type output-stream

+

output-stream

+

+

type pollable

+

pollable

+

+

type duration

+

duration

+

+

type network

+

network

+

+

type error-code

+

error-code

+

+

type ip-socket-address

+

ip-socket-address

+

+

type ip-address-family

+

ip-address-family

+

+

enum shutdown-type

+
Enum Cases
+ +

resource tcp-socket

+

A TCP socket resource.

+

The socket can be in one of the following states:

+ +

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.

+

Functions

+

[method]tcp-socket.start-bind: func

+

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

+ +

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

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.finish-bind: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.start-connect: func

+

Connect to a remote endpoint.

+

On success:

+ +

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

+ +

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

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.finish-connect: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.start-listen: func

+

Start listening for new connections.

+

Transitions the socket into the listening state.

+

Unlike POSIX, the socket must already be explicitly bound.

+

Typical errors

+ +

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

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.finish-listen: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.accept: func

+

Accept a new client socket.

+

The returned socket is bound and in the connected state. The following properties are inherited from the listener socket:

+ +

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

+ +

References

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.local-address: func

+

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

+ +

References

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.remote-address: func

+

Get the remote address.

+

Typical errors

+ +

References

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.is-listening: func

+

Whether the socket is in the listening state.

+

Equivalent to the SO_ACCEPTCONN socket option.

+
Params
+ +
Return values
+ +

[method]tcp-socket.address-family: func

+

Whether this is a IPv4 or IPv6 socket.

+

Equivalent to the SO_DOMAIN socket option.

+
Params
+ +
Return values
+ +

[method]tcp-socket.set-listen-backlog-size: func

+

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

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.keep-alive-enabled: func

+

Enables or disables keepalive.

+

The keepalive behavior can be adjusted using:

+ +

Equivalent to the SO_KEEPALIVE socket option.

+
Params
+ +
Return values
+ +

[method]tcp-socket.set-keep-alive-enabled: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.keep-alive-idle-time: func

+

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

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.set-keep-alive-idle-time: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.keep-alive-interval: func

+

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

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.set-keep-alive-interval: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.keep-alive-count: func

+

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

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.set-keep-alive-count: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.hop-limit: func

+

Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options.

+

If the provided value is 0, an invalid-argument error is returned.

+

Typical errors

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.set-hop-limit: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.receive-buffer-size: func

+

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

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.set-receive-buffer-size: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.send-buffer-size: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.set-send-buffer-size: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.subscribe: func

+

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 https://github.com/WebAssembly/wasi-sockets/blob/main/TcpSocketOperationalSemantics.md#pollable-readiness +for more information.

+

Note: this function is here for WASI 0.2 only. +It's planned to be removed when future is natively supported in Preview3.

+
Params
+ +
Return values
+ +

[method]tcp-socket.shutdown: func

+

Initiate a graceful shutdown.

+ +

This function is idempotent; shutting down a direction more than once +has no effect and returns ok.

+

The shutdown function does not close (drop) the socket.

+

Typical errors

+ +

References

+ +
Params
+ +
Return values
+ +

Import interface wasi:sockets/tcp-create-socket@0.2.8

+
+

Types

+

type network

+

network

+

+

type error-code

+

error-code

+

+

type ip-address-family

+

ip-address-family

+

+

type tcp-socket

+

tcp-socket

+

+


+

Functions

+

create-tcp-socket: func

+

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

+ +

References

+ +
Params
+ +
Return values
+ +

Import interface wasi:sockets/ip-name-lookup@0.2.8

+
+

Types

+

type pollable

+

pollable

+

+

type network

+

network

+

+

type error-code

+

error-code

+

+

type ip-address

+

ip-address

+

+

resource resolve-address-stream

+
+

Functions

+

resolve-addresses: func

+

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

+ +

References:

+ +
Params
+ +
Return values
+ +

[method]resolve-address-stream.resolve-next-address: func

+

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

+ +
Params
+ +
Return values
+ +

[method]resolve-address-stream.subscribe: func

+

Create a pollable which will resolve once the stream is ready for I/O.

+

Note: this function is here for WASI 0.2 only. +It's planned to be removed when future is natively supported in Preview3.

+
Params
+ +
Return values
+ +

Import interface wasi:random/random@0.2.8

+

WASI Random is a random data API.

+

It is intended to be portable at least between Unix-family platforms and +Windows.

+
+

Functions

+

get-random-bytes: func

+

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.

+
Params
+ +
Return values
+ +

get-random-u64: func

+

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.

+
Return values
+ +

Import interface wasi:random/insecure@0.2.8

+

The insecure interface for insecure pseudo-random numbers.

+

It is intended to be portable at least between Unix-family platforms and +Windows.

+
+

Functions

+

get-insecure-random-bytes: func

+

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.

+
Params
+ +
Return values
+ +

get-insecure-random-u64: func

+

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.

+
Return values
+ +

Import interface wasi:random/insecure-seed@0.2.8

+

The insecure-seed interface for seeding hash-map DoS resistance.

+

It is intended to be portable at least between Unix-family platforms and +Windows.

+
+

Functions

+

insecure-seed: func

+

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.

+
Return values
+ diff --git a/proposals/cli/test/README.md b/proposals/cli/test/README.md new file mode 100644 index 000000000..c274acd9d --- /dev/null +++ b/proposals/cli/test/README.md @@ -0,0 +1,11 @@ +# Testing guidelines + +TK fill in testing guidelines + +## Installing the tools + +TK fill in instructions + +## Running the tests + +TK fill in instructions diff --git a/proposals/cli/wit-0.3.0-draft/command.wit b/proposals/cli/wit-0.3.0-draft/command.wit new file mode 100644 index 000000000..f2f613e55 --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/command.wit @@ -0,0 +1,10 @@ +package wasi:cli@0.3.0-rc-2025-09-16; + +@since(version = 0.3.0-rc-2025-09-16) +world command { + @since(version = 0.3.0-rc-2025-09-16) + include imports; + + @since(version = 0.3.0-rc-2025-09-16) + export run; +} diff --git a/proposals/cli/wit-0.3.0-draft/deps.lock b/proposals/cli/wit-0.3.0-draft/deps.lock new file mode 100644 index 000000000..931f9574c --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/deps.lock @@ -0,0 +1,23 @@ +[clocks] +sha256 = "cf61a3785c2838340ce530ee1cdc6dbee3257f1672d6000ca748dfe253808dec" +sha512 = "f647de7d6c470595c3e5bf0dba6af98703beb9f701c66543cea5d42e81f7a1a73f199c3949035a9c2c1bd717056e5e68788f520af39b9d26480242b7626f22ce" + +[filesystem] +url = "https://github.com/WebAssembly/wasi-filesystem/archive/main.tar.gz" +subdir = "wit-0.3.0-draft" +sha256 = "99292288bdb7ecb04e0a1a7bee478a9410df9ab57af222c3dcde375f7b957181" +sha512 = "4da72faf65b99263bd0521871a6004ea19fc9189e906451fb4d48b83d9da3269a8e4470c5775faf037a05e03151a0c05fd05cc0dfeb36757715fda2799dd1d85" +deps = ["clocks"] + +[random] +url = "https://github.com/WebAssembly/wasi-random/archive/main.tar.gz" +subdir = "wit-0.3.0-draft" +sha256 = "0a0cead69094ce1773468ff363b2d324ded025aab4f03a1d53b2538710c31e43" +sha512 = "3596bbd164c28254aefb0f7c7a047d81121df1de170808d16975f021c5170ea35dfe6fc1867f93469013ab8d36df8de14d4c5e1c9b70197bfd10e699fd6757e5" + +[sockets] +url = "https://github.com/WebAssembly/wasi-sockets/archive/main.tar.gz" +subdir = "wit-0.3.0-draft" +sha256 = "57e9d6df8389015116c5407641af76b717cf0d1a79e36384af3cb7d7fa9687ed" +sha512 = "45dab8dd2fa48450c480b1e770a3739793f6156b07b39075414510ce2cde3db6e714da87f47f0e9b9c82b5ef38a963a59f4d86449aa5f2310c78bc79134d0dd5" +deps = ["clocks"] diff --git a/proposals/cli/wit-0.3.0-draft/deps.toml b/proposals/cli/wit-0.3.0-draft/deps.toml new file mode 100644 index 000000000..39bc16e55 --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/deps.toml @@ -0,0 +1,3 @@ +filesystem = { url = "https://github.com/WebAssembly/wasi-filesystem/archive/main.tar.gz", subdir = "wit-0.3.0-draft" } +random = { url = "https://github.com/WebAssembly/wasi-random/archive/main.tar.gz", subdir = "wit-0.3.0-draft" } +sockets = { url = "https://github.com/WebAssembly/wasi-sockets/archive/main.tar.gz", subdir = "wit-0.3.0-draft" } diff --git a/proposals/cli/wit-0.3.0-draft/deps/clocks/monotonic-clock.wit b/proposals/cli/wit-0.3.0-draft/deps/clocks/monotonic-clock.wit new file mode 100644 index 000000000..a91d495c6 --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/deps/clocks/monotonic-clock.wit @@ -0,0 +1,48 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; +/// 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. +@since(version = 0.3.0-rc-2025-09-16) +interface monotonic-clock { + use types.{duration}; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + type instant = 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. + /// + /// For completeness, this function traps if it's not possible to represent + /// the value of the clock in an `instant`. Consequently, implementations + /// should ensure that the starting time is low enough to avoid the + /// possibility of overflow in practice. + @since(version = 0.3.0-rc-2025-09-16) + now: func() -> instant; + + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + @since(version = 0.3.0-rc-2025-09-16) + get-resolution: func() -> duration; + + /// Wait until the specified instant has occurred. + @since(version = 0.3.0-rc-2025-09-16) + wait-until: async func( + when: instant, + ); + + /// Wait for the specified duration to elapse. + @since(version = 0.3.0-rc-2025-09-16) + wait-for: async func( + how-long: duration, + ); +} diff --git a/proposals/cli/wit-0.3.0-draft/deps/clocks/timezone.wit b/proposals/cli/wit-0.3.0-draft/deps/clocks/timezone.wit new file mode 100644 index 000000000..ab8f5c080 --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/deps/clocks/timezone.wit @@ -0,0 +1,55 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; + +@unstable(feature = clocks-timezone) +interface timezone { + @unstable(feature = clocks-timezone) + use wall-clock.{datetime}; + + /// Return information needed to display the given `datetime`. This includes + /// the UTC offset, the time zone name, and a flag indicating whether + /// daylight saving time is active. + /// + /// If the timezone cannot be determined for the given `datetime`, return a + /// `timezone-display` for `UTC` with a `utc-offset` of 0 and no daylight + /// saving time. + @unstable(feature = clocks-timezone) + display: func(when: datetime) -> timezone-display; + + /// The same as `display`, but only return the UTC offset. + @unstable(feature = clocks-timezone) + utc-offset: func(when: datetime) -> s32; + + /// Information useful for displaying the timezone of a specific `datetime`. + /// + /// This information may vary within a single `timezone` to reflect daylight + /// saving time adjustments. + @unstable(feature = clocks-timezone) + record timezone-display { + /// The number of seconds difference between UTC time and the local + /// time of the timezone. + /// + /// The returned value will always be less than 86400 which is the + /// number of seconds in a day (24*60*60). + /// + /// In implementations that do not expose an actual time zone, this + /// should return 0. + utc-offset: s32, + + /// The abbreviated name of the timezone to display to a user. The name + /// `UTC` indicates Coordinated Universal Time. Otherwise, this should + /// reference local standards for the name of the time zone. + /// + /// In implementations that do not expose an actual time zone, this + /// should be the string `UTC`. + /// + /// In time zones that do not have an applicable name, a formatted + /// representation of the UTC offset may be returned, such as `-04:00`. + name: string, + + /// Whether daylight saving time is active. + /// + /// In implementations that do not expose an actual time zone, this + /// should return false. + in-daylight-saving-time: bool, + } +} diff --git a/proposals/cli/wit-0.3.0-draft/deps/clocks/types.wit b/proposals/cli/wit-0.3.0-draft/deps/clocks/types.wit new file mode 100644 index 000000000..aff7c2a22 --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/deps/clocks/types.wit @@ -0,0 +1,8 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; +/// This interface common types used throughout wasi:clocks. +@since(version = 0.3.0-rc-2025-09-16) +interface types { + /// A duration of time, in nanoseconds. + @since(version = 0.3.0-rc-2025-09-16) + type duration = u64; +} diff --git a/proposals/cli/wit-0.3.0-draft/deps/clocks/wall-clock.wit b/proposals/cli/wit-0.3.0-draft/deps/clocks/wall-clock.wit new file mode 100644 index 000000000..ea940500f --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/deps/clocks/wall-clock.wit @@ -0,0 +1,46 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; +/// 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. +@since(version = 0.3.0-rc-2025-09-16) +interface wall-clock { + /// A time and date in seconds plus nanoseconds. + @since(version = 0.3.0-rc-2025-09-16) + 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 + @since(version = 0.3.0-rc-2025-09-16) + now: func() -> datetime; + + /// Query the resolution of the clock. + /// + /// The nanoseconds field of the output is always less than 1000000000. + @since(version = 0.3.0-rc-2025-09-16) + get-resolution: func() -> datetime; +} diff --git a/proposals/cli/wit-0.3.0-draft/deps/clocks/world.wit b/proposals/cli/wit-0.3.0-draft/deps/clocks/world.wit new file mode 100644 index 000000000..a6b885f07 --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/deps/clocks/world.wit @@ -0,0 +1,11 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; + +@since(version = 0.3.0-rc-2025-09-16) +world imports { + @since(version = 0.3.0-rc-2025-09-16) + import monotonic-clock; + @since(version = 0.3.0-rc-2025-09-16) + import wall-clock; + @unstable(feature = clocks-timezone) + import timezone; +} diff --git a/proposals/cli/wit-0.3.0-draft/deps/filesystem/preopens.wit b/proposals/cli/wit-0.3.0-draft/deps/filesystem/preopens.wit new file mode 100644 index 000000000..9036e90e8 --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/deps/filesystem/preopens.wit @@ -0,0 +1,11 @@ +package wasi:filesystem@0.3.0-rc-2025-09-16; + +@since(version = 0.3.0-rc-2025-09-16) +interface preopens { + @since(version = 0.3.0-rc-2025-09-16) + use types.{descriptor}; + + /// Return the set of preopened directories, and their paths. + @since(version = 0.3.0-rc-2025-09-16) + get-directories: func() -> list>; +} diff --git a/proposals/cli/wit-0.3.0-draft/deps/filesystem/types.wit b/proposals/cli/wit-0.3.0-draft/deps/filesystem/types.wit new file mode 100644 index 000000000..41d91beee --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/deps/filesystem/types.wit @@ -0,0 +1,636 @@ +package wasi:filesystem@0.3.0-rc-2025-09-16; +/// 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 +@since(version = 0.3.0-rc-2025-09-16) +interface types { + @since(version = 0.3.0-rc-2025-09-16) + use wasi:clocks/wall-clock@0.3.0-rc-2025-09-16.{datetime}; + + /// File size or length of a region within a file. + @since(version = 0.3.0-rc-2025-09-16) + type filesize = u64; + + /// The type of a filesystem object referenced by a descriptor. + /// + /// Note: This was called `filetype` in earlier versions of WASI. + @since(version = 0.3.0-rc-2025-09-16) + 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. + @since(version = 0.3.0-rc-2025-09-16) + 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 integrity + /// 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, + } + + /// File attributes. + /// + /// Note: This was called `filestat` in earlier versions of WASI. + @since(version = 0.3.0-rc-2025-09-16) + 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, + } + + /// Flags determining the method of how paths are resolved. + @since(version = 0.3.0-rc-2025-09-16) + 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`. + @since(version = 0.3.0-rc-2025-09-16) + 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. + @since(version = 0.3.0-rc-2025-09-16) + type link-count = u64; + + /// When setting a timestamp, this gives the value to set it to. + @since(version = 0.3.0-rc-2025-09-16) + 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, + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + 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. + @since(version = 0.3.0-rc-2025-09-16) + 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. + @since(version = 0.3.0-rc-2025-09-16) + resource descriptor { + /// Return a stream for reading from a file. + /// + /// Multiple read, write, and append streams may be active on the same open + /// file and they do not interfere with each other. + /// + /// This function returns a `stream` which provides the data received from the + /// file, and a `future` providing additional error information in case an + /// error is encountered. + /// + /// If no error is encountered, `stream.read` on the `stream` will return + /// `read-status::closed` with no `error-context` and the future resolves to + /// the value `ok`. If an error is encountered, `stream.read` on the + /// `stream` returns `read-status::closed` with an `error-context` and the future + /// resolves to `err` with an `error-code`. + /// + /// Note: This is similar to `pread` in POSIX. + @since(version = 0.3.0-rc-2025-09-16) + read-via-stream: func( + /// The offset within the file at which to start reading. + offset: filesize, + ) -> tuple, future>>; + + /// Return a stream for writing to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be written. + /// + /// 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. + /// + /// This function returns once either full contents of the stream are + /// written or an error is encountered. + /// + /// Note: This is similar to `pwrite` in POSIX. + @since(version = 0.3.0-rc-2025-09-16) + write-via-stream: async func( + /// Data to write + data: stream, + /// The offset within the file at which to start writing. + offset: filesize, + ) -> 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. + /// + /// This function returns once either full contents of the stream are + /// written or an error is encountered. + /// + /// Note: This is similar to `write` with `O_APPEND` in POSIX. + @since(version = 0.3.0-rc-2025-09-16) + append-via-stream: async func(data: stream) -> result<_, error-code>; + + /// Provide file advisory information on a descriptor. + /// + /// This is similar to `posix_fadvise` in POSIX. + @since(version = 0.3.0-rc-2025-09-16) + advise: async func( + /// The offset within the file to which the advisory applies. + offset: filesize, + /// The length of the region to which the advisory applies. + length: filesize, + /// The advice. + advice: advice + ) -> 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. + @since(version = 0.3.0-rc-2025-09-16) + sync-data: async func() -> 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. + @since(version = 0.3.0-rc-2025-09-16) + get-flags: async 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. + @since(version = 0.3.0-rc-2025-09-16) + get-type: async func() -> result; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + set-size: async 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. + @since(version = 0.3.0-rc-2025-09-16) + set-times: async func( + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, 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. + /// + /// This function returns a future, which will resolve to an error code if + /// reading full contents of the directory fails. + @since(version = 0.3.0-rc-2025-09-16) + read-directory: async func() -> tuple, future>>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + sync: async func() -> result<_, error-code>; + + /// Create a directory. + /// + /// Note: This is similar to `mkdirat` in POSIX. + @since(version = 0.3.0-rc-2025-09-16) + create-directory-at: async func( + /// The relative path at which to create the directory. + path: string, + ) -> 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. + @since(version = 0.3.0-rc-2025-09-16) + stat: async 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. + @since(version = 0.3.0-rc-2025-09-16) + stat-at: async func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + set-times-at: async func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to operate on. + path: string, + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, error-code>; + + /// Create a hard link. + /// + /// Fails with `error-code::no-entry` if the old path does not exist, + /// with `error-code::exist` if the new path already exists, and + /// `error-code::not-permitted` if the old path is not a file. + /// + /// Note: This is similar to `linkat` in POSIX. + @since(version = 0.3.0-rc-2025-09-16) + link-at: async func( + /// Flags determining the method of how the path is resolved. + old-path-flags: path-flags, + /// The relative source path from which to link. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path at which to create the hard link. + new-path: string, + ) -> result<_, error-code>; + + /// Open a file or directory. + /// + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + open-at: async func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the object to open. + path: string, + /// The method by which to open the file. + open-flags: open-flags, + /// Flags to use for the resulting descriptor. + %flags: descriptor-flags, + ) -> 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. + @since(version = 0.3.0-rc-2025-09-16) + readlink-at: async func( + /// The relative path of the symbolic link from which to read. + 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. + @since(version = 0.3.0-rc-2025-09-16) + remove-directory-at: async func( + /// The relative path to a directory to remove. + path: string, + ) -> result<_, error-code>; + + /// Rename a filesystem object. + /// + /// Note: This is similar to `renameat` in POSIX. + @since(version = 0.3.0-rc-2025-09-16) + rename-at: async func( + /// The relative source path of the file or directory to rename. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path to which to rename the file or directory. + new-path: string, + ) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + symlink-at: async func( + /// The contents of the symbolic link. + old-path: string, + /// The relative destination path at which to create the symbolic link. + new-path: string, + ) -> 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. + @since(version = 0.3.0-rc-2025-09-16) + unlink-file-at: async func( + /// The relative path to a file to unlink. + path: string, + ) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + is-same-object: async func(other: borrow) -> bool; + + /// 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 encouraged 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. + @since(version = 0.3.0-rc-2025-09-16) + metadata-hash: async 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`. + @since(version = 0.3.0-rc-2025-09-16) + metadata-hash-at: async func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + } +} diff --git a/proposals/cli/wit-0.3.0-draft/deps/filesystem/world.wit b/proposals/cli/wit-0.3.0-draft/deps/filesystem/world.wit new file mode 100644 index 000000000..87fc72716 --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/deps/filesystem/world.wit @@ -0,0 +1,9 @@ +package wasi:filesystem@0.3.0-rc-2025-09-16; + +@since(version = 0.3.0-rc-2025-09-16) +world imports { + @since(version = 0.3.0-rc-2025-09-16) + import types; + @since(version = 0.3.0-rc-2025-09-16) + import preopens; +} diff --git a/proposals/cli/wit-0.3.0-draft/deps/random/insecure-seed.wit b/proposals/cli/wit-0.3.0-draft/deps/random/insecure-seed.wit new file mode 100644 index 000000000..302151ba6 --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/deps/random/insecure-seed.wit @@ -0,0 +1,27 @@ +package wasi:random@0.3.0-rc-2025-09-16; +/// The insecure-seed interface for seeding hash-map DoS resistance. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.3.0-rc-2025-09-16) +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. + @since(version = 0.3.0-rc-2025-09-16) + get-insecure-seed: func() -> tuple; +} diff --git a/proposals/cli/wit-0.3.0-draft/deps/random/insecure.wit b/proposals/cli/wit-0.3.0-draft/deps/random/insecure.wit new file mode 100644 index 000000000..39146e391 --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/deps/random/insecure.wit @@ -0,0 +1,25 @@ +package wasi:random@0.3.0-rc-2025-09-16; +/// The insecure interface for insecure pseudo-random numbers. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.3.0-rc-2025-09-16) +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. + @since(version = 0.3.0-rc-2025-09-16) + 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`. + @since(version = 0.3.0-rc-2025-09-16) + get-insecure-random-u64: func() -> u64; +} diff --git a/proposals/cli/wit-0.3.0-draft/deps/random/random.wit b/proposals/cli/wit-0.3.0-draft/deps/random/random.wit new file mode 100644 index 000000000..fa1f111dc --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/deps/random/random.wit @@ -0,0 +1,29 @@ +package wasi:random@0.3.0-rc-2025-09-16; +/// WASI Random is a random data API. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.3.0-rc-2025-09-16) +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. + @since(version = 0.3.0-rc-2025-09-16) + 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`. + @since(version = 0.3.0-rc-2025-09-16) + get-random-u64: func() -> u64; +} diff --git a/proposals/cli/wit-0.3.0-draft/deps/random/world.wit b/proposals/cli/wit-0.3.0-draft/deps/random/world.wit new file mode 100644 index 000000000..08c5ed88b --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/deps/random/world.wit @@ -0,0 +1,13 @@ +package wasi:random@0.3.0-rc-2025-09-16; + +@since(version = 0.3.0-rc-2025-09-16) +world imports { + @since(version = 0.3.0-rc-2025-09-16) + import random; + + @since(version = 0.3.0-rc-2025-09-16) + import insecure; + + @since(version = 0.3.0-rc-2025-09-16) + import insecure-seed; +} diff --git a/proposals/cli/wit-0.3.0-draft/deps/sockets/ip-name-lookup.wit b/proposals/cli/wit-0.3.0-draft/deps/sockets/ip-name-lookup.wit new file mode 100644 index 000000000..6a652ff23 --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/deps/sockets/ip-name-lookup.wit @@ -0,0 +1,62 @@ +@since(version = 0.3.0-rc-2025-09-16) +interface ip-name-lookup { + @since(version = 0.3.0-rc-2025-09-16) + use types.{ip-address}; + + /// Lookup error codes. + @since(version = 0.3.0-rc-2025-09-16) + enum error-code { + /// Unknown error + unknown, + + /// Access denied. + /// + /// POSIX equivalent: EACCES, EPERM + access-denied, + + /// `name` is a syntactically invalid domain name or IP address. + /// + /// POSIX equivalent: EINVAL + invalid-argument, + + /// Name does not exist or has no suitable associated IP addresses. + /// + /// POSIX equivalent: EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY + name-unresolvable, + + /// A temporary failure in name resolution occurred. + /// + /// POSIX equivalent: EAI_AGAIN + temporary-resolver-failure, + + /// A permanent failure in name resolution occurred. + /// + /// POSIX equivalent: EAI_FAIL + permanent-resolver-failure, + } + + /// 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. + /// + /// The results are returned in connection order preference. + /// + /// This function never succeeds with 0 results. It either fails or succeeds + /// with at least one address. Additionally, this function never returns + /// IPv4-mapped IPv6 addresses. + /// + /// The returned future will resolve to an error code in case of failure. + /// It will resolve to success once the returned stream is exhausted. + /// + /// # References: + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + resolve-addresses: async func(name: string) -> result, error-code>; +} diff --git a/proposals/cli/wit-0.3.0-draft/deps/sockets/types.wit b/proposals/cli/wit-0.3.0-draft/deps/sockets/types.wit new file mode 100644 index 000000000..2ed1912e4 --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/deps/sockets/types.wit @@ -0,0 +1,725 @@ +@since(version = 0.3.0-rc-2025-09-16) +interface types { + @since(version = 0.3.0-rc-2025-09-16) + use wasi:clocks/monotonic-clock@0.3.0-rc-2025-09-16.{duration}; + + /// 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` + /// + /// See each individual API for what the POSIX equivalents are. They sometimes differ per API. + @since(version = 0.3.0-rc-2025-09-16) + 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, + + /// The operation is not valid in the socket's current state. + invalid-state, + + /// 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, + } + + @since(version = 0.3.0-rc-2025-09-16) + enum ip-address-family { + /// Similar to `AF_INET` in POSIX. + ipv4, + + /// Similar to `AF_INET6` in POSIX. + ipv6, + } + + @since(version = 0.3.0-rc-2025-09-16) + type ipv4-address = tuple; + @since(version = 0.3.0-rc-2025-09-16) + type ipv6-address = tuple; + + @since(version = 0.3.0-rc-2025-09-16) + variant ip-address { + ipv4(ipv4-address), + ipv6(ipv6-address), + } + + @since(version = 0.3.0-rc-2025-09-16) + record ipv4-socket-address { + /// sin_port + port: u16, + /// sin_addr + address: ipv4-address, + } + + @since(version = 0.3.0-rc-2025-09-16) + record ipv6-socket-address { + /// sin6_port + port: u16, + /// sin6_flowinfo + flow-info: u32, + /// sin6_addr + address: ipv6-address, + /// sin6_scope_id + scope-id: u32, + } + + @since(version = 0.3.0-rc-2025-09-16) + variant ip-socket-address { + ipv4(ipv4-socket-address), + ipv6(ipv6-socket-address), + } + + /// A TCP socket resource. + /// + /// The socket can be in one of the following states: + /// - `unbound` + /// - `bound` (See note below) + /// - `listening` + /// - `connecting` + /// - `connected` + /// - `closed` + /// See + /// for 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`, `listening`, `connecting` or `connected`) + /// + /// In addition to the general error codes documented on the + /// `types::error-code` type, TCP socket methods may always return + /// `error(invalid-state)` when in the `closed` state. + @since(version = 0.3.0-rc-2025-09-16) + resource 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. + /// + /// Unlike POSIX, WASI sockets have no notion of a socket-level + /// `O_NONBLOCK` flag. Instead they fully rely on the Component Model's + /// async support. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + create: static func(address-family: ip-address-family) -> result; + + /// Bind the socket to 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 can be bound to. (EADDRNOTAVAIL) + /// + /// # 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. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + bind: func(local-address: ip-socket-address) -> result<_, error-code>; + + /// Connect to a remote endpoint. + /// + /// On success, the socket is transitioned into the `connected` state and this function returns a connection resource. + /// + /// 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-state`: The socket is already in the `connecting` state. (EALREADY) + /// - `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) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + connect: async func(remote-address: ip-socket-address) -> result<_, error-code>; + + /// Start listening and return a stream of new inbound connections. + /// + /// Transitions the socket into the `listening` state. This can be called + /// at most once per socket. + /// + /// If the socket is not already explicitly bound, this function will + /// implicitly bind the socket to a random free port. + /// + /// Normally, the returned sockets are bound, in the `connected` state + /// and immediately ready for I/O. Though, depending on exact timing and + /// circumstances, a newly accepted connection may already be `closed` + /// by the time the server attempts to perform its first I/O on it. This + /// is true regardless of whether the WASI implementation uses + /// "synthesized" sockets or not (see Implementors Notes below). + /// + /// 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` + /// + /// # Typical errors + /// - `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) + /// + /// # Implementors note + /// This method returns a single perpetual stream that should only close + /// on fatal errors (if any). Yet, the POSIX' `accept` function may also + /// return transient errors (e.g. ECONNABORTED). The exact details differ + /// per operation system. For example, the Linux manual mentions: + /// + /// > Linux accept() passes already-pending network errors on the new + /// > socket as an error code from accept(). This behavior differs from + /// > other BSD socket implementations. For reliable operation the + /// > application should detect the network errors defined for the + /// > protocol after accept() and treat them like EAGAIN by retrying. + /// > In the case of TCP/IP, these are ENETDOWN, EPROTO, ENOPROTOOPT, + /// > EHOSTDOWN, ENONET, EHOSTUNREACH, EOPNOTSUPP, and ENETUNREACH. + /// Source: https://man7.org/linux/man-pages/man2/accept.2.html + /// + /// WASI implementations have two options to handle this: + /// - Optionally log it and then skip over non-fatal errors returned by + /// `accept`. Guest code never gets to see these failures. Or: + /// - Synthesize a `tcp-socket` resource that exposes the error when + /// attempting to send or receive on it. Guest code then sees these + /// failures as regular I/O errors. + /// + /// In either case, the stream returned by this `listen` method remains + /// operational. + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + listen: func() -> result, error-code>; + + /// Transmit data to peer. + /// + /// The caller should close the stream when it has no more data to send + /// to the peer. Under normal circumstances this will cause a FIN packet + /// to be sent out. Closing the stream is equivalent to calling + /// `shutdown(SHUT_WR)` in POSIX. + /// + /// This function may be called at most once and returns once the full + /// contents of the stream are transmitted or an error is encountered. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) + /// - `connection-reset`: The connection was reset. (ECONNRESET) + /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + send: async func(data: stream) -> result<_, error-code>; + + /// Read data from peer. + /// + /// This function returns a `stream` which provides the data received from the + /// socket, and a `future` providing additional error information in case the + /// socket is closed abnormally. + /// + /// If the socket is closed normally, `stream.read` on the `stream` will return + /// `read-status::closed` with no `error-context` and the future resolves to + /// the value `ok`. If the socket is closed abnormally, `stream.read` on the + /// `stream` returns `read-status::closed` with an `error-context` and the future + /// resolves to `err` with an `error-code`. + /// + /// `receive` is meant to be called only once per socket. If it is called more + /// than once, the subsequent calls return a new `stream` that fails as if it + /// were closed abnormally. + /// + /// If the caller is not expecting to receive any data from the peer, + /// they may drop the stream. Any data still in the receive queue + /// will be discarded. This is equivalent to calling `shutdown(SHUT_RD)` + /// in POSIX. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) + /// - `connection-reset`: The connection was reset. (ECONNRESET) + /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + receive: func() -> tuple, future>>; + + /// 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 `get-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 + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + get-local-address: func() -> result; + + /// Get the remote address. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + get-remote-address: func() -> result; + + /// Whether the socket is in the `listening` state. + /// + /// Equivalent to the SO_ACCEPTCONN socket option. + @since(version = 0.3.0-rc-2025-09-16) + get-is-listening: func() -> bool; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// This is the value passed to the constructor. + /// + /// Equivalent to the SO_DOMAIN socket option. + @since(version = 0.3.0-rc-2025-09-16) + get-address-family: func() -> ip-address-family; + + /// 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 `connecting` or `connected` state. + @since(version = 0.3.0-rc-2025-09-16) + set-listen-backlog-size: func(value: u64) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + get-keep-alive-enabled: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-keep-alive-enabled: func(value: bool) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + get-keep-alive-idle-time: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-keep-alive-idle-time: func(value: duration) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + get-keep-alive-interval: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-keep-alive-interval: func(value: duration) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + get-keep-alive-count: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-keep-alive-count: func(value: u32) -> 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. + @since(version = 0.3.0-rc-2025-09-16) + get-hop-limit: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-hop-limit: func(value: u8) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + get-receive-buffer-size: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + @since(version = 0.3.0-rc-2025-09-16) + get-send-buffer-size: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + } + + /// A UDP socket handle. + @since(version = 0.3.0-rc-2025-09-16) + resource 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. + /// + /// Unlike POSIX, WASI sockets have no notion of a socket-level + /// `O_NONBLOCK` flag. Instead they fully rely on the Component Model's + /// async support. + /// + /// # References: + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + create: static func(address-family: ip-address-family) -> result; + + /// Bind the socket to 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 can be bound to. (EADDRNOTAVAIL) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + bind: func(local-address: ip-socket-address) -> result<_, error-code>; + + /// Associate this socket with a specific peer address. + /// + /// 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`. If the socket was not already explicitly + /// bound, this function will implicitly bind the socket to a random + /// free port. + /// + /// When a UDP socket is "connected", the `send` and `receive` methods + /// are limited to communicating with that peer only: + /// - `send` can only be used to send to this destination. + /// - `receive` will only return datagrams sent from the provided `remote-address`. + /// + /// The name "connect" was kept to align with the existing POSIX + /// terminology. Other than that, this function only changes the local + /// socket configuration and does not generate any network traffic. + /// The peer is not aware of this "connection". + /// + /// This method may be called multiple times on the same socket to change + /// its association, but only the most recent one will be effective. + /// + /// # 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) + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// + /// # Implementors note + /// If the socket is already connected, some platforms (e.g. Linux) + /// require a disconnect before connecting to a different peer address. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + connect: func(remote-address: ip-socket-address) -> result<_, error-code>; + + /// Dissociate this socket from its peer address. + /// + /// After calling this method, `send` & `receive` are free to communicate + /// with any address again. + /// + /// The POSIX equivalent of this is calling `connect` with an `AF_UNSPEC` address. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not connected. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + disconnect: func() -> result<_, error-code>; + + /// Send a message on the socket to a particular peer. + /// + /// If the socket is connected, the peer address may be left empty. In + /// that case this is equivalent to `send` in POSIX. Otherwise it is + /// equivalent to `sendto`. + /// + /// Additionally, if the socket is connected, a `remote-address` argument + /// _may_ be provided but then it must be identical to the address + /// passed to `connect`. + /// + /// Implementations may trap if the `data` length exceeds 64 KiB. + /// + /// # 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 `connect`. (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 + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + send: async func(data: list, remote-address: option) -> result<_, error-code>; + + /// Receive a message on the socket. + /// + /// On success, the return value contains a tuple of the received data + /// and the address of the sender. Theoretical maximum length of the + /// data is 64 KiB. Though in practice, it will typically be less than + /// 1500 bytes. + /// + /// If the socket is connected, the sender address is guaranteed to + /// match the remote address passed to `connect`. + /// + /// # Typical errors + /// - `invalid-state`: The socket has not been bound yet. + /// - `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 + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + receive: async func() -> result, ip-socket-address>, 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 `get-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 + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + get-local-address: func() -> result; + + /// Get the address the socket is currently "connected" to. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not "connected" to a specific remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + get-remote-address: func() -> result; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// This is the value passed to the constructor. + /// + /// Equivalent to the SO_DOMAIN socket option. + @since(version = 0.3.0-rc-2025-09-16) + get-address-family: func() -> ip-address-family; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + get-unicast-hop-limit: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + get-receive-buffer-size: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + @since(version = 0.3.0-rc-2025-09-16) + get-send-buffer-size: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + } +} diff --git a/proposals/cli/wit-0.3.0-draft/deps/sockets/world.wit b/proposals/cli/wit-0.3.0-draft/deps/sockets/world.wit new file mode 100644 index 000000000..44cc427ed --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/deps/sockets/world.wit @@ -0,0 +1,9 @@ +package wasi:sockets@0.3.0-rc-2025-09-16; + +@since(version = 0.3.0-rc-2025-09-16) +world imports { + @since(version = 0.3.0-rc-2025-09-16) + import types; + @since(version = 0.3.0-rc-2025-09-16) + import ip-name-lookup; +} diff --git a/proposals/cli/wit-0.3.0-draft/environment.wit b/proposals/cli/wit-0.3.0-draft/environment.wit new file mode 100644 index 000000000..3763f2f6c --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/environment.wit @@ -0,0 +1,22 @@ +@since(version = 0.3.0-rc-2025-09-16) +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. + @since(version = 0.3.0-rc-2025-09-16) + get-environment: func() -> list>; + + /// Get the POSIX-style arguments to the program. + @since(version = 0.3.0-rc-2025-09-16) + get-arguments: func() -> list; + + /// Return a path that programs should use as their initial current working + /// directory, interpreting `.` as shorthand for this. + @since(version = 0.3.0-rc-2025-09-16) + get-initial-cwd: func() -> option; +} diff --git a/proposals/cli/wit-0.3.0-draft/exit.wit b/proposals/cli/wit-0.3.0-draft/exit.wit new file mode 100644 index 000000000..1efba7d68 --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/exit.wit @@ -0,0 +1,17 @@ +@since(version = 0.3.0-rc-2025-09-16) +interface exit { + /// Exit the current instance and any linked instances. + @since(version = 0.3.0-rc-2025-09-16) + exit: func(status: result); + + /// Exit the current instance and any linked instances, reporting the + /// specified status code to the host. + /// + /// The meaning of the code depends on the context, with 0 usually meaning + /// "success", and other values indicating various types of failure. + /// + /// This function does not return; the effect is analogous to a trap, but + /// without the connotation that something bad has happened. + @unstable(feature = cli-exit-with-code) + exit-with-code: func(status-code: u8); +} diff --git a/proposals/cli/wit-0.3.0-draft/imports.wit b/proposals/cli/wit-0.3.0-draft/imports.wit new file mode 100644 index 000000000..660a2dd95 --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/imports.wit @@ -0,0 +1,34 @@ +package wasi:cli@0.3.0-rc-2025-09-16; + +@since(version = 0.3.0-rc-2025-09-16) +world imports { + @since(version = 0.3.0-rc-2025-09-16) + include wasi:clocks/imports@0.3.0-rc-2025-09-16; + @since(version = 0.3.0-rc-2025-09-16) + include wasi:filesystem/imports@0.3.0-rc-2025-09-16; + @since(version = 0.3.0-rc-2025-09-16) + include wasi:sockets/imports@0.3.0-rc-2025-09-16; + @since(version = 0.3.0-rc-2025-09-16) + include wasi:random/imports@0.3.0-rc-2025-09-16; + + @since(version = 0.3.0-rc-2025-09-16) + import environment; + @since(version = 0.3.0-rc-2025-09-16) + import exit; + @since(version = 0.3.0-rc-2025-09-16) + import stdin; + @since(version = 0.3.0-rc-2025-09-16) + import stdout; + @since(version = 0.3.0-rc-2025-09-16) + import stderr; + @since(version = 0.3.0-rc-2025-09-16) + import terminal-input; + @since(version = 0.3.0-rc-2025-09-16) + import terminal-output; + @since(version = 0.3.0-rc-2025-09-16) + import terminal-stdin; + @since(version = 0.3.0-rc-2025-09-16) + import terminal-stdout; + @since(version = 0.3.0-rc-2025-09-16) + import terminal-stderr; +} diff --git a/proposals/cli/wit-0.3.0-draft/run.wit b/proposals/cli/wit-0.3.0-draft/run.wit new file mode 100644 index 000000000..631441a3f --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/run.wit @@ -0,0 +1,6 @@ +@since(version = 0.3.0-rc-2025-09-16) +interface run { + /// Run the program. + @since(version = 0.3.0-rc-2025-09-16) + run: async func() -> result; +} diff --git a/proposals/cli/wit-0.3.0-draft/stdio.wit b/proposals/cli/wit-0.3.0-draft/stdio.wit new file mode 100644 index 000000000..51e5ae4b4 --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/stdio.wit @@ -0,0 +1,65 @@ +@since(version = 0.3.0-rc-2025-09-16) +interface types { + @since(version = 0.3.0-rc-2025-09-16) + enum error-code { + /// Input/output error + io, + /// Invalid or incomplete multibyte or wide character + illegal-byte-sequence, + /// Broken pipe + pipe, + } +} + +@since(version = 0.3.0-rc-2025-09-16) +interface stdin { + use types.{error-code}; + + /// Return a stream for reading from stdin. + /// + /// This function returns a stream which provides data read from stdin, + /// and a future to signal read results. + /// + /// If the stream's readable end is dropped the future will resolve to success. + /// + /// If the stream's writable end is dropped the future will either resolve to + /// success if stdin was closed by the writer or to an error-code if reading + /// failed for some other reason. + /// + /// Multiple streams may be active at the same time. The behavior of concurrent + /// reads is implementation-specific. + @since(version = 0.3.0-rc-2025-09-16) + read-via-stream: func() -> tuple, future>>; +} + +@since(version = 0.3.0-rc-2025-09-16) +interface stdout { + use types.{error-code}; + + /// Write the given stream to stdout. + /// + /// If the stream's writable end is dropped this function will either return + /// success once the entire contents of the stream have been written or an + /// error-code representing a failure. + /// + /// Otherwise if there is an error the readable end of the stream will be + /// dropped and this function will return an error-code. + @since(version = 0.3.0-rc-2025-09-16) + write-via-stream: async func(data: stream) -> result<_, error-code>; +} + +@since(version = 0.3.0-rc-2025-09-16) +interface stderr { + use types.{error-code}; + + /// Write the given stream to stderr. + /// + /// If the stream's writable end is dropped this function will either return + /// success once the entire contents of the stream have been written or an + /// error-code representing a failure. + /// + /// Otherwise if there is an error the readable end of the stream will be + /// dropped and this function will return an error-code. + @since(version = 0.3.0-rc-2025-09-16) + write-via-stream: async func(data: stream) -> result<_, error-code>; +} diff --git a/proposals/cli/wit-0.3.0-draft/terminal.wit b/proposals/cli/wit-0.3.0-draft/terminal.wit new file mode 100644 index 000000000..74c17694a --- /dev/null +++ b/proposals/cli/wit-0.3.0-draft/terminal.wit @@ -0,0 +1,62 @@ +/// 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. +@since(version = 0.3.0-rc-2025-09-16) +interface terminal-input { + /// The input side of a terminal. + @since(version = 0.3.0-rc-2025-09-16) + 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. +@since(version = 0.3.0-rc-2025-09-16) +interface terminal-output { + /// The output side of a terminal. + @since(version = 0.3.0-rc-2025-09-16) + resource terminal-output; +} + +/// An interface providing an optional `terminal-input` for stdin as a +/// link-time authority. +@since(version = 0.3.0-rc-2025-09-16) +interface terminal-stdin { + @since(version = 0.3.0-rc-2025-09-16) + use terminal-input.{terminal-input}; + + /// If stdin is connected to a terminal, return a `terminal-input` handle + /// allowing further interaction with it. + @since(version = 0.3.0-rc-2025-09-16) + get-terminal-stdin: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stdout as a +/// link-time authority. +@since(version = 0.3.0-rc-2025-09-16) +interface terminal-stdout { + @since(version = 0.3.0-rc-2025-09-16) + use terminal-output.{terminal-output}; + + /// If stdout is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + @since(version = 0.3.0-rc-2025-09-16) + get-terminal-stdout: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stderr as a +/// link-time authority. +@since(version = 0.3.0-rc-2025-09-16) +interface terminal-stderr { + @since(version = 0.3.0-rc-2025-09-16) + use terminal-output.{terminal-output}; + + /// If stderr is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + @since(version = 0.3.0-rc-2025-09-16) + get-terminal-stderr: func() -> option; +} diff --git a/proposals/cli/wit/command.wit b/proposals/cli/wit/command.wit new file mode 100644 index 000000000..38ef86b86 --- /dev/null +++ b/proposals/cli/wit/command.wit @@ -0,0 +1,10 @@ +package wasi:cli@0.2.8; + +@since(version = 0.2.0) +world command { + @since(version = 0.2.0) + include imports; + + @since(version = 0.2.0) + export run; +} diff --git a/proposals/cli/wit/deps.lock b/proposals/cli/wit/deps.lock new file mode 100644 index 000000000..525406a2b --- /dev/null +++ b/proposals/cli/wit/deps.lock @@ -0,0 +1,24 @@ +[clocks] +sha256 = "be1d8c61e2544e2b48d902c60df73577e293349063344ce752cda4d323f8b913" +sha512 = "0fd7962c62b135da0e584c2b58a55147bf09873848b0bb5bd3913019bc3f8d4b5969fbd6f7f96fd99a015efaf562a3eeafe3bc13049f8572a6e13ef9ef0e7e75" + +[filesystem] +url = "https://github.com/WebAssembly/wasi-filesystem/archive/v0.2.8.tar.gz" +sha256 = "57c2e5e40c57d54a2eacb55d8855d2963a6c0b33971a3620c1468b732233d593" +sha512 = "11d1dee738bea1fdd15f5cc07ea10bfb9953a4e84361bbdc2c1051f9520463329ec839caffe0e5cf22870584846f9bfe627c1b77ee4b555fcc990b8106791c68" +deps = ["clocks", "io"] + +[io] +sha256 = "9f1ad5da70f621bbd4c69e3bd90250a0c12ecfde266aa8f99684fc44bc1e7c15" +sha512 = "6d0a9db6848f24762933d1c168a5b5b1065ba838c253ee20454afeb8dd1a049b918d25deff556083d68095dd3126ae131ac3e738774320eee5d918f5a4b5354e" + +[random] +url = "https://github.com/WebAssembly/wasi-random/archive/v0.2.8.tar.gz" +sha256 = "febd6f75dec1fa733b8e25c1cdee4de9acd922ddf755a192d85f479b1f96b445" +sha512 = "1689d2eee3c64b9fc91faaf43741ff95f343b05acc758342dbf3aa86830de1ec66b4bcd0fe22bf1f77abc4a1feeaae90cdc2c06eedc30952a6667f70edca7d8f" + +[sockets] +url = "https://github.com/WebAssembly/wasi-sockets/archive/v0.2.8.tar.gz" +sha256 = "e82bb0502324f44ef22f6fdadec51f4963faf8ccd21187c37397ea872c0548c0" +sha512 = "b8139db2b26a95d6948e345cf036497883943134ea832abfabd7267682d9f84b4c86ff38fc771125f1a8e2bcd237ea0a731d83bf22df9d78f19e452061227d77" +deps = ["clocks", "io"] diff --git a/proposals/cli/wit/deps.toml b/proposals/cli/wit/deps.toml new file mode 100644 index 000000000..59d97afe4 --- /dev/null +++ b/proposals/cli/wit/deps.toml @@ -0,0 +1,3 @@ +filesystem = "https://github.com/WebAssembly/wasi-filesystem/archive/v0.2.8.tar.gz" +random = "https://github.com/WebAssembly/wasi-random/archive/v0.2.8.tar.gz" +sockets = "https://github.com/WebAssembly/wasi-sockets/archive/v0.2.8.tar.gz" diff --git a/proposals/cli/wit/deps/clocks/monotonic-clock.wit b/proposals/cli/wit/deps/clocks/monotonic-clock.wit new file mode 100644 index 000000000..e60f366f2 --- /dev/null +++ b/proposals/cli/wit/deps/clocks/monotonic-clock.wit @@ -0,0 +1,55 @@ +package wasi:clocks@0.2.8; +/// 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. +@since(version = 0.2.0) +interface monotonic-clock { + @since(version = 0.2.0) + use wasi:io/poll@0.2.8.{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. + @since(version = 0.2.0) + type instant = u64; + + /// A duration of time, in nanoseconds. + @since(version = 0.2.0) + 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. + /// + /// For completeness, this function traps if it's not possible to represent + /// the value of the clock in an `instant`. Consequently, implementations + /// should ensure that the starting time is low enough to avoid the + /// possibility of overflow in practice. + @since(version = 0.2.0) + now: func() -> instant; + + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + @since(version = 0.2.0) + resolution: func() -> duration; + + /// Create a `pollable` which will resolve once the specified instant + /// has occurred. + @since(version = 0.2.0) + subscribe-instant: func( + when: instant, + ) -> pollable; + + /// Create a `pollable` that will resolve after the specified duration has + /// elapsed from the time this function is invoked. + @since(version = 0.2.0) + subscribe-duration: func( + when: duration, + ) -> pollable; +} diff --git a/proposals/cli/wit/deps/clocks/timezone.wit b/proposals/cli/wit/deps/clocks/timezone.wit new file mode 100644 index 000000000..534814a63 --- /dev/null +++ b/proposals/cli/wit/deps/clocks/timezone.wit @@ -0,0 +1,55 @@ +package wasi:clocks@0.2.8; + +@unstable(feature = clocks-timezone) +interface timezone { + @unstable(feature = clocks-timezone) + use wall-clock.{datetime}; + + /// Return information needed to display the given `datetime`. This includes + /// the UTC offset, the time zone name, and a flag indicating whether + /// daylight saving time is active. + /// + /// If the timezone cannot be determined for the given `datetime`, return a + /// `timezone-display` for `UTC` with a `utc-offset` of 0 and no daylight + /// saving time. + @unstable(feature = clocks-timezone) + display: func(when: datetime) -> timezone-display; + + /// The same as `display`, but only return the UTC offset. + @unstable(feature = clocks-timezone) + utc-offset: func(when: datetime) -> s32; + + /// Information useful for displaying the timezone of a specific `datetime`. + /// + /// This information may vary within a single `timezone` to reflect daylight + /// saving time adjustments. + @unstable(feature = clocks-timezone) + record timezone-display { + /// The number of seconds difference between UTC time and the local + /// time of the timezone. + /// + /// The returned value will always be less than 86400 which is the + /// number of seconds in a day (24*60*60). + /// + /// In implementations that do not expose an actual time zone, this + /// should return 0. + utc-offset: s32, + + /// The abbreviated name of the timezone to display to a user. The name + /// `UTC` indicates Coordinated Universal Time. Otherwise, this should + /// reference local standards for the name of the time zone. + /// + /// In implementations that do not expose an actual time zone, this + /// should be the string `UTC`. + /// + /// In time zones that do not have an applicable name, a formatted + /// representation of the UTC offset may be returned, such as `-04:00`. + name: string, + + /// Whether daylight saving time is active. + /// + /// In implementations that do not expose an actual time zone, this + /// should return false. + in-daylight-saving-time: bool, + } +} diff --git a/proposals/cli/wit/deps/clocks/wall-clock.wit b/proposals/cli/wit/deps/clocks/wall-clock.wit new file mode 100644 index 000000000..3386c800b --- /dev/null +++ b/proposals/cli/wit/deps/clocks/wall-clock.wit @@ -0,0 +1,46 @@ +package wasi:clocks@0.2.8; +/// 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. +@since(version = 0.2.0) +interface wall-clock { + /// A time and date in seconds plus nanoseconds. + @since(version = 0.2.0) + 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 + @since(version = 0.2.0) + now: func() -> datetime; + + /// Query the resolution of the clock. + /// + /// The nanoseconds field of the output is always less than 1000000000. + @since(version = 0.2.0) + resolution: func() -> datetime; +} diff --git a/proposals/cli/wit/deps/clocks/world.wit b/proposals/cli/wit/deps/clocks/world.wit new file mode 100644 index 000000000..1655ca830 --- /dev/null +++ b/proposals/cli/wit/deps/clocks/world.wit @@ -0,0 +1,11 @@ +package wasi:clocks@0.2.8; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import monotonic-clock; + @since(version = 0.2.0) + import wall-clock; + @unstable(feature = clocks-timezone) + import timezone; +} diff --git a/proposals/cli/wit/deps/filesystem/preopens.wit b/proposals/cli/wit/deps/filesystem/preopens.wit new file mode 100644 index 000000000..0d2cca65d --- /dev/null +++ b/proposals/cli/wit/deps/filesystem/preopens.wit @@ -0,0 +1,11 @@ +package wasi:filesystem@0.2.8; + +@since(version = 0.2.0) +interface preopens { + @since(version = 0.2.0) + use types.{descriptor}; + + /// Return the set of preopened directories, and their paths. + @since(version = 0.2.0) + get-directories: func() -> list>; +} diff --git a/proposals/cli/wit/deps/filesystem/types.wit b/proposals/cli/wit/deps/filesystem/types.wit new file mode 100644 index 000000000..ac68f88af --- /dev/null +++ b/proposals/cli/wit/deps/filesystem/types.wit @@ -0,0 +1,676 @@ +package wasi:filesystem@0.2.8; +/// 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 +@since(version = 0.2.0) +interface types { + @since(version = 0.2.0) + use wasi:io/streams@0.2.8.{input-stream, output-stream, error}; + @since(version = 0.2.0) + use wasi:clocks/wall-clock@0.2.8.{datetime}; + + /// File size or length of a region within a file. + @since(version = 0.2.0) + type filesize = u64; + + /// The type of a filesystem object referenced by a descriptor. + /// + /// Note: This was called `filetype` in earlier versions of WASI. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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 integrity + /// 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, + } + + /// File attributes. + /// + /// Note: This was called `filestat` in earlier versions of WASI. + @since(version = 0.2.0) + 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, + } + + /// Flags determining the method of how paths are resolved. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + type link-count = u64; + + /// When setting a timestamp, this gives the value to set it to. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + resource descriptor { + /// 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. + @since(version = 0.2.0) + read-via-stream: func( + /// The offset within the file at which to start reading. + 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. + @since(version = 0.2.0) + write-via-stream: func( + /// The offset within the file at which to start writing. + offset: filesize, + ) -> result; + + /// 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 POSIX. + @since(version = 0.2.0) + append-via-stream: func() -> result; + + /// Provide file advisory information on a descriptor. + /// + /// This is similar to `posix_fadvise` in POSIX. + @since(version = 0.2.0) + advise: func( + /// The offset within the file to which the advisory applies. + offset: filesize, + /// The length of the region to which the advisory applies. + length: filesize, + /// The advice. + advice: advice + ) -> 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. + @since(version = 0.2.0) + sync-data: func() -> 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + get-type: func() -> result; + + /// 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + set-times: func( + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + read: func( + /// The maximum number of bytes to read. + length: filesize, + /// The offset within the file at which to read. + offset: filesize, + ) -> result, bool>, 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. + @since(version = 0.2.0) + write: func( + /// Data to write + buffer: list, + /// The offset within the file at which to write. + offset: filesize, + ) -> result; + + /// 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. + @since(version = 0.2.0) + read-directory: func() -> result; + + /// 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. + @since(version = 0.2.0) + sync: func() -> result<_, error-code>; + + /// Create a directory. + /// + /// Note: This is similar to `mkdirat` in POSIX. + @since(version = 0.2.0) + create-directory-at: func( + /// The relative path at which to create the directory. + path: string, + ) -> 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + stat-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + + /// 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. + @since(version = 0.2.0) + set-times-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to operate on. + path: string, + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, error-code>; + + /// Create a hard link. + /// + /// Fails with `error-code::no-entry` if the old path does not exist, + /// with `error-code::exist` if the new path already exists, and + /// `error-code::not-permitted` if the old path is not a file. + /// + /// Note: This is similar to `linkat` in POSIX. + @since(version = 0.2.0) + link-at: func( + /// Flags determining the method of how the path is resolved. + old-path-flags: path-flags, + /// The relative source path from which to link. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path at which to create the hard link. + new-path: string, + ) -> result<_, error-code>; + + /// Open a file or directory. + /// + /// 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. + @since(version = 0.2.0) + open-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the object to open. + path: string, + /// The method by which to open the file. + open-flags: open-flags, + /// Flags to use for the resulting descriptor. + %flags: descriptor-flags, + ) -> 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. + @since(version = 0.2.0) + readlink-at: func( + /// The relative path of the symbolic link from which to read. + 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. + @since(version = 0.2.0) + remove-directory-at: func( + /// The relative path to a directory to remove. + path: string, + ) -> result<_, error-code>; + + /// Rename a filesystem object. + /// + /// Note: This is similar to `renameat` in POSIX. + @since(version = 0.2.0) + rename-at: func( + /// The relative source path of the file or directory to rename. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path to which to rename the file or directory. + new-path: string, + ) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + symlink-at: func( + /// The contents of the symbolic link. + old-path: string, + /// The relative destination path at which to create the symbolic link. + new-path: string, + ) -> 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. + @since(version = 0.2.0) + unlink-file-at: func( + /// The relative path to a file to unlink. + path: string, + ) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + is-same-object: func(other: borrow) -> bool; + + /// 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 encouraged 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. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + metadata-hash-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + } + + /// A stream of directory entries. + @since(version = 0.2.0) + resource directory-entry-stream { + /// Read a single directory entry from a `directory-entry-stream`. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + filesystem-error-code: func(err: borrow) -> option; +} diff --git a/proposals/cli/wit/deps/filesystem/world.wit b/proposals/cli/wit/deps/filesystem/world.wit new file mode 100644 index 000000000..7daf06758 --- /dev/null +++ b/proposals/cli/wit/deps/filesystem/world.wit @@ -0,0 +1,9 @@ +package wasi:filesystem@0.2.8; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import types; + @since(version = 0.2.0) + import preopens; +} diff --git a/proposals/cli/wit/deps/io/error.wit b/proposals/cli/wit/deps/io/error.wit new file mode 100644 index 000000000..dd5a1af03 --- /dev/null +++ b/proposals/cli/wit/deps/io/error.wit @@ -0,0 +1,34 @@ +package wasi:io@0.2.8; + +@since(version = 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 + /// offer functions to "downcast" this error into more specific types. For example, + /// errors returned from streams derived from filesystem types can be described using + /// the filesystem's own error-code type. This is done using the function + /// `wasi:filesystem/types/filesystem-error-code`, which takes a `borrow` + /// parameter and returns an `option`. + /// + /// The set of functions which can "downcast" an `error` into a more + /// concrete type is open. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + to-debug-string: func() -> string; + } +} diff --git a/proposals/cli/wit/deps/io/poll.wit b/proposals/cli/wit/deps/io/poll.wit new file mode 100644 index 000000000..833b381d9 --- /dev/null +++ b/proposals/cli/wit/deps/io/poll.wit @@ -0,0 +1,47 @@ +package wasi:io@0.2.8; + +/// A poll API intended to let users wait for I/O events on multiple handles +/// at once. +@since(version = 0.2.0) +interface poll { + /// `pollable` represents a single I/O event which may be ready, or not. + @since(version = 0.2.0) + resource pollable { + + /// Return the readiness of a pollable. This function never blocks. + /// + /// Returns `true` when the pollable is ready, and `false` otherwise. + @since(version = 0.2.0) + ready: func() -> bool; + + /// `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. + @since(version = 0.2.0) + block: func(); + } + + /// 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. + /// + /// This function traps if either: + /// - the list is empty, or: + /// - the list contains more elements than can be indexed with a `u32` value. + /// + /// 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 ready for I/O. + @since(version = 0.2.0) + poll: func(in: list>) -> list; +} diff --git a/proposals/cli/wit/deps/io/streams.wit b/proposals/cli/wit/deps/io/streams.wit new file mode 100644 index 000000000..fbb0268b0 --- /dev/null +++ b/proposals/cli/wit/deps/io/streams.wit @@ -0,0 +1,258 @@ +package wasi:io@0.2.8; + +/// 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. +@since(version = 0.2.0) +interface streams { + @since(version = 0.2.0) + use error.{error}; + @since(version = 0.2.0) + use poll.{pollable}; + + /// An error for input-stream and output-stream operations. + @since(version = 0.2.0) + variant stream-error { + /// The last operation (a write or flush) failed before completion. + /// + /// More information is available in the `error` payload. + /// + /// After this, the stream will be closed. All future operations return + /// `stream-error::closed`. + 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`. + @since(version = 0.2.0) + resource input-stream { + /// 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. + @since(version = 0.2.0) + read: func( + /// The maximum number of bytes to read + len: u64 + ) -> result, stream-error>; + + /// Read bytes from a stream, after blocking until at least one byte can + /// be read. Except for blocking, behavior is identical to `read`. + @since(version = 0.2.0) + blocking-read: func( + /// The maximum number of bytes to read + 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. + @since(version = 0.2.0) + skip: func( + /// The maximum number of bytes to skip. + len: u64, + ) -> result; + + /// Skip bytes from a stream, after blocking until at least one byte + /// can be skipped. Except for blocking behavior, identical to `skip`. + @since(version = 0.2.0) + blocking-skip: func( + /// The maximum number of bytes to skip. + 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. + @since(version = 0.2.0) + 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`. + /// + /// Dropping an `output-stream` while there's still an active write in + /// progress may result in the data being lost. Before dropping the stream, + /// be sure to fully flush your writes. + @since(version = 0.2.0) + resource output-stream { + /// 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. + @since(version = 0.2.0) + check-write: func() -> result; + + /// 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. + @since(version = 0.2.0) + write: func( + contents: list + ) -> result<_, stream-error>; + + /// 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. + /// + /// Returns success when all of the contents written are successfully + /// flushed to output. If an error occurs at any point before all + /// contents are successfully flushed, that error is returned as soon as + /// possible. If writing and flushing the complete contents causes the + /// stream to become closed, this call should return success, and + /// subsequent calls to check-write or other interfaces should return + /// stream-error::closed. + @since(version = 0.2.0) + blocking-write-and-flush: func( + contents: list + ) -> result<_, stream-error>; + + /// 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. + @since(version = 0.2.0) + flush: func() -> result<_, stream-error>; + + /// Request to flush buffered output, and block until flush completes + /// and stream is ready for writing again. + @since(version = 0.2.0) + blocking-flush: func() -> result<_, stream-error>; + + /// Create a `pollable` which will resolve once the output-stream + /// is ready for more writing, or an error has occurred. 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. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// 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. + @since(version = 0.2.0) + write-zeroes: func( + /// The number of zero-bytes to write + len: u64 + ) -> 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. + /// + /// Functionality is equivelant to `blocking-write-and-flush` with + /// contents given as a list of len containing only zeroes. + @since(version = 0.2.0) + blocking-write-zeroes-and-flush: func( + /// The number of zero-bytes to write + len: u64 + ) -> result<_, stream-error>; + + /// Read from one stream and write to another. + /// + /// The behavior of splice is equivalent 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`. + @since(version = 0.2.0) + splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + + /// 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`. + @since(version = 0.2.0) + blocking-splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + } +} diff --git a/proposals/cli/wit/deps/io/world.wit b/proposals/cli/wit/deps/io/world.wit new file mode 100644 index 000000000..1cc3fce12 --- /dev/null +++ b/proposals/cli/wit/deps/io/world.wit @@ -0,0 +1,10 @@ +package wasi:io@0.2.8; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import streams; + + @since(version = 0.2.0) + import poll; +} diff --git a/proposals/cli/wit/deps/random/insecure-seed.wit b/proposals/cli/wit/deps/random/insecure-seed.wit new file mode 100644 index 000000000..b2b435e55 --- /dev/null +++ b/proposals/cli/wit/deps/random/insecure-seed.wit @@ -0,0 +1,27 @@ +package wasi:random@0.2.8; +/// The insecure-seed interface for seeding hash-map DoS resistance. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.2.0) +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. + @since(version = 0.2.0) + insecure-seed: func() -> tuple; +} diff --git a/proposals/cli/wit/deps/random/insecure.wit b/proposals/cli/wit/deps/random/insecure.wit new file mode 100644 index 000000000..6dc77adec --- /dev/null +++ b/proposals/cli/wit/deps/random/insecure.wit @@ -0,0 +1,25 @@ +package wasi:random@0.2.8; +/// The insecure interface for insecure pseudo-random numbers. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.2.0) +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. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + get-insecure-random-u64: func() -> u64; +} diff --git a/proposals/cli/wit/deps/random/random.wit b/proposals/cli/wit/deps/random/random.wit new file mode 100644 index 000000000..524e77d4a --- /dev/null +++ b/proposals/cli/wit/deps/random/random.wit @@ -0,0 +1,29 @@ +package wasi:random@0.2.8; +/// WASI Random is a random data API. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.2.0) +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. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + get-random-u64: func() -> u64; +} diff --git a/proposals/cli/wit/deps/random/world.wit b/proposals/cli/wit/deps/random/world.wit new file mode 100644 index 000000000..c0c3272c9 --- /dev/null +++ b/proposals/cli/wit/deps/random/world.wit @@ -0,0 +1,13 @@ +package wasi:random@0.2.8; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import random; + + @since(version = 0.2.0) + import insecure; + + @since(version = 0.2.0) + import insecure-seed; +} diff --git a/proposals/cli/wit/deps/sockets/instance-network.wit b/proposals/cli/wit/deps/sockets/instance-network.wit new file mode 100644 index 000000000..5f6e6c1cc --- /dev/null +++ b/proposals/cli/wit/deps/sockets/instance-network.wit @@ -0,0 +1,11 @@ + +/// This interface provides a value-export of the default network handle.. +@since(version = 0.2.0) +interface instance-network { + @since(version = 0.2.0) + use network.{network}; + + /// Get a handle to the default network. + @since(version = 0.2.0) + instance-network: func() -> network; +} diff --git a/proposals/cli/wit/deps/sockets/ip-name-lookup.wit b/proposals/cli/wit/deps/sockets/ip-name-lookup.wit new file mode 100644 index 000000000..ecdaa8493 --- /dev/null +++ b/proposals/cli/wit/deps/sockets/ip-name-lookup.wit @@ -0,0 +1,56 @@ +@since(version = 0.2.0) +interface ip-name-lookup { + @since(version = 0.2.0) + use wasi:io/poll@0.2.8.{pollable}; + @since(version = 0.2.0) + use network.{network, error-code, ip-address}; + + /// 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: + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + resolve-addresses: func(network: borrow, name: string) -> result; + + @since(version = 0.2.0) + 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) + @since(version = 0.2.0) + 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 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } +} diff --git a/proposals/cli/wit/deps/sockets/network.wit b/proposals/cli/wit/deps/sockets/network.wit new file mode 100644 index 000000000..75a4f7d7f --- /dev/null +++ b/proposals/cli/wit/deps/sockets/network.wit @@ -0,0 +1,169 @@ +@since(version = 0.2.0) +interface network { + @unstable(feature = network-error-code) + use wasi:io/error@0.2.8.{error}; + + /// 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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, + } + + /// Attempts to extract a network-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 + /// network-related information about the error to return. + /// + /// Note that this function is fallible because not all stream-related + /// errors are network-related errors. + @unstable(feature = network-error-code) + network-error-code: func(err: borrow) -> option; + + @since(version = 0.2.0) + enum ip-address-family { + /// Similar to `AF_INET` in POSIX. + ipv4, + + /// Similar to `AF_INET6` in POSIX. + ipv6, + } + + @since(version = 0.2.0) + type ipv4-address = tuple; + @since(version = 0.2.0) + type ipv6-address = tuple; + + @since(version = 0.2.0) + variant ip-address { + ipv4(ipv4-address), + ipv6(ipv6-address), + } + + @since(version = 0.2.0) + record ipv4-socket-address { + /// sin_port + port: u16, + /// sin_addr + address: ipv4-address, + } + + @since(version = 0.2.0) + record ipv6-socket-address { + /// sin6_port + port: u16, + /// sin6_flowinfo + flow-info: u32, + /// sin6_addr + address: ipv6-address, + /// sin6_scope_id + scope-id: u32, + } + + @since(version = 0.2.0) + variant ip-socket-address { + ipv4(ipv4-socket-address), + ipv6(ipv6-socket-address), + } +} diff --git a/proposals/cli/wit/deps/sockets/tcp-create-socket.wit b/proposals/cli/wit/deps/sockets/tcp-create-socket.wit new file mode 100644 index 000000000..eedbd3076 --- /dev/null +++ b/proposals/cli/wit/deps/sockets/tcp-create-socket.wit @@ -0,0 +1,30 @@ +@since(version = 0.2.0) +interface tcp-create-socket { + @since(version = 0.2.0) + use network.{network, error-code, ip-address-family}; + @since(version = 0.2.0) + 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + create-tcp-socket: func(address-family: ip-address-family) -> result; +} diff --git a/proposals/cli/wit/deps/sockets/tcp.wit b/proposals/cli/wit/deps/sockets/tcp.wit new file mode 100644 index 000000000..9b5552d2e --- /dev/null +++ b/proposals/cli/wit/deps/sockets/tcp.wit @@ -0,0 +1,387 @@ +@since(version = 0.2.0) +interface tcp { + @since(version = 0.2.0) + use wasi:io/streams@0.2.8.{input-stream, output-stream}; + @since(version = 0.2.0) + use wasi:io/poll@0.2.8.{pollable}; + @since(version = 0.2.0) + use wasi:clocks/monotonic-clock@0.2.8.{duration}; + @since(version = 0.2.0) + use network.{network, error-code, ip-socket-address, ip-address-family}; + + @since(version = 0.2.0) + 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 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. + @since(version = 0.2.0) + resource tcp-socket { + /// 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + @since(version = 0.2.0) + finish-bind: func() -> result<_, error-code>; + + /// Connect to a remote endpoint. + /// + /// On success: + /// - the socket is transitioned into the `connected` 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-connect: func(network: borrow, remote-address: ip-socket-address) -> result<_, error-code>; + @since(version = 0.2.0) + finish-connect: func() -> 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-listen: func() -> result<_, error-code>; + @since(version = 0.2.0) + finish-listen: func() -> result<_, error-code>; + + /// 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + accept: func() -> result, error-code>; + + /// 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + local-address: func() -> result; + + /// Get the remote address. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + remote-address: func() -> result; + + /// Whether the socket is in the `listening` state. + /// + /// Equivalent to the SO_ACCEPTCONN socket option. + @since(version = 0.2.0) + is-listening: func() -> bool; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + @since(version = 0.2.0) + address-family: func() -> ip-address-family; + + /// 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. + @since(version = 0.2.0) + set-listen-backlog-size: func(value: u64) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + keep-alive-enabled: func() -> result; + @since(version = 0.2.0) + set-keep-alive-enabled: func(value: bool) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + keep-alive-idle-time: func() -> result; + @since(version = 0.2.0) + set-keep-alive-idle-time: func(value: duration) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + keep-alive-interval: func() -> result; + @since(version = 0.2.0) + set-keep-alive-interval: func(value: duration) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + keep-alive-count: func() -> result; + @since(version = 0.2.0) + set-keep-alive-count: func(value: u32) -> 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. + @since(version = 0.2.0) + hop-limit: func() -> result; + @since(version = 0.2.0) + set-hop-limit: func(value: u8) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + receive-buffer-size: func() -> result; + @since(version = 0.2.0) + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + @since(version = 0.2.0) + send-buffer-size: func() -> result; + @since(version = 0.2.0) + set-send-buffer-size: func(value: 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. + /// + /// 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 more information. + /// + /// Note: this function is here for WASI 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// 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 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code>; + } +} diff --git a/proposals/cli/wit/deps/sockets/udp-create-socket.wit b/proposals/cli/wit/deps/sockets/udp-create-socket.wit new file mode 100644 index 000000000..e8eeacbfe --- /dev/null +++ b/proposals/cli/wit/deps/sockets/udp-create-socket.wit @@ -0,0 +1,30 @@ +@since(version = 0.2.0) +interface udp-create-socket { + @since(version = 0.2.0) + use network.{network, error-code, ip-address-family}; + @since(version = 0.2.0) + 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: + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + create-udp-socket: func(address-family: ip-address-family) -> result; +} diff --git a/proposals/cli/wit/deps/sockets/udp.wit b/proposals/cli/wit/deps/sockets/udp.wit new file mode 100644 index 000000000..0000a157e --- /dev/null +++ b/proposals/cli/wit/deps/sockets/udp.wit @@ -0,0 +1,288 @@ +@since(version = 0.2.0) +interface udp { + @since(version = 0.2.0) + use wasi:io/poll@0.2.8.{pollable}; + @since(version = 0.2.0) + use network.{network, error-code, ip-socket-address, ip-address-family}; + + /// A received datagram. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + resource udp-socket { + /// 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + @since(version = 0.2.0) + finish-bind: func() -> 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + %stream: func(remote-address: option) -> 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + local-address: 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + remote-address: func() -> result; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + @since(version = 0.2.0) + address-family: func() -> ip-address-family; + + /// 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. + @since(version = 0.2.0) + unicast-hop-limit: func() -> result; + @since(version = 0.2.0) + set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + receive-buffer-size: func() -> result; + @since(version = 0.2.0) + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + @since(version = 0.2.0) + send-buffer-size: func() -> result; + @since(version = 0.2.0) + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + + /// Create a `pollable` which will resolve once the socket is ready for I/O. + /// + /// Note: this function is here for WASI 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } + + @since(version = 0.2.0) + 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 + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + 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 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } + + @since(version = 0.2.0) + 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 + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + 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 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } +} diff --git a/proposals/cli/wit/deps/sockets/world.wit b/proposals/cli/wit/deps/sockets/world.wit new file mode 100644 index 000000000..4441e9119 --- /dev/null +++ b/proposals/cli/wit/deps/sockets/world.wit @@ -0,0 +1,19 @@ +package wasi:sockets@0.2.8; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import instance-network; + @since(version = 0.2.0) + import network; + @since(version = 0.2.0) + import udp; + @since(version = 0.2.0) + import udp-create-socket; + @since(version = 0.2.0) + import tcp; + @since(version = 0.2.0) + import tcp-create-socket; + @since(version = 0.2.0) + import ip-name-lookup; +} diff --git a/proposals/cli/wit/environment.wit b/proposals/cli/wit/environment.wit new file mode 100644 index 000000000..2f449bd7c --- /dev/null +++ b/proposals/cli/wit/environment.wit @@ -0,0 +1,22 @@ +@since(version = 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. + @since(version = 0.2.0) + get-environment: func() -> list>; + + /// Get the POSIX-style arguments to the program. + @since(version = 0.2.0) + get-arguments: func() -> list; + + /// Return a path that programs should use as their initial current working + /// directory, interpreting `.` as shorthand for this. + @since(version = 0.2.0) + initial-cwd: func() -> option; +} diff --git a/proposals/cli/wit/exit.wit b/proposals/cli/wit/exit.wit new file mode 100644 index 000000000..427935c8d --- /dev/null +++ b/proposals/cli/wit/exit.wit @@ -0,0 +1,17 @@ +@since(version = 0.2.0) +interface exit { + /// Exit the current instance and any linked instances. + @since(version = 0.2.0) + exit: func(status: result); + + /// Exit the current instance and any linked instances, reporting the + /// specified status code to the host. + /// + /// The meaning of the code depends on the context, with 0 usually meaning + /// "success", and other values indicating various types of failure. + /// + /// This function does not return; the effect is analogous to a trap, but + /// without the connotation that something bad has happened. + @unstable(feature = cli-exit-with-code) + exit-with-code: func(status-code: u8); +} diff --git a/proposals/cli/wit/imports.wit b/proposals/cli/wit/imports.wit new file mode 100644 index 000000000..cec1be520 --- /dev/null +++ b/proposals/cli/wit/imports.wit @@ -0,0 +1,36 @@ +package wasi:cli@0.2.8; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + include wasi:clocks/imports@0.2.8; + @since(version = 0.2.0) + include wasi:filesystem/imports@0.2.8; + @since(version = 0.2.0) + include wasi:sockets/imports@0.2.8; + @since(version = 0.2.0) + include wasi:random/imports@0.2.8; + @since(version = 0.2.0) + include wasi:io/imports@0.2.8; + + @since(version = 0.2.0) + import environment; + @since(version = 0.2.0) + import exit; + @since(version = 0.2.0) + import stdin; + @since(version = 0.2.0) + import stdout; + @since(version = 0.2.0) + import stderr; + @since(version = 0.2.0) + import terminal-input; + @since(version = 0.2.0) + import terminal-output; + @since(version = 0.2.0) + import terminal-stdin; + @since(version = 0.2.0) + import terminal-stdout; + @since(version = 0.2.0) + import terminal-stderr; +} diff --git a/proposals/cli/wit/run.wit b/proposals/cli/wit/run.wit new file mode 100644 index 000000000..655346efb --- /dev/null +++ b/proposals/cli/wit/run.wit @@ -0,0 +1,6 @@ +@since(version = 0.2.0) +interface run { + /// Run the program. + @since(version = 0.2.0) + run: func() -> result; +} diff --git a/proposals/cli/wit/stdio.wit b/proposals/cli/wit/stdio.wit new file mode 100644 index 000000000..44767c647 --- /dev/null +++ b/proposals/cli/wit/stdio.wit @@ -0,0 +1,26 @@ +@since(version = 0.2.0) +interface stdin { + @since(version = 0.2.0) + use wasi:io/streams@0.2.8.{input-stream}; + + @since(version = 0.2.0) + get-stdin: func() -> input-stream; +} + +@since(version = 0.2.0) +interface stdout { + @since(version = 0.2.0) + use wasi:io/streams@0.2.8.{output-stream}; + + @since(version = 0.2.0) + get-stdout: func() -> output-stream; +} + +@since(version = 0.2.0) +interface stderr { + @since(version = 0.2.0) + use wasi:io/streams@0.2.8.{output-stream}; + + @since(version = 0.2.0) + get-stderr: func() -> output-stream; +} diff --git a/proposals/cli/wit/terminal.wit b/proposals/cli/wit/terminal.wit new file mode 100644 index 000000000..d305498c6 --- /dev/null +++ b/proposals/cli/wit/terminal.wit @@ -0,0 +1,62 @@ +/// 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. +@since(version = 0.2.0) +interface terminal-input { + /// The input side of a terminal. + @since(version = 0.2.0) + 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. +@since(version = 0.2.0) +interface terminal-output { + /// The output side of a terminal. + @since(version = 0.2.0) + resource terminal-output; +} + +/// An interface providing an optional `terminal-input` for stdin as a +/// link-time authority. +@since(version = 0.2.0) +interface terminal-stdin { + @since(version = 0.2.0) + use terminal-input.{terminal-input}; + + /// If stdin is connected to a terminal, return a `terminal-input` handle + /// allowing further interaction with it. + @since(version = 0.2.0) + get-terminal-stdin: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stdout as a +/// link-time authority. +@since(version = 0.2.0) +interface terminal-stdout { + @since(version = 0.2.0) + use terminal-output.{terminal-output}; + + /// If stdout is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + @since(version = 0.2.0) + get-terminal-stdout: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stderr as a +/// link-time authority. +@since(version = 0.2.0) +interface terminal-stderr { + @since(version = 0.2.0) + use terminal-output.{terminal-output}; + + /// If stderr is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + @since(version = 0.2.0) + get-terminal-stderr: func() -> option; +} diff --git a/proposals/clocks/README.md b/proposals/clocks/README.md new file mode 100644 index 000000000..a99080fae --- /dev/null +++ b/proposals/clocks/README.md @@ -0,0 +1,149 @@ +# WASI Clocks + +A proposed [WebAssembly System Interface](https://github.com/WebAssembly/WASI) API. + +### Current Phase + +WASI-clocks is currently in [Phase 3]. + +[Phase 3]: https://github.com/WebAssembly/WASI/blob/main/Proposals.md#phase-3---implementation-phase-cg--wg + +### Champions + +- Dan Gohman + +### Portability Criteria + +WASI clocks must have host implementations which can pass the testsuite +on at least Windows, macOS, and Linux. + +WASI clocks must have at least two complete independent implementations. + +## Table of Contents + +- [WASI Clocks](#wasi-clocks) + - [Current Phase](#current-phase) + - [Champions](#champions) + - [Portability Criteria](#portability-criteria) + - [Table of Contents](#table-of-contents) + - [Introduction](#introduction) + - [Goals](#goals) + - [Non-goals](#non-goals) + - [API walk-through](#api-walk-through) + - [Measuring elapsed time](#measuring-elapsed-time) + - [Telling the current human time:](#telling-the-current-human-time) + - [Retrieving the timezone:](#retrieving-the-timezone) + - [Detailed design discussion](#detailed-design-discussion) + - [What should the type of a timestamp be?](#what-should-the-type-of-a-timestamp-be) + - [Considered alternatives](#considered-alternatives) + - [Per-process and per-thread clocks](#per-process-and-per-thread-clocks) + - [Stakeholder Interest \& Feedback](#stakeholder-interest--feedback) + - [References \& acknowledgements](#references--acknowledgements) + - [Development](#development) + - [Generating imports.md](#generating-importsmd) + +### Introduction + +WASI Clocks is a WASI API for reading the current time and measuring elapsed +time. + +Unlike many clock APIs, WASI Clocks is capability-oriented. Instead +of having functions that implicitly reference a clock, WASI Clocks' APIs are +passed a clock handle. + +### Goals + +The primary goal of WASI Clocks is to allow users to use WASI programs to +read the current time and to measure elapsed time. + +### Non-goals + +WASI Clocks is not aiming to cover date formatting, or modifying the time of a clock. + +### API walk-through + +#### Measuring elapsed time + +The monotonic clock APIs can be used to measure the elapsed time of a region of code: + +```wit +default-monotonic-clock: monotonic-clock +``` + +```rust + let start: Mark = monotonic_clock::now(clock); + + // some stuff + + let stop: Mark = monotonic_clock::now(clock); + + let elapsed: Duration = stop - start; +``` + + +#### Telling the current human time: + +```rust + let the_current_time = system_clock::now(); + + println!("it has been {} seconds and {} nanoseconds since the Unix epoch!", the_current_time.seconds, the_current_time.nanoseconds); +``` + +#### Retrieving the timezone: + +```rust + let instant: Instant = system_clock::now(); + let id = timezone::id(); + let offset_h = timezone::utc_offset(instant) as f64 / 3600e9; + println!("the timezone is {} at UTC{:+}", id, offset_h); +``` + +### Detailed design discussion + +### What should the type of a timestamp be? + +In POSIX, `clock_gettime` uses a single `timespec` type to represent timestamps +from all clocks, with two fields: seconds and nanoseconds. However, in applications +that just need to measure elapsed time, and don't need to care about absolute +time, working with seconds and nanoseconds as separate fields adds extra code size +and complexity. For these use cases, a single 64-bit nanoseconds value, which can +measure up to about 584 years, is sufficient and simpler. + +For system time, it's still useful to have both seconds and nanoseconds, both +to be able to represent dates in the far future, and to reflect the fact that +code working with system time will often want to treat seconds and fractions +of seconds differently. + +And so, this API uses different data types for different types of clocks. + +### Considered alternatives + +#### Per-process and per-thread clocks + +WASI preview1 included two clocks which measured the CPU time of the current process and the current thread, respectively. These clocks are difficult to implement efficiently in WASI implementations that have multiple wasm instances in the same host process, so they've been omitted from this API. + +Wasi-libc has support for emulating these clocks, by using the monotonic clock instead, which isn't a technically precise replacement, but is enough to ensure minimal compatibility with existing code. + +### Stakeholder Interest & Feedback + +TODO before entering Phase 3. + +Preview1 has monotonic and wall clock functions, and they're widely exposed in toolchains. + +### References & acknowledgements + +Many thanks for valuable feedback and advice from: + +- [Person 1] +- [Person 2] +- [etc.] + +### Development + +#### Generating imports.md + +The file `imports.md` is generated using [wit-bindgen](https://github.com/bytecodealliance/wit-bindgen). + +```bash +wit-bindgen markdown wit --html-in-md --features clocks-timezone +``` diff --git a/proposals/clocks/imports.md b/proposals/clocks/imports.md new file mode 100644 index 000000000..bc5c90e20 --- /dev/null +++ b/proposals/clocks/imports.md @@ -0,0 +1,233 @@ +

World imports

+ +

Import interface wasi:io/poll@0.2.8

+

A poll API intended to let users wait for I/O events on multiple handles +at once.

+
+

Types

+

resource pollable

+

pollable represents a single I/O event which may be ready, or not.

+

Functions

+

[method]pollable.ready: func

+

Return the readiness of a pollable. This function never blocks.

+

Returns true when the pollable is ready, and false otherwise.

+
Params
+ +
Return values
+
    +
  • bool
  • +
+

[method]pollable.block: func

+

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.

+
Params
+ +

poll: func

+

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<u32> contains one or more indices of handles in the +argument list that is ready for I/O.

+

This function traps if either:

+
    +
  • the list is empty, or:
  • +
  • the list contains more elements than can be indexed with a u32 value.
  • +
+

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 ready for I/O.

+
Params
+ +
Return values
+
    +
  • list<u32>
  • +
+

Import interface wasi:clocks/monotonic-clock@0.2.8

+

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.

+
+

Types

+

type pollable

+

pollable

+

+

type instant

+

u64

+

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 duration

+

u64

+

A duration of time, in nanoseconds. +


+

Functions

+

now: func

+

Read the current value of the clock.

+

The clock is monotonic, therefore calling this function repeatedly will +produce a sequence of non-decreasing values.

+

For completeness, this function traps if it's not possible to represent +the value of the clock in an instant. Consequently, implementations +should ensure that the starting time is low enough to avoid the +possibility of overflow in practice.

+
Return values
+ +

resolution: func

+

Query the resolution of the clock. Returns the duration of time +corresponding to a clock tick.

+
Return values
+ +

subscribe-instant: func

+

Create a pollable which will resolve once the specified instant +has occurred.

+
Params
+ +
Return values
+ +

subscribe-duration: func

+

Create a pollable that will resolve after the specified duration has +elapsed from the time this function is invoked.

+
Params
+ +
Return values
+ +

Import interface wasi:clocks/wall-clock@0.2.8

+

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.

+
+

Types

+

record datetime

+

A time and date in seconds plus nanoseconds.

+
Record Fields
+
    +
  • seconds: u64
  • +
  • nanoseconds: u32
  • +
+
+

Functions

+

now: func

+

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.

+
Return values
+ +

resolution: func

+

Query the resolution of the clock.

+

The nanoseconds field of the output is always less than 1000000000.

+
Return values
+ +

Import interface wasi:clocks/timezone@0.2.8

+
+

Types

+

type datetime

+

datetime

+

+

record timezone-display

+

Information useful for displaying the timezone of a specific datetime.

+

This information may vary within a single timezone to reflect daylight +saving time adjustments.

+
Record Fields
+
    +
  • +

    utc-offset: s32

    +

    The number of seconds difference between UTC time and the local +time of the timezone. +

    The returned value will always be less than 86400 which is the +number of seconds in a day (246060).

    +

    In implementations that do not expose an actual time zone, this +should return 0.

    +
  • +
  • +

    name: string

    +

    The abbreviated name of the timezone to display to a user. The name +`UTC` indicates Coordinated Universal Time. Otherwise, this should +reference local standards for the name of the time zone. +

    In implementations that do not expose an actual time zone, this +should be the string UTC.

    +

    In time zones that do not have an applicable name, a formatted +representation of the UTC offset may be returned, such as -04:00.

    +
  • +
  • +

    in-daylight-saving-time: bool

    +

    Whether daylight saving time is active. +

    In implementations that do not expose an actual time zone, this +should return false.

    +
  • +
+
+

Functions

+

display: func

+

Return information needed to display the given datetime. This includes +the UTC offset, the time zone name, and a flag indicating whether +daylight saving time is active.

+

If the timezone cannot be determined for the given datetime, return a +timezone-display for UTC with a utc-offset of 0 and no daylight +saving time.

+
Params
+ +
Return values
+ +

utc-offset: func

+

The same as display, but only return the UTC offset.

+
Params
+ +
Return values
+
    +
  • s32
  • +
diff --git a/proposals/clocks/test/README.md b/proposals/clocks/test/README.md new file mode 100644 index 000000000..c274acd9d --- /dev/null +++ b/proposals/clocks/test/README.md @@ -0,0 +1,11 @@ +# Testing guidelines + +TK fill in testing guidelines + +## Installing the tools + +TK fill in instructions + +## Running the tests + +TK fill in instructions diff --git a/proposals/clocks/wit-0.3.0-draft/monotonic-clock.wit b/proposals/clocks/wit-0.3.0-draft/monotonic-clock.wit new file mode 100644 index 000000000..7f364665a --- /dev/null +++ b/proposals/clocks/wit-0.3.0-draft/monotonic-clock.wit @@ -0,0 +1,48 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; +/// 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. +@since(version = 0.3.0-rc-2025-09-16) +interface monotonic-clock { + use types.{duration}; + + /// A mark on a monotonic clock is a number of nanoseconds since an + /// unspecified initial value, and can only be compared to instances from + /// the same monotonic-clock. + @since(version = 0.3.0-rc-2025-09-16) + type mark = 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. + /// + /// For completeness, this function traps if it's not possible to represent + /// the value of the clock in a `mark`. Consequently, implementations + /// should ensure that the starting time is low enough to avoid the + /// possibility of overflow in practice. + @since(version = 0.3.0-rc-2025-09-16) + now: func() -> mark; + + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + @since(version = 0.3.0-rc-2025-09-16) + get-resolution: func() -> duration; + + /// Wait until the specified mark has occurred. + @since(version = 0.3.0-rc-2025-09-16) + wait-until: async func( + when: mark, + ); + + /// Wait for the specified duration to elapse. + @since(version = 0.3.0-rc-2025-09-16) + wait-for: async func( + how-long: duration, + ); +} diff --git a/proposals/clocks/wit-0.3.0-draft/system-clock.wit b/proposals/clocks/wit-0.3.0-draft/system-clock.wit new file mode 100644 index 000000000..bd3049fd4 --- /dev/null +++ b/proposals/clocks/wit-0.3.0-draft/system-clock.wit @@ -0,0 +1,51 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; +/// WASI System Clock is a clock API intended to let users query the current +/// time. The clock is not necessarily monotonic as it may be reset. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +/// +/// 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. +@since(version = 0.3.0-rc-2025-09-16) +interface system-clock { + use types.{duration}; + + /// An "instant", or "exact time", is a point in time without regard to any + /// time zone: just the time since a particular external reference point, + /// often called an "epoch". + /// + /// Here, the epoch is 1970-01-01T00:00:00Z, also known as + /// [POSIX's Seconds Since the Epoch], also known as [Unix Time]. + /// + /// Note that even if the seconds field is negative, incrementing + /// nanoseconds always represents moving forwards in time. + /// For example, `{ -1 seconds, 999999999 nanoseconds }` represents the + /// instant one nanosecond before the epoch. + /// For more on various different ways to represent time, see + /// https://tc39.es/proposal-temporal/docs/timezone.html + /// + /// [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 + @since(version = 0.3.0-rc-2025-09-16) + record instant { + seconds: s64, + 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 nanoseconds field of the output is always less than 1000000000. + @since(version = 0.3.0-rc-2025-09-16) + now: func() -> instant; + + /// Query the resolution of the clock. Returns the smallest duration of time + /// that the implementation permits distinguishing. + @since(version = 0.3.0-rc-2025-09-16) + get-resolution: func() -> duration; +} diff --git a/proposals/clocks/wit-0.3.0-draft/timezone.wit b/proposals/clocks/wit-0.3.0-draft/timezone.wit new file mode 100644 index 000000000..d8d5732dc --- /dev/null +++ b/proposals/clocks/wit-0.3.0-draft/timezone.wit @@ -0,0 +1,46 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; + +@unstable(feature = clocks-timezone) +interface timezone { + @unstable(feature = clocks-timezone) + use system-clock.{instant}; + + /// Return the IANA identifier of the currently configured timezone. This + /// should be an identifier from the IANA Time Zone Database. + /// + /// For displaying to a user, the identifier should be converted into a + /// localized name by means of an internationalization API. + /// + /// If the implementation does not expose an actual timezone, or is unable + /// to provide mappings from times to deltas between the configured timezone + /// and UTC, or determining the current timezone fails, or the timezone does + /// not have an IANA identifier, this returns nothing. + @unstable(feature = clocks-timezone) + iana-id: func() -> option; + + /// The number of nanoseconds difference between UTC time and the local + /// time of the currently configured timezone, at the exact time of + /// `instant`. + /// + /// The magnitude of the returned value will always be less than + /// 86,400,000,000,000 which is the number of nanoseconds in a day + /// (24*60*60*1e9). + /// + /// If the implementation does not expose an actual timezone, or is unable + /// to provide mappings from times to deltas between the configured timezone + /// and UTC, or determining the current timezone fails, this returns + /// nothing. + @unstable(feature = clocks-timezone) + utc-offset: func(when: instant) -> option; + + /// Returns a string that is suitable to assist humans in debugging whether + /// any timezone is available, and if so, which. This may be the same string + /// as `iana-id`, or a formatted representation of the UTC offset such as + /// `-04:00`, or something else. + /// + /// 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. + @unstable(feature = clocks-timezone) + to-debug-string: func() -> string; +} diff --git a/proposals/clocks/wit-0.3.0-draft/types.wit b/proposals/clocks/wit-0.3.0-draft/types.wit new file mode 100644 index 000000000..aff7c2a22 --- /dev/null +++ b/proposals/clocks/wit-0.3.0-draft/types.wit @@ -0,0 +1,8 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; +/// This interface common types used throughout wasi:clocks. +@since(version = 0.3.0-rc-2025-09-16) +interface types { + /// A duration of time, in nanoseconds. + @since(version = 0.3.0-rc-2025-09-16) + type duration = u64; +} diff --git a/proposals/clocks/wit-0.3.0-draft/world.wit b/proposals/clocks/wit-0.3.0-draft/world.wit new file mode 100644 index 000000000..f274bceb0 --- /dev/null +++ b/proposals/clocks/wit-0.3.0-draft/world.wit @@ -0,0 +1,11 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; + +@since(version = 0.3.0-rc-2025-09-16) +world imports { + @since(version = 0.3.0-rc-2025-09-16) + import monotonic-clock; + @since(version = 0.3.0-rc-2025-09-16) + import system-clock; + @unstable(feature = clocks-timezone) + import timezone; +} diff --git a/proposals/clocks/wit/deps.lock b/proposals/clocks/wit/deps.lock new file mode 100644 index 000000000..cc63e4b2f --- /dev/null +++ b/proposals/clocks/wit/deps.lock @@ -0,0 +1,4 @@ +[io] +url = "https://github.com/WebAssembly/wasi-io/archive/main.tar.gz" +sha256 = "9f1ad5da70f621bbd4c69e3bd90250a0c12ecfde266aa8f99684fc44bc1e7c15" +sha512 = "6d0a9db6848f24762933d1c168a5b5b1065ba838c253ee20454afeb8dd1a049b918d25deff556083d68095dd3126ae131ac3e738774320eee5d918f5a4b5354e" diff --git a/proposals/clocks/wit/deps.toml b/proposals/clocks/wit/deps.toml new file mode 100644 index 000000000..b178cb257 --- /dev/null +++ b/proposals/clocks/wit/deps.toml @@ -0,0 +1 @@ +io = "https://github.com/WebAssembly/wasi-io/archive/main.tar.gz" diff --git a/proposals/clocks/wit/deps/io/error.wit b/proposals/clocks/wit/deps/io/error.wit new file mode 100644 index 000000000..dd5a1af03 --- /dev/null +++ b/proposals/clocks/wit/deps/io/error.wit @@ -0,0 +1,34 @@ +package wasi:io@0.2.8; + +@since(version = 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 + /// offer functions to "downcast" this error into more specific types. For example, + /// errors returned from streams derived from filesystem types can be described using + /// the filesystem's own error-code type. This is done using the function + /// `wasi:filesystem/types/filesystem-error-code`, which takes a `borrow` + /// parameter and returns an `option`. + /// + /// The set of functions which can "downcast" an `error` into a more + /// concrete type is open. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + to-debug-string: func() -> string; + } +} diff --git a/proposals/clocks/wit/deps/io/poll.wit b/proposals/clocks/wit/deps/io/poll.wit new file mode 100644 index 000000000..833b381d9 --- /dev/null +++ b/proposals/clocks/wit/deps/io/poll.wit @@ -0,0 +1,47 @@ +package wasi:io@0.2.8; + +/// A poll API intended to let users wait for I/O events on multiple handles +/// at once. +@since(version = 0.2.0) +interface poll { + /// `pollable` represents a single I/O event which may be ready, or not. + @since(version = 0.2.0) + resource pollable { + + /// Return the readiness of a pollable. This function never blocks. + /// + /// Returns `true` when the pollable is ready, and `false` otherwise. + @since(version = 0.2.0) + ready: func() -> bool; + + /// `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. + @since(version = 0.2.0) + block: func(); + } + + /// 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. + /// + /// This function traps if either: + /// - the list is empty, or: + /// - the list contains more elements than can be indexed with a `u32` value. + /// + /// 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 ready for I/O. + @since(version = 0.2.0) + poll: func(in: list>) -> list; +} diff --git a/proposals/clocks/wit/deps/io/streams.wit b/proposals/clocks/wit/deps/io/streams.wit new file mode 100644 index 000000000..fbb0268b0 --- /dev/null +++ b/proposals/clocks/wit/deps/io/streams.wit @@ -0,0 +1,258 @@ +package wasi:io@0.2.8; + +/// 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. +@since(version = 0.2.0) +interface streams { + @since(version = 0.2.0) + use error.{error}; + @since(version = 0.2.0) + use poll.{pollable}; + + /// An error for input-stream and output-stream operations. + @since(version = 0.2.0) + variant stream-error { + /// The last operation (a write or flush) failed before completion. + /// + /// More information is available in the `error` payload. + /// + /// After this, the stream will be closed. All future operations return + /// `stream-error::closed`. + 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`. + @since(version = 0.2.0) + resource input-stream { + /// 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. + @since(version = 0.2.0) + read: func( + /// The maximum number of bytes to read + len: u64 + ) -> result, stream-error>; + + /// Read bytes from a stream, after blocking until at least one byte can + /// be read. Except for blocking, behavior is identical to `read`. + @since(version = 0.2.0) + blocking-read: func( + /// The maximum number of bytes to read + 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. + @since(version = 0.2.0) + skip: func( + /// The maximum number of bytes to skip. + len: u64, + ) -> result; + + /// Skip bytes from a stream, after blocking until at least one byte + /// can be skipped. Except for blocking behavior, identical to `skip`. + @since(version = 0.2.0) + blocking-skip: func( + /// The maximum number of bytes to skip. + 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. + @since(version = 0.2.0) + 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`. + /// + /// Dropping an `output-stream` while there's still an active write in + /// progress may result in the data being lost. Before dropping the stream, + /// be sure to fully flush your writes. + @since(version = 0.2.0) + resource output-stream { + /// 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. + @since(version = 0.2.0) + check-write: func() -> result; + + /// 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. + @since(version = 0.2.0) + write: func( + contents: list + ) -> result<_, stream-error>; + + /// 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. + /// + /// Returns success when all of the contents written are successfully + /// flushed to output. If an error occurs at any point before all + /// contents are successfully flushed, that error is returned as soon as + /// possible. If writing and flushing the complete contents causes the + /// stream to become closed, this call should return success, and + /// subsequent calls to check-write or other interfaces should return + /// stream-error::closed. + @since(version = 0.2.0) + blocking-write-and-flush: func( + contents: list + ) -> result<_, stream-error>; + + /// 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. + @since(version = 0.2.0) + flush: func() -> result<_, stream-error>; + + /// Request to flush buffered output, and block until flush completes + /// and stream is ready for writing again. + @since(version = 0.2.0) + blocking-flush: func() -> result<_, stream-error>; + + /// Create a `pollable` which will resolve once the output-stream + /// is ready for more writing, or an error has occurred. 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. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// 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. + @since(version = 0.2.0) + write-zeroes: func( + /// The number of zero-bytes to write + len: u64 + ) -> 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. + /// + /// Functionality is equivelant to `blocking-write-and-flush` with + /// contents given as a list of len containing only zeroes. + @since(version = 0.2.0) + blocking-write-zeroes-and-flush: func( + /// The number of zero-bytes to write + len: u64 + ) -> result<_, stream-error>; + + /// Read from one stream and write to another. + /// + /// The behavior of splice is equivalent 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`. + @since(version = 0.2.0) + splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + + /// 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`. + @since(version = 0.2.0) + blocking-splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + } +} diff --git a/proposals/clocks/wit/deps/io/world.wit b/proposals/clocks/wit/deps/io/world.wit new file mode 100644 index 000000000..1cc3fce12 --- /dev/null +++ b/proposals/clocks/wit/deps/io/world.wit @@ -0,0 +1,10 @@ +package wasi:io@0.2.8; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import streams; + + @since(version = 0.2.0) + import poll; +} diff --git a/proposals/clocks/wit/monotonic-clock.wit b/proposals/clocks/wit/monotonic-clock.wit new file mode 100644 index 000000000..e60f366f2 --- /dev/null +++ b/proposals/clocks/wit/monotonic-clock.wit @@ -0,0 +1,55 @@ +package wasi:clocks@0.2.8; +/// 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. +@since(version = 0.2.0) +interface monotonic-clock { + @since(version = 0.2.0) + use wasi:io/poll@0.2.8.{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. + @since(version = 0.2.0) + type instant = u64; + + /// A duration of time, in nanoseconds. + @since(version = 0.2.0) + 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. + /// + /// For completeness, this function traps if it's not possible to represent + /// the value of the clock in an `instant`. Consequently, implementations + /// should ensure that the starting time is low enough to avoid the + /// possibility of overflow in practice. + @since(version = 0.2.0) + now: func() -> instant; + + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + @since(version = 0.2.0) + resolution: func() -> duration; + + /// Create a `pollable` which will resolve once the specified instant + /// has occurred. + @since(version = 0.2.0) + subscribe-instant: func( + when: instant, + ) -> pollable; + + /// Create a `pollable` that will resolve after the specified duration has + /// elapsed from the time this function is invoked. + @since(version = 0.2.0) + subscribe-duration: func( + when: duration, + ) -> pollable; +} diff --git a/proposals/clocks/wit/timezone.wit b/proposals/clocks/wit/timezone.wit new file mode 100644 index 000000000..534814a63 --- /dev/null +++ b/proposals/clocks/wit/timezone.wit @@ -0,0 +1,55 @@ +package wasi:clocks@0.2.8; + +@unstable(feature = clocks-timezone) +interface timezone { + @unstable(feature = clocks-timezone) + use wall-clock.{datetime}; + + /// Return information needed to display the given `datetime`. This includes + /// the UTC offset, the time zone name, and a flag indicating whether + /// daylight saving time is active. + /// + /// If the timezone cannot be determined for the given `datetime`, return a + /// `timezone-display` for `UTC` with a `utc-offset` of 0 and no daylight + /// saving time. + @unstable(feature = clocks-timezone) + display: func(when: datetime) -> timezone-display; + + /// The same as `display`, but only return the UTC offset. + @unstable(feature = clocks-timezone) + utc-offset: func(when: datetime) -> s32; + + /// Information useful for displaying the timezone of a specific `datetime`. + /// + /// This information may vary within a single `timezone` to reflect daylight + /// saving time adjustments. + @unstable(feature = clocks-timezone) + record timezone-display { + /// The number of seconds difference between UTC time and the local + /// time of the timezone. + /// + /// The returned value will always be less than 86400 which is the + /// number of seconds in a day (24*60*60). + /// + /// In implementations that do not expose an actual time zone, this + /// should return 0. + utc-offset: s32, + + /// The abbreviated name of the timezone to display to a user. The name + /// `UTC` indicates Coordinated Universal Time. Otherwise, this should + /// reference local standards for the name of the time zone. + /// + /// In implementations that do not expose an actual time zone, this + /// should be the string `UTC`. + /// + /// In time zones that do not have an applicable name, a formatted + /// representation of the UTC offset may be returned, such as `-04:00`. + name: string, + + /// Whether daylight saving time is active. + /// + /// In implementations that do not expose an actual time zone, this + /// should return false. + in-daylight-saving-time: bool, + } +} diff --git a/proposals/clocks/wit/wall-clock.wit b/proposals/clocks/wit/wall-clock.wit new file mode 100644 index 000000000..3386c800b --- /dev/null +++ b/proposals/clocks/wit/wall-clock.wit @@ -0,0 +1,46 @@ +package wasi:clocks@0.2.8; +/// 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. +@since(version = 0.2.0) +interface wall-clock { + /// A time and date in seconds plus nanoseconds. + @since(version = 0.2.0) + 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 + @since(version = 0.2.0) + now: func() -> datetime; + + /// Query the resolution of the clock. + /// + /// The nanoseconds field of the output is always less than 1000000000. + @since(version = 0.2.0) + resolution: func() -> datetime; +} diff --git a/proposals/clocks/wit/world.wit b/proposals/clocks/wit/world.wit new file mode 100644 index 000000000..1655ca830 --- /dev/null +++ b/proposals/clocks/wit/world.wit @@ -0,0 +1,11 @@ +package wasi:clocks@0.2.8; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import monotonic-clock; + @since(version = 0.2.0) + import wall-clock; + @unstable(feature = clocks-timezone) + import timezone; +} diff --git a/proposals/filesystem/LICENSE.md b/proposals/filesystem/LICENSE.md new file mode 100644 index 000000000..c1c3b9443 --- /dev/null +++ b/proposals/filesystem/LICENSE.md @@ -0,0 +1,8 @@ +Copyright © 2019-2024 the Contributors to the WASI Specification, published +by the [WebAssembly Community Group][cg] under the +[W3C Community Contributor License Agreement (CLA)][cla]. A human-readable +[summary][summary] is available. + +[cg]: https://www.w3.org/community/webassembly/ +[cla]: https://www.w3.org/community/about/agreements/cla/ +[summary]: https://www.w3.org/community/about/agreements/cla-deed/ diff --git a/proposals/filesystem/README.md b/proposals/filesystem/README.md new file mode 100644 index 000000000..b71eab4ee --- /dev/null +++ b/proposals/filesystem/README.md @@ -0,0 +1,166 @@ +# WASI filesystem + +A proposed [WebAssembly System Interface](https://github.com/WebAssembly/WASI) API. + +### Current Phase + +WASI-filesystem is currently in [Phase 3]. + +[Phase 3]: https://github.com/WebAssembly/WASI/blob/main/Proposals.md#phase-3---implementation-phase-cg--wg + +### Champions + +- Dan Gohman + +### Portability Criteria + +WASI filesystem must have host implementations which can pass the testsuite +on at least Windows, macOS, and Linux. + +WASI filesystem must have at least two complete independent implementations. + +## Table of Contents + +- [Introduction](#introduction) +- [Goals](#goals) +- [Non-goals](#non-goals) +- [API walk-through](#api-walk-through) + - [Use case 1](#use-case-1) + - [Use case 2](#use-case-2) +- [Detailed design discussion](#detailed-design-discussion) + - [[Tricky design choice 1]](#tricky-design-choice-1) + - [[Tricky design choice 2]](#tricky-design-choice-2) +- [Considered alternatives](#considered-alternatives) + - [[Alternative 1]](#alternative-1) + - [[Alternative 2]](#alternative-2) +- [Stakeholder Interest & Feedback](#stakeholder-interest--feedback) +- [References & acknowledgements](#references--acknowledgements) + +### Introduction + +WASI filesystem is a WASI API primarily for accessing host filesystems. It +has functions for opening, reading, and writing files, and for working with +directories. + +Unlike many filesystem APIs, WASI filesystem is capability-oriented. Instead +of having functions that implicitly reference a filesystem namespace, +WASI filesystems' APIs are passed a directory handle along with a path, and +the path is looked up relative to the given handle, and sandboxed to be +resolved within that directory. For more information about sandbox, see +[WASI filesystem path resolution](path-resolution.md). + +WASI filesystem hides some of the surface differences between Windows and +Unix-style filesystems, however much of its behavior, including the +semantics of path lookup, and the semantics of files, directories, and +symlinks, and the constraints on filesystem paths, is host-dependent. + +WASI filesystem is not intended to be used as a virtual API for accessing +arbitrary resources. Unix's "everything is a file" philosophy is in conflict +with the goals of supporting modularity and the principle of least authority. + +Many of the ideas related to doing capability-based filesystem sandboxing with +`openat` come from [CloudABI](https://github.com/NuxiNL/cloudabi) and +[Capsicum](https://wiki.freebsd.org/Capsicum). + +### Goals + +The primary goal of WASI filesystem is to allow users to use WASI programs to +access their existing filesystems in a straightforward and efficient manner. + +### Non-goals + +WASI filesystem is not aiming for deterministic semantics. That would either +require restricting it to fully controlled private filesystems, which would +conflict with the goal of giving users access to their existing filesystems, +or requiring implementations to do a lot of extra work to emulate specific +defined behaviors, which would conflict with the goal of being efficient. + +### API walk-through + +#### Opening a file + +```rust +/// Write "Hello, World" into a file called "greeting.txt" in `dir`. +fn write_hello_world_to_a_file(dir: Descriptor) -> Result<(), Errno> { + let at_flags = AtFlags::FollowSymlinks; + let o_flags = OFlags::Create | OFlags::Trunc; + let descriptor_flags = DescriptorFlags::Write; + let mode = Mode::Readable; + let file = + dir.openat(at_flags, "greeting.txt", o_flags, descriptor_flags, mode)?; + let message = b"Hello, World\n"; + let mut view = &message[..]; + let mut offset = 0; + while !view.is_empty() { + let num_written = file.pwrite(view.to_owned(), 0)?; + offset += num_written; + view = &view[num_written..]; + } + // The file descriptor is closed when it's dropped! +} +``` + +Perhaps the biggest change from the preview1 version of openat, called +`path_open`, is the removal of the *rights* flags. Preview1 associates +a set of flags with every file descriptor enumerating which operations +may be performed on it, such as reading, writing, appending, truncating, +and many other operations. In practice, this created a lot of ambiguity +about how it mapped to POSIX semantics, as it doesn't directly correspond +to any feature in POSIX, or in Windows either. + +The other major change from preview1 is the introduction of the mode +argument, which controls the permissions of the generated file. There +was no way to control permissions in preview1, so this is new +functionality. + +#### Streaming read from a file + +TODO + +#### Reading from a directory + +fn read_entries(dir: Descriptor) -> Result<(), Errno> { + // TODO: Implement this example. +} + +[etc. + +### Detailed design discussion + +#### Should WASI filesystem be case-sensitive, case-insensitive, or platform-dependent? + +Even just among popular platforms, there are case-sensitive and +case-insensitive filesystems in wide use. + +It would be nice to have an API which presented consistent behavior across +platforms, so that applications don't have to worry about subtle differences, +and subtle bugs due to those differences. + +However, implementing case sensitivity on a case-insensitive filesystem, or +case-insensitivity on a case-sensitive filesystem, are both tricky to do. + +One issue is that case insensitivity depends on a Unicode version, so the +details can differ between different case-insensitive platforms. Another +issue is the WASI filesystem in general can't assume it has exclusive access +to the filesystem, so approaches that involve checking for files with names +that differ only by case can race with other processes creating new files. + +### Considered alternatives + +#### Fully deterministic filesystem + +The main tradeoff with full determinism is that it makes it difficult to access existing filesystems that the Wasm runtime doesn't have full control over. This proposal is aiming to address use cases where users have existing filesystems they want to access. + +### Stakeholder Interest & Feedback + +TODO before entering Phase 3. + +Preview1 has a similar filesystem API, and it's widely exposed in toolchains. + +### References & acknowledgements + +Many thanks for valuable feedback and advice from: + +- [Person 1] +- [Person 2] +- [etc.] diff --git a/proposals/filesystem/imports.md b/proposals/filesystem/imports.md new file mode 100644 index 000000000..537c59b68 --- /dev/null +++ b/proposals/filesystem/imports.md @@ -0,0 +1,1334 @@ +

World imports

+ +

Import interface wasi:io/error@0.2.8

+
+

Types

+

resource 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 +offer functions to "downcast" this error into more specific types. For example, +errors returned from streams derived from filesystem types can be described using +the filesystem's own error-code type. This is done using the function +wasi:filesystem/types/filesystem-error-code, which takes a borrow<error> +parameter and returns an option<wasi:filesystem/types/error-code>.

+

The set of functions which can "downcast" an error into a more +concrete type is open.

+

Functions

+

[method]error.to-debug-string: func

+

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.

+
Params
+ +
Return values
+
    +
  • string
  • +
+

Import interface wasi:io/poll@0.2.8

+

A poll API intended to let users wait for I/O events on multiple handles +at once.

+
+

Types

+

resource pollable

+

pollable represents a single I/O event which may be ready, or not.

+

Functions

+

[method]pollable.ready: func

+

Return the readiness of a pollable. This function never blocks.

+

Returns true when the pollable is ready, and false otherwise.

+
Params
+ +
Return values
+
    +
  • bool
  • +
+

[method]pollable.block: func

+

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.

+
Params
+ +

poll: func

+

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<u32> contains one or more indices of handles in the +argument list that is ready for I/O.

+

This function traps if either:

+
    +
  • the list is empty, or:
  • +
  • the list contains more elements than can be indexed with a u32 value.
  • +
+

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 ready for I/O.

+
Params
+ +
Return values
+
    +
  • list<u32>
  • +
+

Import interface wasi:io/streams@0.2.8

+

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.

+
+

Types

+

type error

+

error

+

+

type pollable

+

pollable

+

+

variant stream-error

+

An error for input-stream and output-stream operations.

+
Variant Cases
+
    +
  • +

    last-operation-failed: own<error>

    +

    The last operation (a write or flush) failed before completion. +

    More information is available in the error payload.

    +

    After this, the stream will be closed. All future operations return +stream-error::closed.

    +
  • +
  • +

    closed

    +

    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. +

  • +
+

resource input-stream

+

An input bytestream.

+

input-streams 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 output-stream

+

An output bytestream.

+

output-streams 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.

+

Dropping an output-stream while there's still an active write in +progress may result in the data being lost. Before dropping the stream, +be sure to fully flush your writes.

+

Functions

+

[method]input-stream.read: func

+

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.

+
Params
+ +
Return values
+ +

[method]input-stream.blocking-read: func

+

Read bytes from a stream, after blocking until at least one byte can +be read. Except for blocking, behavior is identical to read.

+
Params
+ +
Return values
+ +

[method]input-stream.skip: func

+

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.

+
Params
+ +
Return values
+ +

[method]input-stream.blocking-skip: func

+

Skip bytes from a stream, after blocking until at least one byte +can be skipped. Except for blocking behavior, identical to skip.

+
Params
+ +
Return values
+ +

[method]input-stream.subscribe: func

+

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 pollables created with this function are dropped.

+
Params
+ +
Return values
+ +

[method]output-stream.check-write: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.write: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-write-and-flush: func

+

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.

+

Returns success when all of the contents written are successfully +flushed to output. If an error occurs at any point before all +contents are successfully flushed, that error is returned as soon as +possible. If writing and flushing the complete contents causes the +stream to become closed, this call should return success, and +subsequent calls to check-write or other interfaces should return +stream-error::closed.

+
Params
+ +
Return values
+ +

[method]output-stream.flush: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-flush: func

+

Request to flush buffered output, and block until flush completes +and stream is ready for writing again.

+
Params
+ +
Return values
+ +

[method]output-stream.subscribe: func

+

Create a pollable which will resolve once the output-stream +is ready for more writing, or an error has occurred. 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 pollables created with this function are dropped.

+
Params
+ +
Return values
+ +

[method]output-stream.write-zeroes: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-write-zeroes-and-flush: func

+

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.

+

Functionality is equivelant to blocking-write-and-flush with +contents given as a list of len containing only zeroes.

+
Params
+ +
Return values
+ +

[method]output-stream.splice: func

+

Read from one stream and write to another.

+

The behavior of splice is equivalent to:

+
    +
  1. calling check-write on the output-stream
  2. +
  3. calling read on the input-stream with the smaller of the +check-write permitted length and the len provided to splice
  4. +
  5. calling write on the output-stream with that read data.
  6. +
+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-splice: func

+

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.

+
Params
+ +
Return values
+ +

Import interface wasi:clocks/wall-clock@0.2.8

+

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.

+
+

Types

+

record datetime

+

A time and date in seconds plus nanoseconds.

+
Record Fields
+
    +
  • seconds: u64
  • +
  • nanoseconds: u32
  • +
+
+

Functions

+

now: func

+

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.

+
Return values
+ +

resolution: func

+

Query the resolution of the clock.

+

The nanoseconds field of the output is always less than 1000000000.

+
Return values
+ +

Import interface wasi:filesystem/types@0.2.8

+

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 strings, 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.

+
+

Types

+

type input-stream

+

input-stream

+

+

type output-stream

+

output-stream

+

+

type error

+

error

+

+

type datetime

+

datetime

+

+

type filesize

+

u64

+

File size or length of a region within a file. +

enum descriptor-type

+

The type of a filesystem object referenced by a descriptor.

+

Note: This was called filetype in earlier versions of WASI.

+
Enum Cases
+
    +
  • +

    unknown

    +

    The type of the descriptor or file is unknown or is different from +any of the other types specified. +

  • +
  • +

    block-device

    +

    The descriptor refers to a block device inode. +

  • +
  • +

    character-device

    +

    The descriptor refers to a character device inode. +

  • +
  • +

    directory

    +

    The descriptor refers to a directory inode. +

  • +
  • +

    fifo

    +

    The descriptor refers to a named pipe. +

  • +
  • +

    symbolic-link

    +

    The file refers to a symbolic link inode. +

  • +
  • +

    regular-file

    +

    The descriptor refers to a regular file inode. +

  • +
  • +

    socket

    +

    The descriptor refers to a socket. +

  • +
+

flags descriptor-flags

+

Descriptor flags.

+

Note: This was called fdflags in earlier versions of WASI.

+
Flags members
+
    +
  • +

    read:

    +

    Read mode: Data can be read. +

  • +
  • +

    write:

    +

    Write mode: Data can be written to. +

  • +
  • +

    file-integrity-sync:

    +

    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.

    +
  • +
  • +

    data-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.

    +
  • +
  • +

    requested-write-sync:

    +

    Requests that reads be performed at the same level of integrity +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.

    +
  • +
  • +

    mutate-directory:

    +

    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.

    +
  • +
+

flags path-flags

+

Flags determining the method of how paths are resolved.

+
Flags members
+
    +
  • symlink-follow:

    As long as the resolved path corresponds to a symbolic link, it is +expanded. +

  • +
+

flags open-flags

+

Open flags used by open-at.

+
Flags members
+
    +
  • +

    create:

    +

    Create file if it does not exist, similar to `O_CREAT` in POSIX. +

  • +
  • +

    directory:

    +

    Fail if not a directory, similar to `O_DIRECTORY` in POSIX. +

  • +
  • +

    exclusive:

    +

    Fail if file already exists, similar to `O_EXCL` in POSIX. +

  • +
  • +

    truncate:

    +

    Truncate file to size 0, similar to `O_TRUNC` in POSIX. +

  • +
+

type link-count

+

u64

+

Number of hard links to an inode. +

record descriptor-stat

+

File attributes.

+

Note: This was called filestat in earlier versions of WASI.

+
Record Fields
+
    +
  • +

    type: descriptor-type

    +

    File type. +

  • +
  • +

    link-count: link-count

    +

    Number of hard links to the file. +

  • +
  • +

    size: filesize

    +

    For regular files, the file size in bytes. For symbolic links, the +length in bytes of the pathname contained in the symbolic link. +

  • +
  • +

    data-access-timestamp: option<datetime>

    +

    Last data access timestamp. +

    If the option is none, the platform doesn't maintain an access +timestamp for this file.

    +
  • +
  • +

    data-modification-timestamp: option<datetime>

    +

    Last data modification timestamp. +

    If the option is none, the platform doesn't maintain a +modification timestamp for this file.

    +
  • +
  • +

    status-change-timestamp: option<datetime>

    +

    Last file status-change timestamp. +

    If the option is none, the platform doesn't maintain a +status-change timestamp for this file.

    +
  • +
+

variant new-timestamp

+

When setting a timestamp, this gives the value to set it to.

+
Variant Cases
+
    +
  • +

    no-change

    +

    Leave the timestamp set to its previous value. +

  • +
  • +

    now

    +

    Set the timestamp to the current time of the system clock associated +with the filesystem. +

  • +
  • +

    timestamp: datetime

    +

    Set the timestamp to the given value. +

  • +
+

record directory-entry

+

A directory entry.

+
Record Fields
+
    +
  • +

    type: descriptor-type

    +

    The type of the file referred to by this directory entry. +

  • +
  • +

    name: string

    +

    The name of the object. +

  • +
+

enum error-code

+

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 Cases
+
    +
  • +

    access

    +

    Permission denied, similar to `EACCES` in POSIX. +

  • +
  • +

    would-block

    +

    Resource unavailable, or operation would block, similar to `EAGAIN` and `EWOULDBLOCK` in POSIX. +

  • +
  • +

    already

    +

    Connection already in progress, similar to `EALREADY` in POSIX. +

  • +
  • +

    bad-descriptor

    +

    Bad descriptor, similar to `EBADF` in POSIX. +

  • +
  • +

    busy

    +

    Device or resource busy, similar to `EBUSY` in POSIX. +

  • +
  • +

    deadlock

    +

    Resource deadlock would occur, similar to `EDEADLK` in POSIX. +

  • +
  • +

    quota

    +

    Storage quota exceeded, similar to `EDQUOT` in POSIX. +

  • +
  • +

    exist

    +

    File exists, similar to `EEXIST` in POSIX. +

  • +
  • +

    file-too-large

    +

    File too large, similar to `EFBIG` in POSIX. +

  • +
  • +

    illegal-byte-sequence

    +

    Illegal byte sequence, similar to `EILSEQ` in POSIX. +

  • +
  • +

    in-progress

    +

    Operation in progress, similar to `EINPROGRESS` in POSIX. +

  • +
  • +

    interrupted

    +

    Interrupted function, similar to `EINTR` in POSIX. +

  • +
  • +

    invalid

    +

    Invalid argument, similar to `EINVAL` in POSIX. +

  • +
  • +

    io

    +

    I/O error, similar to `EIO` in POSIX. +

  • +
  • +

    is-directory

    +

    Is a directory, similar to `EISDIR` in POSIX. +

  • +
  • +

    loop

    +

    Too many levels of symbolic links, similar to `ELOOP` in POSIX. +

  • +
  • +

    too-many-links

    +

    Too many links, similar to `EMLINK` in POSIX. +

  • +
  • +

    message-size

    +

    Message too large, similar to `EMSGSIZE` in POSIX. +

  • +
  • +

    name-too-long

    +

    Filename too long, similar to `ENAMETOOLONG` in POSIX. +

  • +
  • +

    no-device

    +

    No such device, similar to `ENODEV` in POSIX. +

  • +
  • +

    no-entry

    +

    No such file or directory, similar to `ENOENT` in POSIX. +

  • +
  • +

    no-lock

    +

    No locks available, similar to `ENOLCK` in POSIX. +

  • +
  • +

    insufficient-memory

    +

    Not enough space, similar to `ENOMEM` in POSIX. +

  • +
  • +

    insufficient-space

    +

    No space left on device, similar to `ENOSPC` in POSIX. +

  • +
  • +

    not-directory

    +

    Not a directory or a symbolic link to a directory, similar to `ENOTDIR` in POSIX. +

  • +
  • +

    not-empty

    +

    Directory not empty, similar to `ENOTEMPTY` in POSIX. +

  • +
  • +

    not-recoverable

    +

    State not recoverable, similar to `ENOTRECOVERABLE` in POSIX. +

  • +
  • +

    unsupported

    +

    Not supported, similar to `ENOTSUP` and `ENOSYS` in POSIX. +

  • +
  • +

    no-tty

    +

    Inappropriate I/O control operation, similar to `ENOTTY` in POSIX. +

  • +
  • +

    no-such-device

    +

    No such device or address, similar to `ENXIO` in POSIX. +

  • +
  • +

    overflow

    +

    Value too large to be stored in data type, similar to `EOVERFLOW` in POSIX. +

  • +
  • +

    not-permitted

    +

    Operation not permitted, similar to `EPERM` in POSIX. +

  • +
  • +

    pipe

    +

    Broken pipe, similar to `EPIPE` in POSIX. +

  • +
  • +

    read-only

    +

    Read-only file system, similar to `EROFS` in POSIX. +

  • +
  • +

    invalid-seek

    +

    Invalid seek, similar to `ESPIPE` in POSIX. +

  • +
  • +

    text-file-busy

    +

    Text file busy, similar to `ETXTBSY` in POSIX. +

  • +
  • +

    cross-device

    +

    Cross-device link, similar to `EXDEV` in POSIX. +

  • +
+

enum advice

+

File or memory access pattern advisory information.

+
Enum Cases
+
    +
  • +

    normal

    +

    The application has no advice to give on its behavior with respect +to the specified data. +

  • +
  • +

    sequential

    +

    The application expects to access the specified data sequentially +from lower offsets to higher offsets. +

  • +
  • +

    random

    +

    The application expects to access the specified data in a random +order. +

  • +
  • +

    will-need

    +

    The application expects to access the specified data in the near +future. +

  • +
  • +

    dont-need

    +

    The application expects that it will not access the specified data +in the near future. +

  • +
  • +

    no-reuse

    +

    The application expects to access the specified data once and then +not reuse it thereafter. +

  • +
+

record metadata-hash-value

+

A 128-bit hash value, split into parts because wasm doesn't have a +128-bit integer type.

+
Record Fields
+
    +
  • +

    lower: u64

    +

    64 bits of a 128-bit hash value. +

  • +
  • +

    upper: u64

    +

    Another 64 bits of a 128-bit hash value. +

  • +
+

resource descriptor

+

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 directory-entry-stream

+

A stream of directory entries.

+

Functions

+

[method]descriptor.read-via-stream: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.write-via-stream: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.append-via-stream: func

+

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 POSIX.

+
Params
+ +
Return values
+ +

[method]descriptor.advise: func

+

Provide file advisory information on a descriptor.

+

This is similar to posix_fadvise in POSIX.

+
Params
+ +
Return values
+ +

[method]descriptor.sync-data: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.get-flags: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.get-type: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.set-size: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.set-times: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.read: func

+

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<u8, error-code>.

+

Note: This is similar to pread in POSIX.

+
Params
+ +
Return values
+ +

[method]descriptor.write: func

+

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<u8, error-code>.

+

Note: This is similar to pwrite in POSIX.

+
Params
+ +
Return values
+ +

[method]descriptor.read-directory: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.sync: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.create-directory-at: func

+

Create a directory.

+

Note: This is similar to mkdirat in POSIX.

+
Params
+ +
Return values
+ +

[method]descriptor.stat: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.stat-at: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.set-times-at: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.link-at: func

+

Create a hard link.

+

Fails with error-code::no-entry if the old path does not exist, +with error-code::exist if the new path already exists, and +error-code::not-permitted if the old path is not a file.

+

Note: This is similar to linkat in POSIX.

+
Params
+ +
Return values
+ +

[method]descriptor.open-at: func

+

Open a file or directory.

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.readlink-at: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.remove-directory-at: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.rename-at: func

+

Rename a filesystem object.

+

Note: This is similar to renameat in POSIX.

+
Params
+
    +
  • self: borrow<descriptor>
  • +
  • old-path: string
  • +
  • new-descriptor: borrow<descriptor>
  • +
  • new-path: string
  • +
+
Return values
+ +

[method]descriptor.symlink-at: func

+

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.

+
Params
+
    +
  • self: borrow<descriptor>
  • +
  • old-path: string
  • +
  • new-path: string
  • +
+
Return values
+ +

[method]descriptor.unlink-file-at: func

+

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.

+
Params
+ +
Return values
+ +

[method]descriptor.is-same-object: func

+

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.

+
Params
+ +
Return values
+
    +
  • bool
  • +
+

[method]descriptor.metadata-hash: func

+

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 encouraged 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.

+
Params
+ +
Return values
+ +

[method]descriptor.metadata-hash-at: func

+

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.

+
Params
+ +
Return values
+ +

[method]directory-entry-stream.read-directory-entry: func

+

Read a single directory entry from a directory-entry-stream.

+
Params
+ +
Return values
+ +

filesystem-error-code: func

+

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.

+
Params
+ +
Return values
+ +

Import interface wasi:filesystem/preopens@0.2.8

+
+

Types

+

type descriptor

+

descriptor

+

+


+

Functions

+

get-directories: func

+

Return the set of preopened directories, and their paths.

+
Return values
+ diff --git a/proposals/filesystem/path-resolution.md b/proposals/filesystem/path-resolution.md new file mode 100644 index 000000000..45f20b1b5 --- /dev/null +++ b/proposals/filesystem/path-resolution.md @@ -0,0 +1,91 @@ +# WASI filesystem path resolution + +wasi-filesystem uses a filesystem path sandboxing scheme modeled after the +system used in [CloudABI], which is also similar to the system used in +[Capsicum]. + +On Linux, it corresponds to the `RESOLVE_BENEATH` behavior in +[Linux's `openat2`]. In FreeBSD, it corresponds to the `O_RESOLVE_BENEATH` +behavior in [FreeBSD's `open`]. However, path resolution can also be +implemented manually using `openat` and `readlinkat` or similar primitives. + +## Sandboxing overview + +All functions in wasi-filesystem which operate on filesystem paths take +a pair of values: a base directory handle, and a relative path. Absolute +paths are not permitted, and there is no global namespace. All path +accesses are relative to a base directory handle. + +Path resolution is constrained to occur within the sub-filesystem referenced +by the base handle. Information about the filesystem outside of the base +directory handles is not visible. In particular, it's not permitted to use +paths that temporarily step outside the sandbox with something like +"../../../stuff/here", even if the final resolved path is back inside the +sandbox, because that would leak information about the existence of +directories outside the sandbox. + +Importantly, the sandboxing is designed to be implementable even in the presence +of outside processes accessing the same filesystem, including renaming, +unlinking, and creating new files and directories. + +## Symlinks + +Creating a symlink with an absolute path string fails with a "not permitted" +error. + +Other than that, symlinks may be created with any string, provided the +underlying filesystem implementation supports it. + +Sandboxing for symlink strings is performed at the time of an access, when a +path is being resolved, and not at the time that the symlink is created or +moved. This ensures that the sandbox is respected even if there are symlinks +created or renamed by other entities with access to the filesystem. + +## Host Implementation + +### Implementing path resolution manually + +Plain `openat` doesn't perform any sandboxing; it will readily open paths +containing ".." or starting with "/", or symlinks to paths containing ".." +or starting with "/". It has an `O_NOFOLLOW` flag, however this flag only +applies to the last component of the path (eg. the "c" in "a/b/c"). So +the strategy for using `openat` to implement sandboxing is to split paths +into components (eg. "a", "b", "c") and open them one component at a time, +so that each component can be opened with `O_NOFOLLOW`. + +If the `openat` call fails, and the OS error code indicates that it *was* +a symlink (eg. `ELOOP`), then call `readlinkat` to read the link contents, +split the contents into components, and prepend these new components to the +component list. If it starts with an absolute path, that's an attempt to +jump outside the sandbox, so path resolution should fail with an +"access denied" error message. + +If a path component is "..", instead of opening it, pop an item off of the +component list. If the list was empty, that represents an attempt to use +".." to step outside the sandbox, so path resolution should fail with an +"access denied" error message. + +### Implementation notes + +On Linux, `openat2` with `RESOLVE_BENEATH` may be used as an optimization to +implement many system calls other than just "open" by utilizing Linux's +`O_PATH` and "/proc/self/fd" features. + +On Windows, the [`NtCreateFile`] function can accept a directory handle and +can behave like an `openat` function, which can be used in the +[manual algorithm](implementing-path-resolution-manually). + +The Rust library [cap-std] implements WASI's filesystem sandboxing semantics, +but is otherwise independent of WASI or Wasm, so it can be reused in other +settings. It uses `openat2` and `NtCreateFile` and other optimizations. + +cloudabi-utils has an [implementation of the manual technique in C], though +that repository is no longer maintained. + +[implementation of the manual technique in C]: https://github.com/NuxiNL/cloudabi-utils/blob/master/src/libemulator/posix.c#L1205 +[cap-std]: https://github.com/bytecodealliance/cap-std +[Linux's `openat2`]: https://man7.org/linux/man-pages/man2/openat2.2.html +[CloudABI]: https://github.com/NuxiNL/cloudabi +[Capsicum]: https://wiki.freebsd.org/Capsicum +[FreeBSD's `open`]: https://man.freebsd.org/cgi/man.cgi?sektion=2&query=open +[`NtCreateFile`]: https://learn.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntcreatefile diff --git a/proposals/filesystem/test/README.md b/proposals/filesystem/test/README.md new file mode 100644 index 000000000..c274acd9d --- /dev/null +++ b/proposals/filesystem/test/README.md @@ -0,0 +1,11 @@ +# Testing guidelines + +TK fill in testing guidelines + +## Installing the tools + +TK fill in instructions + +## Running the tests + +TK fill in instructions diff --git a/proposals/filesystem/wit-0.3.0-draft/deps.lock b/proposals/filesystem/wit-0.3.0-draft/deps.lock new file mode 100644 index 000000000..4f3b1fe94 --- /dev/null +++ b/proposals/filesystem/wit-0.3.0-draft/deps.lock @@ -0,0 +1,5 @@ +[clocks] +url = "https://github.com/WebAssembly/wasi-clocks/archive/main.tar.gz" +subdir = "wit-0.3.0-draft" +sha256 = "cf61a3785c2838340ce530ee1cdc6dbee3257f1672d6000ca748dfe253808dec" +sha512 = "f647de7d6c470595c3e5bf0dba6af98703beb9f701c66543cea5d42e81f7a1a73f199c3949035a9c2c1bd717056e5e68788f520af39b9d26480242b7626f22ce" diff --git a/proposals/filesystem/wit-0.3.0-draft/deps.toml b/proposals/filesystem/wit-0.3.0-draft/deps.toml new file mode 100644 index 000000000..e00454742 --- /dev/null +++ b/proposals/filesystem/wit-0.3.0-draft/deps.toml @@ -0,0 +1 @@ +clocks = { url = "https://github.com/WebAssembly/wasi-clocks/archive/main.tar.gz", subdir = "wit-0.3.0-draft" } diff --git a/proposals/filesystem/wit-0.3.0-draft/deps/clocks/monotonic-clock.wit b/proposals/filesystem/wit-0.3.0-draft/deps/clocks/monotonic-clock.wit new file mode 100644 index 000000000..a91d495c6 --- /dev/null +++ b/proposals/filesystem/wit-0.3.0-draft/deps/clocks/monotonic-clock.wit @@ -0,0 +1,48 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; +/// 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. +@since(version = 0.3.0-rc-2025-09-16) +interface monotonic-clock { + use types.{duration}; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + type instant = 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. + /// + /// For completeness, this function traps if it's not possible to represent + /// the value of the clock in an `instant`. Consequently, implementations + /// should ensure that the starting time is low enough to avoid the + /// possibility of overflow in practice. + @since(version = 0.3.0-rc-2025-09-16) + now: func() -> instant; + + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + @since(version = 0.3.0-rc-2025-09-16) + get-resolution: func() -> duration; + + /// Wait until the specified instant has occurred. + @since(version = 0.3.0-rc-2025-09-16) + wait-until: async func( + when: instant, + ); + + /// Wait for the specified duration to elapse. + @since(version = 0.3.0-rc-2025-09-16) + wait-for: async func( + how-long: duration, + ); +} diff --git a/proposals/filesystem/wit-0.3.0-draft/deps/clocks/timezone.wit b/proposals/filesystem/wit-0.3.0-draft/deps/clocks/timezone.wit new file mode 100644 index 000000000..ab8f5c080 --- /dev/null +++ b/proposals/filesystem/wit-0.3.0-draft/deps/clocks/timezone.wit @@ -0,0 +1,55 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; + +@unstable(feature = clocks-timezone) +interface timezone { + @unstable(feature = clocks-timezone) + use wall-clock.{datetime}; + + /// Return information needed to display the given `datetime`. This includes + /// the UTC offset, the time zone name, and a flag indicating whether + /// daylight saving time is active. + /// + /// If the timezone cannot be determined for the given `datetime`, return a + /// `timezone-display` for `UTC` with a `utc-offset` of 0 and no daylight + /// saving time. + @unstable(feature = clocks-timezone) + display: func(when: datetime) -> timezone-display; + + /// The same as `display`, but only return the UTC offset. + @unstable(feature = clocks-timezone) + utc-offset: func(when: datetime) -> s32; + + /// Information useful for displaying the timezone of a specific `datetime`. + /// + /// This information may vary within a single `timezone` to reflect daylight + /// saving time adjustments. + @unstable(feature = clocks-timezone) + record timezone-display { + /// The number of seconds difference between UTC time and the local + /// time of the timezone. + /// + /// The returned value will always be less than 86400 which is the + /// number of seconds in a day (24*60*60). + /// + /// In implementations that do not expose an actual time zone, this + /// should return 0. + utc-offset: s32, + + /// The abbreviated name of the timezone to display to a user. The name + /// `UTC` indicates Coordinated Universal Time. Otherwise, this should + /// reference local standards for the name of the time zone. + /// + /// In implementations that do not expose an actual time zone, this + /// should be the string `UTC`. + /// + /// In time zones that do not have an applicable name, a formatted + /// representation of the UTC offset may be returned, such as `-04:00`. + name: string, + + /// Whether daylight saving time is active. + /// + /// In implementations that do not expose an actual time zone, this + /// should return false. + in-daylight-saving-time: bool, + } +} diff --git a/proposals/filesystem/wit-0.3.0-draft/deps/clocks/types.wit b/proposals/filesystem/wit-0.3.0-draft/deps/clocks/types.wit new file mode 100644 index 000000000..aff7c2a22 --- /dev/null +++ b/proposals/filesystem/wit-0.3.0-draft/deps/clocks/types.wit @@ -0,0 +1,8 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; +/// This interface common types used throughout wasi:clocks. +@since(version = 0.3.0-rc-2025-09-16) +interface types { + /// A duration of time, in nanoseconds. + @since(version = 0.3.0-rc-2025-09-16) + type duration = u64; +} diff --git a/proposals/filesystem/wit-0.3.0-draft/deps/clocks/wall-clock.wit b/proposals/filesystem/wit-0.3.0-draft/deps/clocks/wall-clock.wit new file mode 100644 index 000000000..ea940500f --- /dev/null +++ b/proposals/filesystem/wit-0.3.0-draft/deps/clocks/wall-clock.wit @@ -0,0 +1,46 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; +/// 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. +@since(version = 0.3.0-rc-2025-09-16) +interface wall-clock { + /// A time and date in seconds plus nanoseconds. + @since(version = 0.3.0-rc-2025-09-16) + 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 + @since(version = 0.3.0-rc-2025-09-16) + now: func() -> datetime; + + /// Query the resolution of the clock. + /// + /// The nanoseconds field of the output is always less than 1000000000. + @since(version = 0.3.0-rc-2025-09-16) + get-resolution: func() -> datetime; +} diff --git a/proposals/filesystem/wit-0.3.0-draft/deps/clocks/world.wit b/proposals/filesystem/wit-0.3.0-draft/deps/clocks/world.wit new file mode 100644 index 000000000..a6b885f07 --- /dev/null +++ b/proposals/filesystem/wit-0.3.0-draft/deps/clocks/world.wit @@ -0,0 +1,11 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; + +@since(version = 0.3.0-rc-2025-09-16) +world imports { + @since(version = 0.3.0-rc-2025-09-16) + import monotonic-clock; + @since(version = 0.3.0-rc-2025-09-16) + import wall-clock; + @unstable(feature = clocks-timezone) + import timezone; +} diff --git a/proposals/filesystem/wit-0.3.0-draft/preopens.wit b/proposals/filesystem/wit-0.3.0-draft/preopens.wit new file mode 100644 index 000000000..9036e90e8 --- /dev/null +++ b/proposals/filesystem/wit-0.3.0-draft/preopens.wit @@ -0,0 +1,11 @@ +package wasi:filesystem@0.3.0-rc-2025-09-16; + +@since(version = 0.3.0-rc-2025-09-16) +interface preopens { + @since(version = 0.3.0-rc-2025-09-16) + use types.{descriptor}; + + /// Return the set of preopened directories, and their paths. + @since(version = 0.3.0-rc-2025-09-16) + get-directories: func() -> list>; +} diff --git a/proposals/filesystem/wit-0.3.0-draft/types.wit b/proposals/filesystem/wit-0.3.0-draft/types.wit new file mode 100644 index 000000000..41d91beee --- /dev/null +++ b/proposals/filesystem/wit-0.3.0-draft/types.wit @@ -0,0 +1,636 @@ +package wasi:filesystem@0.3.0-rc-2025-09-16; +/// 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 +@since(version = 0.3.0-rc-2025-09-16) +interface types { + @since(version = 0.3.0-rc-2025-09-16) + use wasi:clocks/wall-clock@0.3.0-rc-2025-09-16.{datetime}; + + /// File size or length of a region within a file. + @since(version = 0.3.0-rc-2025-09-16) + type filesize = u64; + + /// The type of a filesystem object referenced by a descriptor. + /// + /// Note: This was called `filetype` in earlier versions of WASI. + @since(version = 0.3.0-rc-2025-09-16) + 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. + @since(version = 0.3.0-rc-2025-09-16) + 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 integrity + /// 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, + } + + /// File attributes. + /// + /// Note: This was called `filestat` in earlier versions of WASI. + @since(version = 0.3.0-rc-2025-09-16) + 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, + } + + /// Flags determining the method of how paths are resolved. + @since(version = 0.3.0-rc-2025-09-16) + 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`. + @since(version = 0.3.0-rc-2025-09-16) + 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. + @since(version = 0.3.0-rc-2025-09-16) + type link-count = u64; + + /// When setting a timestamp, this gives the value to set it to. + @since(version = 0.3.0-rc-2025-09-16) + 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, + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + 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. + @since(version = 0.3.0-rc-2025-09-16) + 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. + @since(version = 0.3.0-rc-2025-09-16) + resource descriptor { + /// Return a stream for reading from a file. + /// + /// Multiple read, write, and append streams may be active on the same open + /// file and they do not interfere with each other. + /// + /// This function returns a `stream` which provides the data received from the + /// file, and a `future` providing additional error information in case an + /// error is encountered. + /// + /// If no error is encountered, `stream.read` on the `stream` will return + /// `read-status::closed` with no `error-context` and the future resolves to + /// the value `ok`. If an error is encountered, `stream.read` on the + /// `stream` returns `read-status::closed` with an `error-context` and the future + /// resolves to `err` with an `error-code`. + /// + /// Note: This is similar to `pread` in POSIX. + @since(version = 0.3.0-rc-2025-09-16) + read-via-stream: func( + /// The offset within the file at which to start reading. + offset: filesize, + ) -> tuple, future>>; + + /// Return a stream for writing to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be written. + /// + /// 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. + /// + /// This function returns once either full contents of the stream are + /// written or an error is encountered. + /// + /// Note: This is similar to `pwrite` in POSIX. + @since(version = 0.3.0-rc-2025-09-16) + write-via-stream: async func( + /// Data to write + data: stream, + /// The offset within the file at which to start writing. + offset: filesize, + ) -> 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. + /// + /// This function returns once either full contents of the stream are + /// written or an error is encountered. + /// + /// Note: This is similar to `write` with `O_APPEND` in POSIX. + @since(version = 0.3.0-rc-2025-09-16) + append-via-stream: async func(data: stream) -> result<_, error-code>; + + /// Provide file advisory information on a descriptor. + /// + /// This is similar to `posix_fadvise` in POSIX. + @since(version = 0.3.0-rc-2025-09-16) + advise: async func( + /// The offset within the file to which the advisory applies. + offset: filesize, + /// The length of the region to which the advisory applies. + length: filesize, + /// The advice. + advice: advice + ) -> 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. + @since(version = 0.3.0-rc-2025-09-16) + sync-data: async func() -> 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. + @since(version = 0.3.0-rc-2025-09-16) + get-flags: async 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. + @since(version = 0.3.0-rc-2025-09-16) + get-type: async func() -> result; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + set-size: async 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. + @since(version = 0.3.0-rc-2025-09-16) + set-times: async func( + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, 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. + /// + /// This function returns a future, which will resolve to an error code if + /// reading full contents of the directory fails. + @since(version = 0.3.0-rc-2025-09-16) + read-directory: async func() -> tuple, future>>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + sync: async func() -> result<_, error-code>; + + /// Create a directory. + /// + /// Note: This is similar to `mkdirat` in POSIX. + @since(version = 0.3.0-rc-2025-09-16) + create-directory-at: async func( + /// The relative path at which to create the directory. + path: string, + ) -> 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. + @since(version = 0.3.0-rc-2025-09-16) + stat: async 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. + @since(version = 0.3.0-rc-2025-09-16) + stat-at: async func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + set-times-at: async func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to operate on. + path: string, + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, error-code>; + + /// Create a hard link. + /// + /// Fails with `error-code::no-entry` if the old path does not exist, + /// with `error-code::exist` if the new path already exists, and + /// `error-code::not-permitted` if the old path is not a file. + /// + /// Note: This is similar to `linkat` in POSIX. + @since(version = 0.3.0-rc-2025-09-16) + link-at: async func( + /// Flags determining the method of how the path is resolved. + old-path-flags: path-flags, + /// The relative source path from which to link. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path at which to create the hard link. + new-path: string, + ) -> result<_, error-code>; + + /// Open a file or directory. + /// + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + open-at: async func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the object to open. + path: string, + /// The method by which to open the file. + open-flags: open-flags, + /// Flags to use for the resulting descriptor. + %flags: descriptor-flags, + ) -> 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. + @since(version = 0.3.0-rc-2025-09-16) + readlink-at: async func( + /// The relative path of the symbolic link from which to read. + 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. + @since(version = 0.3.0-rc-2025-09-16) + remove-directory-at: async func( + /// The relative path to a directory to remove. + path: string, + ) -> result<_, error-code>; + + /// Rename a filesystem object. + /// + /// Note: This is similar to `renameat` in POSIX. + @since(version = 0.3.0-rc-2025-09-16) + rename-at: async func( + /// The relative source path of the file or directory to rename. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path to which to rename the file or directory. + new-path: string, + ) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + symlink-at: async func( + /// The contents of the symbolic link. + old-path: string, + /// The relative destination path at which to create the symbolic link. + new-path: string, + ) -> 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. + @since(version = 0.3.0-rc-2025-09-16) + unlink-file-at: async func( + /// The relative path to a file to unlink. + path: string, + ) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + is-same-object: async func(other: borrow) -> bool; + + /// 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 encouraged 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. + @since(version = 0.3.0-rc-2025-09-16) + metadata-hash: async 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`. + @since(version = 0.3.0-rc-2025-09-16) + metadata-hash-at: async func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + } +} diff --git a/proposals/filesystem/wit-0.3.0-draft/world.wit b/proposals/filesystem/wit-0.3.0-draft/world.wit new file mode 100644 index 000000000..87fc72716 --- /dev/null +++ b/proposals/filesystem/wit-0.3.0-draft/world.wit @@ -0,0 +1,9 @@ +package wasi:filesystem@0.3.0-rc-2025-09-16; + +@since(version = 0.3.0-rc-2025-09-16) +world imports { + @since(version = 0.3.0-rc-2025-09-16) + import types; + @since(version = 0.3.0-rc-2025-09-16) + import preopens; +} diff --git a/proposals/filesystem/wit/deps.lock b/proposals/filesystem/wit/deps.lock new file mode 100644 index 000000000..b0d60f694 --- /dev/null +++ b/proposals/filesystem/wit/deps.lock @@ -0,0 +1,9 @@ +[clocks] +url = "https://github.com/WebAssembly/wasi-clocks/archive/main.tar.gz" +sha256 = "be1d8c61e2544e2b48d902c60df73577e293349063344ce752cda4d323f8b913" +sha512 = "0fd7962c62b135da0e584c2b58a55147bf09873848b0bb5bd3913019bc3f8d4b5969fbd6f7f96fd99a015efaf562a3eeafe3bc13049f8572a6e13ef9ef0e7e75" + +[io] +url = "https://github.com/WebAssembly/wasi-io/archive/main.tar.gz" +sha256 = "9f1ad5da70f621bbd4c69e3bd90250a0c12ecfde266aa8f99684fc44bc1e7c15" +sha512 = "6d0a9db6848f24762933d1c168a5b5b1065ba838c253ee20454afeb8dd1a049b918d25deff556083d68095dd3126ae131ac3e738774320eee5d918f5a4b5354e" diff --git a/proposals/filesystem/wit/deps.toml b/proposals/filesystem/wit/deps.toml new file mode 100644 index 000000000..23c019844 --- /dev/null +++ b/proposals/filesystem/wit/deps.toml @@ -0,0 +1,2 @@ +io = "https://github.com/WebAssembly/wasi-io/archive/main.tar.gz" +clocks = "https://github.com/WebAssembly/wasi-clocks/archive/main.tar.gz" diff --git a/proposals/filesystem/wit/deps/clocks/monotonic-clock.wit b/proposals/filesystem/wit/deps/clocks/monotonic-clock.wit new file mode 100644 index 000000000..e60f366f2 --- /dev/null +++ b/proposals/filesystem/wit/deps/clocks/monotonic-clock.wit @@ -0,0 +1,55 @@ +package wasi:clocks@0.2.8; +/// 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. +@since(version = 0.2.0) +interface monotonic-clock { + @since(version = 0.2.0) + use wasi:io/poll@0.2.8.{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. + @since(version = 0.2.0) + type instant = u64; + + /// A duration of time, in nanoseconds. + @since(version = 0.2.0) + 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. + /// + /// For completeness, this function traps if it's not possible to represent + /// the value of the clock in an `instant`. Consequently, implementations + /// should ensure that the starting time is low enough to avoid the + /// possibility of overflow in practice. + @since(version = 0.2.0) + now: func() -> instant; + + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + @since(version = 0.2.0) + resolution: func() -> duration; + + /// Create a `pollable` which will resolve once the specified instant + /// has occurred. + @since(version = 0.2.0) + subscribe-instant: func( + when: instant, + ) -> pollable; + + /// Create a `pollable` that will resolve after the specified duration has + /// elapsed from the time this function is invoked. + @since(version = 0.2.0) + subscribe-duration: func( + when: duration, + ) -> pollable; +} diff --git a/proposals/filesystem/wit/deps/clocks/timezone.wit b/proposals/filesystem/wit/deps/clocks/timezone.wit new file mode 100644 index 000000000..534814a63 --- /dev/null +++ b/proposals/filesystem/wit/deps/clocks/timezone.wit @@ -0,0 +1,55 @@ +package wasi:clocks@0.2.8; + +@unstable(feature = clocks-timezone) +interface timezone { + @unstable(feature = clocks-timezone) + use wall-clock.{datetime}; + + /// Return information needed to display the given `datetime`. This includes + /// the UTC offset, the time zone name, and a flag indicating whether + /// daylight saving time is active. + /// + /// If the timezone cannot be determined for the given `datetime`, return a + /// `timezone-display` for `UTC` with a `utc-offset` of 0 and no daylight + /// saving time. + @unstable(feature = clocks-timezone) + display: func(when: datetime) -> timezone-display; + + /// The same as `display`, but only return the UTC offset. + @unstable(feature = clocks-timezone) + utc-offset: func(when: datetime) -> s32; + + /// Information useful for displaying the timezone of a specific `datetime`. + /// + /// This information may vary within a single `timezone` to reflect daylight + /// saving time adjustments. + @unstable(feature = clocks-timezone) + record timezone-display { + /// The number of seconds difference between UTC time and the local + /// time of the timezone. + /// + /// The returned value will always be less than 86400 which is the + /// number of seconds in a day (24*60*60). + /// + /// In implementations that do not expose an actual time zone, this + /// should return 0. + utc-offset: s32, + + /// The abbreviated name of the timezone to display to a user. The name + /// `UTC` indicates Coordinated Universal Time. Otherwise, this should + /// reference local standards for the name of the time zone. + /// + /// In implementations that do not expose an actual time zone, this + /// should be the string `UTC`. + /// + /// In time zones that do not have an applicable name, a formatted + /// representation of the UTC offset may be returned, such as `-04:00`. + name: string, + + /// Whether daylight saving time is active. + /// + /// In implementations that do not expose an actual time zone, this + /// should return false. + in-daylight-saving-time: bool, + } +} diff --git a/proposals/filesystem/wit/deps/clocks/wall-clock.wit b/proposals/filesystem/wit/deps/clocks/wall-clock.wit new file mode 100644 index 000000000..3386c800b --- /dev/null +++ b/proposals/filesystem/wit/deps/clocks/wall-clock.wit @@ -0,0 +1,46 @@ +package wasi:clocks@0.2.8; +/// 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. +@since(version = 0.2.0) +interface wall-clock { + /// A time and date in seconds plus nanoseconds. + @since(version = 0.2.0) + 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 + @since(version = 0.2.0) + now: func() -> datetime; + + /// Query the resolution of the clock. + /// + /// The nanoseconds field of the output is always less than 1000000000. + @since(version = 0.2.0) + resolution: func() -> datetime; +} diff --git a/proposals/filesystem/wit/deps/clocks/world.wit b/proposals/filesystem/wit/deps/clocks/world.wit new file mode 100644 index 000000000..1655ca830 --- /dev/null +++ b/proposals/filesystem/wit/deps/clocks/world.wit @@ -0,0 +1,11 @@ +package wasi:clocks@0.2.8; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import monotonic-clock; + @since(version = 0.2.0) + import wall-clock; + @unstable(feature = clocks-timezone) + import timezone; +} diff --git a/proposals/filesystem/wit/deps/io/error.wit b/proposals/filesystem/wit/deps/io/error.wit new file mode 100644 index 000000000..dd5a1af03 --- /dev/null +++ b/proposals/filesystem/wit/deps/io/error.wit @@ -0,0 +1,34 @@ +package wasi:io@0.2.8; + +@since(version = 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 + /// offer functions to "downcast" this error into more specific types. For example, + /// errors returned from streams derived from filesystem types can be described using + /// the filesystem's own error-code type. This is done using the function + /// `wasi:filesystem/types/filesystem-error-code`, which takes a `borrow` + /// parameter and returns an `option`. + /// + /// The set of functions which can "downcast" an `error` into a more + /// concrete type is open. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + to-debug-string: func() -> string; + } +} diff --git a/proposals/filesystem/wit/deps/io/poll.wit b/proposals/filesystem/wit/deps/io/poll.wit new file mode 100644 index 000000000..833b381d9 --- /dev/null +++ b/proposals/filesystem/wit/deps/io/poll.wit @@ -0,0 +1,47 @@ +package wasi:io@0.2.8; + +/// A poll API intended to let users wait for I/O events on multiple handles +/// at once. +@since(version = 0.2.0) +interface poll { + /// `pollable` represents a single I/O event which may be ready, or not. + @since(version = 0.2.0) + resource pollable { + + /// Return the readiness of a pollable. This function never blocks. + /// + /// Returns `true` when the pollable is ready, and `false` otherwise. + @since(version = 0.2.0) + ready: func() -> bool; + + /// `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. + @since(version = 0.2.0) + block: func(); + } + + /// 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. + /// + /// This function traps if either: + /// - the list is empty, or: + /// - the list contains more elements than can be indexed with a `u32` value. + /// + /// 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 ready for I/O. + @since(version = 0.2.0) + poll: func(in: list>) -> list; +} diff --git a/proposals/filesystem/wit/deps/io/streams.wit b/proposals/filesystem/wit/deps/io/streams.wit new file mode 100644 index 000000000..fbb0268b0 --- /dev/null +++ b/proposals/filesystem/wit/deps/io/streams.wit @@ -0,0 +1,258 @@ +package wasi:io@0.2.8; + +/// 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. +@since(version = 0.2.0) +interface streams { + @since(version = 0.2.0) + use error.{error}; + @since(version = 0.2.0) + use poll.{pollable}; + + /// An error for input-stream and output-stream operations. + @since(version = 0.2.0) + variant stream-error { + /// The last operation (a write or flush) failed before completion. + /// + /// More information is available in the `error` payload. + /// + /// After this, the stream will be closed. All future operations return + /// `stream-error::closed`. + 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`. + @since(version = 0.2.0) + resource input-stream { + /// 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. + @since(version = 0.2.0) + read: func( + /// The maximum number of bytes to read + len: u64 + ) -> result, stream-error>; + + /// Read bytes from a stream, after blocking until at least one byte can + /// be read. Except for blocking, behavior is identical to `read`. + @since(version = 0.2.0) + blocking-read: func( + /// The maximum number of bytes to read + 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. + @since(version = 0.2.0) + skip: func( + /// The maximum number of bytes to skip. + len: u64, + ) -> result; + + /// Skip bytes from a stream, after blocking until at least one byte + /// can be skipped. Except for blocking behavior, identical to `skip`. + @since(version = 0.2.0) + blocking-skip: func( + /// The maximum number of bytes to skip. + 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. + @since(version = 0.2.0) + 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`. + /// + /// Dropping an `output-stream` while there's still an active write in + /// progress may result in the data being lost. Before dropping the stream, + /// be sure to fully flush your writes. + @since(version = 0.2.0) + resource output-stream { + /// 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. + @since(version = 0.2.0) + check-write: func() -> result; + + /// 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. + @since(version = 0.2.0) + write: func( + contents: list + ) -> result<_, stream-error>; + + /// 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. + /// + /// Returns success when all of the contents written are successfully + /// flushed to output. If an error occurs at any point before all + /// contents are successfully flushed, that error is returned as soon as + /// possible. If writing and flushing the complete contents causes the + /// stream to become closed, this call should return success, and + /// subsequent calls to check-write or other interfaces should return + /// stream-error::closed. + @since(version = 0.2.0) + blocking-write-and-flush: func( + contents: list + ) -> result<_, stream-error>; + + /// 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. + @since(version = 0.2.0) + flush: func() -> result<_, stream-error>; + + /// Request to flush buffered output, and block until flush completes + /// and stream is ready for writing again. + @since(version = 0.2.0) + blocking-flush: func() -> result<_, stream-error>; + + /// Create a `pollable` which will resolve once the output-stream + /// is ready for more writing, or an error has occurred. 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. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// 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. + @since(version = 0.2.0) + write-zeroes: func( + /// The number of zero-bytes to write + len: u64 + ) -> 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. + /// + /// Functionality is equivelant to `blocking-write-and-flush` with + /// contents given as a list of len containing only zeroes. + @since(version = 0.2.0) + blocking-write-zeroes-and-flush: func( + /// The number of zero-bytes to write + len: u64 + ) -> result<_, stream-error>; + + /// Read from one stream and write to another. + /// + /// The behavior of splice is equivalent 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`. + @since(version = 0.2.0) + splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + + /// 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`. + @since(version = 0.2.0) + blocking-splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + } +} diff --git a/proposals/filesystem/wit/deps/io/world.wit b/proposals/filesystem/wit/deps/io/world.wit new file mode 100644 index 000000000..1cc3fce12 --- /dev/null +++ b/proposals/filesystem/wit/deps/io/world.wit @@ -0,0 +1,10 @@ +package wasi:io@0.2.8; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import streams; + + @since(version = 0.2.0) + import poll; +} diff --git a/proposals/filesystem/wit/preopens.wit b/proposals/filesystem/wit/preopens.wit new file mode 100644 index 000000000..0d2cca65d --- /dev/null +++ b/proposals/filesystem/wit/preopens.wit @@ -0,0 +1,11 @@ +package wasi:filesystem@0.2.8; + +@since(version = 0.2.0) +interface preopens { + @since(version = 0.2.0) + use types.{descriptor}; + + /// Return the set of preopened directories, and their paths. + @since(version = 0.2.0) + get-directories: func() -> list>; +} diff --git a/proposals/filesystem/wit/types.wit b/proposals/filesystem/wit/types.wit new file mode 100644 index 000000000..ac68f88af --- /dev/null +++ b/proposals/filesystem/wit/types.wit @@ -0,0 +1,676 @@ +package wasi:filesystem@0.2.8; +/// 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 +@since(version = 0.2.0) +interface types { + @since(version = 0.2.0) + use wasi:io/streams@0.2.8.{input-stream, output-stream, error}; + @since(version = 0.2.0) + use wasi:clocks/wall-clock@0.2.8.{datetime}; + + /// File size or length of a region within a file. + @since(version = 0.2.0) + type filesize = u64; + + /// The type of a filesystem object referenced by a descriptor. + /// + /// Note: This was called `filetype` in earlier versions of WASI. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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 integrity + /// 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, + } + + /// File attributes. + /// + /// Note: This was called `filestat` in earlier versions of WASI. + @since(version = 0.2.0) + 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, + } + + /// Flags determining the method of how paths are resolved. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + type link-count = u64; + + /// When setting a timestamp, this gives the value to set it to. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + resource descriptor { + /// 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. + @since(version = 0.2.0) + read-via-stream: func( + /// The offset within the file at which to start reading. + 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. + @since(version = 0.2.0) + write-via-stream: func( + /// The offset within the file at which to start writing. + offset: filesize, + ) -> result; + + /// 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 POSIX. + @since(version = 0.2.0) + append-via-stream: func() -> result; + + /// Provide file advisory information on a descriptor. + /// + /// This is similar to `posix_fadvise` in POSIX. + @since(version = 0.2.0) + advise: func( + /// The offset within the file to which the advisory applies. + offset: filesize, + /// The length of the region to which the advisory applies. + length: filesize, + /// The advice. + advice: advice + ) -> 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. + @since(version = 0.2.0) + sync-data: func() -> 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + get-type: func() -> result; + + /// 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + set-times: func( + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + read: func( + /// The maximum number of bytes to read. + length: filesize, + /// The offset within the file at which to read. + offset: filesize, + ) -> result, bool>, 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. + @since(version = 0.2.0) + write: func( + /// Data to write + buffer: list, + /// The offset within the file at which to write. + offset: filesize, + ) -> result; + + /// 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. + @since(version = 0.2.0) + read-directory: func() -> result; + + /// 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. + @since(version = 0.2.0) + sync: func() -> result<_, error-code>; + + /// Create a directory. + /// + /// Note: This is similar to `mkdirat` in POSIX. + @since(version = 0.2.0) + create-directory-at: func( + /// The relative path at which to create the directory. + path: string, + ) -> 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + stat-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + + /// 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. + @since(version = 0.2.0) + set-times-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to operate on. + path: string, + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, error-code>; + + /// Create a hard link. + /// + /// Fails with `error-code::no-entry` if the old path does not exist, + /// with `error-code::exist` if the new path already exists, and + /// `error-code::not-permitted` if the old path is not a file. + /// + /// Note: This is similar to `linkat` in POSIX. + @since(version = 0.2.0) + link-at: func( + /// Flags determining the method of how the path is resolved. + old-path-flags: path-flags, + /// The relative source path from which to link. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path at which to create the hard link. + new-path: string, + ) -> result<_, error-code>; + + /// Open a file or directory. + /// + /// 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. + @since(version = 0.2.0) + open-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the object to open. + path: string, + /// The method by which to open the file. + open-flags: open-flags, + /// Flags to use for the resulting descriptor. + %flags: descriptor-flags, + ) -> 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. + @since(version = 0.2.0) + readlink-at: func( + /// The relative path of the symbolic link from which to read. + 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. + @since(version = 0.2.0) + remove-directory-at: func( + /// The relative path to a directory to remove. + path: string, + ) -> result<_, error-code>; + + /// Rename a filesystem object. + /// + /// Note: This is similar to `renameat` in POSIX. + @since(version = 0.2.0) + rename-at: func( + /// The relative source path of the file or directory to rename. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path to which to rename the file or directory. + new-path: string, + ) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + symlink-at: func( + /// The contents of the symbolic link. + old-path: string, + /// The relative destination path at which to create the symbolic link. + new-path: string, + ) -> 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. + @since(version = 0.2.0) + unlink-file-at: func( + /// The relative path to a file to unlink. + path: string, + ) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + is-same-object: func(other: borrow) -> bool; + + /// 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 encouraged 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. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + metadata-hash-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + } + + /// A stream of directory entries. + @since(version = 0.2.0) + resource directory-entry-stream { + /// Read a single directory entry from a `directory-entry-stream`. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + filesystem-error-code: func(err: borrow) -> option; +} diff --git a/proposals/filesystem/wit/world.wit b/proposals/filesystem/wit/world.wit new file mode 100644 index 000000000..7daf06758 --- /dev/null +++ b/proposals/filesystem/wit/world.wit @@ -0,0 +1,9 @@ +package wasi:filesystem@0.2.8; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import types; + @since(version = 0.2.0) + import preopens; +} diff --git a/proposals/http/LICENSE.md b/proposals/http/LICENSE.md new file mode 100644 index 000000000..c1c3b9443 --- /dev/null +++ b/proposals/http/LICENSE.md @@ -0,0 +1,8 @@ +Copyright © 2019-2024 the Contributors to the WASI Specification, published +by the [WebAssembly Community Group][cg] under the +[W3C Community Contributor License Agreement (CLA)][cla]. A human-readable +[summary][summary] is available. + +[cg]: https://www.w3.org/community/webassembly/ +[cla]: https://www.w3.org/community/about/agreements/cla/ +[summary]: https://www.w3.org/community/about/agreements/cla-deed/ diff --git a/proposals/http/README.md b/proposals/http/README.md new file mode 100644 index 000000000..bfe0572a4 --- /dev/null +++ b/proposals/http/README.md @@ -0,0 +1,98 @@ +# WASI HTTP + +A proposed [WebAssembly System Interface](https://github.com/WebAssembly/WASI) API. + +### Current Phase + +wasi-http is currently in [Phase 3](https://github.com/WebAssembly/WASI/blob/main/Proposals.md#phase-3---implementation-phase-cg--wg) + +### Champions + +* Piotr Sikora +* Jiaxiao Zhou +* Dan Chiarlone +* David Justice +* Luke Wagner + +### Portability Criteria + +WASI-http must have at least two complete independent implementations +demonstrating embeddability in a production HTTP server context. + +### Introduction + +The WASI-http proposal defines a collection of [interfaces] for sending and +receiving HTTP requests and responses. WASI-http additionally defines a +[world], `wasi:http/proxy`, that circumscribes a minimal execution environment +for wasm HTTP [proxies]. + +[Interfaces]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/WIT.md#wit-interfaces +[World]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/WIT.md#wit-worlds +[Proxies]: https://httpwg.org/http-core/draft-ietf-httpbis-semantics-latest.html#intermediaries + +### Goals + +The proposal intends to abstract over HTTP version and transport protocol +choices (such as HTTP/1.1, HTTP/2 or HTTP/3) by mapping directly to the +abstract [HTTP Semantics], allowing hosts to (mostly) transparently use any of +these. + +The `wasi:http/proxy` world is meant to be implementable by a wide variety of +hosts including Web [service workers], forward- and reverse-[proxies] and +[origin servers] by requiring a minimal set of additional runtime support. + +The `wasi:http/proxy` world is meant to support flexible auto-scaling +("serverless") execution by moving the core `accept()` loop into the host and +allowing the host to dynamically spin up wasm instances in response to arriving +requests. + +The `wasi:http/proxy` world is meant to allow the chaining of HTTP +intermediaries to be implemented directly in terms of [Component Model] linking. +(Fully realizing this goal will require additional features only available in +the [Preview 3] timeframe.) + +[HTTP Semantics]: https://httpwg.org/http-core/draft-ietf-httpbis-semantics-latest.html +[Service Workers]: https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API +[Origin Servers]: https://httpwg.org/http-core/draft-ietf-httpbis-semantics-latest.html#origin.server +[Component Model]: https://github.com/WebAssembly/component-model/ +[Preview 3]: https://github.com/WebAssembly/WASI/blob/main/docs/WitInWasi.md#streams + +### Non-goals + +WASI-http does not intend to define a more fully-featured cloud execution +environment (for this, see the [wasi-cloud-core] proposal). + +[wasi-cloud-core]: https://github.com/WebAssembly/wasi-cloud-core + +### API walk-through + +The proposal can be understood by first reading the comments of [`proxy.wit`], +then [`handler.wit`] and finally [`types.wit`]. + +[`proxy.wit`]: ./wit/proxy.wit +[`handler.wit`]: ./wit/handler.wit +[`types.wit`]: ./wit/types.wit + +### Working with the WIT + +Bindings can be generated from the `wit` directory via: +``` +wit-bindgen c wit/ --world proxy +``` +and can be validated and otherwise manipulated via: +``` +wasm-tools component wit wit/ ... +``` + +The `wit/deps` directory contains a live snapshot of the contents of several +other WASI proposals upon which this proposal depends. It is automatically +updated by running [`wit-deps update`](https://crates.io/crates/wit-deps-cli) +in the root directory, which fetches the live contents of the `main` branch of +each proposal. As things stabilize, `wit/deps.toml` will be updated to refer to +versioned releases. + +### References & acknowledgements + +* This proposal was seeded by and developed in consultation with + [proxy-wasm](https://github.com/proxy-wasm/spec). + diff --git a/proposals/http/imports.md b/proposals/http/imports.md new file mode 100644 index 000000000..b099e2edf --- /dev/null +++ b/proposals/http/imports.md @@ -0,0 +1,1541 @@ +

World imports

+

The wasi:http/imports world imports all the APIs for HTTP proxies. +It is intended to be included in other worlds.

+ +

Import interface wasi:io/poll@0.2.8

+

A poll API intended to let users wait for I/O events on multiple handles +at once.

+
+

Types

+

resource pollable

+

pollable represents a single I/O event which may be ready, or not.

+

Functions

+

[method]pollable.ready: func

+

Return the readiness of a pollable. This function never blocks.

+

Returns true when the pollable is ready, and false otherwise.

+
Params
+ +
Return values
+
    +
  • bool
  • +
+

[method]pollable.block: func

+

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.

+
Params
+ +

poll: func

+

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<u32> contains one or more indices of handles in the +argument list that is ready for I/O.

+

This function traps if either:

+
    +
  • the list is empty, or:
  • +
  • the list contains more elements than can be indexed with a u32 value.
  • +
+

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 ready for I/O.

+
Params
+ +
Return values
+
    +
  • list<u32>
  • +
+

Import interface wasi:clocks/monotonic-clock@0.2.8

+

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.

+
+

Types

+

type pollable

+

pollable

+

+#### `type instant` +`u64` +

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 duration

+

u64

+

A duration of time, in nanoseconds. +


+

Functions

+

now: func

+

Read the current value of the clock.

+

The clock is monotonic, therefore calling this function repeatedly will +produce a sequence of non-decreasing values.

+

For completeness, this function traps if it's not possible to represent +the value of the clock in an instant. Consequently, implementations +should ensure that the starting time is low enough to avoid the +possibility of overflow in practice.

+
Return values
+ +

resolution: func

+

Query the resolution of the clock. Returns the duration of time +corresponding to a clock tick.

+
Return values
+ +

subscribe-instant: func

+

Create a pollable which will resolve once the specified instant +has occurred.

+
Params
+ +
Return values
+ +

subscribe-duration: func

+

Create a pollable that will resolve after the specified duration has +elapsed from the time this function is invoked.

+
Params
+ +
Return values
+ +

Import interface wasi:clocks/wall-clock@0.2.8

+

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.

+
+

Types

+

record datetime

+

A time and date in seconds plus nanoseconds.

+
Record Fields
+
    +
  • seconds: u64
  • +
  • nanoseconds: u32
  • +
+
+

Functions

+

now: func

+

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.

+
Return values
+ +

resolution: func

+

Query the resolution of the clock.

+

The nanoseconds field of the output is always less than 1000000000.

+
Return values
+ +

Import interface wasi:random/random@0.2.8

+

WASI Random is a random data API.

+

It is intended to be portable at least between Unix-family platforms and +Windows.

+
+

Functions

+

get-random-bytes: func

+

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.

+
Params
+
    +
  • len: u64
  • +
+
Return values
+
    +
  • list<u8>
  • +
+

get-random-u64: func

+

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.

+
Return values
+
    +
  • u64
  • +
+

Import interface wasi:io/error@0.2.8

+
+

Types

+

resource 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 +offer functions to "downcast" this error into more specific types. For example, +errors returned from streams derived from filesystem types can be described using +the filesystem's own error-code type. This is done using the function +wasi:filesystem/types/filesystem-error-code, which takes a borrow<error> +parameter and returns an option<wasi:filesystem/types/error-code>.

+

The set of functions which can "downcast" an error into a more +concrete type is open.

+

Functions

+

[method]error.to-debug-string: func

+

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.

+
Params
+ +
Return values
+
    +
  • string
  • +
+

Import interface wasi:io/streams@0.2.8

+

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.

+
+

Types

+

type error

+

error

+

+#### `type pollable` +[`pollable`](#pollable) +

+#### `variant stream-error` +

An error for input-stream and output-stream operations.

+
Variant Cases
+
    +
  • +

    last-operation-failed: own<error>

    +

    The last operation (a write or flush) failed before completion. +

    More information is available in the error payload.

    +

    After this, the stream will be closed. All future operations return +stream-error::closed.

    +
  • +
  • +

    closed

    +

    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. +

  • +
+

resource input-stream

+

An input bytestream.

+

input-streams 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 output-stream

+

An output bytestream.

+

output-streams 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.

+

Dropping an output-stream while there's still an active write in +progress may result in the data being lost. Before dropping the stream, +be sure to fully flush your writes.

+

Functions

+

[method]input-stream.read: func

+

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.

+
Params
+ +
Return values
+ +

[method]input-stream.blocking-read: func

+

Read bytes from a stream, after blocking until at least one byte can +be read. Except for blocking, behavior is identical to read.

+
Params
+ +
Return values
+ +

[method]input-stream.skip: func

+

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.

+
Params
+ +
Return values
+ +

[method]input-stream.blocking-skip: func

+

Skip bytes from a stream, after blocking until at least one byte +can be skipped. Except for blocking behavior, identical to skip.

+
Params
+ +
Return values
+ +

[method]input-stream.subscribe: func

+

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 pollables created with this function are dropped.

+
Params
+ +
Return values
+ +

[method]output-stream.check-write: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.write: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-write-and-flush: func

+

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.

+

Returns success when all of the contents written are successfully +flushed to output. If an error occurs at any point before all +contents are successfully flushed, that error is returned as soon as +possible. If writing and flushing the complete contents causes the +stream to become closed, this call should return success, and +subsequent calls to check-write or other interfaces should return +stream-error::closed.

+
Params
+ +
Return values
+ +

[method]output-stream.flush: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-flush: func

+

Request to flush buffered output, and block until flush completes +and stream is ready for writing again.

+
Params
+ +
Return values
+ +

[method]output-stream.subscribe: func

+

Create a pollable which will resolve once the output-stream +is ready for more writing, or an error has occurred. 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 pollables created with this function are dropped.

+
Params
+ +
Return values
+ +

[method]output-stream.write-zeroes: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-write-zeroes-and-flush: func

+

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.

+

Functionality is equivelant to blocking-write-and-flush with +contents given as a list of len containing only zeroes.

+
Params
+ +
Return values
+ +

[method]output-stream.splice: func

+

Read from one stream and write to another.

+

The behavior of splice is equivalent to:

+
    +
  1. calling check-write on the output-stream
  2. +
  3. calling read on the input-stream with the smaller of the +check-write permitted length and the len provided to splice
  4. +
  5. calling write on the output-stream with that read data.
  6. +
+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-splice: func

+

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.

+
Params
+ +
Return values
+ +

Import interface wasi:cli/stdout@0.2.8

+
+

Types

+

type output-stream

+

output-stream

+

+---- +

Functions

+

get-stdout: func

+
Return values
+ +

Import interface wasi:cli/stderr@0.2.8

+
+

Types

+

type output-stream

+

output-stream

+

+---- +

Functions

+

get-stderr: func

+
Return values
+ +

Import interface wasi:cli/stdin@0.2.8

+
+

Types

+

type input-stream

+

input-stream

+

+---- +

Functions

+

get-stdin: func

+
Return values
+ +

Import interface wasi:http/types@0.2.8

+

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.

+
+

Types

+

type duration

+

duration

+

+#### `type input-stream` +[`input-stream`](#input_stream) +

+#### `type output-stream` +[`output-stream`](#output_stream) +

+#### `type io-error` +[`error`](#error) +

+#### `type pollable` +[`pollable`](#pollable) +

+#### `variant method` +

This type corresponds to HTTP standard Methods.

+
Variant Cases
+
    +
  • get
  • +
  • head
  • +
  • post
  • +
  • put
  • +
  • delete
  • +
  • connect
  • +
  • options
  • +
  • trace
  • +
  • patch
  • +
  • other: string
  • +
+

variant scheme

+

This type corresponds to HTTP standard Related Schemes.

+
Variant Cases
+
    +
  • HTTP
  • +
  • HTTPS
  • +
  • other: string
  • +
+

record DNS-error-payload

+

Defines the case payload type for DNS-error above:

+
Record Fields
+
    +
  • rcode: option<string>
  • +
  • info-code: option<u16>
  • +
+

record TLS-alert-received-payload

+

Defines the case payload type for TLS-alert-received above:

+
Record Fields
+
    +
  • alert-id: option<u8>
  • +
  • alert-message: option<string>
  • +
+

record field-size-payload

+

Defines the case payload type for HTTP-response-{header,trailer}-size above:

+
Record Fields
+
    +
  • field-name: option<string>
  • +
  • field-size: option<u32>
  • +
+

variant error-code

+

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 Cases
+
    +
  • 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<u64>
  • +
  • HTTP-request-method-invalid
  • +
  • HTTP-request-URI-invalid
  • +
  • HTTP-request-URI-too-long
  • +
  • HTTP-request-header-section-size: option<u32>
  • +
  • HTTP-request-header-size: option<field-size-payload>
  • +
  • HTTP-request-trailer-section-size: option<u32>
  • +
  • HTTP-request-trailer-size: field-size-payload
  • +
  • HTTP-response-incomplete
  • +
  • HTTP-response-header-section-size: option<u32>
  • +
  • HTTP-response-header-size: field-size-payload
  • +
  • HTTP-response-body-size: option<u64>
  • +
  • HTTP-response-trailer-section-size: option<u32>
  • +
  • HTTP-response-trailer-size: field-size-payload
  • +
  • HTTP-response-transfer-coding: option<string>
  • +
  • HTTP-response-content-coding: option<string>
  • +
  • HTTP-response-timeout
  • +
  • HTTP-upgrade-failed
  • +
  • HTTP-protocol-error
  • +
  • loop-detected
  • +
  • configuration-error
  • +
  • internal-error: option<string>

    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. +

  • +
+

variant header-error

+

This type enumerates the different kinds of errors that may occur when +setting or appending to a fields resource.

+
Variant Cases
+
    +
  • +

    invalid-syntax

    +

    This error indicates that a `field-name` or `field-value` was +syntactically invalid when used with an operation that sets headers in a +`fields`. +

  • +
  • +

    forbidden

    +

    This error indicates that a forbidden `field-name` was used when trying +to set a header in a `fields`. +

  • +
  • +

    immutable

    +

    This error indicates that the operation on the `fields` was not +permitted because the fields are immutable. +

  • +
+

type field-key

+

string

+

Field keys are always strings. +

Field keys should always be treated as case insensitive by the fields +resource for the purposes of equality checking.

+

Deprecation

+

This type has been deprecated in favor of the field-name type.

+

type field-name

+

field-key

+

Field names are always strings. +

Field names should always be treated as case insensitive by the fields +resource for the purposes of equality checking.

+

type field-value

+

field-value

+

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. +

resource fields

+

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 +immutable. In an immutable fields, the set, append, and delete +operations will fail with header-error.immutable.

+

type headers

+

fields

+

Headers is an alias for Fields. +

type trailers

+

fields

+

Trailers is an alias for Fields. +

resource incoming-request

+

Represents an incoming HTTP Request.

+

resource outgoing-request

+

Represents an outgoing HTTP Request.

+

resource request-options

+

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 response-outparam

+

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.

+

type status-code

+

u16

+

This type corresponds to the HTTP standard Status Code. +

resource incoming-response

+

Represents an incoming HTTP Response.

+

resource incoming-body

+

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 future-trailers

+

Represents a future which may eventually 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 outgoing-response

+

Represents an outgoing HTTP Response.

+

resource outgoing-body

+

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 occurred. The implementation should propagate 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 future-incoming-response

+

Represents a future which may eventually 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.

+

Functions

+

http-error-code: func

+

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.

+
Params
+ +
Return values
+ +

[constructor]fields: func

+

Construct an empty HTTP Fields.

+

The resulting fields is mutable.

+
Return values
+ +

[static]fields.from-list: func

+

Construct an HTTP Fields.

+

The resulting fields is mutable.

+

The list represents each name-value pair in the Fields. Names +which have multiple values are represented by multiple entries in this +list with the same name.

+

The tuple is a pair of the field name, represented as a string, and +Value, represented as a list of bytes.

+

An error result will be returned if any field-name or field-value is +syntactically invalid, or if a field is forbidden.

+
Params
+ +
Return values
+ +

[method]fields.get: func

+

Get all of the values corresponding to a name. If the name is not present +in this fields or is syntactically invalid, an empty list is returned. +However, if the name is present but empty, this is represented by a list +with one or more empty field-values present.

+
Params
+ +
Return values
+ +

[method]fields.has: func

+

Returns true when the name is present in this fields. If the name is +syntactically invalid, false is returned.

+
Params
+ +
Return values
+
    +
  • bool
  • +
+

[method]fields.set: func

+

Set all of the values for a name. Clears any existing values for that +name, if they have been set.

+

Fails with header-error.immutable if the fields are immutable.

+

Fails with header-error.invalid-syntax if the field-name or any of +the field-values are syntactically invalid.

+
Params
+ +
Return values
+ +

[method]fields.delete: func

+

Delete all values for a name. Does nothing if no values for the name +exist.

+

Fails with header-error.immutable if the fields are immutable.

+

Fails with header-error.invalid-syntax if the field-name is +syntactically invalid.

+
Params
+ +
Return values
+ +

[method]fields.append: func

+

Append a value for a name. Does not change or delete any existing +values for that name.

+

Fails with header-error.immutable if the fields are immutable.

+

Fails with header-error.invalid-syntax if the field-name or +field-value are syntactically invalid.

+
Params
+ +
Return values
+ +

[method]fields.entries: func

+

Retrieve the full set of names and values in the Fields. Like the +constructor, the list represents each name-value pair.

+

The outer list represents each name-value pair in the Fields. Names +which have multiple values are represented by multiple entries in this +list with the same name.

+

The names and values are always returned in the original casing and in +the order in which they will be serialized for transport.

+
Params
+ +
Return values
+ +

[method]fields.clone: func

+

Make a deep copy of the Fields. Equivalent in behavior to calling the +fields constructor on the return value of entries. The resulting +fields is mutable.

+
Params
+ +
Return values
+ +

[method]incoming-request.method: func

+

Returns the method of the incoming request.

+
Params
+ +
Return values
+ +

[method]incoming-request.path-with-query: func

+

Returns the path with query parameters from the request, as a string.

+
Params
+ +
Return values
+
    +
  • option<string>
  • +
+

[method]incoming-request.scheme: func

+

Returns the protocol scheme from the request.

+
Params
+ +
Return values
+ +

[method]incoming-request.authority: func

+

Returns the authority of the Request's target URI, if present.

+
Params
+ +
Return values
+
    +
  • option<string>
  • +
+

[method]incoming-request.headers: func

+

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.

+
Params
+ +
Return values
+ +

[method]incoming-request.consume: func

+

Gives the incoming-body associated with this request. Will only +return success at most once, and subsequent calls will return error.

+
Params
+ +
Return values
+ +

[constructor]outgoing-request: func

+

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.

+
Params
+ +
Return values
+ +

[method]outgoing-request.body: func

+

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.

+
Params
+ +
Return values
+ +

[method]outgoing-request.method: func

+

Get the Method for the Request.

+
Params
+ +
Return values
+ +

[method]outgoing-request.set-method: func

+

Set the Method for the Request. Fails if the string present in a +method.other argument is not a syntactically valid method.

+
Params
+ +
Return values
+
    +
  • result
  • +
+

[method]outgoing-request.path-with-query: func

+

Get the combination of the HTTP Path and Query for the Request. +When none, this represents an empty Path and empty Query.

+
Params
+ +
Return values
+
    +
  • option<string>
  • +
+

[method]outgoing-request.set-path-with-query: func

+

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.

+
Params
+ +
Return values
+
    +
  • result
  • +
+

[method]outgoing-request.scheme: func

+

Get the HTTP Related Scheme for the Request. When none, the +implementation may choose an appropriate default scheme.

+
Params
+ +
Return values
+ +

[method]outgoing-request.set-scheme: func

+

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.

+
Params
+ +
Return values
+
    +
  • result
  • +
+

[method]outgoing-request.authority: func

+

Get the authority of the Request's target URI. 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.

+
Params
+ +
Return values
+
    +
  • option<string>
  • +
+

[method]outgoing-request.set-authority: func

+

Set the authority of the Request's target URI. 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.

+
Params
+ +
Return values
+
    +
  • result
  • +
+

[method]outgoing-request.headers: func

+

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 transferred to +another component by e.g. outgoing-handler.handle.

+
Params
+ +
Return values
+ +

[constructor]request-options: func

+

Construct a default request-options value.

+
Return values
+ +

[method]request-options.connect-timeout: func

+

The timeout for the initial connect to the HTTP Server.

+
Params
+ +
Return values
+ +

[method]request-options.set-connect-timeout: func

+

Set the timeout for the initial connect to the HTTP Server. An error +return value indicates that this timeout is not supported.

+
Params
+ +
Return values
+
    +
  • result
  • +
+

[method]request-options.first-byte-timeout: func

+

The timeout for receiving the first byte of the Response body.

+
Params
+ +
Return values
+ +

[method]request-options.set-first-byte-timeout: func

+

Set the timeout for receiving the first byte of the Response body. An +error return value indicates that this timeout is not supported.

+
Params
+ +
Return values
+
    +
  • result
  • +
+

[method]request-options.between-bytes-timeout: func

+

The timeout for receiving subsequent chunks of bytes in the Response +body stream.

+
Params
+ +
Return values
+ +

[method]request-options.set-between-bytes-timeout: func

+

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.

+
Params
+ +
Return values
+
    +
  • result
  • +
+

[method]response-outparam.send-informational: func

+

Send an HTTP 1xx response.

+

Unlike response-outparam.set, this does not consume the +response-outparam, allowing the guest to send an arbitrary number of +informational responses before sending the final response using +response-outparam.set.

+

This will return an HTTP-protocol-error if status is not in the +range [100-199], or an internal-error if the implementation does not +support informational responses.

+
Params
+ +
Return values
+ +

[static]response-outparam.set: func

+

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.

+
Params
+ +

[method]incoming-response.status: func

+

Returns the status code from the incoming response.

+
Params
+ +
Return values
+ +

[method]incoming-response.headers: func

+

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.

+
Params
+ +
Return values
+ +

[method]incoming-response.consume: func

+

Returns the incoming body. May be called at most once. Returns error +if called additional times.

+
Params
+ +
Return values
+ +

[method]incoming-body.stream: func

+

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.

+
Params
+ +
Return values
+ +

[static]incoming-body.finish: func

+

Takes ownership of incoming-body, and returns a future-trailers. +This function will trap if the input-stream child is still alive.

+
Params
+ +
Return values
+ +

[method]future-trailers.subscribe: func

+

Returns a pollable which becomes ready when either the trailers have +been received, or an error has occurred. When this pollable is ready, +the get method will return some.

+
Params
+ +
Return values
+ +

[method]future-trailers.get: func

+

Returns the contents of the trailers, or an error which occurred, +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 occurred 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.

+
Params
+ +
Return values
+ +

[constructor]outgoing-response: func

+

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.
  • +
+
Params
+ +
Return values
+ +

[method]outgoing-response.status-code: func

+

Get the HTTP Status Code for the Response.

+
Params
+ +
Return values
+ +

[method]outgoing-response.set-status-code: func

+

Set the HTTP Status Code for the Response. Fails if the status-code +given is not a valid http status code.

+
Params
+ +
Return values
+
    +
  • result
  • +
+

[method]outgoing-response.headers: func

+

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 transferred to +another component by e.g. outgoing-handler.handle.

+
Params
+ +
Return values
+ +

[method]outgoing-response.body: func

+

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.

+
Params
+ +
Return values
+ +

[method]outgoing-body.write: func

+

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.

+
Params
+ +
Return values
+ +

[static]outgoing-body.finish: func

+

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.

+
Params
+ +
Return values
+ +

[method]future-incoming-response.subscribe: func

+

Returns a pollable which becomes ready when either the Response has +been received, or an error has occurred. When this pollable is ready, +the get method will return some.

+
Params
+ +
Return values
+ +

[method]future-incoming-response.get: func

+

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 received successfully, or that an error +occurred. Errors may also occur while consuming the response body, +but those will be reported by the incoming-body and its +output-stream child.

+
Params
+ +
Return values
+ +

Import interface wasi:http/outgoing-handler@0.2.8

+

This interface defines a handler of outgoing HTTP Requests. It should be +imported by components which wish to make HTTP Requests.

+
+

Types

+

type outgoing-request

+

outgoing-request

+

+#### `type request-options` +[`request-options`](#request_options) +

+#### `type future-incoming-response` +[`future-incoming-response`](#future_incoming_response) +

+#### `type error-code` +[`error-code`](#error_code) +

+---- +

Functions

+

handle: func

+

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.

+
Params
+ +
Return values
+ diff --git a/proposals/http/proxy.md b/proposals/http/proxy.md new file mode 100644 index 000000000..aed35c1a3 --- /dev/null +++ b/proposals/http/proxy.md @@ -0,0 +1,1574 @@ +

World proxy

+

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.

+ +

Import interface wasi:io/poll@0.2.8

+

A poll API intended to let users wait for I/O events on multiple handles +at once.

+
+

Types

+

resource pollable

+

pollable represents a single I/O event which may be ready, or not.

+

Functions

+

[method]pollable.ready: func

+

Return the readiness of a pollable. This function never blocks.

+

Returns true when the pollable is ready, and false otherwise.

+
Params
+ +
Return values
+
    +
  • bool
  • +
+

[method]pollable.block: func

+

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.

+
Params
+ +

poll: func

+

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<u32> contains one or more indices of handles in the +argument list that is ready for I/O.

+

This function traps if either:

+
    +
  • the list is empty, or:
  • +
  • the list contains more elements than can be indexed with a u32 value.
  • +
+

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 ready for I/O.

+
Params
+ +
Return values
+
    +
  • list<u32>
  • +
+

Import interface wasi:clocks/monotonic-clock@0.2.8

+

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.

+
+

Types

+

type pollable

+

pollable

+

+#### `type instant` +`u64` +

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 duration

+

u64

+

A duration of time, in nanoseconds. +


+

Functions

+

now: func

+

Read the current value of the clock.

+

The clock is monotonic, therefore calling this function repeatedly will +produce a sequence of non-decreasing values.

+

For completeness, this function traps if it's not possible to represent +the value of the clock in an instant. Consequently, implementations +should ensure that the starting time is low enough to avoid the +possibility of overflow in practice.

+
Return values
+ +

resolution: func

+

Query the resolution of the clock. Returns the duration of time +corresponding to a clock tick.

+
Return values
+ +

subscribe-instant: func

+

Create a pollable which will resolve once the specified instant +has occurred.

+
Params
+ +
Return values
+ +

subscribe-duration: func

+

Create a pollable that will resolve after the specified duration has +elapsed from the time this function is invoked.

+
Params
+ +
Return values
+ +

Import interface wasi:clocks/wall-clock@0.2.8

+

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.

+
+

Types

+

record datetime

+

A time and date in seconds plus nanoseconds.

+
Record Fields
+
    +
  • seconds: u64
  • +
  • nanoseconds: u32
  • +
+
+

Functions

+

now: func

+

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.

+
Return values
+ +

resolution: func

+

Query the resolution of the clock.

+

The nanoseconds field of the output is always less than 1000000000.

+
Return values
+ +

Import interface wasi:random/random@0.2.8

+

WASI Random is a random data API.

+

It is intended to be portable at least between Unix-family platforms and +Windows.

+
+

Functions

+

get-random-bytes: func

+

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.

+
Params
+
    +
  • len: u64
  • +
+
Return values
+
    +
  • list<u8>
  • +
+

get-random-u64: func

+

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.

+
Return values
+
    +
  • u64
  • +
+

Import interface wasi:io/error@0.2.8

+
+

Types

+

resource 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 +offer functions to "downcast" this error into more specific types. For example, +errors returned from streams derived from filesystem types can be described using +the filesystem's own error-code type. This is done using the function +wasi:filesystem/types/filesystem-error-code, which takes a borrow<error> +parameter and returns an option<wasi:filesystem/types/error-code>.

+

The set of functions which can "downcast" an error into a more +concrete type is open.

+

Functions

+

[method]error.to-debug-string: func

+

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.

+
Params
+ +
Return values
+
    +
  • string
  • +
+

Import interface wasi:io/streams@0.2.8

+

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.

+
+

Types

+

type error

+

error

+

+#### `type pollable` +[`pollable`](#pollable) +

+#### `variant stream-error` +

An error for input-stream and output-stream operations.

+
Variant Cases
+
    +
  • +

    last-operation-failed: own<error>

    +

    The last operation (a write or flush) failed before completion. +

    More information is available in the error payload.

    +

    After this, the stream will be closed. All future operations return +stream-error::closed.

    +
  • +
  • +

    closed

    +

    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. +

  • +
+

resource input-stream

+

An input bytestream.

+

input-streams 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 output-stream

+

An output bytestream.

+

output-streams 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.

+

Dropping an output-stream while there's still an active write in +progress may result in the data being lost. Before dropping the stream, +be sure to fully flush your writes.

+

Functions

+

[method]input-stream.read: func

+

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.

+
Params
+ +
Return values
+ +

[method]input-stream.blocking-read: func

+

Read bytes from a stream, after blocking until at least one byte can +be read. Except for blocking, behavior is identical to read.

+
Params
+ +
Return values
+ +

[method]input-stream.skip: func

+

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.

+
Params
+ +
Return values
+ +

[method]input-stream.blocking-skip: func

+

Skip bytes from a stream, after blocking until at least one byte +can be skipped. Except for blocking behavior, identical to skip.

+
Params
+ +
Return values
+ +

[method]input-stream.subscribe: func

+

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 pollables created with this function are dropped.

+
Params
+ +
Return values
+ +

[method]output-stream.check-write: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.write: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-write-and-flush: func

+

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.

+

Returns success when all of the contents written are successfully +flushed to output. If an error occurs at any point before all +contents are successfully flushed, that error is returned as soon as +possible. If writing and flushing the complete contents causes the +stream to become closed, this call should return success, and +subsequent calls to check-write or other interfaces should return +stream-error::closed.

+
Params
+ +
Return values
+ +

[method]output-stream.flush: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-flush: func

+

Request to flush buffered output, and block until flush completes +and stream is ready for writing again.

+
Params
+ +
Return values
+ +

[method]output-stream.subscribe: func

+

Create a pollable which will resolve once the output-stream +is ready for more writing, or an error has occurred. 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 pollables created with this function are dropped.

+
Params
+ +
Return values
+ +

[method]output-stream.write-zeroes: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-write-zeroes-and-flush: func

+

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.

+

Functionality is equivelant to blocking-write-and-flush with +contents given as a list of len containing only zeroes.

+
Params
+ +
Return values
+ +

[method]output-stream.splice: func

+

Read from one stream and write to another.

+

The behavior of splice is equivalent to:

+
    +
  1. calling check-write on the output-stream
  2. +
  3. calling read on the input-stream with the smaller of the +check-write permitted length and the len provided to splice
  4. +
  5. calling write on the output-stream with that read data.
  6. +
+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-splice: func

+

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.

+
Params
+ +
Return values
+ +

Import interface wasi:cli/stdout@0.2.8

+
+

Types

+

type output-stream

+

output-stream

+

+---- +

Functions

+

get-stdout: func

+
Return values
+ +

Import interface wasi:cli/stderr@0.2.8

+
+

Types

+

type output-stream

+

output-stream

+

+---- +

Functions

+

get-stderr: func

+
Return values
+ +

Import interface wasi:cli/stdin@0.2.8

+
+

Types

+

type input-stream

+

input-stream

+

+---- +

Functions

+

get-stdin: func

+
Return values
+ +

Import interface wasi:http/types@0.2.8

+

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.

+
+

Types

+

type duration

+

duration

+

+#### `type input-stream` +[`input-stream`](#input_stream) +

+#### `type output-stream` +[`output-stream`](#output_stream) +

+#### `type io-error` +[`error`](#error) +

+#### `type pollable` +[`pollable`](#pollable) +

+#### `variant method` +

This type corresponds to HTTP standard Methods.

+
Variant Cases
+
    +
  • get
  • +
  • head
  • +
  • post
  • +
  • put
  • +
  • delete
  • +
  • connect
  • +
  • options
  • +
  • trace
  • +
  • patch
  • +
  • other: string
  • +
+

variant scheme

+

This type corresponds to HTTP standard Related Schemes.

+
Variant Cases
+
    +
  • HTTP
  • +
  • HTTPS
  • +
  • other: string
  • +
+

record DNS-error-payload

+

Defines the case payload type for DNS-error above:

+
Record Fields
+
    +
  • rcode: option<string>
  • +
  • info-code: option<u16>
  • +
+

record TLS-alert-received-payload

+

Defines the case payload type for TLS-alert-received above:

+
Record Fields
+
    +
  • alert-id: option<u8>
  • +
  • alert-message: option<string>
  • +
+

record field-size-payload

+

Defines the case payload type for HTTP-response-{header,trailer}-size above:

+
Record Fields
+
    +
  • field-name: option<string>
  • +
  • field-size: option<u32>
  • +
+

variant error-code

+

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 Cases
+
    +
  • 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<u64>
  • +
  • HTTP-request-method-invalid
  • +
  • HTTP-request-URI-invalid
  • +
  • HTTP-request-URI-too-long
  • +
  • HTTP-request-header-section-size: option<u32>
  • +
  • HTTP-request-header-size: option<field-size-payload>
  • +
  • HTTP-request-trailer-section-size: option<u32>
  • +
  • HTTP-request-trailer-size: field-size-payload
  • +
  • HTTP-response-incomplete
  • +
  • HTTP-response-header-section-size: option<u32>
  • +
  • HTTP-response-header-size: field-size-payload
  • +
  • HTTP-response-body-size: option<u64>
  • +
  • HTTP-response-trailer-section-size: option<u32>
  • +
  • HTTP-response-trailer-size: field-size-payload
  • +
  • HTTP-response-transfer-coding: option<string>
  • +
  • HTTP-response-content-coding: option<string>
  • +
  • HTTP-response-timeout
  • +
  • HTTP-upgrade-failed
  • +
  • HTTP-protocol-error
  • +
  • loop-detected
  • +
  • configuration-error
  • +
  • internal-error: option<string>

    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. +

  • +
+

variant header-error

+

This type enumerates the different kinds of errors that may occur when +setting or appending to a fields resource.

+
Variant Cases
+
    +
  • +

    invalid-syntax

    +

    This error indicates that a `field-name` or `field-value` was +syntactically invalid when used with an operation that sets headers in a +`fields`. +

  • +
  • +

    forbidden

    +

    This error indicates that a forbidden `field-name` was used when trying +to set a header in a `fields`. +

  • +
  • +

    immutable

    +

    This error indicates that the operation on the `fields` was not +permitted because the fields are immutable. +

  • +
+

type field-key

+

string

+

Field keys are always strings. +

Field keys should always be treated as case insensitive by the fields +resource for the purposes of equality checking.

+

Deprecation

+

This type has been deprecated in favor of the field-name type.

+

type field-name

+

field-key

+

Field names are always strings. +

Field names should always be treated as case insensitive by the fields +resource for the purposes of equality checking.

+

type field-value

+

field-value

+

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. +

resource fields

+

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 +immutable. In an immutable fields, the set, append, and delete +operations will fail with header-error.immutable.

+

type headers

+

fields

+

Headers is an alias for Fields. +

type trailers

+

fields

+

Trailers is an alias for Fields. +

resource incoming-request

+

Represents an incoming HTTP Request.

+

resource outgoing-request

+

Represents an outgoing HTTP Request.

+

resource request-options

+

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 response-outparam

+

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.

+

type status-code

+

u16

+

This type corresponds to the HTTP standard Status Code. +

resource incoming-response

+

Represents an incoming HTTP Response.

+

resource incoming-body

+

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 future-trailers

+

Represents a future which may eventually 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 outgoing-response

+

Represents an outgoing HTTP Response.

+

resource outgoing-body

+

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 occurred. The implementation should propagate 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 future-incoming-response

+

Represents a future which may eventually 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.

+

Functions

+

http-error-code: func

+

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.

+
Params
+ +
Return values
+ +

[constructor]fields: func

+

Construct an empty HTTP Fields.

+

The resulting fields is mutable.

+
Return values
+ +

[static]fields.from-list: func

+

Construct an HTTP Fields.

+

The resulting fields is mutable.

+

The list represents each name-value pair in the Fields. Names +which have multiple values are represented by multiple entries in this +list with the same name.

+

The tuple is a pair of the field name, represented as a string, and +Value, represented as a list of bytes.

+

An error result will be returned if any field-name or field-value is +syntactically invalid, or if a field is forbidden.

+
Params
+ +
Return values
+ +

[method]fields.get: func

+

Get all of the values corresponding to a name. If the name is not present +in this fields or is syntactically invalid, an empty list is returned. +However, if the name is present but empty, this is represented by a list +with one or more empty field-values present.

+
Params
+ +
Return values
+ +

[method]fields.has: func

+

Returns true when the name is present in this fields. If the name is +syntactically invalid, false is returned.

+
Params
+ +
Return values
+
    +
  • bool
  • +
+

[method]fields.set: func

+

Set all of the values for a name. Clears any existing values for that +name, if they have been set.

+

Fails with header-error.immutable if the fields are immutable.

+

Fails with header-error.invalid-syntax if the field-name or any of +the field-values are syntactically invalid.

+
Params
+ +
Return values
+ +

[method]fields.delete: func

+

Delete all values for a name. Does nothing if no values for the name +exist.

+

Fails with header-error.immutable if the fields are immutable.

+

Fails with header-error.invalid-syntax if the field-name is +syntactically invalid.

+
Params
+ +
Return values
+ +

[method]fields.append: func

+

Append a value for a name. Does not change or delete any existing +values for that name.

+

Fails with header-error.immutable if the fields are immutable.

+

Fails with header-error.invalid-syntax if the field-name or +field-value are syntactically invalid.

+
Params
+ +
Return values
+ +

[method]fields.entries: func

+

Retrieve the full set of names and values in the Fields. Like the +constructor, the list represents each name-value pair.

+

The outer list represents each name-value pair in the Fields. Names +which have multiple values are represented by multiple entries in this +list with the same name.

+

The names and values are always returned in the original casing and in +the order in which they will be serialized for transport.

+
Params
+ +
Return values
+ +

[method]fields.clone: func

+

Make a deep copy of the Fields. Equivalent in behavior to calling the +fields constructor on the return value of entries. The resulting +fields is mutable.

+
Params
+ +
Return values
+ +

[method]incoming-request.method: func

+

Returns the method of the incoming request.

+
Params
+ +
Return values
+ +

[method]incoming-request.path-with-query: func

+

Returns the path with query parameters from the request, as a string.

+
Params
+ +
Return values
+
    +
  • option<string>
  • +
+

[method]incoming-request.scheme: func

+

Returns the protocol scheme from the request.

+
Params
+ +
Return values
+ +

[method]incoming-request.authority: func

+

Returns the authority of the Request's target URI, if present.

+
Params
+ +
Return values
+
    +
  • option<string>
  • +
+

[method]incoming-request.headers: func

+

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.

+
Params
+ +
Return values
+ +

[method]incoming-request.consume: func

+

Gives the incoming-body associated with this request. Will only +return success at most once, and subsequent calls will return error.

+
Params
+ +
Return values
+ +

[constructor]outgoing-request: func

+

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.

+
Params
+ +
Return values
+ +

[method]outgoing-request.body: func

+

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.

+
Params
+ +
Return values
+ +

[method]outgoing-request.method: func

+

Get the Method for the Request.

+
Params
+ +
Return values
+ +

[method]outgoing-request.set-method: func

+

Set the Method for the Request. Fails if the string present in a +method.other argument is not a syntactically valid method.

+
Params
+ +
Return values
+
    +
  • result
  • +
+

[method]outgoing-request.path-with-query: func

+

Get the combination of the HTTP Path and Query for the Request. +When none, this represents an empty Path and empty Query.

+
Params
+ +
Return values
+
    +
  • option<string>
  • +
+

[method]outgoing-request.set-path-with-query: func

+

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.

+
Params
+ +
Return values
+
    +
  • result
  • +
+

[method]outgoing-request.scheme: func

+

Get the HTTP Related Scheme for the Request. When none, the +implementation may choose an appropriate default scheme.

+
Params
+ +
Return values
+ +

[method]outgoing-request.set-scheme: func

+

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.

+
Params
+ +
Return values
+
    +
  • result
  • +
+

[method]outgoing-request.authority: func

+

Get the authority of the Request's target URI. 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.

+
Params
+ +
Return values
+
    +
  • option<string>
  • +
+

[method]outgoing-request.set-authority: func

+

Set the authority of the Request's target URI. 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.

+
Params
+ +
Return values
+
    +
  • result
  • +
+

[method]outgoing-request.headers: func

+

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 transferred to +another component by e.g. outgoing-handler.handle.

+
Params
+ +
Return values
+ +

[constructor]request-options: func

+

Construct a default request-options value.

+
Return values
+ +

[method]request-options.connect-timeout: func

+

The timeout for the initial connect to the HTTP Server.

+
Params
+ +
Return values
+ +

[method]request-options.set-connect-timeout: func

+

Set the timeout for the initial connect to the HTTP Server. An error +return value indicates that this timeout is not supported.

+
Params
+ +
Return values
+
    +
  • result
  • +
+

[method]request-options.first-byte-timeout: func

+

The timeout for receiving the first byte of the Response body.

+
Params
+ +
Return values
+ +

[method]request-options.set-first-byte-timeout: func

+

Set the timeout for receiving the first byte of the Response body. An +error return value indicates that this timeout is not supported.

+
Params
+ +
Return values
+
    +
  • result
  • +
+

[method]request-options.between-bytes-timeout: func

+

The timeout for receiving subsequent chunks of bytes in the Response +body stream.

+
Params
+ +
Return values
+ +

[method]request-options.set-between-bytes-timeout: func

+

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.

+
Params
+ +
Return values
+
    +
  • result
  • +
+

[method]response-outparam.send-informational: func

+

Send an HTTP 1xx response.

+

Unlike response-outparam.set, this does not consume the +response-outparam, allowing the guest to send an arbitrary number of +informational responses before sending the final response using +response-outparam.set.

+

This will return an HTTP-protocol-error if status is not in the +range [100-199], or an internal-error if the implementation does not +support informational responses.

+
Params
+ +
Return values
+ +

[static]response-outparam.set: func

+

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.

+
Params
+ +

[method]incoming-response.status: func

+

Returns the status code from the incoming response.

+
Params
+ +
Return values
+ +

[method]incoming-response.headers: func

+

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.

+
Params
+ +
Return values
+ +

[method]incoming-response.consume: func

+

Returns the incoming body. May be called at most once. Returns error +if called additional times.

+
Params
+ +
Return values
+ +

[method]incoming-body.stream: func

+

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.

+
Params
+ +
Return values
+ +

[static]incoming-body.finish: func

+

Takes ownership of incoming-body, and returns a future-trailers. +This function will trap if the input-stream child is still alive.

+
Params
+ +
Return values
+ +

[method]future-trailers.subscribe: func

+

Returns a pollable which becomes ready when either the trailers have +been received, or an error has occurred. When this pollable is ready, +the get method will return some.

+
Params
+ +
Return values
+ +

[method]future-trailers.get: func

+

Returns the contents of the trailers, or an error which occurred, +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 occurred 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.

+
Params
+ +
Return values
+ +

[constructor]outgoing-response: func

+

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.
  • +
+
Params
+ +
Return values
+ +

[method]outgoing-response.status-code: func

+

Get the HTTP Status Code for the Response.

+
Params
+ +
Return values
+ +

[method]outgoing-response.set-status-code: func

+

Set the HTTP Status Code for the Response. Fails if the status-code +given is not a valid http status code.

+
Params
+ +
Return values
+
    +
  • result
  • +
+

[method]outgoing-response.headers: func

+

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 transferred to +another component by e.g. outgoing-handler.handle.

+
Params
+ +
Return values
+ +

[method]outgoing-response.body: func

+

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.

+
Params
+ +
Return values
+ +

[method]outgoing-body.write: func

+

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.

+
Params
+ +
Return values
+ +

[static]outgoing-body.finish: func

+

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.

+
Params
+ +
Return values
+ +

[method]future-incoming-response.subscribe: func

+

Returns a pollable which becomes ready when either the Response has +been received, or an error has occurred. When this pollable is ready, +the get method will return some.

+
Params
+ +
Return values
+ +

[method]future-incoming-response.get: func

+

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 received successfully, or that an error +occurred. Errors may also occur while consuming the response body, +but those will be reported by the incoming-body and its +output-stream child.

+
Params
+ +
Return values
+ +

Import interface wasi:http/outgoing-handler@0.2.8

+

This interface defines a handler of outgoing HTTP Requests. It should be +imported by components which wish to make HTTP Requests.

+
+

Types

+

type outgoing-request

+

outgoing-request

+

+#### `type request-options` +[`request-options`](#request_options) +

+#### `type future-incoming-response` +[`future-incoming-response`](#future_incoming_response) +

+#### `type error-code` +[`error-code`](#error_code) +

+---- +

Functions

+

handle: func

+

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.

+
Params
+ +
Return values
+ +

Export interface wasi:http/incoming-handler@0.2.8

+
+

Types

+

type incoming-request

+

incoming-request

+

+#### `type response-outparam` +[`response-outparam`](#response_outparam) +

+---- +

Functions

+

handle: func

+

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.

+
Params
+ diff --git a/proposals/http/wit-0.3.0-draft/deps.lock b/proposals/http/wit-0.3.0-draft/deps.lock new file mode 100644 index 000000000..eb9014bd2 --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps.lock @@ -0,0 +1,22 @@ +[cli] +url = "https://github.com/WebAssembly/wasi-cli/archive/main.tar.gz" +subdir = "wit-0.3.0-draft" +sha256 = "5a4fb9ecf963e19b131821132dd835cc140424e6b03aa8434d4fb4df25a52ec4" +sha512 = "48319184c0b7157bd358cdaf20b9bd054731a06fa032a4c785c72e1f8ced7c1260b135f9801d46d7e031efb3a38b62f0b1a1538955e44ef3abfda7ab353215e6" +deps = ["clocks", "filesystem", "random", "sockets"] + +[clocks] +sha256 = "cf61a3785c2838340ce530ee1cdc6dbee3257f1672d6000ca748dfe253808dec" +sha512 = "f647de7d6c470595c3e5bf0dba6af98703beb9f701c66543cea5d42e81f7a1a73f199c3949035a9c2c1bd717056e5e68788f520af39b9d26480242b7626f22ce" + +[filesystem] +sha256 = "99292288bdb7ecb04e0a1a7bee478a9410df9ab57af222c3dcde375f7b957181" +sha512 = "4da72faf65b99263bd0521871a6004ea19fc9189e906451fb4d48b83d9da3269a8e4470c5775faf037a05e03151a0c05fd05cc0dfeb36757715fda2799dd1d85" + +[random] +sha256 = "0a0cead69094ce1773468ff363b2d324ded025aab4f03a1d53b2538710c31e43" +sha512 = "3596bbd164c28254aefb0f7c7a047d81121df1de170808d16975f021c5170ea35dfe6fc1867f93469013ab8d36df8de14d4c5e1c9b70197bfd10e699fd6757e5" + +[sockets] +sha256 = "57e9d6df8389015116c5407641af76b717cf0d1a79e36384af3cb7d7fa9687ed" +sha512 = "45dab8dd2fa48450c480b1e770a3739793f6156b07b39075414510ce2cde3db6e714da87f47f0e9b9c82b5ef38a963a59f4d86449aa5f2310c78bc79134d0dd5" diff --git a/proposals/http/wit-0.3.0-draft/deps.toml b/proposals/http/wit-0.3.0-draft/deps.toml new file mode 100644 index 000000000..b80f1e2d1 --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps.toml @@ -0,0 +1 @@ +cli = { url = "https://github.com/WebAssembly/wasi-cli/archive/main.tar.gz", subdir = "wit-0.3.0-draft" } diff --git a/proposals/http/wit-0.3.0-draft/deps/cli/command.wit b/proposals/http/wit-0.3.0-draft/deps/cli/command.wit new file mode 100644 index 000000000..f2f613e55 --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps/cli/command.wit @@ -0,0 +1,10 @@ +package wasi:cli@0.3.0-rc-2025-09-16; + +@since(version = 0.3.0-rc-2025-09-16) +world command { + @since(version = 0.3.0-rc-2025-09-16) + include imports; + + @since(version = 0.3.0-rc-2025-09-16) + export run; +} diff --git a/proposals/http/wit-0.3.0-draft/deps/cli/environment.wit b/proposals/http/wit-0.3.0-draft/deps/cli/environment.wit new file mode 100644 index 000000000..3763f2f6c --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps/cli/environment.wit @@ -0,0 +1,22 @@ +@since(version = 0.3.0-rc-2025-09-16) +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. + @since(version = 0.3.0-rc-2025-09-16) + get-environment: func() -> list>; + + /// Get the POSIX-style arguments to the program. + @since(version = 0.3.0-rc-2025-09-16) + get-arguments: func() -> list; + + /// Return a path that programs should use as their initial current working + /// directory, interpreting `.` as shorthand for this. + @since(version = 0.3.0-rc-2025-09-16) + get-initial-cwd: func() -> option; +} diff --git a/proposals/http/wit-0.3.0-draft/deps/cli/exit.wit b/proposals/http/wit-0.3.0-draft/deps/cli/exit.wit new file mode 100644 index 000000000..1efba7d68 --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps/cli/exit.wit @@ -0,0 +1,17 @@ +@since(version = 0.3.0-rc-2025-09-16) +interface exit { + /// Exit the current instance and any linked instances. + @since(version = 0.3.0-rc-2025-09-16) + exit: func(status: result); + + /// Exit the current instance and any linked instances, reporting the + /// specified status code to the host. + /// + /// The meaning of the code depends on the context, with 0 usually meaning + /// "success", and other values indicating various types of failure. + /// + /// This function does not return; the effect is analogous to a trap, but + /// without the connotation that something bad has happened. + @unstable(feature = cli-exit-with-code) + exit-with-code: func(status-code: u8); +} diff --git a/proposals/http/wit-0.3.0-draft/deps/cli/imports.wit b/proposals/http/wit-0.3.0-draft/deps/cli/imports.wit new file mode 100644 index 000000000..660a2dd95 --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps/cli/imports.wit @@ -0,0 +1,34 @@ +package wasi:cli@0.3.0-rc-2025-09-16; + +@since(version = 0.3.0-rc-2025-09-16) +world imports { + @since(version = 0.3.0-rc-2025-09-16) + include wasi:clocks/imports@0.3.0-rc-2025-09-16; + @since(version = 0.3.0-rc-2025-09-16) + include wasi:filesystem/imports@0.3.0-rc-2025-09-16; + @since(version = 0.3.0-rc-2025-09-16) + include wasi:sockets/imports@0.3.0-rc-2025-09-16; + @since(version = 0.3.0-rc-2025-09-16) + include wasi:random/imports@0.3.0-rc-2025-09-16; + + @since(version = 0.3.0-rc-2025-09-16) + import environment; + @since(version = 0.3.0-rc-2025-09-16) + import exit; + @since(version = 0.3.0-rc-2025-09-16) + import stdin; + @since(version = 0.3.0-rc-2025-09-16) + import stdout; + @since(version = 0.3.0-rc-2025-09-16) + import stderr; + @since(version = 0.3.0-rc-2025-09-16) + import terminal-input; + @since(version = 0.3.0-rc-2025-09-16) + import terminal-output; + @since(version = 0.3.0-rc-2025-09-16) + import terminal-stdin; + @since(version = 0.3.0-rc-2025-09-16) + import terminal-stdout; + @since(version = 0.3.0-rc-2025-09-16) + import terminal-stderr; +} diff --git a/proposals/http/wit-0.3.0-draft/deps/cli/run.wit b/proposals/http/wit-0.3.0-draft/deps/cli/run.wit new file mode 100644 index 000000000..631441a3f --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps/cli/run.wit @@ -0,0 +1,6 @@ +@since(version = 0.3.0-rc-2025-09-16) +interface run { + /// Run the program. + @since(version = 0.3.0-rc-2025-09-16) + run: async func() -> result; +} diff --git a/proposals/http/wit-0.3.0-draft/deps/cli/stdio.wit b/proposals/http/wit-0.3.0-draft/deps/cli/stdio.wit new file mode 100644 index 000000000..51e5ae4b4 --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps/cli/stdio.wit @@ -0,0 +1,65 @@ +@since(version = 0.3.0-rc-2025-09-16) +interface types { + @since(version = 0.3.0-rc-2025-09-16) + enum error-code { + /// Input/output error + io, + /// Invalid or incomplete multibyte or wide character + illegal-byte-sequence, + /// Broken pipe + pipe, + } +} + +@since(version = 0.3.0-rc-2025-09-16) +interface stdin { + use types.{error-code}; + + /// Return a stream for reading from stdin. + /// + /// This function returns a stream which provides data read from stdin, + /// and a future to signal read results. + /// + /// If the stream's readable end is dropped the future will resolve to success. + /// + /// If the stream's writable end is dropped the future will either resolve to + /// success if stdin was closed by the writer or to an error-code if reading + /// failed for some other reason. + /// + /// Multiple streams may be active at the same time. The behavior of concurrent + /// reads is implementation-specific. + @since(version = 0.3.0-rc-2025-09-16) + read-via-stream: func() -> tuple, future>>; +} + +@since(version = 0.3.0-rc-2025-09-16) +interface stdout { + use types.{error-code}; + + /// Write the given stream to stdout. + /// + /// If the stream's writable end is dropped this function will either return + /// success once the entire contents of the stream have been written or an + /// error-code representing a failure. + /// + /// Otherwise if there is an error the readable end of the stream will be + /// dropped and this function will return an error-code. + @since(version = 0.3.0-rc-2025-09-16) + write-via-stream: async func(data: stream) -> result<_, error-code>; +} + +@since(version = 0.3.0-rc-2025-09-16) +interface stderr { + use types.{error-code}; + + /// Write the given stream to stderr. + /// + /// If the stream's writable end is dropped this function will either return + /// success once the entire contents of the stream have been written or an + /// error-code representing a failure. + /// + /// Otherwise if there is an error the readable end of the stream will be + /// dropped and this function will return an error-code. + @since(version = 0.3.0-rc-2025-09-16) + write-via-stream: async func(data: stream) -> result<_, error-code>; +} diff --git a/proposals/http/wit-0.3.0-draft/deps/cli/terminal.wit b/proposals/http/wit-0.3.0-draft/deps/cli/terminal.wit new file mode 100644 index 000000000..74c17694a --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps/cli/terminal.wit @@ -0,0 +1,62 @@ +/// 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. +@since(version = 0.3.0-rc-2025-09-16) +interface terminal-input { + /// The input side of a terminal. + @since(version = 0.3.0-rc-2025-09-16) + 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. +@since(version = 0.3.0-rc-2025-09-16) +interface terminal-output { + /// The output side of a terminal. + @since(version = 0.3.0-rc-2025-09-16) + resource terminal-output; +} + +/// An interface providing an optional `terminal-input` for stdin as a +/// link-time authority. +@since(version = 0.3.0-rc-2025-09-16) +interface terminal-stdin { + @since(version = 0.3.0-rc-2025-09-16) + use terminal-input.{terminal-input}; + + /// If stdin is connected to a terminal, return a `terminal-input` handle + /// allowing further interaction with it. + @since(version = 0.3.0-rc-2025-09-16) + get-terminal-stdin: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stdout as a +/// link-time authority. +@since(version = 0.3.0-rc-2025-09-16) +interface terminal-stdout { + @since(version = 0.3.0-rc-2025-09-16) + use terminal-output.{terminal-output}; + + /// If stdout is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + @since(version = 0.3.0-rc-2025-09-16) + get-terminal-stdout: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stderr as a +/// link-time authority. +@since(version = 0.3.0-rc-2025-09-16) +interface terminal-stderr { + @since(version = 0.3.0-rc-2025-09-16) + use terminal-output.{terminal-output}; + + /// If stderr is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + @since(version = 0.3.0-rc-2025-09-16) + get-terminal-stderr: func() -> option; +} diff --git a/proposals/http/wit-0.3.0-draft/deps/clocks/monotonic-clock.wit b/proposals/http/wit-0.3.0-draft/deps/clocks/monotonic-clock.wit new file mode 100644 index 000000000..a91d495c6 --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps/clocks/monotonic-clock.wit @@ -0,0 +1,48 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; +/// 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. +@since(version = 0.3.0-rc-2025-09-16) +interface monotonic-clock { + use types.{duration}; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + type instant = 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. + /// + /// For completeness, this function traps if it's not possible to represent + /// the value of the clock in an `instant`. Consequently, implementations + /// should ensure that the starting time is low enough to avoid the + /// possibility of overflow in practice. + @since(version = 0.3.0-rc-2025-09-16) + now: func() -> instant; + + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + @since(version = 0.3.0-rc-2025-09-16) + get-resolution: func() -> duration; + + /// Wait until the specified instant has occurred. + @since(version = 0.3.0-rc-2025-09-16) + wait-until: async func( + when: instant, + ); + + /// Wait for the specified duration to elapse. + @since(version = 0.3.0-rc-2025-09-16) + wait-for: async func( + how-long: duration, + ); +} diff --git a/proposals/http/wit-0.3.0-draft/deps/clocks/timezone.wit b/proposals/http/wit-0.3.0-draft/deps/clocks/timezone.wit new file mode 100644 index 000000000..ab8f5c080 --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps/clocks/timezone.wit @@ -0,0 +1,55 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; + +@unstable(feature = clocks-timezone) +interface timezone { + @unstable(feature = clocks-timezone) + use wall-clock.{datetime}; + + /// Return information needed to display the given `datetime`. This includes + /// the UTC offset, the time zone name, and a flag indicating whether + /// daylight saving time is active. + /// + /// If the timezone cannot be determined for the given `datetime`, return a + /// `timezone-display` for `UTC` with a `utc-offset` of 0 and no daylight + /// saving time. + @unstable(feature = clocks-timezone) + display: func(when: datetime) -> timezone-display; + + /// The same as `display`, but only return the UTC offset. + @unstable(feature = clocks-timezone) + utc-offset: func(when: datetime) -> s32; + + /// Information useful for displaying the timezone of a specific `datetime`. + /// + /// This information may vary within a single `timezone` to reflect daylight + /// saving time adjustments. + @unstable(feature = clocks-timezone) + record timezone-display { + /// The number of seconds difference between UTC time and the local + /// time of the timezone. + /// + /// The returned value will always be less than 86400 which is the + /// number of seconds in a day (24*60*60). + /// + /// In implementations that do not expose an actual time zone, this + /// should return 0. + utc-offset: s32, + + /// The abbreviated name of the timezone to display to a user. The name + /// `UTC` indicates Coordinated Universal Time. Otherwise, this should + /// reference local standards for the name of the time zone. + /// + /// In implementations that do not expose an actual time zone, this + /// should be the string `UTC`. + /// + /// In time zones that do not have an applicable name, a formatted + /// representation of the UTC offset may be returned, such as `-04:00`. + name: string, + + /// Whether daylight saving time is active. + /// + /// In implementations that do not expose an actual time zone, this + /// should return false. + in-daylight-saving-time: bool, + } +} diff --git a/proposals/http/wit-0.3.0-draft/deps/clocks/types.wit b/proposals/http/wit-0.3.0-draft/deps/clocks/types.wit new file mode 100644 index 000000000..aff7c2a22 --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps/clocks/types.wit @@ -0,0 +1,8 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; +/// This interface common types used throughout wasi:clocks. +@since(version = 0.3.0-rc-2025-09-16) +interface types { + /// A duration of time, in nanoseconds. + @since(version = 0.3.0-rc-2025-09-16) + type duration = u64; +} diff --git a/proposals/http/wit-0.3.0-draft/deps/clocks/wall-clock.wit b/proposals/http/wit-0.3.0-draft/deps/clocks/wall-clock.wit new file mode 100644 index 000000000..ea940500f --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps/clocks/wall-clock.wit @@ -0,0 +1,46 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; +/// 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. +@since(version = 0.3.0-rc-2025-09-16) +interface wall-clock { + /// A time and date in seconds plus nanoseconds. + @since(version = 0.3.0-rc-2025-09-16) + 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 + @since(version = 0.3.0-rc-2025-09-16) + now: func() -> datetime; + + /// Query the resolution of the clock. + /// + /// The nanoseconds field of the output is always less than 1000000000. + @since(version = 0.3.0-rc-2025-09-16) + get-resolution: func() -> datetime; +} diff --git a/proposals/http/wit-0.3.0-draft/deps/clocks/world.wit b/proposals/http/wit-0.3.0-draft/deps/clocks/world.wit new file mode 100644 index 000000000..a6b885f07 --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps/clocks/world.wit @@ -0,0 +1,11 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; + +@since(version = 0.3.0-rc-2025-09-16) +world imports { + @since(version = 0.3.0-rc-2025-09-16) + import monotonic-clock; + @since(version = 0.3.0-rc-2025-09-16) + import wall-clock; + @unstable(feature = clocks-timezone) + import timezone; +} diff --git a/proposals/http/wit-0.3.0-draft/deps/filesystem/preopens.wit b/proposals/http/wit-0.3.0-draft/deps/filesystem/preopens.wit new file mode 100644 index 000000000..9036e90e8 --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps/filesystem/preopens.wit @@ -0,0 +1,11 @@ +package wasi:filesystem@0.3.0-rc-2025-09-16; + +@since(version = 0.3.0-rc-2025-09-16) +interface preopens { + @since(version = 0.3.0-rc-2025-09-16) + use types.{descriptor}; + + /// Return the set of preopened directories, and their paths. + @since(version = 0.3.0-rc-2025-09-16) + get-directories: func() -> list>; +} diff --git a/proposals/http/wit-0.3.0-draft/deps/filesystem/types.wit b/proposals/http/wit-0.3.0-draft/deps/filesystem/types.wit new file mode 100644 index 000000000..41d91beee --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps/filesystem/types.wit @@ -0,0 +1,636 @@ +package wasi:filesystem@0.3.0-rc-2025-09-16; +/// 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 +@since(version = 0.3.0-rc-2025-09-16) +interface types { + @since(version = 0.3.0-rc-2025-09-16) + use wasi:clocks/wall-clock@0.3.0-rc-2025-09-16.{datetime}; + + /// File size or length of a region within a file. + @since(version = 0.3.0-rc-2025-09-16) + type filesize = u64; + + /// The type of a filesystem object referenced by a descriptor. + /// + /// Note: This was called `filetype` in earlier versions of WASI. + @since(version = 0.3.0-rc-2025-09-16) + 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. + @since(version = 0.3.0-rc-2025-09-16) + 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 integrity + /// 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, + } + + /// File attributes. + /// + /// Note: This was called `filestat` in earlier versions of WASI. + @since(version = 0.3.0-rc-2025-09-16) + 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, + } + + /// Flags determining the method of how paths are resolved. + @since(version = 0.3.0-rc-2025-09-16) + 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`. + @since(version = 0.3.0-rc-2025-09-16) + 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. + @since(version = 0.3.0-rc-2025-09-16) + type link-count = u64; + + /// When setting a timestamp, this gives the value to set it to. + @since(version = 0.3.0-rc-2025-09-16) + 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, + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + 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. + @since(version = 0.3.0-rc-2025-09-16) + 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. + @since(version = 0.3.0-rc-2025-09-16) + resource descriptor { + /// Return a stream for reading from a file. + /// + /// Multiple read, write, and append streams may be active on the same open + /// file and they do not interfere with each other. + /// + /// This function returns a `stream` which provides the data received from the + /// file, and a `future` providing additional error information in case an + /// error is encountered. + /// + /// If no error is encountered, `stream.read` on the `stream` will return + /// `read-status::closed` with no `error-context` and the future resolves to + /// the value `ok`. If an error is encountered, `stream.read` on the + /// `stream` returns `read-status::closed` with an `error-context` and the future + /// resolves to `err` with an `error-code`. + /// + /// Note: This is similar to `pread` in POSIX. + @since(version = 0.3.0-rc-2025-09-16) + read-via-stream: func( + /// The offset within the file at which to start reading. + offset: filesize, + ) -> tuple, future>>; + + /// Return a stream for writing to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be written. + /// + /// 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. + /// + /// This function returns once either full contents of the stream are + /// written or an error is encountered. + /// + /// Note: This is similar to `pwrite` in POSIX. + @since(version = 0.3.0-rc-2025-09-16) + write-via-stream: async func( + /// Data to write + data: stream, + /// The offset within the file at which to start writing. + offset: filesize, + ) -> 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. + /// + /// This function returns once either full contents of the stream are + /// written or an error is encountered. + /// + /// Note: This is similar to `write` with `O_APPEND` in POSIX. + @since(version = 0.3.0-rc-2025-09-16) + append-via-stream: async func(data: stream) -> result<_, error-code>; + + /// Provide file advisory information on a descriptor. + /// + /// This is similar to `posix_fadvise` in POSIX. + @since(version = 0.3.0-rc-2025-09-16) + advise: async func( + /// The offset within the file to which the advisory applies. + offset: filesize, + /// The length of the region to which the advisory applies. + length: filesize, + /// The advice. + advice: advice + ) -> 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. + @since(version = 0.3.0-rc-2025-09-16) + sync-data: async func() -> 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. + @since(version = 0.3.0-rc-2025-09-16) + get-flags: async 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. + @since(version = 0.3.0-rc-2025-09-16) + get-type: async func() -> result; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + set-size: async 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. + @since(version = 0.3.0-rc-2025-09-16) + set-times: async func( + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, 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. + /// + /// This function returns a future, which will resolve to an error code if + /// reading full contents of the directory fails. + @since(version = 0.3.0-rc-2025-09-16) + read-directory: async func() -> tuple, future>>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + sync: async func() -> result<_, error-code>; + + /// Create a directory. + /// + /// Note: This is similar to `mkdirat` in POSIX. + @since(version = 0.3.0-rc-2025-09-16) + create-directory-at: async func( + /// The relative path at which to create the directory. + path: string, + ) -> 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. + @since(version = 0.3.0-rc-2025-09-16) + stat: async 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. + @since(version = 0.3.0-rc-2025-09-16) + stat-at: async func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + set-times-at: async func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to operate on. + path: string, + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, error-code>; + + /// Create a hard link. + /// + /// Fails with `error-code::no-entry` if the old path does not exist, + /// with `error-code::exist` if the new path already exists, and + /// `error-code::not-permitted` if the old path is not a file. + /// + /// Note: This is similar to `linkat` in POSIX. + @since(version = 0.3.0-rc-2025-09-16) + link-at: async func( + /// Flags determining the method of how the path is resolved. + old-path-flags: path-flags, + /// The relative source path from which to link. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path at which to create the hard link. + new-path: string, + ) -> result<_, error-code>; + + /// Open a file or directory. + /// + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + open-at: async func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the object to open. + path: string, + /// The method by which to open the file. + open-flags: open-flags, + /// Flags to use for the resulting descriptor. + %flags: descriptor-flags, + ) -> 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. + @since(version = 0.3.0-rc-2025-09-16) + readlink-at: async func( + /// The relative path of the symbolic link from which to read. + 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. + @since(version = 0.3.0-rc-2025-09-16) + remove-directory-at: async func( + /// The relative path to a directory to remove. + path: string, + ) -> result<_, error-code>; + + /// Rename a filesystem object. + /// + /// Note: This is similar to `renameat` in POSIX. + @since(version = 0.3.0-rc-2025-09-16) + rename-at: async func( + /// The relative source path of the file or directory to rename. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path to which to rename the file or directory. + new-path: string, + ) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + symlink-at: async func( + /// The contents of the symbolic link. + old-path: string, + /// The relative destination path at which to create the symbolic link. + new-path: string, + ) -> 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. + @since(version = 0.3.0-rc-2025-09-16) + unlink-file-at: async func( + /// The relative path to a file to unlink. + path: string, + ) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + is-same-object: async func(other: borrow) -> bool; + + /// 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 encouraged 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. + @since(version = 0.3.0-rc-2025-09-16) + metadata-hash: async 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`. + @since(version = 0.3.0-rc-2025-09-16) + metadata-hash-at: async func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + } +} diff --git a/proposals/http/wit-0.3.0-draft/deps/filesystem/world.wit b/proposals/http/wit-0.3.0-draft/deps/filesystem/world.wit new file mode 100644 index 000000000..87fc72716 --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps/filesystem/world.wit @@ -0,0 +1,9 @@ +package wasi:filesystem@0.3.0-rc-2025-09-16; + +@since(version = 0.3.0-rc-2025-09-16) +world imports { + @since(version = 0.3.0-rc-2025-09-16) + import types; + @since(version = 0.3.0-rc-2025-09-16) + import preopens; +} diff --git a/proposals/http/wit-0.3.0-draft/deps/random/insecure-seed.wit b/proposals/http/wit-0.3.0-draft/deps/random/insecure-seed.wit new file mode 100644 index 000000000..302151ba6 --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps/random/insecure-seed.wit @@ -0,0 +1,27 @@ +package wasi:random@0.3.0-rc-2025-09-16; +/// The insecure-seed interface for seeding hash-map DoS resistance. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.3.0-rc-2025-09-16) +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. + @since(version = 0.3.0-rc-2025-09-16) + get-insecure-seed: func() -> tuple; +} diff --git a/proposals/http/wit-0.3.0-draft/deps/random/insecure.wit b/proposals/http/wit-0.3.0-draft/deps/random/insecure.wit new file mode 100644 index 000000000..39146e391 --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps/random/insecure.wit @@ -0,0 +1,25 @@ +package wasi:random@0.3.0-rc-2025-09-16; +/// The insecure interface for insecure pseudo-random numbers. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.3.0-rc-2025-09-16) +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. + @since(version = 0.3.0-rc-2025-09-16) + 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`. + @since(version = 0.3.0-rc-2025-09-16) + get-insecure-random-u64: func() -> u64; +} diff --git a/proposals/http/wit-0.3.0-draft/deps/random/random.wit b/proposals/http/wit-0.3.0-draft/deps/random/random.wit new file mode 100644 index 000000000..fa1f111dc --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps/random/random.wit @@ -0,0 +1,29 @@ +package wasi:random@0.3.0-rc-2025-09-16; +/// WASI Random is a random data API. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.3.0-rc-2025-09-16) +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. + @since(version = 0.3.0-rc-2025-09-16) + 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`. + @since(version = 0.3.0-rc-2025-09-16) + get-random-u64: func() -> u64; +} diff --git a/proposals/http/wit-0.3.0-draft/deps/random/world.wit b/proposals/http/wit-0.3.0-draft/deps/random/world.wit new file mode 100644 index 000000000..08c5ed88b --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps/random/world.wit @@ -0,0 +1,13 @@ +package wasi:random@0.3.0-rc-2025-09-16; + +@since(version = 0.3.0-rc-2025-09-16) +world imports { + @since(version = 0.3.0-rc-2025-09-16) + import random; + + @since(version = 0.3.0-rc-2025-09-16) + import insecure; + + @since(version = 0.3.0-rc-2025-09-16) + import insecure-seed; +} diff --git a/proposals/http/wit-0.3.0-draft/deps/sockets/ip-name-lookup.wit b/proposals/http/wit-0.3.0-draft/deps/sockets/ip-name-lookup.wit new file mode 100644 index 000000000..6a652ff23 --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps/sockets/ip-name-lookup.wit @@ -0,0 +1,62 @@ +@since(version = 0.3.0-rc-2025-09-16) +interface ip-name-lookup { + @since(version = 0.3.0-rc-2025-09-16) + use types.{ip-address}; + + /// Lookup error codes. + @since(version = 0.3.0-rc-2025-09-16) + enum error-code { + /// Unknown error + unknown, + + /// Access denied. + /// + /// POSIX equivalent: EACCES, EPERM + access-denied, + + /// `name` is a syntactically invalid domain name or IP address. + /// + /// POSIX equivalent: EINVAL + invalid-argument, + + /// Name does not exist or has no suitable associated IP addresses. + /// + /// POSIX equivalent: EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY + name-unresolvable, + + /// A temporary failure in name resolution occurred. + /// + /// POSIX equivalent: EAI_AGAIN + temporary-resolver-failure, + + /// A permanent failure in name resolution occurred. + /// + /// POSIX equivalent: EAI_FAIL + permanent-resolver-failure, + } + + /// 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. + /// + /// The results are returned in connection order preference. + /// + /// This function never succeeds with 0 results. It either fails or succeeds + /// with at least one address. Additionally, this function never returns + /// IPv4-mapped IPv6 addresses. + /// + /// The returned future will resolve to an error code in case of failure. + /// It will resolve to success once the returned stream is exhausted. + /// + /// # References: + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + resolve-addresses: async func(name: string) -> result, error-code>; +} diff --git a/proposals/http/wit-0.3.0-draft/deps/sockets/types.wit b/proposals/http/wit-0.3.0-draft/deps/sockets/types.wit new file mode 100644 index 000000000..2ed1912e4 --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps/sockets/types.wit @@ -0,0 +1,725 @@ +@since(version = 0.3.0-rc-2025-09-16) +interface types { + @since(version = 0.3.0-rc-2025-09-16) + use wasi:clocks/monotonic-clock@0.3.0-rc-2025-09-16.{duration}; + + /// 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` + /// + /// See each individual API for what the POSIX equivalents are. They sometimes differ per API. + @since(version = 0.3.0-rc-2025-09-16) + 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, + + /// The operation is not valid in the socket's current state. + invalid-state, + + /// 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, + } + + @since(version = 0.3.0-rc-2025-09-16) + enum ip-address-family { + /// Similar to `AF_INET` in POSIX. + ipv4, + + /// Similar to `AF_INET6` in POSIX. + ipv6, + } + + @since(version = 0.3.0-rc-2025-09-16) + type ipv4-address = tuple; + @since(version = 0.3.0-rc-2025-09-16) + type ipv6-address = tuple; + + @since(version = 0.3.0-rc-2025-09-16) + variant ip-address { + ipv4(ipv4-address), + ipv6(ipv6-address), + } + + @since(version = 0.3.0-rc-2025-09-16) + record ipv4-socket-address { + /// sin_port + port: u16, + /// sin_addr + address: ipv4-address, + } + + @since(version = 0.3.0-rc-2025-09-16) + record ipv6-socket-address { + /// sin6_port + port: u16, + /// sin6_flowinfo + flow-info: u32, + /// sin6_addr + address: ipv6-address, + /// sin6_scope_id + scope-id: u32, + } + + @since(version = 0.3.0-rc-2025-09-16) + variant ip-socket-address { + ipv4(ipv4-socket-address), + ipv6(ipv6-socket-address), + } + + /// A TCP socket resource. + /// + /// The socket can be in one of the following states: + /// - `unbound` + /// - `bound` (See note below) + /// - `listening` + /// - `connecting` + /// - `connected` + /// - `closed` + /// See + /// for 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`, `listening`, `connecting` or `connected`) + /// + /// In addition to the general error codes documented on the + /// `types::error-code` type, TCP socket methods may always return + /// `error(invalid-state)` when in the `closed` state. + @since(version = 0.3.0-rc-2025-09-16) + resource 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. + /// + /// Unlike POSIX, WASI sockets have no notion of a socket-level + /// `O_NONBLOCK` flag. Instead they fully rely on the Component Model's + /// async support. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + create: static func(address-family: ip-address-family) -> result; + + /// Bind the socket to 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 can be bound to. (EADDRNOTAVAIL) + /// + /// # 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. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + bind: func(local-address: ip-socket-address) -> result<_, error-code>; + + /// Connect to a remote endpoint. + /// + /// On success, the socket is transitioned into the `connected` state and this function returns a connection resource. + /// + /// 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-state`: The socket is already in the `connecting` state. (EALREADY) + /// - `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) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + connect: async func(remote-address: ip-socket-address) -> result<_, error-code>; + + /// Start listening and return a stream of new inbound connections. + /// + /// Transitions the socket into the `listening` state. This can be called + /// at most once per socket. + /// + /// If the socket is not already explicitly bound, this function will + /// implicitly bind the socket to a random free port. + /// + /// Normally, the returned sockets are bound, in the `connected` state + /// and immediately ready for I/O. Though, depending on exact timing and + /// circumstances, a newly accepted connection may already be `closed` + /// by the time the server attempts to perform its first I/O on it. This + /// is true regardless of whether the WASI implementation uses + /// "synthesized" sockets or not (see Implementors Notes below). + /// + /// 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` + /// + /// # Typical errors + /// - `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) + /// + /// # Implementors note + /// This method returns a single perpetual stream that should only close + /// on fatal errors (if any). Yet, the POSIX' `accept` function may also + /// return transient errors (e.g. ECONNABORTED). The exact details differ + /// per operation system. For example, the Linux manual mentions: + /// + /// > Linux accept() passes already-pending network errors on the new + /// > socket as an error code from accept(). This behavior differs from + /// > other BSD socket implementations. For reliable operation the + /// > application should detect the network errors defined for the + /// > protocol after accept() and treat them like EAGAIN by retrying. + /// > In the case of TCP/IP, these are ENETDOWN, EPROTO, ENOPROTOOPT, + /// > EHOSTDOWN, ENONET, EHOSTUNREACH, EOPNOTSUPP, and ENETUNREACH. + /// Source: https://man7.org/linux/man-pages/man2/accept.2.html + /// + /// WASI implementations have two options to handle this: + /// - Optionally log it and then skip over non-fatal errors returned by + /// `accept`. Guest code never gets to see these failures. Or: + /// - Synthesize a `tcp-socket` resource that exposes the error when + /// attempting to send or receive on it. Guest code then sees these + /// failures as regular I/O errors. + /// + /// In either case, the stream returned by this `listen` method remains + /// operational. + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + listen: func() -> result, error-code>; + + /// Transmit data to peer. + /// + /// The caller should close the stream when it has no more data to send + /// to the peer. Under normal circumstances this will cause a FIN packet + /// to be sent out. Closing the stream is equivalent to calling + /// `shutdown(SHUT_WR)` in POSIX. + /// + /// This function may be called at most once and returns once the full + /// contents of the stream are transmitted or an error is encountered. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) + /// - `connection-reset`: The connection was reset. (ECONNRESET) + /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + send: async func(data: stream) -> result<_, error-code>; + + /// Read data from peer. + /// + /// This function returns a `stream` which provides the data received from the + /// socket, and a `future` providing additional error information in case the + /// socket is closed abnormally. + /// + /// If the socket is closed normally, `stream.read` on the `stream` will return + /// `read-status::closed` with no `error-context` and the future resolves to + /// the value `ok`. If the socket is closed abnormally, `stream.read` on the + /// `stream` returns `read-status::closed` with an `error-context` and the future + /// resolves to `err` with an `error-code`. + /// + /// `receive` is meant to be called only once per socket. If it is called more + /// than once, the subsequent calls return a new `stream` that fails as if it + /// were closed abnormally. + /// + /// If the caller is not expecting to receive any data from the peer, + /// they may drop the stream. Any data still in the receive queue + /// will be discarded. This is equivalent to calling `shutdown(SHUT_RD)` + /// in POSIX. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) + /// - `connection-reset`: The connection was reset. (ECONNRESET) + /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + receive: func() -> tuple, future>>; + + /// 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 `get-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 + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + get-local-address: func() -> result; + + /// Get the remote address. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + get-remote-address: func() -> result; + + /// Whether the socket is in the `listening` state. + /// + /// Equivalent to the SO_ACCEPTCONN socket option. + @since(version = 0.3.0-rc-2025-09-16) + get-is-listening: func() -> bool; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// This is the value passed to the constructor. + /// + /// Equivalent to the SO_DOMAIN socket option. + @since(version = 0.3.0-rc-2025-09-16) + get-address-family: func() -> ip-address-family; + + /// 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 `connecting` or `connected` state. + @since(version = 0.3.0-rc-2025-09-16) + set-listen-backlog-size: func(value: u64) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + get-keep-alive-enabled: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-keep-alive-enabled: func(value: bool) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + get-keep-alive-idle-time: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-keep-alive-idle-time: func(value: duration) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + get-keep-alive-interval: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-keep-alive-interval: func(value: duration) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + get-keep-alive-count: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-keep-alive-count: func(value: u32) -> 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. + @since(version = 0.3.0-rc-2025-09-16) + get-hop-limit: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-hop-limit: func(value: u8) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + get-receive-buffer-size: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + @since(version = 0.3.0-rc-2025-09-16) + get-send-buffer-size: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + } + + /// A UDP socket handle. + @since(version = 0.3.0-rc-2025-09-16) + resource 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. + /// + /// Unlike POSIX, WASI sockets have no notion of a socket-level + /// `O_NONBLOCK` flag. Instead they fully rely on the Component Model's + /// async support. + /// + /// # References: + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + create: static func(address-family: ip-address-family) -> result; + + /// Bind the socket to 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 can be bound to. (EADDRNOTAVAIL) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + bind: func(local-address: ip-socket-address) -> result<_, error-code>; + + /// Associate this socket with a specific peer address. + /// + /// 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`. If the socket was not already explicitly + /// bound, this function will implicitly bind the socket to a random + /// free port. + /// + /// When a UDP socket is "connected", the `send` and `receive` methods + /// are limited to communicating with that peer only: + /// - `send` can only be used to send to this destination. + /// - `receive` will only return datagrams sent from the provided `remote-address`. + /// + /// The name "connect" was kept to align with the existing POSIX + /// terminology. Other than that, this function only changes the local + /// socket configuration and does not generate any network traffic. + /// The peer is not aware of this "connection". + /// + /// This method may be called multiple times on the same socket to change + /// its association, but only the most recent one will be effective. + /// + /// # 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) + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// + /// # Implementors note + /// If the socket is already connected, some platforms (e.g. Linux) + /// require a disconnect before connecting to a different peer address. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + connect: func(remote-address: ip-socket-address) -> result<_, error-code>; + + /// Dissociate this socket from its peer address. + /// + /// After calling this method, `send` & `receive` are free to communicate + /// with any address again. + /// + /// The POSIX equivalent of this is calling `connect` with an `AF_UNSPEC` address. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not connected. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + disconnect: func() -> result<_, error-code>; + + /// Send a message on the socket to a particular peer. + /// + /// If the socket is connected, the peer address may be left empty. In + /// that case this is equivalent to `send` in POSIX. Otherwise it is + /// equivalent to `sendto`. + /// + /// Additionally, if the socket is connected, a `remote-address` argument + /// _may_ be provided but then it must be identical to the address + /// passed to `connect`. + /// + /// Implementations may trap if the `data` length exceeds 64 KiB. + /// + /// # 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 `connect`. (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 + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + send: async func(data: list, remote-address: option) -> result<_, error-code>; + + /// Receive a message on the socket. + /// + /// On success, the return value contains a tuple of the received data + /// and the address of the sender. Theoretical maximum length of the + /// data is 64 KiB. Though in practice, it will typically be less than + /// 1500 bytes. + /// + /// If the socket is connected, the sender address is guaranteed to + /// match the remote address passed to `connect`. + /// + /// # Typical errors + /// - `invalid-state`: The socket has not been bound yet. + /// - `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 + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + receive: async func() -> result, ip-socket-address>, 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 `get-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 + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + get-local-address: func() -> result; + + /// Get the address the socket is currently "connected" to. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not "connected" to a specific remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + get-remote-address: func() -> result; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// This is the value passed to the constructor. + /// + /// Equivalent to the SO_DOMAIN socket option. + @since(version = 0.3.0-rc-2025-09-16) + get-address-family: func() -> ip-address-family; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + get-unicast-hop-limit: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + get-receive-buffer-size: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + @since(version = 0.3.0-rc-2025-09-16) + get-send-buffer-size: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + } +} diff --git a/proposals/http/wit-0.3.0-draft/deps/sockets/world.wit b/proposals/http/wit-0.3.0-draft/deps/sockets/world.wit new file mode 100644 index 000000000..44cc427ed --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/deps/sockets/world.wit @@ -0,0 +1,9 @@ +package wasi:sockets@0.3.0-rc-2025-09-16; + +@since(version = 0.3.0-rc-2025-09-16) +world imports { + @since(version = 0.3.0-rc-2025-09-16) + import types; + @since(version = 0.3.0-rc-2025-09-16) + import ip-name-lookup; +} diff --git a/proposals/http/wit-0.3.0-draft/types.wit b/proposals/http/wit-0.3.0-draft/types.wit new file mode 100644 index 000000000..0f0e83851 --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/types.wit @@ -0,0 +1,419 @@ +/// This interface defines all of the types and methods for implementing HTTP +/// Requests and Responses, as well as their headers, trailers, and bodies. +interface types { + use wasi:clocks/types@0.3.0-rc-2025-09-16.{duration}; + + /// 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) + } + + /// These cases are inspired by the IANA 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) + } + + /// 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 + } + + /// 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-name` 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-name` 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, + } + + /// This type enumerates the different kinds of errors that may occur when + /// setting fields of a `request-options` resource. + variant request-options-error { + /// Indicates the specified field is not supported by this implementation. + not-supported, + + /// Indicates that the operation on the `request-options` was not permitted + /// because it is immutable. + immutable, + } + + /// Field names are always strings. + /// + /// Field names should always be treated as case insensitive by the `fields` + /// resource for the purposes of equality checking. + type field-name = 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, + /// `request.headers`) might be be immutable. In an immutable fields, the + /// `set`, `append`, and `delete` operations will fail with + /// `header-error.immutable`. + /// + /// A `fields` resource should store `field-name`s and `field-value`s in their + /// original casing used to construct or mutate the `fields` resource. The `fields` + /// resource should use that original casing when serializing the fields for + /// transport or when returning them from a method. + resource fields { + + /// Construct an empty HTTP Fields. + /// + /// The resulting `fields` is mutable. + constructor(); + + /// Construct an HTTP Fields. + /// + /// The resulting `fields` is mutable. + /// + /// The list represents each name-value pair in the Fields. Names + /// which have multiple values are represented by multiple entries in this + /// list with the same name. + /// + /// The tuple is a pair of the field name, represented as a string, and + /// Value, represented as a list of bytes. In a valid Fields, all names + /// and values are valid UTF-8 strings. However, values are not always + /// well-formed, so they are represented as a raw list of bytes. + /// + /// An error result will be returned if any header or value was + /// syntactically invalid, or if a header was forbidden. + from-list: static func( + entries: list> + ) -> result; + + /// Get all of the values corresponding to a name. If the name is not present + /// in this `fields`, an empty list is returned. However, if the name is + /// present but empty, this is represented by a list with one or more + /// empty field-values present. + get: func(name: field-name) -> list; + + /// Returns `true` when the name is present in this `fields`. If the name is + /// syntactically invalid, `false` is returned. + has: func(name: field-name) -> bool; + + /// Set all of the values for a name. Clears any existing values for that + /// name, if they have been set. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + set: func(name: field-name, value: list) -> result<_, header-error>; + + /// Delete all values for a name. Does nothing if no values for the name + /// exist. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + delete: func(name: field-name) -> result<_, header-error>; + + /// Delete all values for a name. Does nothing if no values for the name + /// exist. + /// + /// Returns all values previously corresponding to the name, if any. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + get-and-delete: func(name: field-name) -> result, header-error>; + + /// Append a value for a name. Does not change or delete any existing + /// values for that name. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + append: func(name: field-name, value: field-value) -> result<_, header-error>; + + /// Retrieve the full set of names and values in the Fields. Like the + /// constructor, the list represents each name-value pair. + /// + /// The outer list represents each name-value pair in the Fields. Names + /// which have multiple values are represented by multiple entries in this + /// list with the same name. + /// + /// The names and values are always returned in the original casing and in + /// the order in which they will be serialized for transport. + copy-all: func() -> list>; + + /// Make a deep copy of the Fields. Equivalent in behavior to calling the + /// `fields` constructor on the return value of `copy-all`. The resulting + /// `fields` is mutable. + clone: func() -> fields; + } + + /// Headers is an alias for Fields. + type headers = fields; + + /// Trailers is an alias for Fields. + type trailers = fields; + + /// Represents an HTTP Request. + resource request { + + /// Construct a new `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. + /// + /// `contents` is the optional body content stream with `none` + /// representing a zero-length content stream. + /// Once it is closed, `trailers` future must resolve to a result. + /// If `trailers` resolves to an error, underlying connection + /// will be closed immediately. + /// + /// `options` is optional `request-options` resource to be used + /// if the request is sent over a network connection. + /// + /// It is possible to construct, or manipulate with the accessor functions + /// below, a `request` with an invalid combination of `scheme` + /// and `authority`, or `headers` which are not permitted to be sent. + /// It is the obligation of the `handler.handle` implementation + /// to reject invalid constructions of `request`. + /// + /// The returned future resolves to result of transmission of this request. + new: static func( + headers: headers, + contents: option>, + trailers: future, error-code>>, + options: option + ) -> tuple>>; + + /// Get the Method for the Request. + get-method: func() -> method; + /// 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; + + /// Get the combination of the HTTP Path and Query for the Request. When + /// `none`, this represents an empty Path and empty Query. + get-path-with-query: func() -> option; + /// 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; + + /// Get the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. + get-scheme: func() -> option; + /// 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; + + /// Get the authority of the Request's target URI. 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. + get-authority: func() -> option; + /// Set the authority of the Request's target URI. 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; + + /// Get the `request-options` to be associated with this request + /// + /// The returned `request-options` resource is immutable: `set-*` operations + /// will fail if invoked. + /// + /// This `request-options` resource is a child: it must be dropped before + /// the parent `request` is dropped, or its ownership is transferred to + /// another component by e.g. `handler.handle`. + get-options: func() -> option; + + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + get-headers: func() -> headers; + + /// Get body of the Request. + /// + /// Stream returned by this method represents the contents of the body. + /// Once the stream is reported as closed, callers should await the returned + /// future to determine whether the body was received successfully. + /// The future will only resolve after the stream is reported as closed. + /// + /// This function takes a `res` future as a parameter, which can be used to + /// communicate an error in handling of the request. + /// + /// Note that function will move the `request`, but references to headers or + /// request options acquired from it previously will remain valid. + consume-body: static func(this: request, res: future>) -> tuple, future, error-code>>>; + } + + /// 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 an + /// asynchronous call. + resource request-options { + /// Construct a default `request-options` value. + constructor(); + + /// The timeout for the initial connect to the HTTP Server. + get-connect-timeout: func() -> option; + + /// Set the timeout for the initial connect to the HTTP Server. An error + /// return value indicates that this timeout is not supported or that this + /// handle is immutable. + set-connect-timeout: func(duration: option) -> result<_, request-options-error>; + + /// The timeout for receiving the first byte of the Response body. + get-first-byte-timeout: func() -> option; + + /// Set the timeout for receiving the first byte of the Response body. An + /// error return value indicates that this timeout is not supported or that + /// this handle is immutable. + set-first-byte-timeout: func(duration: option) -> result<_, request-options-error>; + + /// The timeout for receiving subsequent chunks of bytes in the Response + /// body stream. + get-between-bytes-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 or that this handle is immutable. + set-between-bytes-timeout: func(duration: option) -> result<_, request-options-error>; + + /// Make a deep copy of the `request-options`. + /// The resulting `request-options` is mutable. + clone: func() -> request-options; + } + + /// This type corresponds to the HTTP standard Status Code. + type status-code = u16; + + /// Represents an HTTP Response. + resource response { + + /// Construct a new `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. + /// + /// `contents` is the optional body content stream with `none` + /// representing a zero-length content stream. + /// Once it is closed, `trailers` future must resolve to a result. + /// If `trailers` resolves to an error, underlying connection + /// will be closed immediately. + /// + /// The returned future resolves to result of transmission of this response. + new: static func( + headers: headers, + contents: option>, + trailers: future, error-code>>, + ) -> tuple>>; + + /// Get the HTTP Status Code for the Response. + get-status-code: func() -> status-code; + + /// 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 headers associated with the Response. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + get-headers: func() -> headers; + + /// Get body of the Response. + /// + /// Stream returned by this method represents the contents of the body. + /// Once the stream is reported as closed, callers should await the returned + /// future to determine whether the body was received successfully. + /// The future will only resolve after the stream is reported as closed. + /// + /// This function takes a `res` future as a parameter, which can be used to + /// communicate an error in handling of the response. + /// + /// Note that function will move the `response`, but references to headers + /// acquired from it previously will remain valid. + consume-body: static func(this: response, res: future>) -> tuple, future, error-code>>>; + } +} diff --git a/proposals/http/wit-0.3.0-draft/worlds.wit b/proposals/http/wit-0.3.0-draft/worlds.wit new file mode 100644 index 000000000..5a1136809 --- /dev/null +++ b/proposals/http/wit-0.3.0-draft/worlds.wit @@ -0,0 +1,82 @@ +package wasi:http@0.3.0-rc-2025-09-16; + +/// The `wasi:http/service` world captures a broad category of HTTP services +/// including web applications, API servers, and proxies. It may be `include`d +/// in more specific worlds such as `wasi:http/middleware`. +world service { + /// HTTP services have access to time and randomness. + include wasi:clocks/imports@0.3.0-rc-2025-09-16; + include wasi:random/imports@0.3.0-rc-2025-09-16; + + /// Services have standard output and error streams which are expected to + /// terminate in a developer-facing console provided by the host. + import wasi:cli/stdout@0.3.0-rc-2025-09-16; + import wasi:cli/stderr@0.3.0-rc-2025-09-16; + + /// TODO: this is a temporary workaround until component tooling is able to + /// gracefully handle the absence of stdin. Hosts must return an eof stream + /// for this import, which is what wasi-libc + tooling will do automatically + /// when this import is properly removed. + import wasi:cli/stdin@0.3.0-rc-2025-09-16; + + /// This is the default `client` to use when user code simply wants to make an + /// HTTP request (e.g., via `fetch()`). + import client; + + /// The host delivers incoming HTTP requests to a component by calling the + /// `handle` function of this exported interface. A host may arbitrarily reuse + /// or not reuse component instance when delivering incoming HTTP requests and + /// thus a component must be able to handle 0..N calls to `handle`. + /// + /// This may also be used to receive synthesized or forwarded requests from + /// another component. + export handler; +} + +/// The `wasi:http/middleware` world captures HTTP services that forward HTTP +/// Requests to another handler. +/// +/// Components may implement this world to allow them to participate in handler +/// "chains" where a `request` flows through handlers on its way to some terminal +/// `service` and corresponding `response` flows in the opposite direction. +world middleware { + include service; + import handler; +} + +/// This interface defines a handler of HTTP Requests. +/// +/// In a `wasi:http/service` this interface is exported to respond to an +/// incoming HTTP Request with a Response. +/// +/// In `wasi:http/middleware` this interface is both exported and imported as +/// the "downstream" and "upstream" directions of the middleware chain. +interface handler { + use types.{request, response, error-code}; + + /// This function may be called with either an incoming request read from the + /// network or a request synthesized or forwarded by another component. + handle: async func( + request: request, + ) -> result; +} + +/// This interface defines an HTTP client for sending "outgoing" requests. +/// +/// Most components are expected to import this interface to provide the +/// capability to send HTTP requests to arbitrary destinations on a network. +/// +/// The type signature of `client.send` is the same as `handler.handle`. This +/// duplication is currently necessary because some Component Model tooling +/// (including WIT itself) is unable to represent a component importing two +/// instances of the same interface. A `client.send` import may be linked +/// directly to a `handler.handle` export to bypass the network. +interface client { + use types.{request, response, error-code}; + + // This function may be used to either send an outgoing request over the + // network or to forward it to another component. + send: async func( + request: request, + ) -> result; +} \ No newline at end of file diff --git a/proposals/http/wit/deps.lock b/proposals/http/wit/deps.lock new file mode 100644 index 000000000..cac326b93 --- /dev/null +++ b/proposals/http/wit/deps.lock @@ -0,0 +1,25 @@ +[cli] +url = "https://github.com/WebAssembly/wasi-cli/archive/v0.2.8.tar.gz" +sha256 = "d223b55ba73b8a265cc36db836487a16dcb1ed859d92a693827ad5ca2d2dfba8" +sha512 = "db0dd1a7225f08b27092f75aa32ca3e9fc6cda666cdf0a46521ca32702a1985f4e7b7c5b78e61f6eef348c2807d09fb8c11ccfc95d572465aa86f4024d44afa0" +deps = ["clocks", "filesystem", "io", "random", "sockets"] + +[clocks] +sha256 = "be1d8c61e2544e2b48d902c60df73577e293349063344ce752cda4d323f8b913" +sha512 = "0fd7962c62b135da0e584c2b58a55147bf09873848b0bb5bd3913019bc3f8d4b5969fbd6f7f96fd99a015efaf562a3eeafe3bc13049f8572a6e13ef9ef0e7e75" + +[filesystem] +sha256 = "57c2e5e40c57d54a2eacb55d8855d2963a6c0b33971a3620c1468b732233d593" +sha512 = "11d1dee738bea1fdd15f5cc07ea10bfb9953a4e84361bbdc2c1051f9520463329ec839caffe0e5cf22870584846f9bfe627c1b77ee4b555fcc990b8106791c68" + +[io] +sha256 = "9f1ad5da70f621bbd4c69e3bd90250a0c12ecfde266aa8f99684fc44bc1e7c15" +sha512 = "6d0a9db6848f24762933d1c168a5b5b1065ba838c253ee20454afeb8dd1a049b918d25deff556083d68095dd3126ae131ac3e738774320eee5d918f5a4b5354e" + +[random] +sha256 = "febd6f75dec1fa733b8e25c1cdee4de9acd922ddf755a192d85f479b1f96b445" +sha512 = "1689d2eee3c64b9fc91faaf43741ff95f343b05acc758342dbf3aa86830de1ec66b4bcd0fe22bf1f77abc4a1feeaae90cdc2c06eedc30952a6667f70edca7d8f" + +[sockets] +sha256 = "e82bb0502324f44ef22f6fdadec51f4963faf8ccd21187c37397ea872c0548c0" +sha512 = "b8139db2b26a95d6948e345cf036497883943134ea832abfabd7267682d9f84b4c86ff38fc771125f1a8e2bcd237ea0a731d83bf22df9d78f19e452061227d77" diff --git a/proposals/http/wit/deps.toml b/proposals/http/wit/deps.toml new file mode 100644 index 000000000..07d395a31 --- /dev/null +++ b/proposals/http/wit/deps.toml @@ -0,0 +1 @@ +cli = "https://github.com/WebAssembly/wasi-cli/archive/v0.2.8.tar.gz" diff --git a/proposals/http/wit/deps/cli/command.wit b/proposals/http/wit/deps/cli/command.wit new file mode 100644 index 000000000..38ef86b86 --- /dev/null +++ b/proposals/http/wit/deps/cli/command.wit @@ -0,0 +1,10 @@ +package wasi:cli@0.2.8; + +@since(version = 0.2.0) +world command { + @since(version = 0.2.0) + include imports; + + @since(version = 0.2.0) + export run; +} diff --git a/proposals/http/wit/deps/cli/environment.wit b/proposals/http/wit/deps/cli/environment.wit new file mode 100644 index 000000000..2f449bd7c --- /dev/null +++ b/proposals/http/wit/deps/cli/environment.wit @@ -0,0 +1,22 @@ +@since(version = 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. + @since(version = 0.2.0) + get-environment: func() -> list>; + + /// Get the POSIX-style arguments to the program. + @since(version = 0.2.0) + get-arguments: func() -> list; + + /// Return a path that programs should use as their initial current working + /// directory, interpreting `.` as shorthand for this. + @since(version = 0.2.0) + initial-cwd: func() -> option; +} diff --git a/proposals/http/wit/deps/cli/exit.wit b/proposals/http/wit/deps/cli/exit.wit new file mode 100644 index 000000000..427935c8d --- /dev/null +++ b/proposals/http/wit/deps/cli/exit.wit @@ -0,0 +1,17 @@ +@since(version = 0.2.0) +interface exit { + /// Exit the current instance and any linked instances. + @since(version = 0.2.0) + exit: func(status: result); + + /// Exit the current instance and any linked instances, reporting the + /// specified status code to the host. + /// + /// The meaning of the code depends on the context, with 0 usually meaning + /// "success", and other values indicating various types of failure. + /// + /// This function does not return; the effect is analogous to a trap, but + /// without the connotation that something bad has happened. + @unstable(feature = cli-exit-with-code) + exit-with-code: func(status-code: u8); +} diff --git a/proposals/http/wit/deps/cli/imports.wit b/proposals/http/wit/deps/cli/imports.wit new file mode 100644 index 000000000..cec1be520 --- /dev/null +++ b/proposals/http/wit/deps/cli/imports.wit @@ -0,0 +1,36 @@ +package wasi:cli@0.2.8; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + include wasi:clocks/imports@0.2.8; + @since(version = 0.2.0) + include wasi:filesystem/imports@0.2.8; + @since(version = 0.2.0) + include wasi:sockets/imports@0.2.8; + @since(version = 0.2.0) + include wasi:random/imports@0.2.8; + @since(version = 0.2.0) + include wasi:io/imports@0.2.8; + + @since(version = 0.2.0) + import environment; + @since(version = 0.2.0) + import exit; + @since(version = 0.2.0) + import stdin; + @since(version = 0.2.0) + import stdout; + @since(version = 0.2.0) + import stderr; + @since(version = 0.2.0) + import terminal-input; + @since(version = 0.2.0) + import terminal-output; + @since(version = 0.2.0) + import terminal-stdin; + @since(version = 0.2.0) + import terminal-stdout; + @since(version = 0.2.0) + import terminal-stderr; +} diff --git a/proposals/http/wit/deps/cli/run.wit b/proposals/http/wit/deps/cli/run.wit new file mode 100644 index 000000000..655346efb --- /dev/null +++ b/proposals/http/wit/deps/cli/run.wit @@ -0,0 +1,6 @@ +@since(version = 0.2.0) +interface run { + /// Run the program. + @since(version = 0.2.0) + run: func() -> result; +} diff --git a/proposals/http/wit/deps/cli/stdio.wit b/proposals/http/wit/deps/cli/stdio.wit new file mode 100644 index 000000000..44767c647 --- /dev/null +++ b/proposals/http/wit/deps/cli/stdio.wit @@ -0,0 +1,26 @@ +@since(version = 0.2.0) +interface stdin { + @since(version = 0.2.0) + use wasi:io/streams@0.2.8.{input-stream}; + + @since(version = 0.2.0) + get-stdin: func() -> input-stream; +} + +@since(version = 0.2.0) +interface stdout { + @since(version = 0.2.0) + use wasi:io/streams@0.2.8.{output-stream}; + + @since(version = 0.2.0) + get-stdout: func() -> output-stream; +} + +@since(version = 0.2.0) +interface stderr { + @since(version = 0.2.0) + use wasi:io/streams@0.2.8.{output-stream}; + + @since(version = 0.2.0) + get-stderr: func() -> output-stream; +} diff --git a/proposals/http/wit/deps/cli/terminal.wit b/proposals/http/wit/deps/cli/terminal.wit new file mode 100644 index 000000000..d305498c6 --- /dev/null +++ b/proposals/http/wit/deps/cli/terminal.wit @@ -0,0 +1,62 @@ +/// 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. +@since(version = 0.2.0) +interface terminal-input { + /// The input side of a terminal. + @since(version = 0.2.0) + 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. +@since(version = 0.2.0) +interface terminal-output { + /// The output side of a terminal. + @since(version = 0.2.0) + resource terminal-output; +} + +/// An interface providing an optional `terminal-input` for stdin as a +/// link-time authority. +@since(version = 0.2.0) +interface terminal-stdin { + @since(version = 0.2.0) + use terminal-input.{terminal-input}; + + /// If stdin is connected to a terminal, return a `terminal-input` handle + /// allowing further interaction with it. + @since(version = 0.2.0) + get-terminal-stdin: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stdout as a +/// link-time authority. +@since(version = 0.2.0) +interface terminal-stdout { + @since(version = 0.2.0) + use terminal-output.{terminal-output}; + + /// If stdout is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + @since(version = 0.2.0) + get-terminal-stdout: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stderr as a +/// link-time authority. +@since(version = 0.2.0) +interface terminal-stderr { + @since(version = 0.2.0) + use terminal-output.{terminal-output}; + + /// If stderr is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + @since(version = 0.2.0) + get-terminal-stderr: func() -> option; +} diff --git a/proposals/http/wit/deps/clocks/monotonic-clock.wit b/proposals/http/wit/deps/clocks/monotonic-clock.wit new file mode 100644 index 000000000..e60f366f2 --- /dev/null +++ b/proposals/http/wit/deps/clocks/monotonic-clock.wit @@ -0,0 +1,55 @@ +package wasi:clocks@0.2.8; +/// 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. +@since(version = 0.2.0) +interface monotonic-clock { + @since(version = 0.2.0) + use wasi:io/poll@0.2.8.{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. + @since(version = 0.2.0) + type instant = u64; + + /// A duration of time, in nanoseconds. + @since(version = 0.2.0) + 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. + /// + /// For completeness, this function traps if it's not possible to represent + /// the value of the clock in an `instant`. Consequently, implementations + /// should ensure that the starting time is low enough to avoid the + /// possibility of overflow in practice. + @since(version = 0.2.0) + now: func() -> instant; + + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + @since(version = 0.2.0) + resolution: func() -> duration; + + /// Create a `pollable` which will resolve once the specified instant + /// has occurred. + @since(version = 0.2.0) + subscribe-instant: func( + when: instant, + ) -> pollable; + + /// Create a `pollable` that will resolve after the specified duration has + /// elapsed from the time this function is invoked. + @since(version = 0.2.0) + subscribe-duration: func( + when: duration, + ) -> pollable; +} diff --git a/proposals/http/wit/deps/clocks/timezone.wit b/proposals/http/wit/deps/clocks/timezone.wit new file mode 100644 index 000000000..534814a63 --- /dev/null +++ b/proposals/http/wit/deps/clocks/timezone.wit @@ -0,0 +1,55 @@ +package wasi:clocks@0.2.8; + +@unstable(feature = clocks-timezone) +interface timezone { + @unstable(feature = clocks-timezone) + use wall-clock.{datetime}; + + /// Return information needed to display the given `datetime`. This includes + /// the UTC offset, the time zone name, and a flag indicating whether + /// daylight saving time is active. + /// + /// If the timezone cannot be determined for the given `datetime`, return a + /// `timezone-display` for `UTC` with a `utc-offset` of 0 and no daylight + /// saving time. + @unstable(feature = clocks-timezone) + display: func(when: datetime) -> timezone-display; + + /// The same as `display`, but only return the UTC offset. + @unstable(feature = clocks-timezone) + utc-offset: func(when: datetime) -> s32; + + /// Information useful for displaying the timezone of a specific `datetime`. + /// + /// This information may vary within a single `timezone` to reflect daylight + /// saving time adjustments. + @unstable(feature = clocks-timezone) + record timezone-display { + /// The number of seconds difference between UTC time and the local + /// time of the timezone. + /// + /// The returned value will always be less than 86400 which is the + /// number of seconds in a day (24*60*60). + /// + /// In implementations that do not expose an actual time zone, this + /// should return 0. + utc-offset: s32, + + /// The abbreviated name of the timezone to display to a user. The name + /// `UTC` indicates Coordinated Universal Time. Otherwise, this should + /// reference local standards for the name of the time zone. + /// + /// In implementations that do not expose an actual time zone, this + /// should be the string `UTC`. + /// + /// In time zones that do not have an applicable name, a formatted + /// representation of the UTC offset may be returned, such as `-04:00`. + name: string, + + /// Whether daylight saving time is active. + /// + /// In implementations that do not expose an actual time zone, this + /// should return false. + in-daylight-saving-time: bool, + } +} diff --git a/proposals/http/wit/deps/clocks/wall-clock.wit b/proposals/http/wit/deps/clocks/wall-clock.wit new file mode 100644 index 000000000..3386c800b --- /dev/null +++ b/proposals/http/wit/deps/clocks/wall-clock.wit @@ -0,0 +1,46 @@ +package wasi:clocks@0.2.8; +/// 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. +@since(version = 0.2.0) +interface wall-clock { + /// A time and date in seconds plus nanoseconds. + @since(version = 0.2.0) + 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 + @since(version = 0.2.0) + now: func() -> datetime; + + /// Query the resolution of the clock. + /// + /// The nanoseconds field of the output is always less than 1000000000. + @since(version = 0.2.0) + resolution: func() -> datetime; +} diff --git a/proposals/http/wit/deps/clocks/world.wit b/proposals/http/wit/deps/clocks/world.wit new file mode 100644 index 000000000..1655ca830 --- /dev/null +++ b/proposals/http/wit/deps/clocks/world.wit @@ -0,0 +1,11 @@ +package wasi:clocks@0.2.8; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import monotonic-clock; + @since(version = 0.2.0) + import wall-clock; + @unstable(feature = clocks-timezone) + import timezone; +} diff --git a/proposals/http/wit/deps/filesystem/preopens.wit b/proposals/http/wit/deps/filesystem/preopens.wit new file mode 100644 index 000000000..0d2cca65d --- /dev/null +++ b/proposals/http/wit/deps/filesystem/preopens.wit @@ -0,0 +1,11 @@ +package wasi:filesystem@0.2.8; + +@since(version = 0.2.0) +interface preopens { + @since(version = 0.2.0) + use types.{descriptor}; + + /// Return the set of preopened directories, and their paths. + @since(version = 0.2.0) + get-directories: func() -> list>; +} diff --git a/proposals/http/wit/deps/filesystem/types.wit b/proposals/http/wit/deps/filesystem/types.wit new file mode 100644 index 000000000..ac68f88af --- /dev/null +++ b/proposals/http/wit/deps/filesystem/types.wit @@ -0,0 +1,676 @@ +package wasi:filesystem@0.2.8; +/// 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 +@since(version = 0.2.0) +interface types { + @since(version = 0.2.0) + use wasi:io/streams@0.2.8.{input-stream, output-stream, error}; + @since(version = 0.2.0) + use wasi:clocks/wall-clock@0.2.8.{datetime}; + + /// File size or length of a region within a file. + @since(version = 0.2.0) + type filesize = u64; + + /// The type of a filesystem object referenced by a descriptor. + /// + /// Note: This was called `filetype` in earlier versions of WASI. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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 integrity + /// 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, + } + + /// File attributes. + /// + /// Note: This was called `filestat` in earlier versions of WASI. + @since(version = 0.2.0) + 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, + } + + /// Flags determining the method of how paths are resolved. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + type link-count = u64; + + /// When setting a timestamp, this gives the value to set it to. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + resource descriptor { + /// 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. + @since(version = 0.2.0) + read-via-stream: func( + /// The offset within the file at which to start reading. + 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. + @since(version = 0.2.0) + write-via-stream: func( + /// The offset within the file at which to start writing. + offset: filesize, + ) -> result; + + /// 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 POSIX. + @since(version = 0.2.0) + append-via-stream: func() -> result; + + /// Provide file advisory information on a descriptor. + /// + /// This is similar to `posix_fadvise` in POSIX. + @since(version = 0.2.0) + advise: func( + /// The offset within the file to which the advisory applies. + offset: filesize, + /// The length of the region to which the advisory applies. + length: filesize, + /// The advice. + advice: advice + ) -> 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. + @since(version = 0.2.0) + sync-data: func() -> 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + get-type: func() -> result; + + /// 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + set-times: func( + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + read: func( + /// The maximum number of bytes to read. + length: filesize, + /// The offset within the file at which to read. + offset: filesize, + ) -> result, bool>, 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. + @since(version = 0.2.0) + write: func( + /// Data to write + buffer: list, + /// The offset within the file at which to write. + offset: filesize, + ) -> result; + + /// 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. + @since(version = 0.2.0) + read-directory: func() -> result; + + /// 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. + @since(version = 0.2.0) + sync: func() -> result<_, error-code>; + + /// Create a directory. + /// + /// Note: This is similar to `mkdirat` in POSIX. + @since(version = 0.2.0) + create-directory-at: func( + /// The relative path at which to create the directory. + path: string, + ) -> 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + stat-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + + /// 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. + @since(version = 0.2.0) + set-times-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to operate on. + path: string, + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, error-code>; + + /// Create a hard link. + /// + /// Fails with `error-code::no-entry` if the old path does not exist, + /// with `error-code::exist` if the new path already exists, and + /// `error-code::not-permitted` if the old path is not a file. + /// + /// Note: This is similar to `linkat` in POSIX. + @since(version = 0.2.0) + link-at: func( + /// Flags determining the method of how the path is resolved. + old-path-flags: path-flags, + /// The relative source path from which to link. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path at which to create the hard link. + new-path: string, + ) -> result<_, error-code>; + + /// Open a file or directory. + /// + /// 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. + @since(version = 0.2.0) + open-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the object to open. + path: string, + /// The method by which to open the file. + open-flags: open-flags, + /// Flags to use for the resulting descriptor. + %flags: descriptor-flags, + ) -> 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. + @since(version = 0.2.0) + readlink-at: func( + /// The relative path of the symbolic link from which to read. + 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. + @since(version = 0.2.0) + remove-directory-at: func( + /// The relative path to a directory to remove. + path: string, + ) -> result<_, error-code>; + + /// Rename a filesystem object. + /// + /// Note: This is similar to `renameat` in POSIX. + @since(version = 0.2.0) + rename-at: func( + /// The relative source path of the file or directory to rename. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path to which to rename the file or directory. + new-path: string, + ) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + symlink-at: func( + /// The contents of the symbolic link. + old-path: string, + /// The relative destination path at which to create the symbolic link. + new-path: string, + ) -> 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. + @since(version = 0.2.0) + unlink-file-at: func( + /// The relative path to a file to unlink. + path: string, + ) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + is-same-object: func(other: borrow) -> bool; + + /// 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 encouraged 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. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + metadata-hash-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + } + + /// A stream of directory entries. + @since(version = 0.2.0) + resource directory-entry-stream { + /// Read a single directory entry from a `directory-entry-stream`. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + filesystem-error-code: func(err: borrow) -> option; +} diff --git a/proposals/http/wit/deps/filesystem/world.wit b/proposals/http/wit/deps/filesystem/world.wit new file mode 100644 index 000000000..7daf06758 --- /dev/null +++ b/proposals/http/wit/deps/filesystem/world.wit @@ -0,0 +1,9 @@ +package wasi:filesystem@0.2.8; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import types; + @since(version = 0.2.0) + import preopens; +} diff --git a/proposals/http/wit/deps/io/error.wit b/proposals/http/wit/deps/io/error.wit new file mode 100644 index 000000000..dd5a1af03 --- /dev/null +++ b/proposals/http/wit/deps/io/error.wit @@ -0,0 +1,34 @@ +package wasi:io@0.2.8; + +@since(version = 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 + /// offer functions to "downcast" this error into more specific types. For example, + /// errors returned from streams derived from filesystem types can be described using + /// the filesystem's own error-code type. This is done using the function + /// `wasi:filesystem/types/filesystem-error-code`, which takes a `borrow` + /// parameter and returns an `option`. + /// + /// The set of functions which can "downcast" an `error` into a more + /// concrete type is open. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + to-debug-string: func() -> string; + } +} diff --git a/proposals/http/wit/deps/io/poll.wit b/proposals/http/wit/deps/io/poll.wit new file mode 100644 index 000000000..833b381d9 --- /dev/null +++ b/proposals/http/wit/deps/io/poll.wit @@ -0,0 +1,47 @@ +package wasi:io@0.2.8; + +/// A poll API intended to let users wait for I/O events on multiple handles +/// at once. +@since(version = 0.2.0) +interface poll { + /// `pollable` represents a single I/O event which may be ready, or not. + @since(version = 0.2.0) + resource pollable { + + /// Return the readiness of a pollable. This function never blocks. + /// + /// Returns `true` when the pollable is ready, and `false` otherwise. + @since(version = 0.2.0) + ready: func() -> bool; + + /// `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. + @since(version = 0.2.0) + block: func(); + } + + /// 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. + /// + /// This function traps if either: + /// - the list is empty, or: + /// - the list contains more elements than can be indexed with a `u32` value. + /// + /// 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 ready for I/O. + @since(version = 0.2.0) + poll: func(in: list>) -> list; +} diff --git a/proposals/http/wit/deps/io/streams.wit b/proposals/http/wit/deps/io/streams.wit new file mode 100644 index 000000000..fbb0268b0 --- /dev/null +++ b/proposals/http/wit/deps/io/streams.wit @@ -0,0 +1,258 @@ +package wasi:io@0.2.8; + +/// 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. +@since(version = 0.2.0) +interface streams { + @since(version = 0.2.0) + use error.{error}; + @since(version = 0.2.0) + use poll.{pollable}; + + /// An error for input-stream and output-stream operations. + @since(version = 0.2.0) + variant stream-error { + /// The last operation (a write or flush) failed before completion. + /// + /// More information is available in the `error` payload. + /// + /// After this, the stream will be closed. All future operations return + /// `stream-error::closed`. + 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`. + @since(version = 0.2.0) + resource input-stream { + /// 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. + @since(version = 0.2.0) + read: func( + /// The maximum number of bytes to read + len: u64 + ) -> result, stream-error>; + + /// Read bytes from a stream, after blocking until at least one byte can + /// be read. Except for blocking, behavior is identical to `read`. + @since(version = 0.2.0) + blocking-read: func( + /// The maximum number of bytes to read + 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. + @since(version = 0.2.0) + skip: func( + /// The maximum number of bytes to skip. + len: u64, + ) -> result; + + /// Skip bytes from a stream, after blocking until at least one byte + /// can be skipped. Except for blocking behavior, identical to `skip`. + @since(version = 0.2.0) + blocking-skip: func( + /// The maximum number of bytes to skip. + 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. + @since(version = 0.2.0) + 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`. + /// + /// Dropping an `output-stream` while there's still an active write in + /// progress may result in the data being lost. Before dropping the stream, + /// be sure to fully flush your writes. + @since(version = 0.2.0) + resource output-stream { + /// 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. + @since(version = 0.2.0) + check-write: func() -> result; + + /// 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. + @since(version = 0.2.0) + write: func( + contents: list + ) -> result<_, stream-error>; + + /// 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. + /// + /// Returns success when all of the contents written are successfully + /// flushed to output. If an error occurs at any point before all + /// contents are successfully flushed, that error is returned as soon as + /// possible. If writing and flushing the complete contents causes the + /// stream to become closed, this call should return success, and + /// subsequent calls to check-write or other interfaces should return + /// stream-error::closed. + @since(version = 0.2.0) + blocking-write-and-flush: func( + contents: list + ) -> result<_, stream-error>; + + /// 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. + @since(version = 0.2.0) + flush: func() -> result<_, stream-error>; + + /// Request to flush buffered output, and block until flush completes + /// and stream is ready for writing again. + @since(version = 0.2.0) + blocking-flush: func() -> result<_, stream-error>; + + /// Create a `pollable` which will resolve once the output-stream + /// is ready for more writing, or an error has occurred. 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. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// 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. + @since(version = 0.2.0) + write-zeroes: func( + /// The number of zero-bytes to write + len: u64 + ) -> 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. + /// + /// Functionality is equivelant to `blocking-write-and-flush` with + /// contents given as a list of len containing only zeroes. + @since(version = 0.2.0) + blocking-write-zeroes-and-flush: func( + /// The number of zero-bytes to write + len: u64 + ) -> result<_, stream-error>; + + /// Read from one stream and write to another. + /// + /// The behavior of splice is equivalent 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`. + @since(version = 0.2.0) + splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + + /// 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`. + @since(version = 0.2.0) + blocking-splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + } +} diff --git a/proposals/http/wit/deps/io/world.wit b/proposals/http/wit/deps/io/world.wit new file mode 100644 index 000000000..1cc3fce12 --- /dev/null +++ b/proposals/http/wit/deps/io/world.wit @@ -0,0 +1,10 @@ +package wasi:io@0.2.8; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import streams; + + @since(version = 0.2.0) + import poll; +} diff --git a/proposals/http/wit/deps/random/insecure-seed.wit b/proposals/http/wit/deps/random/insecure-seed.wit new file mode 100644 index 000000000..b2b435e55 --- /dev/null +++ b/proposals/http/wit/deps/random/insecure-seed.wit @@ -0,0 +1,27 @@ +package wasi:random@0.2.8; +/// The insecure-seed interface for seeding hash-map DoS resistance. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.2.0) +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. + @since(version = 0.2.0) + insecure-seed: func() -> tuple; +} diff --git a/proposals/http/wit/deps/random/insecure.wit b/proposals/http/wit/deps/random/insecure.wit new file mode 100644 index 000000000..6dc77adec --- /dev/null +++ b/proposals/http/wit/deps/random/insecure.wit @@ -0,0 +1,25 @@ +package wasi:random@0.2.8; +/// The insecure interface for insecure pseudo-random numbers. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.2.0) +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. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + get-insecure-random-u64: func() -> u64; +} diff --git a/proposals/http/wit/deps/random/random.wit b/proposals/http/wit/deps/random/random.wit new file mode 100644 index 000000000..524e77d4a --- /dev/null +++ b/proposals/http/wit/deps/random/random.wit @@ -0,0 +1,29 @@ +package wasi:random@0.2.8; +/// WASI Random is a random data API. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.2.0) +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. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + get-random-u64: func() -> u64; +} diff --git a/proposals/http/wit/deps/random/world.wit b/proposals/http/wit/deps/random/world.wit new file mode 100644 index 000000000..c0c3272c9 --- /dev/null +++ b/proposals/http/wit/deps/random/world.wit @@ -0,0 +1,13 @@ +package wasi:random@0.2.8; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import random; + + @since(version = 0.2.0) + import insecure; + + @since(version = 0.2.0) + import insecure-seed; +} diff --git a/proposals/http/wit/deps/sockets/instance-network.wit b/proposals/http/wit/deps/sockets/instance-network.wit new file mode 100644 index 000000000..5f6e6c1cc --- /dev/null +++ b/proposals/http/wit/deps/sockets/instance-network.wit @@ -0,0 +1,11 @@ + +/// This interface provides a value-export of the default network handle.. +@since(version = 0.2.0) +interface instance-network { + @since(version = 0.2.0) + use network.{network}; + + /// Get a handle to the default network. + @since(version = 0.2.0) + instance-network: func() -> network; +} diff --git a/proposals/http/wit/deps/sockets/ip-name-lookup.wit b/proposals/http/wit/deps/sockets/ip-name-lookup.wit new file mode 100644 index 000000000..ecdaa8493 --- /dev/null +++ b/proposals/http/wit/deps/sockets/ip-name-lookup.wit @@ -0,0 +1,56 @@ +@since(version = 0.2.0) +interface ip-name-lookup { + @since(version = 0.2.0) + use wasi:io/poll@0.2.8.{pollable}; + @since(version = 0.2.0) + use network.{network, error-code, ip-address}; + + /// 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: + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + resolve-addresses: func(network: borrow, name: string) -> result; + + @since(version = 0.2.0) + 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) + @since(version = 0.2.0) + 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 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } +} diff --git a/proposals/http/wit/deps/sockets/network.wit b/proposals/http/wit/deps/sockets/network.wit new file mode 100644 index 000000000..75a4f7d7f --- /dev/null +++ b/proposals/http/wit/deps/sockets/network.wit @@ -0,0 +1,169 @@ +@since(version = 0.2.0) +interface network { + @unstable(feature = network-error-code) + use wasi:io/error@0.2.8.{error}; + + /// 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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, + } + + /// Attempts to extract a network-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 + /// network-related information about the error to return. + /// + /// Note that this function is fallible because not all stream-related + /// errors are network-related errors. + @unstable(feature = network-error-code) + network-error-code: func(err: borrow) -> option; + + @since(version = 0.2.0) + enum ip-address-family { + /// Similar to `AF_INET` in POSIX. + ipv4, + + /// Similar to `AF_INET6` in POSIX. + ipv6, + } + + @since(version = 0.2.0) + type ipv4-address = tuple; + @since(version = 0.2.0) + type ipv6-address = tuple; + + @since(version = 0.2.0) + variant ip-address { + ipv4(ipv4-address), + ipv6(ipv6-address), + } + + @since(version = 0.2.0) + record ipv4-socket-address { + /// sin_port + port: u16, + /// sin_addr + address: ipv4-address, + } + + @since(version = 0.2.0) + record ipv6-socket-address { + /// sin6_port + port: u16, + /// sin6_flowinfo + flow-info: u32, + /// sin6_addr + address: ipv6-address, + /// sin6_scope_id + scope-id: u32, + } + + @since(version = 0.2.0) + variant ip-socket-address { + ipv4(ipv4-socket-address), + ipv6(ipv6-socket-address), + } +} diff --git a/proposals/http/wit/deps/sockets/tcp-create-socket.wit b/proposals/http/wit/deps/sockets/tcp-create-socket.wit new file mode 100644 index 000000000..eedbd3076 --- /dev/null +++ b/proposals/http/wit/deps/sockets/tcp-create-socket.wit @@ -0,0 +1,30 @@ +@since(version = 0.2.0) +interface tcp-create-socket { + @since(version = 0.2.0) + use network.{network, error-code, ip-address-family}; + @since(version = 0.2.0) + 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + create-tcp-socket: func(address-family: ip-address-family) -> result; +} diff --git a/proposals/http/wit/deps/sockets/tcp.wit b/proposals/http/wit/deps/sockets/tcp.wit new file mode 100644 index 000000000..9b5552d2e --- /dev/null +++ b/proposals/http/wit/deps/sockets/tcp.wit @@ -0,0 +1,387 @@ +@since(version = 0.2.0) +interface tcp { + @since(version = 0.2.0) + use wasi:io/streams@0.2.8.{input-stream, output-stream}; + @since(version = 0.2.0) + use wasi:io/poll@0.2.8.{pollable}; + @since(version = 0.2.0) + use wasi:clocks/monotonic-clock@0.2.8.{duration}; + @since(version = 0.2.0) + use network.{network, error-code, ip-socket-address, ip-address-family}; + + @since(version = 0.2.0) + 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 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. + @since(version = 0.2.0) + resource tcp-socket { + /// 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + @since(version = 0.2.0) + finish-bind: func() -> result<_, error-code>; + + /// Connect to a remote endpoint. + /// + /// On success: + /// - the socket is transitioned into the `connected` 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-connect: func(network: borrow, remote-address: ip-socket-address) -> result<_, error-code>; + @since(version = 0.2.0) + finish-connect: func() -> 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-listen: func() -> result<_, error-code>; + @since(version = 0.2.0) + finish-listen: func() -> result<_, error-code>; + + /// 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + accept: func() -> result, error-code>; + + /// 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + local-address: func() -> result; + + /// Get the remote address. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + remote-address: func() -> result; + + /// Whether the socket is in the `listening` state. + /// + /// Equivalent to the SO_ACCEPTCONN socket option. + @since(version = 0.2.0) + is-listening: func() -> bool; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + @since(version = 0.2.0) + address-family: func() -> ip-address-family; + + /// 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. + @since(version = 0.2.0) + set-listen-backlog-size: func(value: u64) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + keep-alive-enabled: func() -> result; + @since(version = 0.2.0) + set-keep-alive-enabled: func(value: bool) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + keep-alive-idle-time: func() -> result; + @since(version = 0.2.0) + set-keep-alive-idle-time: func(value: duration) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + keep-alive-interval: func() -> result; + @since(version = 0.2.0) + set-keep-alive-interval: func(value: duration) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + keep-alive-count: func() -> result; + @since(version = 0.2.0) + set-keep-alive-count: func(value: u32) -> 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. + @since(version = 0.2.0) + hop-limit: func() -> result; + @since(version = 0.2.0) + set-hop-limit: func(value: u8) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + receive-buffer-size: func() -> result; + @since(version = 0.2.0) + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + @since(version = 0.2.0) + send-buffer-size: func() -> result; + @since(version = 0.2.0) + set-send-buffer-size: func(value: 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. + /// + /// 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 more information. + /// + /// Note: this function is here for WASI 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// 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 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code>; + } +} diff --git a/proposals/http/wit/deps/sockets/udp-create-socket.wit b/proposals/http/wit/deps/sockets/udp-create-socket.wit new file mode 100644 index 000000000..e8eeacbfe --- /dev/null +++ b/proposals/http/wit/deps/sockets/udp-create-socket.wit @@ -0,0 +1,30 @@ +@since(version = 0.2.0) +interface udp-create-socket { + @since(version = 0.2.0) + use network.{network, error-code, ip-address-family}; + @since(version = 0.2.0) + 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: + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + create-udp-socket: func(address-family: ip-address-family) -> result; +} diff --git a/proposals/http/wit/deps/sockets/udp.wit b/proposals/http/wit/deps/sockets/udp.wit new file mode 100644 index 000000000..0000a157e --- /dev/null +++ b/proposals/http/wit/deps/sockets/udp.wit @@ -0,0 +1,288 @@ +@since(version = 0.2.0) +interface udp { + @since(version = 0.2.0) + use wasi:io/poll@0.2.8.{pollable}; + @since(version = 0.2.0) + use network.{network, error-code, ip-socket-address, ip-address-family}; + + /// A received datagram. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + resource udp-socket { + /// 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + @since(version = 0.2.0) + finish-bind: func() -> 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + %stream: func(remote-address: option) -> 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + local-address: 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + remote-address: func() -> result; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + @since(version = 0.2.0) + address-family: func() -> ip-address-family; + + /// 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. + @since(version = 0.2.0) + unicast-hop-limit: func() -> result; + @since(version = 0.2.0) + set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + receive-buffer-size: func() -> result; + @since(version = 0.2.0) + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + @since(version = 0.2.0) + send-buffer-size: func() -> result; + @since(version = 0.2.0) + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + + /// Create a `pollable` which will resolve once the socket is ready for I/O. + /// + /// Note: this function is here for WASI 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } + + @since(version = 0.2.0) + 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 + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + 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 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } + + @since(version = 0.2.0) + 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 + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + 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 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } +} diff --git a/proposals/http/wit/deps/sockets/world.wit b/proposals/http/wit/deps/sockets/world.wit new file mode 100644 index 000000000..4441e9119 --- /dev/null +++ b/proposals/http/wit/deps/sockets/world.wit @@ -0,0 +1,19 @@ +package wasi:sockets@0.2.8; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import instance-network; + @since(version = 0.2.0) + import network; + @since(version = 0.2.0) + import udp; + @since(version = 0.2.0) + import udp-create-socket; + @since(version = 0.2.0) + import tcp; + @since(version = 0.2.0) + import tcp-create-socket; + @since(version = 0.2.0) + import ip-name-lookup; +} diff --git a/proposals/http/wit/handler.wit b/proposals/http/wit/handler.wit new file mode 100644 index 000000000..6a6c62966 --- /dev/null +++ b/proposals/http/wit/handler.wit @@ -0,0 +1,49 @@ +/// This interface defines a handler of incoming HTTP Requests. It should +/// be exported by components which can respond to HTTP Requests. +@since(version = 0.2.0) +interface incoming-handler { + @since(version = 0.2.0) + use types.{incoming-request, 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. + @since(version = 0.2.0) + 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. +@since(version = 0.2.0) +interface outgoing-handler { + @since(version = 0.2.0) + use types.{ + outgoing-request, request-options, future-incoming-response, 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`. + @since(version = 0.2.0) + handle: func( + request: outgoing-request, + options: option + ) -> result; +} diff --git a/proposals/http/wit/proxy.wit b/proposals/http/wit/proxy.wit new file mode 100644 index 000000000..5ae19e6d7 --- /dev/null +++ b/proposals/http/wit/proxy.wit @@ -0,0 +1,50 @@ +package wasi:http@0.2.8; + +/// The `wasi:http/imports` world imports all the APIs for HTTP proxies. +/// It is intended to be `include`d in other worlds. +@since(version = 0.2.0) +world imports { + /// HTTP proxies have access to time and randomness. + @since(version = 0.2.0) + import wasi:clocks/monotonic-clock@0.2.8; + @since(version = 0.2.0) + import wasi:clocks/wall-clock@0.2.8; + @since(version = 0.2.0) + import wasi:random/random@0.2.8; + + /// Proxies have standard output and error streams which are expected to + /// terminate in a developer-facing console provided by the host. + @since(version = 0.2.0) + import wasi:cli/stdout@0.2.8; + @since(version = 0.2.0) + import wasi:cli/stderr@0.2.8; + + /// TODO: this is a temporary workaround until component tooling is able to + /// gracefully handle the absence of stdin. Hosts must return an eof stream + /// for this import, which is what wasi-libc + tooling will do automatically + /// when this import is properly removed. + @since(version = 0.2.0) + import wasi:cli/stdin@0.2.8; + + /// This is the default handler to use when user code simply wants to make an + /// HTTP request (e.g., via `fetch()`). + @since(version = 0.2.0) + import outgoing-handler; +} + +/// 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. +@since(version = 0.2.0) +world proxy { + @since(version = 0.2.0) + include imports; + + /// The host delivers incoming HTTP requests to a component by calling the + /// `handle` function of this exported interface. A host may arbitrarily reuse + /// or not reuse component instance when delivering incoming HTTP requests and + /// thus a component must be able to handle 0..N calls to `handle`. + @since(version = 0.2.0) + export incoming-handler; +} diff --git a/proposals/http/wit/types.wit b/proposals/http/wit/types.wit new file mode 100644 index 000000000..f91ee1f19 --- /dev/null +++ b/proposals/http/wit/types.wit @@ -0,0 +1,688 @@ +/// 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. +@since(version = 0.2.0) +interface types { + @since(version = 0.2.0) + use wasi:clocks/monotonic-clock@0.2.8.{duration}; + @since(version = 0.2.0) + use wasi:io/streams@0.2.8.{input-stream, output-stream}; + @since(version = 0.2.0) + use wasi:io/error@0.2.8.{error as io-error}; + @since(version = 0.2.0) + use wasi:io/poll@0.2.8.{pollable}; + + /// This type corresponds to HTTP standard Methods. + @since(version = 0.2.0) + variant method { + get, + head, + post, + put, + delete, + connect, + options, + trace, + patch, + other(string) + } + + /// This type corresponds to HTTP standard Related Schemes. + @since(version = 0.2.0) + variant scheme { + HTTP, + HTTPS, + other(string) + } + + /// These cases are inspired by the IANA HTTP Proxy Error Types: + /// + @since(version = 0.2.0) + 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) + } + + /// Defines the case payload type for `DNS-error` above: + @since(version = 0.2.0) + record DNS-error-payload { + rcode: option, + info-code: option + } + + /// Defines the case payload type for `TLS-alert-received` above: + @since(version = 0.2.0) + record TLS-alert-received-payload { + alert-id: option, + alert-message: option + } + + /// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: + @since(version = 0.2.0) + record field-size-payload { + field-name: option, + field-size: option + } + + /// 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. + @since(version = 0.2.0) + http-error-code: func(err: borrow) -> option; + + /// This type enumerates the different kinds of errors that may occur when + /// setting or appending to a `fields` resource. + @since(version = 0.2.0) + variant header-error { + /// This error indicates that a `field-name` 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-name` 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 names are always strings. + /// + /// Field names should always be treated as case insensitive by the `fields` + /// resource for the purposes of equality checking. + @since(version = 0.2.1) + type field-name = field-key; + + /// Field keys are always strings. + /// + /// Field keys should always be treated as case insensitive by the `fields` + /// resource for the purposes of equality checking. + /// + /// # Deprecation + /// + /// This type has been deprecated in favor of the `field-name` type. + @since(version = 0.2.0) + @deprecated(version = 0.2.2) + 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. + @since(version = 0.2.0) + 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 + /// immutable. In an immutable fields, the `set`, `append`, and `delete` + /// operations will fail with `header-error.immutable`. + @since(version = 0.2.0) + resource fields { + + /// Construct an empty HTTP Fields. + /// + /// The resulting `fields` is mutable. + @since(version = 0.2.0) + constructor(); + + /// Construct an HTTP Fields. + /// + /// The resulting `fields` is mutable. + /// + /// The list represents each name-value pair in the Fields. Names + /// which have multiple values are represented by multiple entries in this + /// list with the same name. + /// + /// The tuple is a pair of the field name, represented as a string, and + /// Value, represented as a list of bytes. + /// + /// An error result will be returned if any `field-name` or `field-value` is + /// syntactically invalid, or if a field is forbidden. + @since(version = 0.2.0) + from-list: static func( + entries: list> + ) -> result; + + /// Get all of the values corresponding to a name. If the name is not present + /// in this `fields` or is syntactically invalid, an empty list is returned. + /// However, if the name is present but empty, this is represented by a list + /// with one or more empty field-values present. + @since(version = 0.2.0) + get: func(name: field-name) -> list; + + /// Returns `true` when the name is present in this `fields`. If the name is + /// syntactically invalid, `false` is returned. + @since(version = 0.2.0) + has: func(name: field-name) -> bool; + + /// Set all of the values for a name. Clears any existing values for that + /// name, if they have been set. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` or any of + /// the `field-value`s are syntactically invalid. + @since(version = 0.2.0) + set: func(name: field-name, value: list) -> result<_, header-error>; + + /// Delete all values for a name. Does nothing if no values for the name + /// exist. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` is + /// syntactically invalid. + @since(version = 0.2.0) + delete: func(name: field-name) -> result<_, header-error>; + + /// Append a value for a name. Does not change or delete any existing + /// values for that name. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` or + /// `field-value` are syntactically invalid. + @since(version = 0.2.0) + append: func(name: field-name, value: field-value) -> result<_, header-error>; + + /// Retrieve the full set of names and values in the Fields. Like the + /// constructor, the list represents each name-value pair. + /// + /// The outer list represents each name-value pair in the Fields. Names + /// which have multiple values are represented by multiple entries in this + /// list with the same name. + /// + /// The names and values are always returned in the original casing and in + /// the order in which they will be serialized for transport. + @since(version = 0.2.0) + entries: func() -> list>; + + /// Make a deep copy of the Fields. Equivalent in behavior to calling the + /// `fields` constructor on the return value of `entries`. The resulting + /// `fields` is mutable. + @since(version = 0.2.0) + clone: func() -> fields; + } + + /// Headers is an alias for Fields. + @since(version = 0.2.0) + type headers = fields; + + /// Trailers is an alias for Fields. + @since(version = 0.2.0) + type trailers = fields; + + /// Represents an incoming HTTP Request. + @since(version = 0.2.0) + resource incoming-request { + + /// Returns the method of the incoming request. + @since(version = 0.2.0) + method: func() -> method; + + /// Returns the path with query parameters from the request, as a string. + @since(version = 0.2.0) + path-with-query: func() -> option; + + /// Returns the protocol scheme from the request. + @since(version = 0.2.0) + scheme: func() -> option; + + /// Returns the authority of the Request's target URI, if present. + @since(version = 0.2.0) + authority: func() -> option; + + /// 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. + @since(version = 0.2.0) + headers: func() -> headers; + + /// Gives the `incoming-body` associated with this request. Will only + /// return success at most once, and subsequent calls will return error. + @since(version = 0.2.0) + consume: func() -> result; + } + + /// Represents an outgoing HTTP Request. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + constructor( + headers: headers + ); + + /// 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. + @since(version = 0.2.0) + body: func() -> result; + + /// Get the Method for the Request. + @since(version = 0.2.0) + method: func() -> method; + /// Set the Method for the Request. Fails if the string present in a + /// `method.other` argument is not a syntactically valid method. + @since(version = 0.2.0) + set-method: func(method: method) -> result; + + /// Get the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. + @since(version = 0.2.0) + path-with-query: func() -> option; + /// 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. + @since(version = 0.2.0) + set-path-with-query: func(path-with-query: option) -> result; + + /// Get the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. + @since(version = 0.2.0) + scheme: func() -> option; + /// 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. + @since(version = 0.2.0) + set-scheme: func(scheme: option) -> result; + + /// Get the authority of the Request's target URI. 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. + @since(version = 0.2.0) + authority: func() -> option; + /// Set the authority of the Request's target URI. 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. + @since(version = 0.2.0) + set-authority: func(authority: option) -> 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 transferred to + /// another component by e.g. `outgoing-handler.handle`. + @since(version = 0.2.0) + headers: func() -> headers; + } + + /// 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`. + @since(version = 0.2.0) + resource request-options { + /// Construct a default `request-options` value. + @since(version = 0.2.0) + constructor(); + + /// The timeout for the initial connect to the HTTP Server. + @since(version = 0.2.0) + connect-timeout: func() -> option; + + /// Set the timeout for the initial connect to the HTTP Server. An error + /// return value indicates that this timeout is not supported. + @since(version = 0.2.0) + set-connect-timeout: func(duration: option) -> result; + + /// The timeout for receiving the first byte of the Response body. + @since(version = 0.2.0) + first-byte-timeout: func() -> option; + + /// Set the timeout for receiving the first byte of the Response body. An + /// error return value indicates that this timeout is not supported. + @since(version = 0.2.0) + set-first-byte-timeout: func(duration: option) -> result; + + /// The timeout for receiving subsequent chunks of bytes in the Response + /// body stream. + @since(version = 0.2.0) + between-bytes-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. + @since(version = 0.2.0) + set-between-bytes-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`. + @since(version = 0.2.0) + resource response-outparam { + /// Send an HTTP 1xx response. + /// + /// Unlike `response-outparam.set`, this does not consume the + /// `response-outparam`, allowing the guest to send an arbitrary number of + /// informational responses before sending the final response using + /// `response-outparam.set`. + /// + /// This will return an `HTTP-protocol-error` if `status` is not in the + /// range [100-199], or an `internal-error` if the implementation does not + /// support informational responses. + @unstable(feature = informational-outbound-responses) + send-informational: func( + status: u16, + headers: headers + ) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + set: static func( + param: response-outparam, + response: result, + ); + } + + /// This type corresponds to the HTTP standard Status Code. + @since(version = 0.2.0) + type status-code = u16; + + /// Represents an incoming HTTP Response. + @since(version = 0.2.0) + resource incoming-response { + + /// Returns the status code from the incoming response. + @since(version = 0.2.0) + status: func() -> status-code; + + /// 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. + @since(version = 0.2.0) + headers: func() -> headers; + + /// Returns the incoming body. May be called at most once. Returns error + /// if called additional times. + @since(version = 0.2.0) + consume: func() -> result; + } + + /// 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + %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. + @since(version = 0.2.0) + finish: static func(this: incoming-body) -> future-trailers; + } + + /// Represents a future which may eventually 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. + @since(version = 0.2.0) + resource future-trailers { + + /// Returns a pollable which becomes ready when either the trailers have + /// been received, or an error has occurred. When this pollable is ready, + /// the `get` method will return `some`. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// Returns the contents of the trailers, or an error which occurred, + /// 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 occurred 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. + @since(version = 0.2.0) + get: func() -> option, error-code>>>; + } + + /// Represents an outgoing HTTP Response. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + constructor(headers: headers); + + /// Get the HTTP Status Code for the Response. + @since(version = 0.2.0) + status-code: func() -> status-code; + + /// Set the HTTP Status Code for the Response. Fails if the status-code + /// given is not a valid http status code. + @since(version = 0.2.0) + set-status-code: func(status-code: status-code) -> 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 transferred to + /// another component by e.g. `outgoing-handler.handle`. + @since(version = 0.2.0) + headers: func() -> 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. + @since(version = 0.2.0) + body: func() -> result; + } + + /// 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 occurred. The implementation should propagate 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + finish: static func( + this: outgoing-body, + trailers: option + ) -> result<_, error-code>; + } + + /// Represents a future which may eventually 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. + @since(version = 0.2.0) + resource future-incoming-response { + /// Returns a pollable which becomes ready when either the Response has + /// been received, or an error has occurred. When this pollable is ready, + /// the `get` method will return `some`. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// 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 received successfully, or that an error + /// occurred. Errors may also occur while consuming the response body, + /// but those will be reported by the `incoming-body` and its + /// `output-stream` child. + @since(version = 0.2.0) + get: func() -> option>>; + } +} diff --git a/proposals/io/LICENSE.md b/proposals/io/LICENSE.md new file mode 100644 index 000000000..475309577 --- /dev/null +++ b/proposals/io/LICENSE.md @@ -0,0 +1,8 @@ +Copyright © 2019-2023 the Contributors to the WASI Specification, published +by the [WebAssembly Community Group][cg] under the +[W3C Community Contributor License Agreement (CLA)][cla]. A human-readable +[summary][summary] is available. + +[cg]: https://www.w3.org/community/webassembly/ +[cla]: https://www.w3.org/community/about/agreements/cla/ +[summary]: https://www.w3.org/community/about/agreements/cla-deed/ diff --git a/proposals/io/README.md b/proposals/io/README.md new file mode 100644 index 000000000..9efd0bcaf --- /dev/null +++ b/proposals/io/README.md @@ -0,0 +1,157 @@ +# WASI I/O + +A proposed [WebAssembly System Interface](https://github.com/WebAssembly/WASI) API. + +### Current Phase + +WASI I/O is currently in [Phase 3]. + +[Phase 3]: https://github.com/WebAssembly/WASI/blob/main/Proposals.md#phase-3---implementation-phase-cg--wg + +### Champions + +- Dan Gohman + +### Portability Criteria + +WASI I/O must have host implementations which can pass the testsuite on at least Windows, macOS, and Linux. + +WASI I/O must have at least two complete independent implementations. + +## Table of Contents + +- [Introduction](#introduction) +- [Goals [or Motivating Use Cases, or Scenarios]](#goals-or-motivating-use-cases-or-scenarios) +- [Non-goals](#non-goals) +- [API walk-through](#api-walk-through) + - [Use case: copying from input to output using `read`/`write`](#use-case-copying-from-input-to-output-using-readwrite) + - [Use case: copying from input to output using `splice`](#use-case-copying-from-input-to-output-using-splice) + - [Use case: copying from input to output using `forward`](#use-case-copying-from-input-to-output-using-forward) +- [Detailed design discussion](#detailed-design-discussion) + - [Should we have support for non-blocking read/write?](#should-we-have-support-for-non-blocking-read-write) + - [Why do read/write use u64 sizes?[Tricky design choice 2]](#why-do-read-write-use-u64-sizes) + - [Why have a `forward` function when you can just `splice` in a loop?](#why-have-a-forward-function-when-you-can-just-splice-in-a-loop) +- [Stakeholder Interest & Feedback](#stakeholder-interest--feedback) +- [References & acknowledgements](#references--acknowledgements) + +### Introduction + +Wasi I/O is an API providing I/O stream abstractions. There are two +types, `input-stream`, and `output-stream`, which support `read` and +`write`, respectively, as well as a number of utility functions. + +### Goals + + - Be usable by wasi-libc to implement POSIX-like file and socket APIs. + - Support many different kinds of host streams, including files, sockets, + pipes, character devices, and more. + +### Non-goals + + - Support for async. That will be addressed in the component-model async + design, where we can have the benefit of tighter integration with language + bindings. + - Bidirectional streams. + +### API walk-through + +#### Use Case: copying from input to output using `read`/`write` + +```rust + fn copy_data(input: InputStream, output: OutputStream) -> Result<(), StreamError> { + const BUFFER_LEN: usize = 4096; + + let wait_input = [subscribe_to_input_stream(input)]; + let wait_output = [subscribe_to_output_stream(output)]; + + loop { + let (mut data, mut eos) = input.read(BUFFER_LEN)?; + + // If we didn't get any data promptly, wait for it. + if data.len() == 0 { + let _ = poll_list(&wait_input[..]); + (data, eos) = input.read(BUFFER_LEN)?; + } + + let mut remaining = &data[..]; + while !remaining.is_empty() { + let mut num_written = output.write(remaining)?; + + // If we didn't put any data promptly, wait for it. + if num_written == 0 { + let _ = poll_list(&wait_output[..]); + num_written = output.write(remaining)?; + } + + remaining = &remaining[num_written..]; + } + if eos { + break; + } + } + Ok(()) + } +``` + +#### Use case: copying from input to output using `splice` + +```rust + fn copy_data(input: InputStream, output: OutputStream) -> Result<(), StreamError> { + let wait_input = [subscribe_to_input_stream(input)]; + + loop { + let (num_copied, eos) = output.splice(input, u64::MAX)?; + if eos { + break; + } + + // If we didn't get any data promptly, wait for it. + if num_copied == 0 { + let _ = poll_list(&wait_input[..]); + } + } + Ok(()) + } +``` + +#### Use case: copying from input to output using `forward` + +```rust + fn copy_data(input: InputStream, output: OutputStream) -> Result<(), StreamError> { + output.forward(input)?; + Ok(()) + } +``` + +### Detailed design discussion + +#### Should we have support for non-blocking read/write? + +This may be something we'll need to revisit, but currently, the way +non-blocking streams work is that they perform reads or writes that +read or write fewer bytes than requested. + +#### Why do read/write use u64 sizes? + +This is to make the API independent of the address space size of +the caller. Callees are still advised to avoid using sizes that +are larger than their instances will be able to allocate. + +#### Why have a `forward` function when you can just `splice` in a loop? + +This seems like it'll be a common use case, and `forward` +addresses it in a very simple way. + +### Stakeholder Interest & Feedback + +Wasi-io is a dependency of wasi-filesystem, wasi-sockets, and wasi-http, and +is a foundational piece of WASI Preview 2. + +### References & acknowledgements + +Many thanks for valuable feedback and advice from: + +- Thanks to Luke Wagner for many design functions and the design of + the component-model async streams which inform the design here. +- Thanks to Calvin Prewitt for the idea to include a `forward` function + in this API. diff --git a/proposals/io/imports.md b/proposals/io/imports.md new file mode 100644 index 000000000..071128df9 --- /dev/null +++ b/proposals/io/imports.md @@ -0,0 +1,398 @@ +

World imports

+ +

Import interface wasi:io/error@0.2.8

+
+

Types

+

resource 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 +offer functions to "downcast" this error into more specific types. For example, +errors returned from streams derived from filesystem types can be described using +the filesystem's own error-code type. This is done using the function +wasi:filesystem/types.filesystem-error-code, which takes a borrow<error> +parameter and returns an option<wasi:filesystem/types.error-code>.

+

The set of functions which can "downcast" an error into a more +concrete type is open.

+

Functions

+

[method]error.to-debug-string: func

+

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.

+
Params
+ +
Return values
+
    +
  • string
  • +
+

Import interface wasi:io/poll@0.2.8

+

A poll API intended to let users wait for I/O events on multiple handles +at once.

+
+

Types

+

resource pollable

+

pollable represents a single I/O event which may be ready, or not.

+

Functions

+

[method]pollable.ready: func

+

Return the readiness of a pollable. This function never blocks.

+

Returns true when the pollable is ready, and false otherwise.

+
Params
+ +
Return values
+
    +
  • bool
  • +
+

[method]pollable.block: func

+

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.

+
Params
+ +

poll: func

+

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<u32> contains one or more indices of handles in the +argument list that is ready for I/O.

+

This function traps if either:

+
    +
  • the list is empty, or:
  • +
  • the list contains more elements than can be indexed with a u32 value.
  • +
+

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 ready for I/O.

+
Params
+ +
Return values
+
    +
  • list<u32>
  • +
+

Import interface wasi:io/streams@0.2.8

+

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.

+
+

Types

+

type error

+

error

+

+#### `type pollable` +[`pollable`](#pollable) +

+#### `variant stream-error` +

An error for input-stream and output-stream operations.

+
Variant Cases
+
    +
  • +

    last-operation-failed: own<error>

    +

    The last operation (a write or flush) failed before completion. +

    More information is available in the error payload.

    +

    After this, the stream will be closed. All future operations return +stream-error::closed.

    +
  • +
  • +

    closed

    +

    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. +

  • +
+

resource input-stream

+

An input bytestream.

+

input-streams 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 output-stream

+

An output bytestream.

+

output-streams 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.

+

Dropping an output-stream while there's still an active write in +progress may result in the data being lost. Before dropping the stream, +be sure to fully flush your writes.

+

Functions

+

[method]input-stream.read: func

+

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.

+
Params
+ +
Return values
+ +

[method]input-stream.blocking-read: func

+

Read bytes from a stream, after blocking until at least one byte can +be read. Except for blocking, behavior is identical to read.

+
Params
+ +
Return values
+ +

[method]input-stream.skip: func

+

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.

+
Params
+ +
Return values
+ +

[method]input-stream.blocking-skip: func

+

Skip bytes from a stream, after blocking until at least one byte +can be skipped. Except for blocking behavior, identical to skip.

+
Params
+ +
Return values
+ +

[method]input-stream.subscribe: func

+

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 pollables created with this function are dropped.

+
Params
+ +
Return values
+ +

[method]output-stream.check-write: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.write: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-write-and-flush: func

+

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.

+

Returns success when all of the contents written are successfully +flushed to output. If an error occurs at any point before all +contents are successfully flushed, that error is returned as soon as +possible. If writing and flushing the complete contents causes the +stream to become closed, this call should return success, and +subsequent calls to check-write or other interfaces should return +stream-error::closed.

+
Params
+ +
Return values
+ +

[method]output-stream.flush: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-flush: func

+

Request to flush buffered output, and block until flush completes +and stream is ready for writing again.

+
Params
+ +
Return values
+ +

[method]output-stream.subscribe: func

+

Create a pollable which will resolve once the output-stream +is ready for more writing, or an error has occurred. 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 pollables created with this function are dropped.

+
Params
+ +
Return values
+ +

[method]output-stream.write-zeroes: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-write-zeroes-and-flush: func

+

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.

+

Functionality is equivelant to blocking-write-and-flush with +contents given as a list of len containing only zeroes.

+
Params
+ +
Return values
+ +

[method]output-stream.splice: func

+

Read from one stream and write to another.

+

The behavior of splice is equivalent to:

+
    +
  1. calling check-write on the output-stream
  2. +
  3. calling read on the input-stream with the smaller of the +check-write permitted length and the len provided to splice
  4. +
  5. calling write on the output-stream with that read data.
  6. +
+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-splice: func

+

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.

+
Params
+ +
Return values
+ diff --git a/proposals/io/test/README.md b/proposals/io/test/README.md new file mode 100644 index 000000000..c274acd9d --- /dev/null +++ b/proposals/io/test/README.md @@ -0,0 +1,11 @@ +# Testing guidelines + +TK fill in testing guidelines + +## Installing the tools + +TK fill in instructions + +## Running the tests + +TK fill in instructions diff --git a/proposals/io/wit/error.wit b/proposals/io/wit/error.wit new file mode 100644 index 000000000..8caf84539 --- /dev/null +++ b/proposals/io/wit/error.wit @@ -0,0 +1,34 @@ +package wasi:io@0.2.8; + +@since(version = 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 + /// offer functions to "downcast" this error into more specific types. For example, + /// errors returned from streams derived from filesystem types can be described using + /// the filesystem's own error-code type. This is done using the function + /// `wasi:filesystem/types.filesystem-error-code`, which takes a `borrow` + /// parameter and returns an `option`. + /// + /// The set of functions which can "downcast" an `error` into a more + /// concrete type is open. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + to-debug-string: func() -> string; + } +} diff --git a/proposals/io/wit/poll.wit b/proposals/io/wit/poll.wit new file mode 100644 index 000000000..833b381d9 --- /dev/null +++ b/proposals/io/wit/poll.wit @@ -0,0 +1,47 @@ +package wasi:io@0.2.8; + +/// A poll API intended to let users wait for I/O events on multiple handles +/// at once. +@since(version = 0.2.0) +interface poll { + /// `pollable` represents a single I/O event which may be ready, or not. + @since(version = 0.2.0) + resource pollable { + + /// Return the readiness of a pollable. This function never blocks. + /// + /// Returns `true` when the pollable is ready, and `false` otherwise. + @since(version = 0.2.0) + ready: func() -> bool; + + /// `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. + @since(version = 0.2.0) + block: func(); + } + + /// 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. + /// + /// This function traps if either: + /// - the list is empty, or: + /// - the list contains more elements than can be indexed with a `u32` value. + /// + /// 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 ready for I/O. + @since(version = 0.2.0) + poll: func(in: list>) -> list; +} diff --git a/proposals/io/wit/streams.wit b/proposals/io/wit/streams.wit new file mode 100644 index 000000000..fbb0268b0 --- /dev/null +++ b/proposals/io/wit/streams.wit @@ -0,0 +1,258 @@ +package wasi:io@0.2.8; + +/// 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. +@since(version = 0.2.0) +interface streams { + @since(version = 0.2.0) + use error.{error}; + @since(version = 0.2.0) + use poll.{pollable}; + + /// An error for input-stream and output-stream operations. + @since(version = 0.2.0) + variant stream-error { + /// The last operation (a write or flush) failed before completion. + /// + /// More information is available in the `error` payload. + /// + /// After this, the stream will be closed. All future operations return + /// `stream-error::closed`. + 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`. + @since(version = 0.2.0) + resource input-stream { + /// 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. + @since(version = 0.2.0) + read: func( + /// The maximum number of bytes to read + len: u64 + ) -> result, stream-error>; + + /// Read bytes from a stream, after blocking until at least one byte can + /// be read. Except for blocking, behavior is identical to `read`. + @since(version = 0.2.0) + blocking-read: func( + /// The maximum number of bytes to read + 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. + @since(version = 0.2.0) + skip: func( + /// The maximum number of bytes to skip. + len: u64, + ) -> result; + + /// Skip bytes from a stream, after blocking until at least one byte + /// can be skipped. Except for blocking behavior, identical to `skip`. + @since(version = 0.2.0) + blocking-skip: func( + /// The maximum number of bytes to skip. + 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. + @since(version = 0.2.0) + 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`. + /// + /// Dropping an `output-stream` while there's still an active write in + /// progress may result in the data being lost. Before dropping the stream, + /// be sure to fully flush your writes. + @since(version = 0.2.0) + resource output-stream { + /// 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. + @since(version = 0.2.0) + check-write: func() -> result; + + /// 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. + @since(version = 0.2.0) + write: func( + contents: list + ) -> result<_, stream-error>; + + /// 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. + /// + /// Returns success when all of the contents written are successfully + /// flushed to output. If an error occurs at any point before all + /// contents are successfully flushed, that error is returned as soon as + /// possible. If writing and flushing the complete contents causes the + /// stream to become closed, this call should return success, and + /// subsequent calls to check-write or other interfaces should return + /// stream-error::closed. + @since(version = 0.2.0) + blocking-write-and-flush: func( + contents: list + ) -> result<_, stream-error>; + + /// 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. + @since(version = 0.2.0) + flush: func() -> result<_, stream-error>; + + /// Request to flush buffered output, and block until flush completes + /// and stream is ready for writing again. + @since(version = 0.2.0) + blocking-flush: func() -> result<_, stream-error>; + + /// Create a `pollable` which will resolve once the output-stream + /// is ready for more writing, or an error has occurred. 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. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// 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. + @since(version = 0.2.0) + write-zeroes: func( + /// The number of zero-bytes to write + len: u64 + ) -> 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. + /// + /// Functionality is equivelant to `blocking-write-and-flush` with + /// contents given as a list of len containing only zeroes. + @since(version = 0.2.0) + blocking-write-zeroes-and-flush: func( + /// The number of zero-bytes to write + len: u64 + ) -> result<_, stream-error>; + + /// Read from one stream and write to another. + /// + /// The behavior of splice is equivalent 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`. + @since(version = 0.2.0) + splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + + /// 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`. + @since(version = 0.2.0) + blocking-splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + } +} diff --git a/proposals/io/wit/world.wit b/proposals/io/wit/world.wit new file mode 100644 index 000000000..1cc3fce12 --- /dev/null +++ b/proposals/io/wit/world.wit @@ -0,0 +1,10 @@ +package wasi:io@0.2.8; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import streams; + + @since(version = 0.2.0) + import poll; +} diff --git a/proposals/random/LICENSE.md b/proposals/random/LICENSE.md new file mode 100644 index 000000000..c1c3b9443 --- /dev/null +++ b/proposals/random/LICENSE.md @@ -0,0 +1,8 @@ +Copyright © 2019-2024 the Contributors to the WASI Specification, published +by the [WebAssembly Community Group][cg] under the +[W3C Community Contributor License Agreement (CLA)][cla]. A human-readable +[summary][summary] is available. + +[cg]: https://www.w3.org/community/webassembly/ +[cla]: https://www.w3.org/community/about/agreements/cla/ +[summary]: https://www.w3.org/community/about/agreements/cla-deed/ diff --git a/proposals/random/README.md b/proposals/random/README.md new file mode 100644 index 000000000..f68b5ace6 --- /dev/null +++ b/proposals/random/README.md @@ -0,0 +1,193 @@ +# WASI Random + +A proposed [WebAssembly System Interface](https://github.com/WebAssembly/WASI) API. + +### Current Phase + +WASI-random is currently in [Phase 3]. + +[Phase 3]: https://github.com/WebAssembly/WASI/blob/main/Proposals.md#phase-3---implementation-phase-cg--wg + +### Champions + +- Dan Gohman + +### Portability Criteria + +WASI random must have host implementations which can pass the testsuite +on at least Windows, macOS, and Linux. + +WASI random must have at least two complete independent implementations. + +## Table of Contents + +- [Introduction](#introduction) +- [Goals](#goals) +- [Non-goals](#non-goals) +- [API walk-through](#api-walk-through) + - [Use case 1](#use-case-1) + - [Use case 2](#use-case-2) +- [Detailed design discussion](#detailed-design-discussion) + - [[Tricky design choice 1]](#tricky-design-choice-1) + - [[Tricky design choice 2]](#tricky-design-choice-2) +- [Considered alternatives](#considered-alternatives) + - [[Alternative 1]](#alternative-1) + - [[Alternative 2]](#alternative-2) +- [Stakeholder Interest & Feedback](#stakeholder-interest--feedback) +- [References & acknowledgements](#references--acknowledgements) + +### Introduction + +WASI Random is a WASI API for obtaining pseudo-random data. + +### Goals + +The primary goals of WASI Random are: + - To allow users to use WASI programs to obtain high-quality low-level + random data suitable for cryptography. + - To allow source languages to enable DoS protection in their hash-maps + in host environments that support it. + +### Non-goals + +WASI Random is not aiming to allow programs to handle errors or to query for +availability. It always succeeds (though on platforms where randomness is +unavailable, programs may fail to be instantiated or may trap). + +WASI Random is not aiming to be a full DRBG API. Such an API could be +considered in WASI, but it should be a separate proposal. + +WASI Random does not include facilities for feeding entropy back into +the system. It is expected that most entropy that applications would observe +should also be observable by the host implementation, and so there should +be little need to feed it back in. There may be other uses for such an API, +but they can be addressed in separate proposals. + +WASI Random does not have an async API. It is expected to be implemented with +a CSPRNG which is expected to be sufficiently seeded. + +WASI Random does not have an explicit facility for domain separation or +personalization messages. If such features are desired, it would make sense to +define them as custom sections, rather than program data, so that they could +easily be excluded from module caching and possibly also from code signing. +This would make sense as a separate proposal. + +WASI Random does not provide an "entropy API" or a "true random" API directly. +The currently expected use cases want a CSPRNG API. + +WASI Random does not expose an entropy estimation. It is expected to always +have sufficient entropy to seed a CSPRNG. + +WASI Random does not provide any facility for replacing random data with +deterministic data. It is intended to be usable in use cases where determinism +would break application assumptions. Implementations may have debugging +facilities which make this API deterministic, however these should only be +used for debugging, and not production use. + +### API walk-through + +#### Main API: getting cryptographically-secure pseudo-random bytes + +Return a list of cryptographically-secure pseudo-random bytes: + +```rust + let len: u32 = your_own_code_to_decide_how_many_bytes_you_want(); + + let bytes: Vec = get_random_bytes(len); +``` + +#### Main API: getting cryptographically-secure pseudo-random bytes faster + +Sometimes the bindings for `list` can have some overhead, so +another function is available which returns the same data but as a +`u64`: + +```rust + let data: u64 = get_random_u64(); +``` + +#### Insecure API: Hash-map DoS protection + +Return a pair of u64's that can be used to initialize a hash implementation: + +```rust + let init: (u64, u64) = insecure_random(); + + let combined: u128 = init.0 as u128 | (init.1 as u128 << 64); + + your_own_code_to_initialize_hash_map(combined); +``` + +### Detailed design discussion + +### What if the system lacks sufficient entropy during early boot? + +Randomness APIs which can fail, or which can be "nonblocking" and return +incomplete results, are error prone and tend to lead applications to resort +to fallbacks which don't tend to be well-tested. + +CSPRNGs are believed to be good enough that most systems in most situations +can provide effectively unlimited random data. The main case where this +isn't the case is on systems which have just booted and which have not yet +collected sufficient entropy to initialize their CSPRNGs. In these cases, +this API is designed with the belief that it's better for implementations +to respond to the problem, rather than to pass the responsibility on to +applications. + +### What should happen on host platforms with weak or broken randomness APIs? + +It's implementations' responsibility to handle these situations. They may do +so by supplementing the host platform APIs with data collected from other +sources, they may refuse to run programs that use Random APIs, or if needed, +they may trap programs dynamically to prevent programs from continuing to +execute with poor data. + +Implementations are encouraged to perform regular reseeding (if the host +platform doesn't already do so). + +### Should there be a randomness resource, and should the API take a handle? + +Programs shouldn't need to be aware of *which* random generator they have, since +the data is random and indistinguishable. + +WASI programs using the Random API will have imports specific to the Random API, +because they are distinct from imports used for general-purpose `stream`. + +### Should random data be provided as a `stream`? + +Reusing the `stream` type is tempting, however it's desirable for users of this +API to be provided actually random data, and not the contents of arbitrary +streams which might be substituted, so it doesn't turn out to be useful to unify +this API with `stream`. + +This also ensures that programs using the Random API can be identified by +their imports, as mentioned in the previous question. + +### Should the API specify a number of bits of security? + +Best practices suggest that implementations should provide at least 196 bits of +security. However, many host platforms' CSPRNG APIs do not currently document +their bits of security, and it doesn't seem desirable to require wasm engines to +run their own CSPRNG on a platform which already has one, so for now, the API +does not specify a specific number. + +### Why is insecure-random a fixed-sized return value? + +This limits the amount of data that can be obtained through it. Since it's +insecure, it's not intended to be used as an alternative to `getrandom`. + +### Stakeholder Interest & Feedback + +TODO before entering Phase 3. + +Preview1 has a random function, and it's widely exposed in toolchains. + +### References & acknowledgements + +Many thanks for valuable feedback and advice from: + +- Zach Lym +- Luke Wagner +- Linux Weekly News' many articles about Linux random APIs including [this one]. + +[this one]: https://lwn.net/Articles/808575/ diff --git a/proposals/random/imports.md b/proposals/random/imports.md new file mode 100644 index 000000000..d283771b6 --- /dev/null +++ b/proposals/random/imports.md @@ -0,0 +1,96 @@ +

World imports

+ +

Import interface wasi:random/random@0.2.8

+

WASI Random is a random data API.

+

It is intended to be portable at least between Unix-family platforms and +Windows.

+
+

Functions

+

get-random-bytes: func

+

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.

+
Params
+
    +
  • len: u64
  • +
+
Return values
+
    +
  • list<u8>
  • +
+

get-random-u64: func

+

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.

+
Return values
+
    +
  • u64
  • +
+

Import interface wasi:random/insecure@0.2.8

+

The insecure interface for insecure pseudo-random numbers.

+

It is intended to be portable at least between Unix-family platforms and +Windows.

+
+

Functions

+

get-insecure-random-bytes: func

+

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.

+
Params
+
    +
  • len: u64
  • +
+
Return values
+
    +
  • list<u8>
  • +
+

get-insecure-random-u64: func

+

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.

+
Return values
+
    +
  • u64
  • +
+

Import interface wasi:random/insecure-seed@0.2.8

+

The insecure-seed interface for seeding hash-map DoS resistance.

+

It is intended to be portable at least between Unix-family platforms and +Windows.

+
+

Functions

+

insecure-seed: func

+

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.

+
Return values
+
    +
  • (u64, u64)
  • +
diff --git a/proposals/random/test/README.md b/proposals/random/test/README.md new file mode 100644 index 000000000..c274acd9d --- /dev/null +++ b/proposals/random/test/README.md @@ -0,0 +1,11 @@ +# Testing guidelines + +TK fill in testing guidelines + +## Installing the tools + +TK fill in instructions + +## Running the tests + +TK fill in instructions diff --git a/proposals/random/wit-0.3.0-draft/insecure-seed.wit b/proposals/random/wit-0.3.0-draft/insecure-seed.wit new file mode 100644 index 000000000..302151ba6 --- /dev/null +++ b/proposals/random/wit-0.3.0-draft/insecure-seed.wit @@ -0,0 +1,27 @@ +package wasi:random@0.3.0-rc-2025-09-16; +/// The insecure-seed interface for seeding hash-map DoS resistance. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.3.0-rc-2025-09-16) +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. + @since(version = 0.3.0-rc-2025-09-16) + get-insecure-seed: func() -> tuple; +} diff --git a/proposals/random/wit-0.3.0-draft/insecure.wit b/proposals/random/wit-0.3.0-draft/insecure.wit new file mode 100644 index 000000000..39146e391 --- /dev/null +++ b/proposals/random/wit-0.3.0-draft/insecure.wit @@ -0,0 +1,25 @@ +package wasi:random@0.3.0-rc-2025-09-16; +/// The insecure interface for insecure pseudo-random numbers. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.3.0-rc-2025-09-16) +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. + @since(version = 0.3.0-rc-2025-09-16) + 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`. + @since(version = 0.3.0-rc-2025-09-16) + get-insecure-random-u64: func() -> u64; +} diff --git a/proposals/random/wit-0.3.0-draft/random.wit b/proposals/random/wit-0.3.0-draft/random.wit new file mode 100644 index 000000000..fa1f111dc --- /dev/null +++ b/proposals/random/wit-0.3.0-draft/random.wit @@ -0,0 +1,29 @@ +package wasi:random@0.3.0-rc-2025-09-16; +/// WASI Random is a random data API. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.3.0-rc-2025-09-16) +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. + @since(version = 0.3.0-rc-2025-09-16) + 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`. + @since(version = 0.3.0-rc-2025-09-16) + get-random-u64: func() -> u64; +} diff --git a/proposals/random/wit-0.3.0-draft/world.wit b/proposals/random/wit-0.3.0-draft/world.wit new file mode 100644 index 000000000..08c5ed88b --- /dev/null +++ b/proposals/random/wit-0.3.0-draft/world.wit @@ -0,0 +1,13 @@ +package wasi:random@0.3.0-rc-2025-09-16; + +@since(version = 0.3.0-rc-2025-09-16) +world imports { + @since(version = 0.3.0-rc-2025-09-16) + import random; + + @since(version = 0.3.0-rc-2025-09-16) + import insecure; + + @since(version = 0.3.0-rc-2025-09-16) + import insecure-seed; +} diff --git a/proposals/random/wit/insecure-seed.wit b/proposals/random/wit/insecure-seed.wit new file mode 100644 index 000000000..b2b435e55 --- /dev/null +++ b/proposals/random/wit/insecure-seed.wit @@ -0,0 +1,27 @@ +package wasi:random@0.2.8; +/// The insecure-seed interface for seeding hash-map DoS resistance. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.2.0) +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. + @since(version = 0.2.0) + insecure-seed: func() -> tuple; +} diff --git a/proposals/random/wit/insecure.wit b/proposals/random/wit/insecure.wit new file mode 100644 index 000000000..6dc77adec --- /dev/null +++ b/proposals/random/wit/insecure.wit @@ -0,0 +1,25 @@ +package wasi:random@0.2.8; +/// The insecure interface for insecure pseudo-random numbers. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.2.0) +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. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + get-insecure-random-u64: func() -> u64; +} diff --git a/proposals/random/wit/random.wit b/proposals/random/wit/random.wit new file mode 100644 index 000000000..524e77d4a --- /dev/null +++ b/proposals/random/wit/random.wit @@ -0,0 +1,29 @@ +package wasi:random@0.2.8; +/// WASI Random is a random data API. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.2.0) +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. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + get-random-u64: func() -> u64; +} diff --git a/proposals/random/wit/world.wit b/proposals/random/wit/world.wit new file mode 100644 index 000000000..c0c3272c9 --- /dev/null +++ b/proposals/random/wit/world.wit @@ -0,0 +1,13 @@ +package wasi:random@0.2.8; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import random; + + @since(version = 0.2.0) + import insecure; + + @since(version = 0.2.0) + import insecure-seed; +} diff --git a/proposals/sockets/.gitattributes b/proposals/sockets/.gitattributes new file mode 100644 index 000000000..4101e25d1 --- /dev/null +++ b/proposals/sockets/.gitattributes @@ -0,0 +1,2 @@ +# Enable some degree of syntax highlighting on GitHub: +*.wit linguist-language=Rust \ No newline at end of file diff --git a/proposals/sockets/GrantingAccess.md b/proposals/sockets/GrantingAccess.md new file mode 100644 index 000000000..d1d993c8f --- /dev/null +++ b/proposals/sockets/GrantingAccess.md @@ -0,0 +1,95 @@ +## Granting access + +This section is mostly here to illustrate the granularity of permissions that ought to be possible. It is by no means a recommendation of any kind. It's just spitballing how a CLI-based implementation might grant network access. + + +```shell + +# Allow TCP connections to any IP address resolved from `example.com` on port 80. This also implies `--allow-resolve=example.com` +--allow-outbound=tcp://example.com:80 + +# Allow listening only on loopback interfaces on port 80 +--allow-inbound=tcp://localhost:80 + + + + + +# Allow the lookup of a specific domain name +--allow-resolve=example.com + +# Allow the lookup of all subdomains +--allow-resolve=*.example.com + +# Allow any lookup +--allow-resolve=* + +# Only look up IPv4 addresses +--allow-resolve=example.com#ipv4-only + +# Only look up IPv6 addresses +--allow-resolve=example.com#ipv6-only + + + + +# Allow TCP connections to 127.0.0.1 on port 80 +--allow-outbound=tcp://127.0.0.1:80 + +# Allow TCP connections to 127.0.0.1 on any port +--allow-outbound=tcp://127.0.0.1:* + +# Allow TCP connections to any server on port 80 +--allow-outbound=tcp://*:80 + +# Allow all TCP connections +--allow-outbound=tcp://*:* + +# Allow TCP connection with IPv4 only +--allow-outbound=tcp://...#ipv4-only + +# Allow TCP connection with IPv6 only +--allow-outbound=tcp://...#ipv6-only + +# Allow TCP connections to a specific list of ports +--allow-outbound=tcp://*:80,443 + +# Allow TCP connections to a range of ports +--allow-outbound=tcp://*:21,35000-35999 + +# Allow UDP client +--allow-outbound=udp://... + + + + +# Allow listening on a specific network interface on port 80 +--allow-inbound=tcp://eth0:80 + +# Allow listening on any network interface on port 80 +--allow-inbound=tcp://*:80 + +# Allow listening on a randomly generated port +--allow-inbound=tcp://*:0 + +``` + +### Virtualization / mapping + +Just like wasmtime already has the ability to remap directories with `--mapdir`, similar constructs can be conceived for networking. Examples: + +_Again: not an official recommendation of any kind._ + +```shell + +# Map a domain name resolvable from within the wasm module to an IP address. +--allow-resolve=my-database.internal->172.17.0.14 + +# Allow listening to TCP port 80 inside the wasm module, which is mapped to port 8888 on the host. +--allow-inbound=tcp://*:80->8888 + +# Allow TCP connections to any IP address resolved from `my-database.internal` which is mapped to `172.17.0.14` on +# port 5432 which is mapped to 5433. This also implies `--allow-resolve=my-database.internal->172.17.0.14` +--allow-outbound=tcp://my-database.internal->172.17.0.14:5432->5433 + +``` \ No newline at end of file diff --git a/proposals/sockets/LICENSE.md b/proposals/sockets/LICENSE.md new file mode 100644 index 000000000..c1c3b9443 --- /dev/null +++ b/proposals/sockets/LICENSE.md @@ -0,0 +1,8 @@ +Copyright © 2019-2024 the Contributors to the WASI Specification, published +by the [WebAssembly Community Group][cg] under the +[W3C Community Contributor License Agreement (CLA)][cla]. A human-readable +[summary][summary] is available. + +[cg]: https://www.w3.org/community/webassembly/ +[cla]: https://www.w3.org/community/about/agreements/cla/ +[summary]: https://www.w3.org/community/about/agreements/cla-deed/ diff --git a/proposals/sockets/Posix-compatibility.md b/proposals/sockets/Posix-compatibility.md new file mode 100644 index 000000000..ae8853a02 --- /dev/null +++ b/proposals/sockets/Posix-compatibility.md @@ -0,0 +1,608 @@ +# POSIX Compatibility + +This document provides an overview of the POSIX interface along with common non-standard extensions and their mapping to functionalities provided by this proposal. + + +## General + +### I/O completion polling (`poll`, `select`, `pselect`, `epoll_*` (non-standard), `kqueue` (non-standard)) +Use the various `subscribe` methods to obtain a `pollable` handle. Then use that to wait for IO events using the [wasi:io/poll][poll] interface. + +### Non-blocking mode (`FIONBIO`, `SOCK_NONBLOCK`, `O_NONBLOCK`) +All WASI sockets are non-blocking and can not be configured to block. +Blocking behaviour can be recreated in userland (or in wasi-libc) by calling [pollable::block][poll] on the relevant pollable. + +### TCP urgent data (`sockatmark`, `MSG_OOB`, `SO_OOBINLINE`, `SIOCATMARK`) +Out-of-band (OOB) data is currently not included in this proposal. Application-level usage of the TCP "urgent" flag is rare in practice and discouraged in general. Including it in WASI would probably interfere with the ability to use WASI/ComponentModel `stream`s. + +### Peeking (`MSG_PEEK`) +Peeking support is not provided by this proposal directly. Including it in WASI would probably interfere with the ability to use WASI/ComponentModel `stream`s. + +Support for it might be able to be recreated in userland (or in wasi-libc). + +### Writing to closed streams (`SIGPIPE`, `SO_NOSIGPIPE`) +WASI has no concept of 'signals'. Implementations that require it are encouraged to set the `SO_NOSIGPIPE` option to `true`, to increase cross-platform consistency. +Writing to a closed stream in WASI returns a regular error. + +### Close-on-exec (`FD_CLOEXEC`, `SOCK_CLOEXEC`, `O_CLOEXEC`) +Not included in proposal. WASI has no concept of UNIX-style processes. + + +## Functions + +### `socket` +- TCP: [`create-tcp-socket`][tcp-create-socket] +- UDP: [`create-udp-socket`][udp-create-socket] + +### `connect` +- TCP: [`tcp-socket::start-connect`][tcp] & [`tcp-socket::finish-connect`][tcp] +- UDP: [`udp-socket::start-connect`][udp] & [`udp-socket::finish-connect`][udp] + +### `bind` +- TCP: [`tcp-socket::start-bind`][tcp] & [`tcp-socket::finish-bind`][tcp] +- UDP: [`udp-socket::start-bind`][udp] & [`udp-socket::finish-bind`][udp] + +### `listen` +- TCP: [`tcp-socket::start-listen`][tcp] & [`tcp-socket::finish-listen`][tcp]. The `backlog` parameter has been split out into a distinct function [`tcp-socket::set-listen-backlog-size`][tcp] ([See #34][34]). +- UDP: N/A + +### `accept`, `accept4` (non-standard) +- TCP: [`tcp-socket::accept`][tcp] +- UDP: N/A + +To collect the remote address, call `tcp-socket::remote-address` on the newly accepted client socket. + +Some platforms provide an `accept4` variant with additional flags. None of these flags make sense in the context of this proposal. See [SOCK_NONBLOCK](#nonblock) & [SOCK_CLOEXEC](#cloexec). + +### `getsockname`, `getpeername` +- TCP: [`tcp-socket::local-address`][tcp] & [`tcp-socket::remote-address`][tcp] +- UDP: [`udp-socket::local-address`][udp] & [`udp-socket::remote-address`][udp] + +### `read`, `readv`, `recv`, `recvfrom`, `recvmsg`, `recvmmsg` (non-standard) + +TCP sockets can be read using the `input-stream` returned by connect or accept. +UDP sockets can be read using the `incoming-datagram-stream` returned by `udp-socket::stream`. + +The various POSIX functions should be implementable on top of these two resources. + +None of the flags are directly present in WASI Sockets: +- `MSG_DONTWAIT`: This is [always the case](#nonblock). +- `MSG_OOB` on TCP sockets: [Not supported](#oob) +- `MSG_OOB` on UDP sockets: N/A +- `MSG_PEEK`: [No direct support](#peek) +- `MSG_TRUNC` on TCP sockets: N/A +- `MSG_TRUNC` on UDP sockets: Not needed, the returned data array always has the exact perfect size. +- `MSG_WAITALL` on TCP sockets: Emulatable in userspace. +- `MSG_WAITALL` on UDP sockets: N/A +- `MSG_EOR`: N/A (not supported on TCP & UDP sockets) +- `MSG_CMSG_CLOEXEC`: N/A (only used on Unix domain sockets) + +Receiving ancillary messages: None supported as of yet. But see the various "RECV" socket options below. + +### `write`, `writev`, `send`, `sendto`, `sendmsg`, `sendmmsg` (non-standard) + +TCP sockets can be written to using the `output-stream` returned by connect or accept. +UDP sockets can be written to using the `outgoing-datagram-stream` returned by `udp-socket::stream`. + +The various POSIX functions should be implementable on top of these two resources. + +None of the flags are directly present in WASI Sockets: +- `MSG_DONTROUTE`: Not included in proposal at the moment. +- `MSG_DONTWAIT`: This is [always the case](#nonblock). +- `MSG_NOSIGNAL`: This is [always the case](#sigpipe). +- `MSG_OOB` on TCP sockets: [Not supported](#oob) +- `MSG_OOB` on UDP sockets: N/A +- `MSG_EOR`: N/A (not supported on TCP & UDP sockets) + +Sending ancillary messages: None supported as of yet. + +### `sendfile` (non-standard) +- TCP: Part of the [wasi:io/streams][streams] proposal as `output-stream::splice` +- UDP: N/A + +### `shutdown` +- TCP: [`tcp-socket::shutdown`][tcp] +- UDP: N/A + +### `sockatmark` +- TCP: Not supported, see [OOB](#oob). +- UDP: N/A + +### `close` +Dropping the socket resource effectively performs a `close`. + +### `socketpair`, `connectat` (non-standard), `bindat` (non-standard) +Specifically for UNIX domain sockets. Out of scope for this proposal. + +### `fcntl` +- `F_GETFL`/`F_SETFL` > `O_NONBLOCK`: [Not needed](#nonblock). +- `F_SETFD`/`F_GETFD` > `FD_CLOEXEC`: [Not included](#cloexec). + +### `ioctl` +- `SIOCATMARK`: [Not included](#oob). +- `FIONREAD`: Currently not included. See [#17][17]. + +### `getsockopt`, `setsockopt` +Socket options have been split out into distinct functions. See table below. + + + + +## Socket options + +POSIX defines the signatures of the `getsockopt` & `setsockopt` functions, but does not provide much guidance on the individual socket options themselves. +Because of this lack of a central authority, a list has been compiled of the options that are used "in the wild". + +The results are not intended to be an exhaustive overview of all possible network applications, but rather to provide input on which options are worth standardizing in WASI. + +Additionally, most columns have been populated semi-automatically by grepping through the respective codebases. The results have not been manually verified and therefore may not be 100% correct. + +Legend: +- ✅ = Included in proposal. +- ⚠️ = Partially supported. +- ⛔ = Consciously decided _not_ to include in WASI. See notes for explanation. +- ❔ = Not included (yet), for no particular reason. + + +| | Option | Notes | Used/implemented by | +|----| ---------------------------------|-----------------------------------------|---------------------| +| ✅ | SO_DOMAIN
SO_PROTOCOL_INFO on Windows | [`tcp-socket::address-family`][tcp]
[`udp-socket::address-family`][udp] | linux, windows, freebsd, .net | +| ✅ | SO_ACCEPTCONN | [`tcp-socket::is-listening`][tcp] | posix, linux, windows, macos, freebsd, .net | +| ✅ | IP_TTL | [`tcp-socket::(set-)hop-limit`][tcp]
[`udp-socket::(set-)unicast-hop-limit`][udp] | linux, windows, macos, freebsd, jvm, .net, rust, libuv | +| ✅ | IPV6_UNICAST_HOPS | [`tcp-socket::(set-)hop-limit`][tcp]
[`udp-socket::(set-)unicast-hop-limit`][udp] | posix, linux, windows, macos, freebsd, jvm, .net, libuv | +| ✅ | SO_RCVBUF | [`tcp-socket::(set-)receive-buffer-size`][tcp]
[`udp-socket::(set-)receive-buffer-size`][udp] | posix, linux, windows, macos, freebsd, jvm, .net, libuv, go, nginx, msquic | +| ✅ | SO_SNDBUF | [`tcp-socket::(set-)send-buffer-size`][tcp]
[`udp-socket::(set-)send-buffer-size`][udp] | posix, linux, windows, macos, freebsd, jvm, .net, libuv, go, nginx, curl | +| ✅ | SO_KEEPALIVE | [`tcp-socket::(set-)keep-alive-enabled`][tcp] | posix, linux, windows, macos, freebsd, jvm, .net, libuv, go, openssl, nginx, curl, exim | +| ✅ | TCP_KEEPIDLE
TCP_KEEPALIVE on MacOS | [`tcp-socket::(set-)keep-alive-idle-time`][tcp] | linux, windows, macos, freebsd, jvm, .net, libuv, go, nginx, curl | +| ✅ | TCP_KEEPINTVL | [`tcp-socket::(set-)keep-alive-interval`][tcp] | linux, windows, macos, freebsd, jvm, .net, libuv, go, nginx, curl | +| ✅ | TCP_KEEPCNT | [`tcp-socket::(set-)keep-alive-count`][tcp] | linux, windows, macos, freebsd, jvm, .net, libuv, nginx | +| ✅ | SO_REUSEADDR for TCP | Enabled by default. See [`tcp-socket::bind`][tcp] | posix, linux, windows, macos, freebsd, jvm, .net, libuv, go, openssl, nginx, curl, exim | +| ⚠️ | IPV6_V6ONLY | In WASI this always `true`. [#1][1] | posix, linux, windows, macos, freebsd, jvm, .net, libuv, go, openssl, curl, msquic, exim | +| ⛔ | SO_ERROR | Not necessary. WIT has (or will have) native support for asynchronous results. | posix, linux, windows, macos, freebsd, jvm, .net, rust, libuv, go, openssl, nginx, curl, msquic | +| ⛔ | SO_TYPE | Can be inferred from the socket resource type. | posix, linux, windows, macos, freebsd, jvm, .net, go, openssl, nginx, curl, exim | +| ⛔ | SO_PROTOCOL
SO_PROTOCOL_INFO on Windows | Can be inferred from the socket resource type. | linux, windows, freebsd, .net, exim | +| ⛔ | IP_HDRINCL | Out of scope. Raw sockets only. | linux, windows, macos, freebsd, .net | +| ⛔ | IPV6_HDRINCL | Out of scope. Raw sockets only. | linux, windows, .net | +| ⛔ | SO_RCVTIMEO | WASI sockets are always non-blocking. Timeouts can be recreated in libc. | posix, linux, windows, macos, freebsd, jvm, .net, rust, openssl, curl | +| ⛔ | SO_SNDTIMEO | WASI sockets are always non-blocking. Timeouts can be recreated in libc. | posix, windows, macos, freebsd, .net, rust, openssl | +| ⛔ | SO_OOBINLINE | Not supported, see [OOB](#oob) | posix, linux, windows, macos, freebsd, jvm, .net | +| ⛔ | SO_PEERCRED | Out of scope; UNIX domain sockets only. | linux, jvm, .net | +| ⛔ | SO_PEERSEC | Out of scope; UNIX domain sockets only. | linux | +| ⛔ | SO_NOSIGPIPE | Not supported, see [SIGPIPE](#sigpipe) | macos, freebsd, libuv, curl | +| ❔ | IP_RECVPKTINFO
IP_PKTINFO on Linux & Windows
IP_RECVDSTADDR+IP_RECVIF on MacOS & FreeBSD | [#77][77] | linux, windows, macos, freebsd, .net, openssl, nginx, msquic | +| ❔ | IPV6_RECVPKTINFO
IPV6_PKTINFO on Windows | [#77][77] | linux, windows, macos, freebsd, .net, openssl, nginx, msquic | +| ❔ | IP_RECVTOS | [#78][78] | linux, windows, macos, freebsd, msquic | +| ❔ | IPV6_RECVTCLASS | [#78][78] | linux, windows, macos, freebsd, msquic | +| ❔ | IP_TOS | [#78][78] | linux, windows, macos, freebsd, jvm, .net, exim | +| ❔ | IPV6_TCLASS | [#78][78] | linux, macos, freebsd, jvm, .net, exim | +| ❔ | TCP_ECN_MODE | [#78][78] | macos | +| ❔ | TCP_ENABLE_ECN | [#78][78] | macos | +| ❔ | SO_LINGER | [#80][80] | posix, linux, windows, macos, freebsd, jvm, .net, rust, libuv, go, openssl, nginx | +| ❔ | IP_DONTFRAG
IP_DONTFRAGMENT on Windows | [#79][79] | linux, windows, macos, freebsd, jvm, .net, openssl, nginx, msquic | +| ❔ | IPV6_DONTFRAG | [#79][79] | linux, windows, macos, freebsd, jvm, .net, openssl, nginx, msquic | +| ❔ | IP_MTU_DISCOVER | [#79][79] | linux, windows, openssl, nginx, curl, msquic | +| ❔ | IPV6_MTU_DISCOVER | [#79][79] | linux, windows, openssl, nginx, curl, msquic | +| ❔ | TCP_NODELAY | [#75][75] | posix, linux, windows, macos, freebsd, jvm, .net, rust, libuv, go, openssl, nginx, curl, exim | +| ❔ | TCP_CORK
TCP_NOPUSH on MacOS & FreeBSD | [#75][75] | linux, macos, freebsd, nginx, exim | +| ❔ | SO_REUSEADDR for UDP | [#74][74] | posix, linux, windows, macos, freebsd, jvm, .net, libuv, go, openssl, nginx, curl, exim | +| ❔ | SO_EXCLUSIVEADDRUSE | [#74][74] | windows | +| ❔ | SO_RANDOMIZE_PORT | [#74][74] | windows | +| ❔ | SO_RANDOMPORT | [#74][74] | macos | +| ❔ | IP_BIND_ADDRESS_NO_PORT | [#74][74] | linux, nginx, curl | +| ❔ | SO_PORT_SCALABILITY | [#74][74] | windows | +| ❔ | SO_REUSE_UNICASTPORT | [#74][74] | windows, .net | +| ❔ | SO_REUSEPORT | [#74][74] | linux, macos, freebsd, .net, libuv, go, nginx, msquic | +| ❔ | SO_REUSEPORT_LB | [#74][74] | freebsd, nginx | +| ❔ | SO_ATTACH_REUSEPORT_CBPF | [#74][74] | linux, msquic | +| ❔ | SO_ATTACH_REUSEPORT_EBPF | [#74][74] | linux, nginx | +| ❔ | SO_DETACH_REUSEPORT_BPF | [#74][74] | linux | +| ❔ | TCP_REUSPORT_LB_NUMA | [#74][74] | freebsd | +| ❔ | SO_INCOMING_CPU | [#74][74] | linux | +| ❔ | SO_INCOMING_NAPI_ID | [#74][74] | linux, jvm | +| ❔ | SO_BINDTODEVICE | [#74][74] | linux, libuv, go, curl | +| ❔ | SO_BINDTOIFINDEX | [#74][74] | linux | +| ❔ | IP_UNICAST_IF | [#74][74] | linux, windows, msquic | +| ❔ | IPV6_UNICAST_IF | [#74][74] | linux, windows, msquic | +| ❔ | IP_BOUND_IF | [#74][74] | macos | +| ❔ | IPV6_BOUND_IF | [#74][74] | macos | +| ❔ | IP_FREEBIND | [#74][74] | linux | +| ❔ | IPV6_FREEBIND | [#74][74] | linux | +| ❔ | IP_TRANSPARENT | [#74][74] | linux, nginx | +| ❔ | IPV6_TRANSPARENT | [#74][74] | linux, nginx | +| ❔ | IP_BINDANY | [#74][74] | freebsd, nginx | +| ❔ | IPV6_BINDANY | [#74][74] | freebsd, nginx | +| ❔ | SO_REUSE_MULTICASTPORT | [#74][74], [#73][73] | windows | +| ❔ | SO_BROADCAST | [#73][73] | posix, linux, windows, macos, freebsd, jvm, .net, rust, libuv, go | +| ❔ | MCAST_JOIN_GROUP
Supersedes: IP_ADD_MEMBERSHIP
Supersedes: IPV6_JOIN_GROUP
Supersedes: IPV6_ADD_MEMBERSHIP | [#73][73] | posix, linux, windows, macos, freebsd, jvm, .net, rust, libuv, go | +| ❔ | MCAST_LEAVE_GROUP
Supersedes: IP_DROP_MEMBERSHIP
Supersedes: IPV6_LEAVE_GROUP
Supersedes: IPV6_DROP_MEMBERSHIP | [#73][73] | posix, linux, windows, macos, freebsd, jvm, .net, rust, libuv | +| ❔ | MCAST_JOIN_SOURCE_GROUP
Supersedes: IP_ADD_SOURCE_MEMBERSHIP | [#73][73] | linux, windows, macos, freebsd, jvm, .net, libuv | +| ❔ | MCAST_LEAVE_SOURCE_GROUP
Supersedes: IP_DROP_SOURCE_MEMBERSHIP | [#73][73] | linux, windows, macos, freebsd, jvm, .net, libuv | +| ❔ | MCAST_BLOCK_SOURCE
Supersedes: IP_BLOCK_SOURCE | [#73][73] | linux, windows, macos, freebsd, jvm, .net | +| ❔ | MCAST_UNBLOCK_SOURCE
Supersedes: IP_UNBLOCK_SOURCE | [#73][73] | linux, windows, macos, freebsd, jvm, .net | +| ❔ | IP_MSFILTER | [#73][73] | linux, windows, macos, freebsd | +| ❔ | IPV6_MSFILTER | [#73][73] | macos, freebsd | +| ❔ | IP_MULTICAST_IF | [#73][73] | linux, windows, macos, freebsd, jvm, .net, libuv, go | +| ❔ | IPV6_MULTICAST_IF | [#73][73] | posix, linux, windows, macos, freebsd, jvm, .net, libuv, go | +| ❔ | IP_MULTICAST_LOOP | [#73][73] | linux, windows, macos, freebsd, jvm, .net, rust, libuv, go | +| ❔ | IPV6_MULTICAST_LOOP | [#73][73] | posix, linux, windows, macos, freebsd, jvm, .net, rust, libuv, go | +| ❔ | IP_MULTICAST_TTL | [#73][73] | linux, windows, macos, freebsd, jvm, .net, rust, libuv | +| ❔ | IPV6_MULTICAST_HOPS | [#73][73] | posix, linux, windows, macos, freebsd, jvm, .net, libuv | +| ❔ | IP_MULTICAST_ALL | [#73][73] | linux | +| ❔ | IPV6_MULTICAST_ALL | [#73][73] | linux | +| ❔ | IP_MULTICAST_IFINDEX | [#73][73] | macos | +| ❔ | TCP_FASTOPEN | [#81][81] | linux, windows, macos, freebsd, openssl, nginx, exim | +| ❔ | TCP_FASTOPEN_CONNECT | [#81][81] | linux, openssl, curl, exim | +| ❔ | TCP_FASTOPEN_KEY | [#81][81] | linux | +| ❔ | TCP_FASTOPEN_NO_COOKIE | [#81][81] | linux | +| ❔ | TCP_FASTOPEN_FORCE_ENABLE | [#81][81] | macos | +| ❔ | TCP_FASTOPEN_FORCE_HEURISTICS | [#81][81] | macos | +| ❔ | SO_SNDLOWAT | Not usefully implemented on Linux & Windows. | posix, linux, macos, freebsd, .net, nginx | +| ❔ | SO_RCVLOWAT | | posix, linux, macos, freebsd, .net | +| ❔ | IP_RECVTTL | | linux, windows, macos, freebsd | +| ❔ | IPV6_RECVHOPLIMIT | | linux, macos, freebsd | +| ❔ | SO_DEBUG | | posix, linux, windows, macos, freebsd, .net | +| ❔ | SO_DONTROUTE | | posix, linux, windows, macos, freebsd, .net | +| ❔ | TCP_INFO
via ioctl on Windows | | linux, windows, macos, freebsd, nginx, exim | +| ❔ | IP_IPSEC_POLICY | | linux, macos, freebsd | +| ❔ | IP_MINTTL | | linux, freebsd | +| ❔ | IPV6_MINHOPCOUNT | | linux | +| ❔ | IP_MTU | | linux, windows, openssl | +| ❔ | IPV6_MTU | | linux, windows, openssl | +| ❔ | IPV6_PATHMTU | | linux, macos, freebsd | +| ❔ | IPV6_RECVPATHMTU | | linux, macos, freebsd | +| ❔ | IPV6_USE_MIN_MTU | | linux, macos, freebsd | +| ❔ | IP_OPTIONS | | linux, windows, macos, freebsd, .net, exim | +| ❔ | IP_RECVOPTS | | linux, macos, freebsd | +| ❔ | IP_RECVORIGDSTADDR
IP_ORIGDSTADDR on FreeBSD | | linux, freebsd | +| ❔ | IP_RECVRETOPTS
Alias: IP_RETOPTS | | linux, macos, freebsd | +| ❔ | IPV6_2292DSTOPTS | | linux, macos, freebsd | +| ❔ | IPV6_2292HOPLIMIT | | linux, macos, freebsd | +| ❔ | IPV6_2292HOPOPTS | | linux, macos, freebsd | +| ❔ | IPV6_2292PKTINFO | | linux, macos, freebsd | +| ❔ | IPV6_2292PKTOPTIONS | | linux, macos, freebsd | +| ❔ | IPV6_2292RTHDR | | linux, macos, freebsd | +| ❔ | IPV6_AUTOFLOWLABEL | | linux, macos, freebsd | +| ❔ | IPV6_CHECKSUM | | linux, macos, freebsd | +| ❔ | IPV6_DSTOPTS | | linux, macos, freebsd | +| ❔ | IPV6_HOPOPTS | | linux, macos, freebsd | +| ❔ | IPV6_IPSEC_POLICY | | linux, macos, freebsd | +| ❔ | IPV6_NEXTHOP | | linux, macos, freebsd | +| ❔ | IPV6_RECVDSTOPTS | | linux, macos, freebsd | +| ❔ | IPV6_RECVHOPOPTS | | linux, macos, freebsd | +| ❔ | IPV6_RECVORIGDSTADDR
IPV6_ORIGDSTADDR on FreeBSD | | linux, freebsd | +| ❔ | IPV6_RECVRTHDR | | linux, macos, freebsd | +| ❔ | IPV6_RTHDR | | linux, macos, freebsd | +| ❔ | IPV6_RTHDRDSTOPTS | | linux, macos, freebsd | +| ❔ | SO_TIMESTAMP | | linux, macos, freebsd | +| ❔ | TCP_CONGESTION | | linux, freebsd | +| ❔ | TCP_MAXSEG | | linux, macos, freebsd | +| ❔ | TCP_MD5SIG | | linux, freebsd | +| ❔ | TCP_NOTSENT_LOWAT | | linux, macos | +| ❔ | UDP_ENCAP | | linux, freebsd | +| ❔ | IP_CHECKSUM | | linux | +| ❔ | IP_NODEFRAG | | linux | +| ❔ | IP_PASSSEC | | linux | +| ❔ | IP_PKTOPTIONS | | linux | +| ❔ | IP_RECVERR | | linux, libuv | +| ❔ | IP_RECVERR_RFC4884 | | linux | +| ❔ | IP_RECVFRAGSIZE | | linux | +| ❔ | IP_ROUTER_ALERT | | linux | +| ❔ | IP_XFRM_POLICY | | linux | +| ❔ | IPV6_ADDR_PREFERENCES | | linux | +| ❔ | IPV6_ADDRFORM | | linux | +| ❔ | IPV6_AUTHHDR | | linux | +| ❔ | IPV6_FLOWINFO | | linux | +| ❔ | IPV6_FLOWINFO_SEND | | linux | +| ❔ | IPV6_FLOWLABEL_MGR | | linux | +| ❔ | IPV6_JOIN_ANYCAST | | linux | +| ❔ | IPV6_LEAVE_ANYCAST | | linux | +| ❔ | IPV6_RECVERR | | linux, libuv | +| ❔ | IPV6_RECVERR_RFC4884 | | linux | +| ❔ | IPV6_RECVFRAGSIZE | | linux | +| ❔ | IPV6_ROUTER_ALERT | | linux | +| ❔ | IPV6_ROUTER_ALERT_ISOLATE | | linux | +| ❔ | IPV6_XFRM_POLICY | | linux | +| ❔ | SO_ATTACH_FILTER | | linux | +| ❔ | SO_BPF_EXTENSIONS | | linux | +| ❔ | SO_BSDCOMPAT | | linux | +| ❔ | SO_BUF_LOCK | | linux | +| ❔ | SO_BUSY_POLL | | linux | +| ❔ | SO_BUSY_POLL_BUDGET | | linux | +| ❔ | SO_CNX_ADVICE | | linux | +| ❔ | SO_COOKIE | | linux, nginx | +| ❔ | SO_DETACH_FILTER | | linux | +| ❔ | SO_LOCK_FILTER | | linux | +| ❔ | SO_MARK | | linux | +| ❔ | SO_MEMINFO | | linux | +| ❔ | SO_NETNS_COOKIE | | linux | +| ❔ | SO_NO_CHECK | | linux | +| ❔ | SO_NOFCS | | linux | +| ❔ | SO_PASSCRED | | linux | +| ❔ | SO_PASSSEC | | linux | +| ❔ | SO_PEEK_OFF | | linux | +| ❔ | SO_PEERNAME | | linux | +| ❔ | SO_PREFER_BUSY_POLL | | linux | +| ❔ | SO_PRIORITY | | linux | +| ❔ | SO_RCVBUFFORCE | | linux | +| ❔ | SO_RCVMARK | | linux | +| ❔ | SO_RESERVE_MEM | | linux | +| ❔ | SO_RXQ_OVFL | | linux | +| ❔ | SO_SELECT_ERR_QUEUE | | linux | +| ❔ | SO_SNDBUFFORCE | | linux | +| ❔ | SO_TIMESTAMPING | | linux | +| ❔ | SO_TIMESTAMPNS | | linux | +| ❔ | SO_TXREHASH | | linux | +| ❔ | SO_TXTIME | | linux | +| ❔ | SO_WIFI_STATUS | | linux | +| ❔ | SO_ZEROCOPY | | linux | +| ❔ | TCP_CC_INFO | | linux | +| ❔ | TCP_CM_INQ | | linux | +| ❔ | TCP_DEFER_ACCEPT | | linux, nginx | +| ❔ | TCP_INQ | | linux | +| ❔ | TCP_LINGER2 | | linux | +| ❔ | TCP_MD5SIG_EXT | | linux | +| ❔ | TCP_QUEUE_SEQ | | linux | +| ❔ | TCP_QUICKACK | | linux, jvm, exim | +| ❔ | TCP_REPAIR | | linux | +| ❔ | TCP_REPAIR_OPTIONS | | linux | +| ❔ | TCP_REPAIR_QUEUE | | linux | +| ❔ | TCP_REPAIR_WINDOW | | linux | +| ❔ | TCP_SAVE_SYN | | linux | +| ❔ | TCP_SAVED_SYN | | linux | +| ❔ | TCP_SYNCNT | | linux | +| ❔ | TCP_THIN_DUPACK | | linux | +| ❔ | TCP_THIN_LINEAR_TIMEOUTS | | linux | +| ❔ | TCP_TIMESTAMP | | linux | +| ❔ | TCP_TX_DELAY | | linux | +| ❔ | TCP_ULP | | linux | +| ❔ | TCP_USER_TIMEOUT | | linux | +| ❔ | TCP_WINDOW_CLAMP | | linux | +| ❔ | TCP_ZEROCOPY_RECEIVE | | linux | +| ❔ | UDP_CORK | | linux | +| ❔ | UDP_GRO | | linux, msquic | +| ❔ | UDP_NO_CHECK6_RX | | linux | +| ❔ | UDP_NO_CHECK6_TX | | linux | +| ❔ | UDP_SEGMENT | | linux, nginx | +| ❔ | IP_ADD_IFLIST | | windows | +| ❔ | IP_DEL_IFLIST | | windows | +| ❔ | IP_GET_IFLIST | | windows | +| ❔ | IP_IFLIST | | windows | +| ❔ | IP_ORIGINAL_ARRIVAL_IF | | windows | +| ❔ | IP_ORIGINAL_ARRIVAL_IF | | windows | +| ❔ | IP_RECEIVE_BROADCAST | | windows | +| ❔ | IP_USER_MTU | | windows | +| ❔ | IP_WFP_REDIRECT_CONTEXT | | windows | +| ❔ | IP_WFP_REDIRECT_RECORDS | | windows | +| ❔ | IPV6_ADD_IFLIST | | windows | +| ❔ | IPV6_DEL_IFLIST | | windows | +| ❔ | IPV6_GET_IFLIST | | windows | +| ❔ | IPV6_IFLIST | | windows | +| ❔ | IPV6_PROTECTION_LEVEL | | windows | +| ❔ | IPV6_RECVIF | | windows | +| ❔ | IPV6_USER_MTU | | windows | +| ❔ | SO_BSP_STATE | | windows | +| ❔ | SO_CONDITIONAL_ACCEPT | | windows | +| ❔ | SO_CONNDATA | | windows | +| ❔ | SO_CONNDATALEN | | windows | +| ❔ | SO_CONNECT_TIME | | windows | +| ❔ | SO_CONNOPT | | windows | +| ❔ | SO_CONNOPTLEN | | windows | +| ❔ | SO_DISCDATA | | windows | +| ❔ | SO_DISCDATALEN | | windows | +| ❔ | SO_DISCOPT | | windows | +| ❔ | SO_DISCOPTLEN | | windows | +| ❔ | SO_GROUP_ID | | windows | +| ❔ | SO_GROUP_PRIORITY | | windows | +| ❔ | SO_MAX_MSG_SIZE | | windows | +| ❔ | SO_MAXDG | | windows | +| ❔ | SO_MAXPATHDG | | windows | +| ❔ | SO_OPENTYPE | | windows | +| ❔ | SO_PAUSE_ACCEPT | | windows | +| ❔ | SO_PROTOCOL_INFO | | windows | +| ❔ | SO_PROTOCOL_INFOA | | windows | +| ❔ | SO_PROTOCOL_INFOW | | windows | +| ❔ | SO_UPDATE_ACCEPT_CONTEXT | | windows | +| ❔ | SO_UPDATE_CONNECT_CONTEXT | | windows | +| ❔ | TCP_BSDURGENT | | windows | +| ❔ | TCP_EXPEDITED_1122 | | windows | +| ❔ | TCP_FAIL_CONNECT_ON_ICMP_ERROR | | windows | +| ❔ | TCP_ICMP_ERROR_INFO | | windows | +| ❔ | TCP_MAXRT | | windows | +| ❔ | TCP_TIMESTAMPS | | windows | +| ❔ | UDP_CHECKSUM_COVERAGE | | windows | +| ❔ | UDP_NOCHECKSUM | | windows | +| ❔ | UDP_RECV_MAX_COALESCED_SIZE | | windows, msquic | +| ❔ | UDP_SEND_MSG_SIZE | | windows, msquic | +| ❔ | IP_FAITH | | macos | +| ❔ | IP_NAT__XXX | | macos | +| ❔ | IP_STRIPHDR | | macos | +| ❔ | IP_TRAFFIC_MGT_BACKGROUND | | macos | +| ❔ | IPV6_3542DSTOPTS | | macos | +| ❔ | IPV6_3542HOPLIMIT | | macos | +| ❔ | IPV6_3542HOPOPTS | | macos | +| ❔ | IPV6_3542NEXTHOP | | macos | +| ❔ | IPV6_3542PKTINFO | | macos | +| ❔ | IPV6_3542RTHDR | | macos | +| ❔ | IPV6_RTHDR_LOOSE | | macos | +| ❔ | IPV6_RTHDR_STRICT | | macos | +| ❔ | IPV6_RTHDR_TYPE_0 | | macos | +| ❔ | SO_AWDL_UNRESTRICTED | | macos | +| ❔ | SO_CFIL_SOCK_ID | | macos | +| ❔ | SO_DELEGATED | | macos | +| ❔ | SO_DELEGATED_UUID | | macos | +| ❔ | SO_DONTTRUNC | | macos | +| ❔ | SO_EXECPATH | | macos | +| ❔ | SO_EXTENDED_BK_IDLE | | macos | +| ❔ | SO_FLOW_DIVERT_TOKEN | | macos | +| ❔ | SO_FLUSH | | macos | +| ❔ | SO_INTCOPROC_ALLOW | | macos | +| ❔ | SO_LINGER_SEC | | macos | +| ❔ | SO_MARK_CELLFALLBACK | | macos | +| ❔ | SO_MPKL_SEND_INFO | | macos | +| ❔ | SO_NECP_ATTRIBUTES | | macos | +| ❔ | SO_NECP_CLIENTUUID | | macos | +| ❔ | SO_NECP_LISTENUUID | | macos | +| ❔ | SO_NET_SERVICE_TYPE | | macos | +| ❔ | SO_NETSVC_MARKING_LEVEL | | macos | +| ❔ | SO_NKE | | macos | +| ❔ | SO_NOADDRERR | | macos | +| ❔ | SO_NOAPNFALLBK | | macos | +| ❔ | SO_NOTIFYCONFLICT | | macos | +| ❔ | SO_NOWAKEFROMSLEEP | | macos | +| ❔ | SO_NP_EXTENSIONS | | macos | +| ❔ | SO_NREAD | | macos | +| ❔ | SO_NUMRCVPKT | | macos | +| ❔ | SO_NWRITE | | macos | +| ❔ | SO_OPPORTUNISTIC | | macos | +| ❔ | SO_QOSMARKING_POLICY_OVERRIDE | | macos | +| ❔ | SO_RECV_ANYIF | | macos | +| ❔ | SO_RESTRICTIONS | | macos | +| ❔ | SO_REUSESHAREUID | | macos | +| ❔ | SO_STATISTICS_EVENT | | macos | +| ❔ | SO_TC_NET_SERVICE_OFFSET | | macos | +| ❔ | SO_TC_NETSVC_SIG | | macos | +| ❔ | SO_TIMESTAMP_CONTINUOUS | | macos | +| ❔ | SO_TIMESTAMP_MONOTONIC | | macos | +| ❔ | SO_TRAFFIC_MGT_BACKGROUND | | macos | +| ❔ | SO_UPCALLCLOSEWAIT | | macos | +| ❔ | SO_WANT_KEV_SOCKET_CLOSED | | macos | +| ❔ | SO_WANTMORE | | macos | +| ❔ | SO_WANTOOBFLAG | | macos | +| ❔ | MPTCP_ALTERNATE_PORT | | macos | +| ❔ | MPTCP_EXPECTED_PROGRESS_TARGET | | macos | +| ❔ | MPTCP_FORCE_ENABLE | | macos | +| ❔ | MPTCP_FORCE_VERSION | | macos | +| ❔ | MPTCP_SERVICE_TYPE | | macos | +| ❔ | PERSIST_TIMEOUT | | macos | +| ❔ | TCP_ADAPTIVE_READ_TIMEOUT | | macos | +| ❔ | TCP_ADAPTIVE_WRITE_TIMEOUT | | macos | +| ❔ | TCP_CONNECTION_INFO | | macos | +| ❔ | TCP_CONNECTIONTIMEOUT | | macos | +| ❔ | TCP_DISABLE_BLACKHOLE_DETECTION | | macos | +| ❔ | TCP_KEEPALIVE_OFFLOAD | | macos | +| ❔ | TCP_MEASURE_BW_BURST | | macos | +| ❔ | TCP_MEASURE_SND_BW | | macos | +| ❔ | TCP_NOTIFY_ACKNOWLEDGEMENT | | macos | +| ❔ | TCP_NOTIMEWAIT | | macos | +| ❔ | TCP_PEER_PID | | macos | +| ❔ | TCP_RXT_CONNDROPTIME | | macos | +| ❔ | TCP_RXT_FINDROP | | macos | +| ❔ | TCP_RXT_MINIMUM_TIMEOUT | | macos | +| ❔ | TCP_SENDMOREACKS | | macos | +| ❔ | UDP_KEEPALIVE_OFFLOAD | | macos | +| ❔ | UDP_NOCKSUM | | macos | +| ❔ | ICMP6_FILTER | | macos, freebsd | +| ❔ | IP_MULTICAST_VIF | | macos, freebsd | +| ❔ | IP_PORTRANGE | | macos, freebsd, go | +| ❔ | IP_RSVP_OFF | | macos, freebsd | +| ❔ | IP_RSVP_ON | | macos, freebsd | +| ❔ | IP_RSVP_VIF_OFF | | macos, freebsd | +| ❔ | IP_RSVP_VIF_ON | | macos, freebsd | +| ❔ | IPV6_2292NEXTHOP | | macos, freebsd | +| ❔ | IPV6_BINDV6ONLY | | macos, freebsd | +| ❔ | IPV6_FAITH | | macos, freebsd | +| ❔ | IPV6_PKTOPTIONS | | macos, freebsd | +| ❔ | IPV6_PORTRANGE | | macos, freebsd, go | +| ❔ | IPV6_PREFER_TEMPADDR | | macos, freebsd | +| ❔ | IPV6_RECVRTHDRDSTOPTS | | macos, freebsd | +| ❔ | SO_ACCEPTFILTER | | macos, freebsd, nginx | +| ❔ | SO_LABEL | | macos, freebsd | +| ❔ | SO_PEERLABEL | | macos, freebsd | +| ❔ | SO_USELOOPBACK | | macos, freebsd | +| ❔ | TCP_NOOPT | | macos, freebsd | +| ❔ | IP_BINDMULTI | | freebsd | +| ❔ | IP_FLOWID | | freebsd | +| ❔ | IP_FLOWTYPE | | freebsd | +| ❔ | IP_MAX_MEMBERSHIPS | | freebsd | +| ❔ | IP_ONESBCAST | | freebsd | +| ❔ | IP_RECVFLOWID | | freebsd | +| ❔ | IP_RECVRSSBUCKETID | | freebsd | +| ❔ | IP_RSS_LISTEN_BUCKET | | freebsd | +| ❔ | IP_RSSBUCKETID | | freebsd | +| ❔ | IP_SENDSRCADDR | | freebsd, nginx | +| ❔ | IP_VLAN_PCP | | freebsd | +| ❔ | IPV6_AUTH_LEVEL | | freebsd | +| ❔ | IPV6_BINDMULTI | | freebsd | +| ❔ | IPV6_ESP_NETWORK_LEVEL | | freebsd | +| ❔ | IPV6_ESP_TRANS_LEVEL | | freebsd | +| ❔ | IPV6_FLOWID | | freebsd | +| ❔ | IPV6_FLOWTYPE | | freebsd | +| ❔ | IPV6_IPCOMP_LEVEL | | freebsd | +| ❔ | IPV6_RECVFLOWID | | freebsd | +| ❔ | IPV6_RECVRSSBUCKETID | | freebsd | +| ❔ | IPV6_RSS_LISTEN_BUCKET | | freebsd | +| ❔ | IPV6_RSSBUCKETID | | freebsd | +| ❔ | IPV6_VLAN_PCP | | freebsd | +| ❔ | SO_BINTIME | | freebsd | +| ❔ | SO_LISTENINCQLEN | | freebsd | +| ❔ | SO_LISTENQLEN | | freebsd, exim | +| ❔ | SO_LISTENQLIMIT | | freebsd | +| ❔ | SO_MAX_PACING_RATE | | freebsd | +| ❔ | SO_NO_DDP | | freebsd | +| ❔ | SO_NO_OFFLOAD | | freebsd | +| ❔ | SO_RERROR | | freebsd | +| ❔ | SO_SETFIB | | freebsd, nginx | +| ❔ | SO_TS_BINTIME | | freebsd | +| ❔ | SO_TS_CLOCK | | freebsd | +| ❔ | SO_TS_CLOCK_MAX | | freebsd | +| ❔ | SO_TS_DEFAULT | | freebsd | +| ❔ | SO_TS_MONOTONIC | | freebsd | +| ❔ | SO_TS_REALTIME | | freebsd | +| ❔ | SO_TS_REALTIME_MICRO | | freebsd | +| ❔ | SO_USER_COOKIE | | freebsd | +| ❔ | TCP_CCALGOOPT | | freebsd | +| ❔ | TCP_DEFER_OPTIONS | | freebsd | +| ❔ | TCP_DELACK | | freebsd | +| ❔ | TCP_FAST_RSM_HACK | | freebsd | +| ❔ | TCP_FIN_IS_RST | | freebsd | +| ❔ | TCP_FUNCTION_ALIAS | | freebsd | +| ❔ | TCP_FUNCTION_BLK | | freebsd | +| ❔ | TCP_HDWR_RATE_CAP | | freebsd | +| ❔ | TCP_HDWR_UP_ONLY | | freebsd | +| ❔ | TCP_IDLE_REDUCE | | freebsd | +| ❔ | TCP_IWND_NB | | freebsd | +| ❔ | TCP_IWND_NSEG | | freebsd | +| ❔ | TCP_KEEPINIT | | freebsd | +| ❔ | TCP_LOG | | freebsd | +| ❔ | TCP_LOG_LIMIT | | freebsd | +| ❔ | TCP_LOG_TAG | | freebsd | +| ❔ | TCP_LOGBUF | | freebsd | +| ❔ | TCP_LOGDUMP | | freebsd | +| ❔ | TCP_LOGDUMPID | | freebsd | +| ❔ | TCP_LOGID | | freebsd | +| ❔ | TCP_LOGID_CNT | | freebsd | +| ❔ | TCP_LRD | | freebsd | +| ❔ | TCP_MAXPEAKRATE | | freebsd | +| ❔ | TCP_MAXUNACKTIME | | freebsd | +| ❔ | TCP_PCAP_IN | | freebsd | +| ❔ | TCP_PCAP_OUT | | freebsd | +| ❔ | TCP_PERF_INFO | | freebsd | +| ❔ | TCP_PROC_ACCOUNTING | | freebsd | +| ❔ | TCP_REMOTE_UDP_ENCAPS_PORT | | freebsd | +| ❔ | TCP_RXTLS_ENABLE | | freebsd | +| ❔ | TCP_RXTLS_MODE | | freebsd | +| ❔ | TCP_STATS | | freebsd | +| ❔ | TCP_TXTLS_ENABLE | | freebsd | +| ❔ | TCP_TXTLS_MODE | | freebsd | +| ❔ | TCP_USE_CMP_ACKS | | freebsd | +| ❔ | TCP_USER_LOG | | freebsd | + +[1]: https://github.com/WebAssembly/wasi-sockets/issues/1 +[17]: https://github.com/WebAssembly/wasi-sockets/issues/17 +[34]: https://github.com/WebAssembly/wasi-sockets/issues/34 +[73]: https://github.com/WebAssembly/wasi-sockets/issues/73 +[74]: https://github.com/WebAssembly/wasi-sockets/issues/74 +[75]: https://github.com/WebAssembly/wasi-sockets/issues/75 +[77]: https://github.com/WebAssembly/wasi-sockets/issues/77 +[78]: https://github.com/WebAssembly/wasi-sockets/issues/78 +[79]: https://github.com/WebAssembly/wasi-sockets/issues/79 +[80]: https://github.com/WebAssembly/wasi-sockets/issues/80 +[81]: https://github.com/WebAssembly/wasi-sockets/issues/81 +[ip-name-lookup]: https://github.com/WebAssembly/wasi-sockets/blob/main/wit/ip-name-lookup.wit +[tcp-create-socket]: https://github.com/WebAssembly/wasi-sockets/blob/main/wit/tcp-create-socket.wit +[tcp]: https://github.com/WebAssembly/wasi-sockets/blob/main/wit/tcp.wit +[udp-create-socket]: https://github.com/WebAssembly/wasi-sockets/blob/main/wit/udp-create-socket.wit +[udp]: https://github.com/WebAssembly/wasi-sockets/blob/main/wit/udp.wit +[poll]: https://github.com/WebAssembly/wasi-poll/blob/main/wit/poll.wit +[streams]: https://github.com/WebAssembly/wasi-io/blob/main/wit/streams.wit +**** diff --git a/proposals/sockets/README.md b/proposals/sockets/README.md new file mode 100644 index 000000000..bc2f088b9 --- /dev/null +++ b/proposals/sockets/README.md @@ -0,0 +1,227 @@ +# WASI Sockets + +A proposed [WebAssembly System Interface](https://github.com/WebAssembly/WASI) API. + +### Current Phase + +[Phase 3](https://github.com/WebAssembly/WASI/blob/main/Proposals.md#phase-3---implementation-phase-cg--wg) + +### Champions + +- Dave Bakker (@badeend) + +### Portability Criteria + +- At least two independent production implementations. +- Implementations available for at least Windows, Linux & MacOS. +- A testsuite that passes on the platforms and implementations mentioned above. + +## Table of Contents + +- [Introduction](#introduction) +- [Goals](#goals) +- [Non-goals](#non-goals) +- [API walk-through](#api-walk-through) + - [Asynchronous APIs](#asynchronous-apis) + - [Use case 1](#use-case-1) + - [Use case 2](#use-case-2) +- [Detailed design discussion](#detailed-design-discussion) + - [Dualstack sockets](#dualstack-sockets) + - [Modularity](#modularity) + - [POSIX compatibility](#posix-compatibility) + - [Why not getaddrinfo?](#why-not-getaddrinfo) + - [Security](#security) + - [Deferred permission requests](#deferred-permission-requests) +- [Considered alternatives](#considered-alternatives) + - [[Alternative 1]](#alternative-1) + - [[Alternative 2]](#alternative-2) +- [Stakeholder Interest & Feedback](#stakeholder-interest--feedback) +- [References & acknowledgements](#references--acknowledgements) + +### Introduction + +This proposal adds TCP & UDP sockets and domain name lookup to WASI. It adds the basic BSD socket interface with the intent to enable server and client networking software running on WebAssembly. + +Unlike BSD sockets, WASI sockets require capability handles to create sockets and perform domain name lookups. On top of capability handles, WASI Socket implementations should implement deny-by-default firewalling. + +The socket APIs have been split up into standalone protocol-specific WASI modules. Both current and future socket modules can then be tailored to the needs of that specific protocol and progress the standardization process independently. + +This proposal introduces 4 new WASI modules: +- [wasi-ip-name-lookup.wit](./wasi-ip-name-lookup.wit) +- [wasi-socket.wit](./wasi-socket.wit) + - [wasi-socket-ip.wit](./wasi-socket-ip.wit) + - [wasi-socket-tcp.wit](./wasi-socket-tcp.wit) + - [wasi-socket-udp.wit](./wasi-socket-udp.wit) + +### Goals + +- Start out as an MVP; add the bare minimum amount of APIs required to create a basic functioning TCP/UDP application. +- Toolchains must be able to provide a POSIX compatible interface on top of the functions introduced in this proposal. + +### Non-goals + +- SSL/TLS support +- HTTP(S) support +- Retrieving network-related information of the executing machine, like: installed network interfaces and the computer hostname. + +### API walk-through + +[Walk through of how someone would use this API.] + +#### Asynchronous APIs + +At the moment, WIT has no built-in way of expressing asynchronous operations. To work around this limitation, we split up async functions into two parts: `start-*` and `finish-*`. + +Desired signature: + +``` +operation: func(this, the-inputs...) -> future> +``` + +Temporary workaround: + +``` +start-operation: func(this, the-inputs...) -> result<_, error-code> +finish-operation: func(this) -> result +``` + + +The semantics are as follows: +- When `start-*` completes successfully: + - The operation should be considered "in progress". + - This is the POSIX equivalent of EINPROGRESS. + - The socket can be polled for completion of the just started operation, using `wasi-poll`. + - Its corresponding `finish-*` function can be called until it returns something other than the `would-block` error code. +- When `finish-*` returns anything other than `would-block`: + - The asynchronous operation should be considered "finished" (either successful or failed) + - Future calls to `finish-*` return the `not-in-progress` error code. +- The documented error codes can be returned from either the `start-*` function or the `finish-*` function. Both are equally correct. + +Runtimes that don't need asynchrony, can simply validate the arguments provided to the `start` function and stash them on their internal socket instance and perform the actual syscall in the `finish` function. Conveniently, sockets only allow one of these `start/finish` asynchronous operation to be active at a time. + + +Example of how to recover blocking semantics in guest code: +```rs +// Pseudo code: +fn blocking-connect(sock: tcp-socket, addr: ip-socket-address) -> result, error-code> { + + let pollable = tcp::subscribe(tcp-socket); + + let start-result = tcp::start-connect(sock, addr); + if (start-result is error) { + return error; + } + + while (true) { + poll::poll-oneoff([ pollable ]); + + let finish-result = tcp::finish-connect(sock); + if (finish-result is NOT error(would-block)) { + return finish-result; + } + } +} + +``` + +#### Use case: Wasm module per connection + +Thanks to the low startup cost of Wasm modules, its feasible for server software with Wasm integration to spawn a Wasm module for each inbound connection. Each module instance is passed only the accepted client socket. This way, all connection handlers are completely isolated from each other. This resembles PHP's "shared nothing" architecture. + +#### [Use case 2] + +[Provide example code snippets and diagrams explaining how the API would be used to solve the given problem] + +### Detailed design discussion + +[This section should mostly refer to the .wit.md file that specifies the API. This section is for any discussion of the choices made in the API which don't make sense to document in the spec file itself.] + +#### Dualstack sockets + +IPv6 sockets returned by this proposal are never dualstack because that can't easily be implemented in a cross platform manner. If an application wants to serve both IPv4 and IPv6 traffic, it should create two sockets; one for IPv4 traffic and one for IPv6 traffic. + +This behaviour is deemed acceptable because all existing applications that are truly cross-platform must already handle this scenario. Dualstack support can be part of a future proposal adding it as an opt-in feature. + +Related issue: [Emulate dualstack sockets in userspace](https://github.com/WebAssembly/wasi-sockets/issues/1) + +#### Modularity + +This proposal is not POSIX compatible by itself. The BSD sockets interface is highly generic. The same functions have different semantics depending on which kind of socket they're called on. The man-pages are riddled with conditional documentation. If this had been translated 1:1 into a WASI API using Interface Types, this would have resulted in a proliferation of optional parameters and result types. + +Instead, the sockets API has been split up into protocol-specific modules. All BSD socket functions have been pushed into these protocol-specific modules and tailored to their specific needs. Functions, parameters and flags that did not apply within a specific context have been dropped. + +A downside of this approach is that functions that do *not* differ per protocol (bind, local_address, connect, shutdown, ...) are duplicated as well. + +#### POSIX compatibility + +See [Posix-compatibility.md](./Posix-compatibility.md). + + +#### Why not getaddrinfo? + +The proposed [wasi-ip-name-lookup](./wasi-ip-name-lookup.wit) module focuses strictly on translating internet domain names to ip addresses and nothing else. + +Like BSD sockets, `getaddrinfo` is very generic and multipurpose by design. The proposed WASI API is *not*. This eliminates many of the other "hats" getaddrinfo has (and potential security holes), like: +- Mapping service names to port numbers (`"https"` -> `443`) +- Mapping service names/ports to socket types (`"https"` -> `SOCK_STREAM`) +- Network interface name translation (`%eth0` -> `1`) +- IP address deserialization (`"127.0.0.1"` -> `Ipv4Address(127, 0, 0, 1)`) +- IP address string canonicalization (`"0:0:0:0:0:0:0:1"` -> `"::1"`) +- Constants lookup for `INADDR_ANY`, `INADDR_LOOPBACK`, `IN6ADDR_ANY_INIT` and `IN6ADDR_LOOPBACK_INIT`. + +Many of these functionalities can be shimmed in the libc implementation. Though some require future WASI additions. An example is network interface name translation. That requires a future `if_nametoindex`-like syscall. + + +#### Security + +Wasm modules can not open sockets by themselves without a network capability handle. Even with capability handles, WASI implementations should deny all network access by default. Access should be granted at the most granular level possible. See [Granting Access](./GrantingAccess.md) for examples. Whenever access is denied, the implementation should return EACCES. + +This means Wasm modules will get a lot more EACCES errors compared to when running unsandboxed. This might break existing applications that, for example, don't expect creating a TCP client to require special permissions. + +At the moment there is no way for a Wasm modules to query which network access permissions it has. The only thing it can do, is to just call the WASI functions it needs and see if they fail. + + +#### Deferred permission requests + +This proposal does not specify how wasm runtimes should handle network permissions. One method could be to let end users declare on the command line which endpoints a wasm component may connect to. Another method could be to somehow let component authors distribute a manifest alongside the component itself, containing the set of permissions that it requires. + +Both of these examples depend on the network permissions being known and granted upfront. This is not always feasible and that's usually where dynamic permission requests come into play. + +The most likely contenders for permission prompt interception are: +- TCP: `connect` +- TCP: `bind` +- TCP: `listen` +- UDP: `bind` +- UDP: `connect` + +Now, again, this proposal does not specify if/how permission prompts should be implemented. However, it does at least facilitate the ability for runtimes to do so. Since waiting for user input takes an unknowable amount of time, the operations listed above have been made asynchronous. POSIX-compatibility layers can simply synchronously block on the returned `future`s. + +### TCP State Machine + +See [Operational Semantics](./TcpSocketOperationalSemantics.md). + +### Considered alternatives + +[This section is not required if you already covered considered alternatives in the design discussion above.] + +#### [Alternative 1] + +[Describe an alternative which was considered, and why you decided against it.] + +#### [Alternative 2] + +[etc.] + +### Stakeholder Interest & Feedback + +TODO before entering Phase 3. + +[This should include a list of implementers who have expressed interest in implementing the proposal] + +### References & acknowledgements + +Many thanks for valuable feedback and advice from: + +- [Person 1] +- [Person 2] +- [etc.] diff --git a/proposals/sockets/TcpSocketOperationalSemantics-0.3.0-draft.md b/proposals/sockets/TcpSocketOperationalSemantics-0.3.0-draft.md new file mode 100644 index 000000000..9aeeddff3 --- /dev/null +++ b/proposals/sockets/TcpSocketOperationalSemantics-0.3.0-draft.md @@ -0,0 +1,54 @@ +# Operational semantics of WASI TCP sockets + +WASI TCP sockets must behave [as-if](https://en.wikipedia.org/wiki/As-if_rule) they are implemented using the state machine described in this document. + +## States +> Note: These refer to the states of the TCP socket, not the [TCP connection](https://datatracker.ietf.org/doc/html/rfc9293#name-state-machine-overview) + +In pseudo code: + +```wit +interface tcp { + variant state { + unbound, + bound, + listening(accept-stream), + connecting(connect-future), + connected, + closed(option), + } +} +``` + +## Transitions +The following diagram describes the exhaustive set of all possible state transitions: + +```mermaid +stateDiagram-v2 + state "unbound" as Unbound + state "bound" as Bound + state "connecting" as Connecting + state "connected" as Connected + state "listening" as Listening + state "closed" as Closed + + + [*] --> Unbound: create-tcp-socket() -> ok + Unbound --> Bound: bind() -> ok + Unbound --> Connecting: connect() + + Connecting --> Connected: «task resolves successfully» + Connecting --> Closed: «task resolves with error» + + Connected --> Closed: «connection terminated» + + Bound --> Connecting: connect() + Bound --> Listening: listen() -> ok + Unbound --> Listening: listen() -> ok +``` + +- Transitions annotated with `-> ok` only apply when the method returns successfully. +- Calling a method from the wrong state returns `error(invalid-state)` and does not affect the state of the socket. +- This diagram only includes the methods that impact the socket's state. For an overview of all methods and their required states, see [tcp.wit](./wit/tcp.wit) +- Client sockets returned by `listen()` are immediately in the `connected` state. +- A socket resource can be dropped in any state. diff --git a/proposals/sockets/TcpSocketOperationalSemantics.md b/proposals/sockets/TcpSocketOperationalSemantics.md new file mode 100644 index 000000000..dd66880b2 --- /dev/null +++ b/proposals/sockets/TcpSocketOperationalSemantics.md @@ -0,0 +1,111 @@ +# Operational semantics of WASI TCP sockets + +WASI TCP sockets must behave [as-if](https://en.wikipedia.org/wiki/As-if_rule) they are implemented using the state machine described in this document. + +## States +> Note: These refer to the states of the TCP socket, not the [TCP connection](https://datatracker.ietf.org/doc/html/rfc9293#name-state-machine-overview) + +In pseudo code: + +```wit +interface tcp { + variant state { + unbound, + bind-in-progress(bind-future), + bound, + listen-in-progress(listen-future), + listening(accept-stream), + connect-in-progress(connect-future), + connected, + closed, + } + + type bind-future = future>; + type listen-future = future>; + type connect-future = future, error-code>>; + type accept-stream = stream, error-code>>; +} +``` + +## Pollable readiness +As seen above, there can be at most one asynchronous operation in progress at any time. The socket's pollable ready state can therefore be unambiguously derived as follows: + +```rs +fn ready() -> bool { + match state { + unbound => true, + bound => true, + connected => true, // To poll for I/O readiness, subscribe to the input and output streams. + closed => true, + + // Assuming that `f.is-resolved` returns true when the + // future has completed, either successfully or with failure. + bind-in-progress(f) => f.is-resolved, + listen-in-progress(f) => f.is-resolved, + connect-in-progress(f) => f.is-resolved, + + // Assuming that `s.has-pending-items` returns true when + // there is an item ready to be read from the stream. + listening(s) => s.has-pending-items, + } +} +``` + +## Transitions +The following diagram describes the exhaustive set of all possible state transitions: + +```mermaid +stateDiagram-v2 + state "unbound" as Unbound + state "bind-in-progress" as BindInProgress + state "bound" as Bound + state "listen-in-progress" as ListenInProgress + state "listening" as Listening + state "connect-in-progress" as ConnectInProgress + state "connected" as Connected + state "closed" as Closed + + [*] --> Unbound: create-tcp-socket()\n#ok + + Unbound --> BindInProgress: start-bind()\n#ok + Unbound --> Unbound: start-bind()\n#error + Unbound --> ConnectInProgress: start-connect()\n#ok + Unbound --> Closed: start-connect()\n#error + + ConnectInProgress --> ConnectInProgress: finish-connect()\n#error(would-block) + ConnectInProgress --> Closed: finish-connect()\n#error(NOT would-block) + ConnectInProgress --> Connected: finish-connect()\n#ok + + Connected --> Connected: shutdown() + Connected --> Closed: «connection terminated» + + BindInProgress --> BindInProgress: finish-bind()\n#error(would-block) + BindInProgress --> Unbound: finish-bind()\n#error(NOT would-block) + BindInProgress --> Bound: finish-bind()\n#ok + + Bound --> ConnectInProgress: start-connect()\n#ok + Bound --> Closed: start-connect()\n#error + Bound --> ListenInProgress: start-listen()\n#ok + Bound --> Closed: start-listen()\n#error + + ListenInProgress --> ListenInProgress: finish-listen()\n#error(would-block) + ListenInProgress --> Closed: finish-listen()\n#error(NOT would-block) + ListenInProgress --> Listening: finish-listen()\n#ok + + Listening --> Listening: accept() +``` + +Most transitions are dependent on the result of the method. Legend: +- `#ok`: this transition only applies when the method returns successfully. +- `#error`: this transition only applies when the method returns a failure. +- `#error(would-block)`: this transition only applies when the method returns the `would-block` error specifically. +- `#error(NOT would-block)`: this transition only applies when the method returns an error other than `would-block`. +- _(no annotation)_: Transition in unconditional. + +#### Not shown in the diagram: +- All state transitions shown above are driven by the caller and occur synchronously during the method invocations. There's one exception: the `«connection terminated»` transition from `connected` to `closed`. This can happen when: the peer closed the connection, a network failure occurred, the connection timed out, etc. +- While `shutdown` immediately closes the input and/or output streams associated with the socket, it does not affect the socket's own state as it just _initiates_ a shutdown. Only after the full shutdown sequence has been completed will the `«connection terminated»` transition be activated. (See previous item) +- Calling a method from the wrong state returns `error(invalid-state)` and does not affect the state of the socket. A special case are the `finish-*` methods; those return `error(not-in-progress)` when the socket is not in the corresponding `*-in-progress` state. +- This diagram only includes the methods that impact the socket's state. For an overview of all methods and their required states, see [tcp.wit](./wit/tcp.wit) +- Client sockets returned by `accept()` are in immediately in the `connected` state. +- A socket resource can be dropped in any state. diff --git a/proposals/sockets/imports.md b/proposals/sockets/imports.md new file mode 100644 index 000000000..441464a7e --- /dev/null +++ b/proposals/sockets/imports.md @@ -0,0 +1,1874 @@ +

World imports

+ +

Import interface wasi:io/error@0.2.8

+
+

Types

+

resource 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 +offer functions to "downcast" this error into more specific types. For example, +errors returned from streams derived from filesystem types can be described using +the filesystem's own error-code type. This is done using the function +wasi:filesystem/types/filesystem-error-code, which takes a borrow<error> +parameter and returns an option<wasi:filesystem/types/error-code>.

+

The set of functions which can "downcast" an error into a more +concrete type is open.

+

Functions

+

[method]error.to-debug-string: func

+

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.

+
Params
+ +
Return values
+
    +
  • string
  • +
+

Import interface wasi:sockets/network@0.2.8

+
+

Types

+

type error

+

error

+

+

resource 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.

+

enum 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 Cases
+
    +
  • +

    unknown

    +

    Unknown error +

  • +
  • +

    access-denied

    +

    Access denied. +

    POSIX equivalent: EACCES, EPERM

    +
  • +
  • +

    not-supported

    +

    The operation is not supported. +

    POSIX equivalent: EOPNOTSUPP

    +
  • +
  • +

    invalid-argument

    +

    One of the arguments is invalid. +

    POSIX equivalent: EINVAL

    +
  • +
  • +

    out-of-memory

    +

    Not enough memory to complete the operation. +

    POSIX equivalent: ENOMEM, ENOBUFS, EAI_MEMORY

    +
  • +
  • +

    timeout

    +

    The operation timed out before it could finish completely. +

  • +
  • +

    concurrency-conflict

    +

    This operation is incompatible with another asynchronous operation that is already in progress. +

    POSIX equivalent: EALREADY

    +
  • +
  • +

    not-in-progress

    +

    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 futures are natively supported.

    +
  • +
  • +

    would-block

    +

    The operation has been aborted because it could not be completed immediately. +

    Note: this is scheduled to be removed when futures are natively supported.

    +
  • +
  • +

    invalid-state

    +

    The operation is not valid in the socket's current state. +

  • +
  • +

    new-socket-limit

    +

    A new socket resource could not be created because of a system limit. +

  • +
  • +

    address-not-bindable

    +

    A bind operation failed because the provided address is not an address that the `network` can bind to. +

  • +
  • +

    address-in-use

    +

    A bind operation failed because the provided address is already in use or because there are no ephemeral ports available. +

  • +
  • +

    remote-unreachable

    +

    The remote address is not reachable +

  • +
  • +

    connection-refused

    +

    The TCP connection was forcefully rejected +

  • +
  • +

    connection-reset

    +

    The TCP connection was reset. +

  • +
  • +

    connection-aborted

    +

    A TCP connection was aborted. +

  • +
  • +

    datagram-too-large

    +

    The size of a datagram sent to a UDP socket exceeded the maximum +supported size. +

  • +
  • +

    name-unresolvable

    +

    Name does not exist or has no suitable associated IP addresses. +

  • +
  • +

    temporary-resolver-failure

    +

    A temporary failure in name resolution occurred. +

  • +
  • +

    permanent-resolver-failure

    +

    A permanent failure in name resolution occurred. +

  • +
+

enum ip-address-family

+
Enum Cases
+
    +
  • +

    ipv4

    +

    Similar to `AF_INET` in POSIX. +

  • +
  • +

    ipv6

    +

    Similar to `AF_INET6` in POSIX. +

  • +
+

tuple ipv4-address

+
Tuple Fields
+
    +
  • 0: u8
  • +
  • 1: u8
  • +
  • 2: u8
  • +
  • 3: u8
  • +
+

tuple ipv6-address

+
Tuple Fields
+
    +
  • 0: u16
  • +
  • 1: u16
  • +
  • 2: u16
  • +
  • 3: u16
  • +
  • 4: u16
  • +
  • 5: u16
  • +
  • 6: u16
  • +
  • 7: u16
  • +
+

variant ip-address

+
Variant Cases
+ +

record ipv4-socket-address

+
Record Fields
+
    +
  • +

    port: u16

    +

    sin_port +

  • +
  • +

    address: ipv4-address

    +

    sin_addr +

  • +
+

record ipv6-socket-address

+
Record Fields
+
    +
  • +

    port: u16

    +

    sin6_port +

  • +
  • +

    flow-info: u32

    +

    sin6_flowinfo +

  • +
  • +

    address: ipv6-address

    +

    sin6_addr +

  • +
  • +

    scope-id: u32

    +

    sin6_scope_id +

  • +
+

variant ip-socket-address

+
Variant Cases
+ +
+

Functions

+

network-error-code: func

+

Attempts to extract a network-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 +network-related information about the error to return.

+

Note that this function is fallible because not all stream-related +errors are network-related errors.

+
Params
+ +
Return values
+ +

Import interface wasi:sockets/instance-network@0.2.8

+

This interface provides a value-export of the default network handle..

+
+

Types

+

type network

+

network

+

+


+

Functions

+

instance-network: func

+

Get a handle to the default network.

+
Return values
+ +

Import interface wasi:io/poll@0.2.8

+

A poll API intended to let users wait for I/O events on multiple handles +at once.

+
+

Types

+

resource pollable

+

pollable represents a single I/O event which may be ready, or not.

+

Functions

+

[method]pollable.ready: func

+

Return the readiness of a pollable. This function never blocks.

+

Returns true when the pollable is ready, and false otherwise.

+
Params
+ +
Return values
+
    +
  • bool
  • +
+

[method]pollable.block: func

+

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.

+
Params
+ +

poll: func

+

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<u32> contains one or more indices of handles in the +argument list that is ready for I/O.

+

This function traps if either:

+
    +
  • the list is empty, or:
  • +
  • the list contains more elements than can be indexed with a u32 value.
  • +
+

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 ready for I/O.

+
Params
+ +
Return values
+
    +
  • list<u32>
  • +
+

Import interface wasi:sockets/udp@0.2.8

+
+

Types

+

type pollable

+

pollable

+

+

type network

+

network

+

+

type error-code

+

error-code

+

+

type ip-socket-address

+

ip-socket-address

+

+

type ip-address-family

+

ip-address-family

+

+

record incoming-datagram

+

A received datagram.

+
Record Fields
+
    +
  • +

    data: list<u8>

    +

    The payload. +

    Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes.

    +
  • +
  • +

    remote-address: ip-socket-address

    +

    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.

    +
  • +
+

record outgoing-datagram

+

A datagram to be sent out.

+
Record Fields
+
    +
  • +

    data: list<u8>

    +

    The payload. +

  • +
  • +

    remote-address: option<ip-socket-address>

    +

    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.

    +
  • +
+

resource udp-socket

+

A UDP socket handle.

+

resource incoming-datagram-stream

+

resource outgoing-datagram-stream

+
+

Functions

+

[method]udp-socket.start-bind: func

+

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

+ +
Params
+ +
Return values
+ +

[method]udp-socket.finish-bind: func

+
Params
+ +
Return values
+ +

[method]udp-socket.stream: func

+

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:

+
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

+ +
Params
+ +
Return values
+ +

[method]udp-socket.local-address: func

+

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

+ +
Params
+ +
Return values
+ +

[method]udp-socket.remote-address: func

+

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

+ +
Params
+ +
Return values
+ +

[method]udp-socket.address-family: func

+

Whether this is a IPv4 or IPv6 socket.

+

Equivalent to the SO_DOMAIN socket option.

+
Params
+ +
Return values
+ +

[method]udp-socket.unicast-hop-limit: func

+

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.
  • +
+
Params
+ +
Return values
+ +

[method]udp-socket.set-unicast-hop-limit: func

+
Params
+ +
Return values
+ +

[method]udp-socket.receive-buffer-size: func

+

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.
  • +
+
Params
+ +
Return values
+ +

[method]udp-socket.set-receive-buffer-size: func

+
Params
+ +
Return values
+ +

[method]udp-socket.send-buffer-size: func

+
Params
+ +
Return values
+ +

[method]udp-socket.set-send-buffer-size: func

+
Params
+ +
Return values
+ +

[method]udp-socket.subscribe: func

+

Create a pollable which will resolve once the socket is ready for I/O.

+

Note: this function is here for WASI 0.2 only. +It's planned to be removed when future is natively supported in Preview3.

+
Params
+ +
Return values
+ +

[method]incoming-datagram-stream.receive: func

+

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

+ +
Params
+ +
Return values
+ +

[method]incoming-datagram-stream.subscribe: func

+

Create a pollable which will resolve once the stream is ready to receive again.

+

Note: this function is here for WASI 0.2 only. +It's planned to be removed when future is natively supported in Preview3.

+
Params
+ +
Return values
+ +

[method]outgoing-datagram-stream.check-send: func

+

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.

+
Params
+ +
Return values
+ +

[method]outgoing-datagram-stream.send: func

+

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

+ +
Params
+ +
Return values
+ +

[method]outgoing-datagram-stream.subscribe: func

+

Create a pollable which will resolve once the stream is ready to send again.

+

Note: this function is here for WASI 0.2 only. +It's planned to be removed when future is natively supported in Preview3.

+
Params
+ +
Return values
+ +

Import interface wasi:sockets/udp-create-socket@0.2.8

+
+

Types

+

type network

+

network

+

+

type error-code

+

error-code

+

+

type ip-address-family

+

ip-address-family

+

+

type udp-socket

+

udp-socket

+

+


+

Functions

+

create-udp-socket: func

+

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:

+ +
Params
+ +
Return values
+ +

Import interface wasi:io/streams@0.2.8

+

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.

+
+

Types

+

type error

+

error

+

+

type pollable

+

pollable

+

+

variant stream-error

+

An error for input-stream and output-stream operations.

+
Variant Cases
+
    +
  • +

    last-operation-failed: own<error>

    +

    The last operation (a write or flush) failed before completion. +

    More information is available in the error payload.

    +

    After this, the stream will be closed. All future operations return +stream-error::closed.

    +
  • +
  • +

    closed

    +

    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. +

  • +
+

resource input-stream

+

An input bytestream.

+

input-streams 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 output-stream

+

An output bytestream.

+

output-streams 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.

+

Dropping an output-stream while there's still an active write in +progress may result in the data being lost. Before dropping the stream, +be sure to fully flush your writes.

+

Functions

+

[method]input-stream.read: func

+

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.

+
Params
+ +
Return values
+ +

[method]input-stream.blocking-read: func

+

Read bytes from a stream, after blocking until at least one byte can +be read. Except for blocking, behavior is identical to read.

+
Params
+ +
Return values
+ +

[method]input-stream.skip: func

+

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.

+
Params
+ +
Return values
+ +

[method]input-stream.blocking-skip: func

+

Skip bytes from a stream, after blocking until at least one byte +can be skipped. Except for blocking behavior, identical to skip.

+
Params
+ +
Return values
+ +

[method]input-stream.subscribe: func

+

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 pollables created with this function are dropped.

+
Params
+ +
Return values
+ +

[method]output-stream.check-write: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.write: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-write-and-flush: func

+

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.

+

Returns success when all of the contents written are successfully +flushed to output. If an error occurs at any point before all +contents are successfully flushed, that error is returned as soon as +possible. If writing and flushing the complete contents causes the +stream to become closed, this call should return success, and +subsequent calls to check-write or other interfaces should return +stream-error::closed.

+
Params
+ +
Return values
+ +

[method]output-stream.flush: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-flush: func

+

Request to flush buffered output, and block until flush completes +and stream is ready for writing again.

+
Params
+ +
Return values
+ +

[method]output-stream.subscribe: func

+

Create a pollable which will resolve once the output-stream +is ready for more writing, or an error has occurred. 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 pollables created with this function are dropped.

+
Params
+ +
Return values
+ +

[method]output-stream.write-zeroes: func

+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-write-zeroes-and-flush: func

+

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.

+

Functionality is equivelant to blocking-write-and-flush with +contents given as a list of len containing only zeroes.

+
Params
+ +
Return values
+ +

[method]output-stream.splice: func

+

Read from one stream and write to another.

+

The behavior of splice is equivalent to:

+
    +
  1. calling check-write on the output-stream
  2. +
  3. calling read on the input-stream with the smaller of the +check-write permitted length and the len provided to splice
  4. +
  5. calling write on the output-stream with that read data.
  6. +
+

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.

+
Params
+ +
Return values
+ +

[method]output-stream.blocking-splice: func

+

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.

+
Params
+ +
Return values
+ +

Import interface wasi:clocks/monotonic-clock@0.2.8

+

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.

+
+

Types

+

type pollable

+

pollable

+

+

type instant

+

u64

+

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 duration

+

u64

+

A duration of time, in nanoseconds. +


+

Functions

+

now: func

+

Read the current value of the clock.

+

The clock is monotonic, therefore calling this function repeatedly will +produce a sequence of non-decreasing values.

+

For completeness, this function traps if it's not possible to represent +the value of the clock in an instant. Consequently, implementations +should ensure that the starting time is low enough to avoid the +possibility of overflow in practice.

+
Return values
+ +

resolution: func

+

Query the resolution of the clock. Returns the duration of time +corresponding to a clock tick.

+
Return values
+ +

subscribe-instant: func

+

Create a pollable which will resolve once the specified instant +has occurred.

+
Params
+ +
Return values
+ +

subscribe-duration: func

+

Create a pollable that will resolve after the specified duration has +elapsed from the time this function is invoked.

+
Params
+ +
Return values
+ +

Import interface wasi:sockets/tcp@0.2.8

+
+

Types

+

type input-stream

+

input-stream

+

+

type output-stream

+

output-stream

+

+

type pollable

+

pollable

+

+

type duration

+

duration

+

+

type network

+

network

+

+

type error-code

+

error-code

+

+

type ip-socket-address

+

ip-socket-address

+

+

type ip-address-family

+

ip-address-family

+

+

enum shutdown-type

+
Enum Cases
+
    +
  • +

    receive

    +

    Similar to `SHUT_RD` in POSIX. +

  • +
  • +

    send

    +

    Similar to `SHUT_WR` in POSIX. +

  • +
  • +

    both

    +

    Similar to `SHUT_RDWR` in POSIX. +

  • +
+

resource tcp-socket

+

A TCP socket resource.

+

The socket can be in one of the following states:

+ +

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.

+

Functions

+

[method]tcp-socket.start-bind: func

+

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

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.finish-bind: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.start-connect: func

+

Connect to a remote endpoint.

+

On success:

+
    +
  • the socket is transitioned into the connected 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

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.finish-connect: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.start-listen: func

+

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

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.finish-listen: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.accept: func

+

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

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.local-address: func

+

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

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.remote-address: func

+

Get the remote address.

+

Typical errors

+
    +
  • invalid-state: The socket is not connected to a remote address. (ENOTCONN)
  • +
+

References

+ +
Params
+ +
Return values
+ +

[method]tcp-socket.is-listening: func

+

Whether the socket is in the listening state.

+

Equivalent to the SO_ACCEPTCONN socket option.

+
Params
+ +
Return values
+
    +
  • bool
  • +
+

[method]tcp-socket.address-family: func

+

Whether this is a IPv4 or IPv6 socket.

+

Equivalent to the SO_DOMAIN socket option.

+
Params
+ +
Return values
+ +

[method]tcp-socket.set-listen-backlog-size: func

+

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.
  • +
+
Params
+ +
Return values
+ +

[method]tcp-socket.keep-alive-enabled: func

+

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.

+
Params
+ +
Return values
+ +

[method]tcp-socket.set-keep-alive-enabled: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.keep-alive-idle-time: func

+

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.
  • +
+
Params
+ +
Return values
+ +

[method]tcp-socket.set-keep-alive-idle-time: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.keep-alive-interval: func

+

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.
  • +
+
Params
+ +
Return values
+ +

[method]tcp-socket.set-keep-alive-interval: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.keep-alive-count: func

+

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.
  • +
+
Params
+ +
Return values
+ +

[method]tcp-socket.set-keep-alive-count: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.hop-limit: func

+

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.
  • +
+
Params
+ +
Return values
+ +

[method]tcp-socket.set-hop-limit: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.receive-buffer-size: func

+

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.
  • +
+
Params
+ +
Return values
+ +

[method]tcp-socket.set-receive-buffer-size: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.send-buffer-size: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.set-send-buffer-size: func

+
Params
+ +
Return values
+ +

[method]tcp-socket.subscribe: func

+

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 https://github.com/WebAssembly/wasi-sockets/blob/main/TcpSocketOperationalSemantics.md#pollable-readiness +for more information.

+

Note: this function is here for WASI 0.2 only. +It's planned to be removed when future is natively supported in Preview3.

+
Params
+ +
Return values
+ +

[method]tcp-socket.shutdown: func

+

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 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

+ +
Params
+ +
Return values
+ +

Import interface wasi:sockets/tcp-create-socket@0.2.8

+
+

Types

+

type network

+

network

+

+

type error-code

+

error-code

+

+

type ip-address-family

+

ip-address-family

+

+

type tcp-socket

+

tcp-socket

+

+


+

Functions

+

create-tcp-socket: func

+

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

+ +
Params
+ +
Return values
+ +

Import interface wasi:sockets/ip-name-lookup@0.2.8

+
+

Types

+

type pollable

+

pollable

+

+

type network

+

network

+

+

type error-code

+

error-code

+

+

type ip-address

+

ip-address

+

+

resource resolve-address-stream

+
+

Functions

+

resolve-addresses: func

+

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:

+ +
Params
+ +
Return values
+ +

[method]resolve-address-stream.resolve-next-address: func

+

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)
  • +
+
Params
+ +
Return values
+ +

[method]resolve-address-stream.subscribe: func

+

Create a pollable which will resolve once the stream is ready for I/O.

+

Note: this function is here for WASI 0.2 only. +It's planned to be removed when future is natively supported in Preview3.

+
Params
+ +
Return values
+ diff --git a/proposals/sockets/test/README.md b/proposals/sockets/test/README.md new file mode 100644 index 000000000..c274acd9d --- /dev/null +++ b/proposals/sockets/test/README.md @@ -0,0 +1,11 @@ +# Testing guidelines + +TK fill in testing guidelines + +## Installing the tools + +TK fill in instructions + +## Running the tests + +TK fill in instructions diff --git a/proposals/sockets/wit-0.3.0-draft/deps.lock b/proposals/sockets/wit-0.3.0-draft/deps.lock new file mode 100644 index 000000000..4f3b1fe94 --- /dev/null +++ b/proposals/sockets/wit-0.3.0-draft/deps.lock @@ -0,0 +1,5 @@ +[clocks] +url = "https://github.com/WebAssembly/wasi-clocks/archive/main.tar.gz" +subdir = "wit-0.3.0-draft" +sha256 = "cf61a3785c2838340ce530ee1cdc6dbee3257f1672d6000ca748dfe253808dec" +sha512 = "f647de7d6c470595c3e5bf0dba6af98703beb9f701c66543cea5d42e81f7a1a73f199c3949035a9c2c1bd717056e5e68788f520af39b9d26480242b7626f22ce" diff --git a/proposals/sockets/wit-0.3.0-draft/deps.toml b/proposals/sockets/wit-0.3.0-draft/deps.toml new file mode 100644 index 000000000..e00454742 --- /dev/null +++ b/proposals/sockets/wit-0.3.0-draft/deps.toml @@ -0,0 +1 @@ +clocks = { url = "https://github.com/WebAssembly/wasi-clocks/archive/main.tar.gz", subdir = "wit-0.3.0-draft" } diff --git a/proposals/sockets/wit-0.3.0-draft/deps/clocks/monotonic-clock.wit b/proposals/sockets/wit-0.3.0-draft/deps/clocks/monotonic-clock.wit new file mode 100644 index 000000000..a91d495c6 --- /dev/null +++ b/proposals/sockets/wit-0.3.0-draft/deps/clocks/monotonic-clock.wit @@ -0,0 +1,48 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; +/// 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. +@since(version = 0.3.0-rc-2025-09-16) +interface monotonic-clock { + use types.{duration}; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + type instant = 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. + /// + /// For completeness, this function traps if it's not possible to represent + /// the value of the clock in an `instant`. Consequently, implementations + /// should ensure that the starting time is low enough to avoid the + /// possibility of overflow in practice. + @since(version = 0.3.0-rc-2025-09-16) + now: func() -> instant; + + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + @since(version = 0.3.0-rc-2025-09-16) + get-resolution: func() -> duration; + + /// Wait until the specified instant has occurred. + @since(version = 0.3.0-rc-2025-09-16) + wait-until: async func( + when: instant, + ); + + /// Wait for the specified duration to elapse. + @since(version = 0.3.0-rc-2025-09-16) + wait-for: async func( + how-long: duration, + ); +} diff --git a/proposals/sockets/wit-0.3.0-draft/deps/clocks/timezone.wit b/proposals/sockets/wit-0.3.0-draft/deps/clocks/timezone.wit new file mode 100644 index 000000000..ab8f5c080 --- /dev/null +++ b/proposals/sockets/wit-0.3.0-draft/deps/clocks/timezone.wit @@ -0,0 +1,55 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; + +@unstable(feature = clocks-timezone) +interface timezone { + @unstable(feature = clocks-timezone) + use wall-clock.{datetime}; + + /// Return information needed to display the given `datetime`. This includes + /// the UTC offset, the time zone name, and a flag indicating whether + /// daylight saving time is active. + /// + /// If the timezone cannot be determined for the given `datetime`, return a + /// `timezone-display` for `UTC` with a `utc-offset` of 0 and no daylight + /// saving time. + @unstable(feature = clocks-timezone) + display: func(when: datetime) -> timezone-display; + + /// The same as `display`, but only return the UTC offset. + @unstable(feature = clocks-timezone) + utc-offset: func(when: datetime) -> s32; + + /// Information useful for displaying the timezone of a specific `datetime`. + /// + /// This information may vary within a single `timezone` to reflect daylight + /// saving time adjustments. + @unstable(feature = clocks-timezone) + record timezone-display { + /// The number of seconds difference between UTC time and the local + /// time of the timezone. + /// + /// The returned value will always be less than 86400 which is the + /// number of seconds in a day (24*60*60). + /// + /// In implementations that do not expose an actual time zone, this + /// should return 0. + utc-offset: s32, + + /// The abbreviated name of the timezone to display to a user. The name + /// `UTC` indicates Coordinated Universal Time. Otherwise, this should + /// reference local standards for the name of the time zone. + /// + /// In implementations that do not expose an actual time zone, this + /// should be the string `UTC`. + /// + /// In time zones that do not have an applicable name, a formatted + /// representation of the UTC offset may be returned, such as `-04:00`. + name: string, + + /// Whether daylight saving time is active. + /// + /// In implementations that do not expose an actual time zone, this + /// should return false. + in-daylight-saving-time: bool, + } +} diff --git a/proposals/sockets/wit-0.3.0-draft/deps/clocks/types.wit b/proposals/sockets/wit-0.3.0-draft/deps/clocks/types.wit new file mode 100644 index 000000000..aff7c2a22 --- /dev/null +++ b/proposals/sockets/wit-0.3.0-draft/deps/clocks/types.wit @@ -0,0 +1,8 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; +/// This interface common types used throughout wasi:clocks. +@since(version = 0.3.0-rc-2025-09-16) +interface types { + /// A duration of time, in nanoseconds. + @since(version = 0.3.0-rc-2025-09-16) + type duration = u64; +} diff --git a/proposals/sockets/wit-0.3.0-draft/deps/clocks/wall-clock.wit b/proposals/sockets/wit-0.3.0-draft/deps/clocks/wall-clock.wit new file mode 100644 index 000000000..ea940500f --- /dev/null +++ b/proposals/sockets/wit-0.3.0-draft/deps/clocks/wall-clock.wit @@ -0,0 +1,46 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; +/// 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. +@since(version = 0.3.0-rc-2025-09-16) +interface wall-clock { + /// A time and date in seconds plus nanoseconds. + @since(version = 0.3.0-rc-2025-09-16) + 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 + @since(version = 0.3.0-rc-2025-09-16) + now: func() -> datetime; + + /// Query the resolution of the clock. + /// + /// The nanoseconds field of the output is always less than 1000000000. + @since(version = 0.3.0-rc-2025-09-16) + get-resolution: func() -> datetime; +} diff --git a/proposals/sockets/wit-0.3.0-draft/deps/clocks/world.wit b/proposals/sockets/wit-0.3.0-draft/deps/clocks/world.wit new file mode 100644 index 000000000..a6b885f07 --- /dev/null +++ b/proposals/sockets/wit-0.3.0-draft/deps/clocks/world.wit @@ -0,0 +1,11 @@ +package wasi:clocks@0.3.0-rc-2025-09-16; + +@since(version = 0.3.0-rc-2025-09-16) +world imports { + @since(version = 0.3.0-rc-2025-09-16) + import monotonic-clock; + @since(version = 0.3.0-rc-2025-09-16) + import wall-clock; + @unstable(feature = clocks-timezone) + import timezone; +} diff --git a/proposals/sockets/wit-0.3.0-draft/ip-name-lookup.wit b/proposals/sockets/wit-0.3.0-draft/ip-name-lookup.wit new file mode 100644 index 000000000..6a652ff23 --- /dev/null +++ b/proposals/sockets/wit-0.3.0-draft/ip-name-lookup.wit @@ -0,0 +1,62 @@ +@since(version = 0.3.0-rc-2025-09-16) +interface ip-name-lookup { + @since(version = 0.3.0-rc-2025-09-16) + use types.{ip-address}; + + /// Lookup error codes. + @since(version = 0.3.0-rc-2025-09-16) + enum error-code { + /// Unknown error + unknown, + + /// Access denied. + /// + /// POSIX equivalent: EACCES, EPERM + access-denied, + + /// `name` is a syntactically invalid domain name or IP address. + /// + /// POSIX equivalent: EINVAL + invalid-argument, + + /// Name does not exist or has no suitable associated IP addresses. + /// + /// POSIX equivalent: EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY + name-unresolvable, + + /// A temporary failure in name resolution occurred. + /// + /// POSIX equivalent: EAI_AGAIN + temporary-resolver-failure, + + /// A permanent failure in name resolution occurred. + /// + /// POSIX equivalent: EAI_FAIL + permanent-resolver-failure, + } + + /// 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. + /// + /// The results are returned in connection order preference. + /// + /// This function never succeeds with 0 results. It either fails or succeeds + /// with at least one address. Additionally, this function never returns + /// IPv4-mapped IPv6 addresses. + /// + /// The returned future will resolve to an error code in case of failure. + /// It will resolve to success once the returned stream is exhausted. + /// + /// # References: + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + resolve-addresses: async func(name: string) -> result, error-code>; +} diff --git a/proposals/sockets/wit-0.3.0-draft/types.wit b/proposals/sockets/wit-0.3.0-draft/types.wit new file mode 100644 index 000000000..fdafa5777 --- /dev/null +++ b/proposals/sockets/wit-0.3.0-draft/types.wit @@ -0,0 +1,725 @@ +@since(version = 0.3.0-rc-2025-09-16) +interface types { + @since(version = 0.3.0-rc-2025-09-16) + use wasi:clocks/types@0.3.0-rc-2025-09-16.{duration}; + + /// 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` + /// + /// See each individual API for what the POSIX equivalents are. They sometimes differ per API. + @since(version = 0.3.0-rc-2025-09-16) + 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, + + /// The operation is not valid in the socket's current state. + invalid-state, + + /// 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, + } + + @since(version = 0.3.0-rc-2025-09-16) + enum ip-address-family { + /// Similar to `AF_INET` in POSIX. + ipv4, + + /// Similar to `AF_INET6` in POSIX. + ipv6, + } + + @since(version = 0.3.0-rc-2025-09-16) + type ipv4-address = tuple; + @since(version = 0.3.0-rc-2025-09-16) + type ipv6-address = tuple; + + @since(version = 0.3.0-rc-2025-09-16) + variant ip-address { + ipv4(ipv4-address), + ipv6(ipv6-address), + } + + @since(version = 0.3.0-rc-2025-09-16) + record ipv4-socket-address { + /// sin_port + port: u16, + /// sin_addr + address: ipv4-address, + } + + @since(version = 0.3.0-rc-2025-09-16) + record ipv6-socket-address { + /// sin6_port + port: u16, + /// sin6_flowinfo + flow-info: u32, + /// sin6_addr + address: ipv6-address, + /// sin6_scope_id + scope-id: u32, + } + + @since(version = 0.3.0-rc-2025-09-16) + variant ip-socket-address { + ipv4(ipv4-socket-address), + ipv6(ipv6-socket-address), + } + + /// A TCP socket resource. + /// + /// The socket can be in one of the following states: + /// - `unbound` + /// - `bound` (See note below) + /// - `listening` + /// - `connecting` + /// - `connected` + /// - `closed` + /// See + /// for 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`, `listening`, `connecting` or `connected`) + /// + /// In addition to the general error codes documented on the + /// `types::error-code` type, TCP socket methods may always return + /// `error(invalid-state)` when in the `closed` state. + @since(version = 0.3.0-rc-2025-09-16) + resource 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. + /// + /// Unlike POSIX, WASI sockets have no notion of a socket-level + /// `O_NONBLOCK` flag. Instead they fully rely on the Component Model's + /// async support. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + create: static func(address-family: ip-address-family) -> result; + + /// Bind the socket to 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 can be bound to. (EADDRNOTAVAIL) + /// + /// # 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. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + bind: func(local-address: ip-socket-address) -> result<_, error-code>; + + /// Connect to a remote endpoint. + /// + /// On success, the socket is transitioned into the `connected` state and this function returns a connection resource. + /// + /// 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-state`: The socket is already in the `connecting` state. (EALREADY) + /// - `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) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + connect: async func(remote-address: ip-socket-address) -> result<_, error-code>; + + /// Start listening and return a stream of new inbound connections. + /// + /// Transitions the socket into the `listening` state. This can be called + /// at most once per socket. + /// + /// If the socket is not already explicitly bound, this function will + /// implicitly bind the socket to a random free port. + /// + /// Normally, the returned sockets are bound, in the `connected` state + /// and immediately ready for I/O. Though, depending on exact timing and + /// circumstances, a newly accepted connection may already be `closed` + /// by the time the server attempts to perform its first I/O on it. This + /// is true regardless of whether the WASI implementation uses + /// "synthesized" sockets or not (see Implementors Notes below). + /// + /// 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` + /// + /// # Typical errors + /// - `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) + /// + /// # Implementors note + /// This method returns a single perpetual stream that should only close + /// on fatal errors (if any). Yet, the POSIX' `accept` function may also + /// return transient errors (e.g. ECONNABORTED). The exact details differ + /// per operation system. For example, the Linux manual mentions: + /// + /// > Linux accept() passes already-pending network errors on the new + /// > socket as an error code from accept(). This behavior differs from + /// > other BSD socket implementations. For reliable operation the + /// > application should detect the network errors defined for the + /// > protocol after accept() and treat them like EAGAIN by retrying. + /// > In the case of TCP/IP, these are ENETDOWN, EPROTO, ENOPROTOOPT, + /// > EHOSTDOWN, ENONET, EHOSTUNREACH, EOPNOTSUPP, and ENETUNREACH. + /// Source: https://man7.org/linux/man-pages/man2/accept.2.html + /// + /// WASI implementations have two options to handle this: + /// - Optionally log it and then skip over non-fatal errors returned by + /// `accept`. Guest code never gets to see these failures. Or: + /// - Synthesize a `tcp-socket` resource that exposes the error when + /// attempting to send or receive on it. Guest code then sees these + /// failures as regular I/O errors. + /// + /// In either case, the stream returned by this `listen` method remains + /// operational. + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + listen: func() -> result, error-code>; + + /// Transmit data to peer. + /// + /// The caller should close the stream when it has no more data to send + /// to the peer. Under normal circumstances this will cause a FIN packet + /// to be sent out. Closing the stream is equivalent to calling + /// `shutdown(SHUT_WR)` in POSIX. + /// + /// This function may be called at most once and returns once the full + /// contents of the stream are transmitted or an error is encountered. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) + /// - `connection-reset`: The connection was reset. (ECONNRESET) + /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + send: async func(data: stream) -> result<_, error-code>; + + /// Read data from peer. + /// + /// This function returns a `stream` which provides the data received from the + /// socket, and a `future` providing additional error information in case the + /// socket is closed abnormally. + /// + /// If the socket is closed normally, `stream.read` on the `stream` will return + /// `read-status::closed` with no `error-context` and the future resolves to + /// the value `ok`. If the socket is closed abnormally, `stream.read` on the + /// `stream` returns `read-status::closed` with an `error-context` and the future + /// resolves to `err` with an `error-code`. + /// + /// `receive` is meant to be called only once per socket. If it is called more + /// than once, the subsequent calls return a new `stream` that fails as if it + /// were closed abnormally. + /// + /// If the caller is not expecting to receive any data from the peer, + /// they may drop the stream. Any data still in the receive queue + /// will be discarded. This is equivalent to calling `shutdown(SHUT_RD)` + /// in POSIX. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) + /// - `connection-reset`: The connection was reset. (ECONNRESET) + /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + receive: func() -> tuple, future>>; + + /// 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 `get-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 + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + get-local-address: func() -> result; + + /// Get the remote address. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + get-remote-address: func() -> result; + + /// Whether the socket is in the `listening` state. + /// + /// Equivalent to the SO_ACCEPTCONN socket option. + @since(version = 0.3.0-rc-2025-09-16) + get-is-listening: func() -> bool; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// This is the value passed to the constructor. + /// + /// Equivalent to the SO_DOMAIN socket option. + @since(version = 0.3.0-rc-2025-09-16) + get-address-family: func() -> ip-address-family; + + /// 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 `connecting` or `connected` state. + @since(version = 0.3.0-rc-2025-09-16) + set-listen-backlog-size: func(value: u64) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + get-keep-alive-enabled: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-keep-alive-enabled: func(value: bool) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + get-keep-alive-idle-time: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-keep-alive-idle-time: func(value: duration) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + get-keep-alive-interval: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-keep-alive-interval: func(value: duration) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + get-keep-alive-count: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-keep-alive-count: func(value: u32) -> 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. + @since(version = 0.3.0-rc-2025-09-16) + get-hop-limit: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-hop-limit: func(value: u8) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + get-receive-buffer-size: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + @since(version = 0.3.0-rc-2025-09-16) + get-send-buffer-size: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + } + + /// A UDP socket handle. + @since(version = 0.3.0-rc-2025-09-16) + resource 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. + /// + /// Unlike POSIX, WASI sockets have no notion of a socket-level + /// `O_NONBLOCK` flag. Instead they fully rely on the Component Model's + /// async support. + /// + /// # References: + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + create: static func(address-family: ip-address-family) -> result; + + /// Bind the socket to 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 can be bound to. (EADDRNOTAVAIL) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + bind: func(local-address: ip-socket-address) -> result<_, error-code>; + + /// Associate this socket with a specific peer address. + /// + /// 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`. If the socket was not already explicitly + /// bound, this function will implicitly bind the socket to a random + /// free port. + /// + /// When a UDP socket is "connected", the `send` and `receive` methods + /// are limited to communicating with that peer only: + /// - `send` can only be used to send to this destination. + /// - `receive` will only return datagrams sent from the provided `remote-address`. + /// + /// The name "connect" was kept to align with the existing POSIX + /// terminology. Other than that, this function only changes the local + /// socket configuration and does not generate any network traffic. + /// The peer is not aware of this "connection". + /// + /// This method may be called multiple times on the same socket to change + /// its association, but only the most recent one will be effective. + /// + /// # 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) + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// + /// # Implementors note + /// If the socket is already connected, some platforms (e.g. Linux) + /// require a disconnect before connecting to a different peer address. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + connect: func(remote-address: ip-socket-address) -> result<_, error-code>; + + /// Dissociate this socket from its peer address. + /// + /// After calling this method, `send` & `receive` are free to communicate + /// with any address again. + /// + /// The POSIX equivalent of this is calling `connect` with an `AF_UNSPEC` address. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not connected. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + disconnect: func() -> result<_, error-code>; + + /// Send a message on the socket to a particular peer. + /// + /// If the socket is connected, the peer address may be left empty. In + /// that case this is equivalent to `send` in POSIX. Otherwise it is + /// equivalent to `sendto`. + /// + /// Additionally, if the socket is connected, a `remote-address` argument + /// _may_ be provided but then it must be identical to the address + /// passed to `connect`. + /// + /// Implementations may trap if the `data` length exceeds 64 KiB. + /// + /// # 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 `connect`. (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 + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + send: async func(data: list, remote-address: option) -> result<_, error-code>; + + /// Receive a message on the socket. + /// + /// On success, the return value contains a tuple of the received data + /// and the address of the sender. Theoretical maximum length of the + /// data is 64 KiB. Though in practice, it will typically be less than + /// 1500 bytes. + /// + /// If the socket is connected, the sender address is guaranteed to + /// match the remote address passed to `connect`. + /// + /// # Typical errors + /// - `invalid-state`: The socket has not been bound yet. + /// - `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 + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + receive: async func() -> result, ip-socket-address>, 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 `get-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 + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + get-local-address: func() -> result; + + /// Get the address the socket is currently "connected" to. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not "connected" to a specific remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0-rc-2025-09-16) + get-remote-address: func() -> result; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// This is the value passed to the constructor. + /// + /// Equivalent to the SO_DOMAIN socket option. + @since(version = 0.3.0-rc-2025-09-16) + get-address-family: func() -> ip-address-family; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + get-unicast-hop-limit: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; + + /// 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. + @since(version = 0.3.0-rc-2025-09-16) + get-receive-buffer-size: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + @since(version = 0.3.0-rc-2025-09-16) + get-send-buffer-size: func() -> result; + @since(version = 0.3.0-rc-2025-09-16) + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + } +} diff --git a/proposals/sockets/wit-0.3.0-draft/world.wit b/proposals/sockets/wit-0.3.0-draft/world.wit new file mode 100644 index 000000000..44cc427ed --- /dev/null +++ b/proposals/sockets/wit-0.3.0-draft/world.wit @@ -0,0 +1,9 @@ +package wasi:sockets@0.3.0-rc-2025-09-16; + +@since(version = 0.3.0-rc-2025-09-16) +world imports { + @since(version = 0.3.0-rc-2025-09-16) + import types; + @since(version = 0.3.0-rc-2025-09-16) + import ip-name-lookup; +} diff --git a/proposals/sockets/wit/deps.lock b/proposals/sockets/wit/deps.lock new file mode 100644 index 000000000..b0d60f694 --- /dev/null +++ b/proposals/sockets/wit/deps.lock @@ -0,0 +1,9 @@ +[clocks] +url = "https://github.com/WebAssembly/wasi-clocks/archive/main.tar.gz" +sha256 = "be1d8c61e2544e2b48d902c60df73577e293349063344ce752cda4d323f8b913" +sha512 = "0fd7962c62b135da0e584c2b58a55147bf09873848b0bb5bd3913019bc3f8d4b5969fbd6f7f96fd99a015efaf562a3eeafe3bc13049f8572a6e13ef9ef0e7e75" + +[io] +url = "https://github.com/WebAssembly/wasi-io/archive/main.tar.gz" +sha256 = "9f1ad5da70f621bbd4c69e3bd90250a0c12ecfde266aa8f99684fc44bc1e7c15" +sha512 = "6d0a9db6848f24762933d1c168a5b5b1065ba838c253ee20454afeb8dd1a049b918d25deff556083d68095dd3126ae131ac3e738774320eee5d918f5a4b5354e" diff --git a/proposals/sockets/wit/deps.toml b/proposals/sockets/wit/deps.toml new file mode 100644 index 000000000..c07efafd6 --- /dev/null +++ b/proposals/sockets/wit/deps.toml @@ -0,0 +1,2 @@ +clocks = "https://github.com/WebAssembly/wasi-clocks/archive/main.tar.gz" +io = "https://github.com/WebAssembly/wasi-io/archive/main.tar.gz" diff --git a/proposals/sockets/wit/deps/clocks/monotonic-clock.wit b/proposals/sockets/wit/deps/clocks/monotonic-clock.wit new file mode 100644 index 000000000..e60f366f2 --- /dev/null +++ b/proposals/sockets/wit/deps/clocks/monotonic-clock.wit @@ -0,0 +1,55 @@ +package wasi:clocks@0.2.8; +/// 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. +@since(version = 0.2.0) +interface monotonic-clock { + @since(version = 0.2.0) + use wasi:io/poll@0.2.8.{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. + @since(version = 0.2.0) + type instant = u64; + + /// A duration of time, in nanoseconds. + @since(version = 0.2.0) + 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. + /// + /// For completeness, this function traps if it's not possible to represent + /// the value of the clock in an `instant`. Consequently, implementations + /// should ensure that the starting time is low enough to avoid the + /// possibility of overflow in practice. + @since(version = 0.2.0) + now: func() -> instant; + + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + @since(version = 0.2.0) + resolution: func() -> duration; + + /// Create a `pollable` which will resolve once the specified instant + /// has occurred. + @since(version = 0.2.0) + subscribe-instant: func( + when: instant, + ) -> pollable; + + /// Create a `pollable` that will resolve after the specified duration has + /// elapsed from the time this function is invoked. + @since(version = 0.2.0) + subscribe-duration: func( + when: duration, + ) -> pollable; +} diff --git a/proposals/sockets/wit/deps/clocks/timezone.wit b/proposals/sockets/wit/deps/clocks/timezone.wit new file mode 100644 index 000000000..534814a63 --- /dev/null +++ b/proposals/sockets/wit/deps/clocks/timezone.wit @@ -0,0 +1,55 @@ +package wasi:clocks@0.2.8; + +@unstable(feature = clocks-timezone) +interface timezone { + @unstable(feature = clocks-timezone) + use wall-clock.{datetime}; + + /// Return information needed to display the given `datetime`. This includes + /// the UTC offset, the time zone name, and a flag indicating whether + /// daylight saving time is active. + /// + /// If the timezone cannot be determined for the given `datetime`, return a + /// `timezone-display` for `UTC` with a `utc-offset` of 0 and no daylight + /// saving time. + @unstable(feature = clocks-timezone) + display: func(when: datetime) -> timezone-display; + + /// The same as `display`, but only return the UTC offset. + @unstable(feature = clocks-timezone) + utc-offset: func(when: datetime) -> s32; + + /// Information useful for displaying the timezone of a specific `datetime`. + /// + /// This information may vary within a single `timezone` to reflect daylight + /// saving time adjustments. + @unstable(feature = clocks-timezone) + record timezone-display { + /// The number of seconds difference between UTC time and the local + /// time of the timezone. + /// + /// The returned value will always be less than 86400 which is the + /// number of seconds in a day (24*60*60). + /// + /// In implementations that do not expose an actual time zone, this + /// should return 0. + utc-offset: s32, + + /// The abbreviated name of the timezone to display to a user. The name + /// `UTC` indicates Coordinated Universal Time. Otherwise, this should + /// reference local standards for the name of the time zone. + /// + /// In implementations that do not expose an actual time zone, this + /// should be the string `UTC`. + /// + /// In time zones that do not have an applicable name, a formatted + /// representation of the UTC offset may be returned, such as `-04:00`. + name: string, + + /// Whether daylight saving time is active. + /// + /// In implementations that do not expose an actual time zone, this + /// should return false. + in-daylight-saving-time: bool, + } +} diff --git a/proposals/sockets/wit/deps/clocks/wall-clock.wit b/proposals/sockets/wit/deps/clocks/wall-clock.wit new file mode 100644 index 000000000..3386c800b --- /dev/null +++ b/proposals/sockets/wit/deps/clocks/wall-clock.wit @@ -0,0 +1,46 @@ +package wasi:clocks@0.2.8; +/// 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. +@since(version = 0.2.0) +interface wall-clock { + /// A time and date in seconds plus nanoseconds. + @since(version = 0.2.0) + 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 + @since(version = 0.2.0) + now: func() -> datetime; + + /// Query the resolution of the clock. + /// + /// The nanoseconds field of the output is always less than 1000000000. + @since(version = 0.2.0) + resolution: func() -> datetime; +} diff --git a/proposals/sockets/wit/deps/clocks/world.wit b/proposals/sockets/wit/deps/clocks/world.wit new file mode 100644 index 000000000..1655ca830 --- /dev/null +++ b/proposals/sockets/wit/deps/clocks/world.wit @@ -0,0 +1,11 @@ +package wasi:clocks@0.2.8; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import monotonic-clock; + @since(version = 0.2.0) + import wall-clock; + @unstable(feature = clocks-timezone) + import timezone; +} diff --git a/proposals/sockets/wit/deps/io/error.wit b/proposals/sockets/wit/deps/io/error.wit new file mode 100644 index 000000000..dd5a1af03 --- /dev/null +++ b/proposals/sockets/wit/deps/io/error.wit @@ -0,0 +1,34 @@ +package wasi:io@0.2.8; + +@since(version = 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 + /// offer functions to "downcast" this error into more specific types. For example, + /// errors returned from streams derived from filesystem types can be described using + /// the filesystem's own error-code type. This is done using the function + /// `wasi:filesystem/types/filesystem-error-code`, which takes a `borrow` + /// parameter and returns an `option`. + /// + /// The set of functions which can "downcast" an `error` into a more + /// concrete type is open. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + to-debug-string: func() -> string; + } +} diff --git a/proposals/sockets/wit/deps/io/poll.wit b/proposals/sockets/wit/deps/io/poll.wit new file mode 100644 index 000000000..833b381d9 --- /dev/null +++ b/proposals/sockets/wit/deps/io/poll.wit @@ -0,0 +1,47 @@ +package wasi:io@0.2.8; + +/// A poll API intended to let users wait for I/O events on multiple handles +/// at once. +@since(version = 0.2.0) +interface poll { + /// `pollable` represents a single I/O event which may be ready, or not. + @since(version = 0.2.0) + resource pollable { + + /// Return the readiness of a pollable. This function never blocks. + /// + /// Returns `true` when the pollable is ready, and `false` otherwise. + @since(version = 0.2.0) + ready: func() -> bool; + + /// `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. + @since(version = 0.2.0) + block: func(); + } + + /// 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. + /// + /// This function traps if either: + /// - the list is empty, or: + /// - the list contains more elements than can be indexed with a `u32` value. + /// + /// 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 ready for I/O. + @since(version = 0.2.0) + poll: func(in: list>) -> list; +} diff --git a/proposals/sockets/wit/deps/io/streams.wit b/proposals/sockets/wit/deps/io/streams.wit new file mode 100644 index 000000000..fbb0268b0 --- /dev/null +++ b/proposals/sockets/wit/deps/io/streams.wit @@ -0,0 +1,258 @@ +package wasi:io@0.2.8; + +/// 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. +@since(version = 0.2.0) +interface streams { + @since(version = 0.2.0) + use error.{error}; + @since(version = 0.2.0) + use poll.{pollable}; + + /// An error for input-stream and output-stream operations. + @since(version = 0.2.0) + variant stream-error { + /// The last operation (a write or flush) failed before completion. + /// + /// More information is available in the `error` payload. + /// + /// After this, the stream will be closed. All future operations return + /// `stream-error::closed`. + 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`. + @since(version = 0.2.0) + resource input-stream { + /// 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. + @since(version = 0.2.0) + read: func( + /// The maximum number of bytes to read + len: u64 + ) -> result, stream-error>; + + /// Read bytes from a stream, after blocking until at least one byte can + /// be read. Except for blocking, behavior is identical to `read`. + @since(version = 0.2.0) + blocking-read: func( + /// The maximum number of bytes to read + 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. + @since(version = 0.2.0) + skip: func( + /// The maximum number of bytes to skip. + len: u64, + ) -> result; + + /// Skip bytes from a stream, after blocking until at least one byte + /// can be skipped. Except for blocking behavior, identical to `skip`. + @since(version = 0.2.0) + blocking-skip: func( + /// The maximum number of bytes to skip. + 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. + @since(version = 0.2.0) + 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`. + /// + /// Dropping an `output-stream` while there's still an active write in + /// progress may result in the data being lost. Before dropping the stream, + /// be sure to fully flush your writes. + @since(version = 0.2.0) + resource output-stream { + /// 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. + @since(version = 0.2.0) + check-write: func() -> result; + + /// 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. + @since(version = 0.2.0) + write: func( + contents: list + ) -> result<_, stream-error>; + + /// 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. + /// + /// Returns success when all of the contents written are successfully + /// flushed to output. If an error occurs at any point before all + /// contents are successfully flushed, that error is returned as soon as + /// possible. If writing and flushing the complete contents causes the + /// stream to become closed, this call should return success, and + /// subsequent calls to check-write or other interfaces should return + /// stream-error::closed. + @since(version = 0.2.0) + blocking-write-and-flush: func( + contents: list + ) -> result<_, stream-error>; + + /// 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. + @since(version = 0.2.0) + flush: func() -> result<_, stream-error>; + + /// Request to flush buffered output, and block until flush completes + /// and stream is ready for writing again. + @since(version = 0.2.0) + blocking-flush: func() -> result<_, stream-error>; + + /// Create a `pollable` which will resolve once the output-stream + /// is ready for more writing, or an error has occurred. 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. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// 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. + @since(version = 0.2.0) + write-zeroes: func( + /// The number of zero-bytes to write + len: u64 + ) -> 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. + /// + /// Functionality is equivelant to `blocking-write-and-flush` with + /// contents given as a list of len containing only zeroes. + @since(version = 0.2.0) + blocking-write-zeroes-and-flush: func( + /// The number of zero-bytes to write + len: u64 + ) -> result<_, stream-error>; + + /// Read from one stream and write to another. + /// + /// The behavior of splice is equivalent 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`. + @since(version = 0.2.0) + splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + + /// 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`. + @since(version = 0.2.0) + blocking-splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + } +} diff --git a/proposals/sockets/wit/deps/io/world.wit b/proposals/sockets/wit/deps/io/world.wit new file mode 100644 index 000000000..1cc3fce12 --- /dev/null +++ b/proposals/sockets/wit/deps/io/world.wit @@ -0,0 +1,10 @@ +package wasi:io@0.2.8; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import streams; + + @since(version = 0.2.0) + import poll; +} diff --git a/proposals/sockets/wit/instance-network.wit b/proposals/sockets/wit/instance-network.wit new file mode 100644 index 000000000..5f6e6c1cc --- /dev/null +++ b/proposals/sockets/wit/instance-network.wit @@ -0,0 +1,11 @@ + +/// This interface provides a value-export of the default network handle.. +@since(version = 0.2.0) +interface instance-network { + @since(version = 0.2.0) + use network.{network}; + + /// Get a handle to the default network. + @since(version = 0.2.0) + instance-network: func() -> network; +} diff --git a/proposals/sockets/wit/ip-name-lookup.wit b/proposals/sockets/wit/ip-name-lookup.wit new file mode 100644 index 000000000..ecdaa8493 --- /dev/null +++ b/proposals/sockets/wit/ip-name-lookup.wit @@ -0,0 +1,56 @@ +@since(version = 0.2.0) +interface ip-name-lookup { + @since(version = 0.2.0) + use wasi:io/poll@0.2.8.{pollable}; + @since(version = 0.2.0) + use network.{network, error-code, ip-address}; + + /// 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: + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + resolve-addresses: func(network: borrow, name: string) -> result; + + @since(version = 0.2.0) + 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) + @since(version = 0.2.0) + 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 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } +} diff --git a/proposals/sockets/wit/network.wit b/proposals/sockets/wit/network.wit new file mode 100644 index 000000000..75a4f7d7f --- /dev/null +++ b/proposals/sockets/wit/network.wit @@ -0,0 +1,169 @@ +@since(version = 0.2.0) +interface network { + @unstable(feature = network-error-code) + use wasi:io/error@0.2.8.{error}; + + /// 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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, + } + + /// Attempts to extract a network-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 + /// network-related information about the error to return. + /// + /// Note that this function is fallible because not all stream-related + /// errors are network-related errors. + @unstable(feature = network-error-code) + network-error-code: func(err: borrow) -> option; + + @since(version = 0.2.0) + enum ip-address-family { + /// Similar to `AF_INET` in POSIX. + ipv4, + + /// Similar to `AF_INET6` in POSIX. + ipv6, + } + + @since(version = 0.2.0) + type ipv4-address = tuple; + @since(version = 0.2.0) + type ipv6-address = tuple; + + @since(version = 0.2.0) + variant ip-address { + ipv4(ipv4-address), + ipv6(ipv6-address), + } + + @since(version = 0.2.0) + record ipv4-socket-address { + /// sin_port + port: u16, + /// sin_addr + address: ipv4-address, + } + + @since(version = 0.2.0) + record ipv6-socket-address { + /// sin6_port + port: u16, + /// sin6_flowinfo + flow-info: u32, + /// sin6_addr + address: ipv6-address, + /// sin6_scope_id + scope-id: u32, + } + + @since(version = 0.2.0) + variant ip-socket-address { + ipv4(ipv4-socket-address), + ipv6(ipv6-socket-address), + } +} diff --git a/proposals/sockets/wit/tcp-create-socket.wit b/proposals/sockets/wit/tcp-create-socket.wit new file mode 100644 index 000000000..eedbd3076 --- /dev/null +++ b/proposals/sockets/wit/tcp-create-socket.wit @@ -0,0 +1,30 @@ +@since(version = 0.2.0) +interface tcp-create-socket { + @since(version = 0.2.0) + use network.{network, error-code, ip-address-family}; + @since(version = 0.2.0) + 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + create-tcp-socket: func(address-family: ip-address-family) -> result; +} diff --git a/proposals/sockets/wit/tcp.wit b/proposals/sockets/wit/tcp.wit new file mode 100644 index 000000000..9b5552d2e --- /dev/null +++ b/proposals/sockets/wit/tcp.wit @@ -0,0 +1,387 @@ +@since(version = 0.2.0) +interface tcp { + @since(version = 0.2.0) + use wasi:io/streams@0.2.8.{input-stream, output-stream}; + @since(version = 0.2.0) + use wasi:io/poll@0.2.8.{pollable}; + @since(version = 0.2.0) + use wasi:clocks/monotonic-clock@0.2.8.{duration}; + @since(version = 0.2.0) + use network.{network, error-code, ip-socket-address, ip-address-family}; + + @since(version = 0.2.0) + 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 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. + @since(version = 0.2.0) + resource tcp-socket { + /// 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + @since(version = 0.2.0) + finish-bind: func() -> result<_, error-code>; + + /// Connect to a remote endpoint. + /// + /// On success: + /// - the socket is transitioned into the `connected` 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-connect: func(network: borrow, remote-address: ip-socket-address) -> result<_, error-code>; + @since(version = 0.2.0) + finish-connect: func() -> 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-listen: func() -> result<_, error-code>; + @since(version = 0.2.0) + finish-listen: func() -> result<_, error-code>; + + /// 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + accept: func() -> result, error-code>; + + /// 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + local-address: func() -> result; + + /// Get the remote address. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + remote-address: func() -> result; + + /// Whether the socket is in the `listening` state. + /// + /// Equivalent to the SO_ACCEPTCONN socket option. + @since(version = 0.2.0) + is-listening: func() -> bool; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + @since(version = 0.2.0) + address-family: func() -> ip-address-family; + + /// 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. + @since(version = 0.2.0) + set-listen-backlog-size: func(value: u64) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + keep-alive-enabled: func() -> result; + @since(version = 0.2.0) + set-keep-alive-enabled: func(value: bool) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + keep-alive-idle-time: func() -> result; + @since(version = 0.2.0) + set-keep-alive-idle-time: func(value: duration) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + keep-alive-interval: func() -> result; + @since(version = 0.2.0) + set-keep-alive-interval: func(value: duration) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + keep-alive-count: func() -> result; + @since(version = 0.2.0) + set-keep-alive-count: func(value: u32) -> 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. + @since(version = 0.2.0) + hop-limit: func() -> result; + @since(version = 0.2.0) + set-hop-limit: func(value: u8) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + receive-buffer-size: func() -> result; + @since(version = 0.2.0) + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + @since(version = 0.2.0) + send-buffer-size: func() -> result; + @since(version = 0.2.0) + set-send-buffer-size: func(value: 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. + /// + /// 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 more information. + /// + /// Note: this function is here for WASI 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// 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 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code>; + } +} diff --git a/proposals/sockets/wit/udp-create-socket.wit b/proposals/sockets/wit/udp-create-socket.wit new file mode 100644 index 000000000..e8eeacbfe --- /dev/null +++ b/proposals/sockets/wit/udp-create-socket.wit @@ -0,0 +1,30 @@ +@since(version = 0.2.0) +interface udp-create-socket { + @since(version = 0.2.0) + use network.{network, error-code, ip-address-family}; + @since(version = 0.2.0) + 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: + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + create-udp-socket: func(address-family: ip-address-family) -> result; +} diff --git a/proposals/sockets/wit/udp.wit b/proposals/sockets/wit/udp.wit new file mode 100644 index 000000000..0000a157e --- /dev/null +++ b/proposals/sockets/wit/udp.wit @@ -0,0 +1,288 @@ +@since(version = 0.2.0) +interface udp { + @since(version = 0.2.0) + use wasi:io/poll@0.2.8.{pollable}; + @since(version = 0.2.0) + use network.{network, error-code, ip-socket-address, ip-address-family}; + + /// A received datagram. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + resource udp-socket { + /// 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + @since(version = 0.2.0) + finish-bind: func() -> 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + %stream: func(remote-address: option) -> 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + local-address: 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + remote-address: func() -> result; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + @since(version = 0.2.0) + address-family: func() -> ip-address-family; + + /// 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. + @since(version = 0.2.0) + unicast-hop-limit: func() -> result; + @since(version = 0.2.0) + set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + receive-buffer-size: func() -> result; + @since(version = 0.2.0) + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + @since(version = 0.2.0) + send-buffer-size: func() -> result; + @since(version = 0.2.0) + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + + /// Create a `pollable` which will resolve once the socket is ready for I/O. + /// + /// Note: this function is here for WASI 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } + + @since(version = 0.2.0) + 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 + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + 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 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } + + @since(version = 0.2.0) + 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 + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + 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 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } +} diff --git a/proposals/sockets/wit/world.wit b/proposals/sockets/wit/world.wit new file mode 100644 index 000000000..4441e9119 --- /dev/null +++ b/proposals/sockets/wit/world.wit @@ -0,0 +1,19 @@ +package wasi:sockets@0.2.8; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import instance-network; + @since(version = 0.2.0) + import network; + @since(version = 0.2.0) + import udp; + @since(version = 0.2.0) + import udp-create-socket; + @since(version = 0.2.0) + import tcp; + @since(version = 0.2.0) + import tcp-create-socket; + @since(version = 0.2.0) + import ip-name-lookup; +}