Wado
<!-- Auto-generated by: wado doc -f markdown --title "WASI Standard Library" wasi:cli wasi:filesystem wasi:http wasi:clocks wasi:random wasi:sockets wasi:tls --> <!-- Do not edit this file directly. -->

WASI Standard Library

wasi:cli

Effects

pub interface Environment

fn get_environment() -> List<[String, String]>

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.

fn get_arguments() -> List<String>

Get the POSIX-style arguments to the program.

fn get_initial_cwd() -> Option<String>

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

pub interface Exit

fn exit(status: Result<(), ()>)

Exit the current instance and any linked instances.

fn exit_with_code(status_code: u8)

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.

pub interface Run

async fn run() -> AsyncCall<Result<(), ()>>

Run the program.

pub interface Stdin

fn read_via_stream() -> [Stream<u8>, Future<Result<(), ErrorCode>>]

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.

pub interface Stdout

fn write_via_stream(data: Stream<u8>) -> Future<Result<(), ErrorCode>>

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.

pub interface Stderr

fn write_via_stream(data: Stream<u8>) -> Future<Result<(), ErrorCode>>

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.

pub interface TerminalStdin

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

fn get_terminal_stdin() -> Option<TerminalInput>

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

pub interface TerminalStdout

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

fn get_terminal_stdout() -> Option<TerminalOutput>

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

pub interface TerminalStderr

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

fn get_terminal_stderr() -> Option<TerminalOutput>

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

Resources

pub resource TerminalInput

The input side of a terminal.

pub resource TerminalOutput

The output side of a terminal.

Enums

pub enum ErrorCode

Io

Input/output error

IllegalByteSequence

Invalid or incomplete multibyte or wide character

Pipe

Broken pipe

wasi:filesystem

Effects

pub interface Preopens

fn get_directories() -> List<[Descriptor, String]>

Return the set of preopened directories, and their paths.

Resources

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

fn read_via_stream(&self, offset: Filesize) -> [Stream<u8>, Future<Result<(), ErrorCode>>]

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.

fn write_via_stream(&self, data: Stream<u8>, offset: Filesize) -> Future<Result<(), ErrorCode>>

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.

fn append_via_stream(&self, data: Stream<u8>) -> Future<Result<(), ErrorCode>>

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.

async fn advise(&self, offset: Filesize, length: Filesize, advice: Advice) -> AsyncCall<Result<(), ErrorCode>>

Provide file advisory information on a descriptor.

This is similar to posix_fadvise in POSIX.

async fn sync_data(&self) -> AsyncCall<Result<(), ErrorCode>>

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.

async fn get_flags(&self) -> AsyncCall<Result<DescriptorFlags, ErrorCode>>

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.

async fn get_type(&self) -> AsyncCall<Result<DescriptorType, ErrorCode>>

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.

async fn set_size(&self, size: Filesize) -> AsyncCall<Result<(), ErrorCode>>

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.

async fn set_times(&self, data_access_timestamp: NewTimestamp, data_modification_timestamp: NewTimestamp) -> AsyncCall<Result<(), ErrorCode>>

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.

fn read_directory(&self) -> [Stream<DirectoryEntry>, Future<Result<(), ErrorCode>>]

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.

async fn sync(&self) -> AsyncCall<Result<(), ErrorCode>>

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.

async fn create_directory_at(&self, path: String) -> AsyncCall<Result<(), ErrorCode>>

Create a directory.

Note: This is similar to mkdirat in POSIX.

async fn stat(&self) -> AsyncCall<Result<DescriptorStat, ErrorCode>>

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.

async fn stat_at(&self, path_flags: PathFlags, path: String) -> AsyncCall<Result<DescriptorStat, ErrorCode>>

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.

async fn set_times_at(&self, path_flags: PathFlags, path: String, data_access_timestamp: NewTimestamp, data_modification_timestamp: NewTimestamp) -> AsyncCall<Result<(), ErrorCode>>

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.

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.

async fn open_at(&self, path_flags: PathFlags, path: String, open_flags: OpenFlags, flags: DescriptorFlags) -> AsyncCall<Result<Descriptor, ErrorCode>>

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.

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.

async fn remove_directory_at(&self, path: String) -> AsyncCall<Result<(), ErrorCode>>

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.

async fn rename_at(&self, old_path: String, new_descriptor: &Descriptor, new_path: String) -> AsyncCall<Result<(), ErrorCode>>

Rename a filesystem object.

Note: This is similar to renameat in POSIX.

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.

Unlink a filesystem object that is not a directory.

This is similar to unlinkat(fd, path, 0) in POSIX.

Error returns are as specified by POSIX.

If the filesystem object is a directory, error-code::access or error-code::is-directory may be returned instead of the POSIX-specified error-code::not-permitted.

async fn is_same_object(&self, other: &Descriptor) -> AsyncCall<bool>

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.

async fn metadata_hash(&self) -> AsyncCall<Result<MetadataHashValue, ErrorCode>>

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.

async fn metadata_hash_at(&self, path_flags: PathFlags, path: String) -> AsyncCall<Result<MetadataHashValue, ErrorCode>>

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.

Types

pub type Filesize = u64

pub type LinkCount = u64

Structs

pub struct DescriptorStat

File attributes.

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

type: DescriptorType

File type.

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<Instant>

Last data access timestamp.

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

data_modification_timestamp: Option<Instant>

Last data modification timestamp.

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

status_change_timestamp: Option<Instant>

Last file status-change timestamp.

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

pub struct DirectoryEntry

A directory entry.

type: DescriptorType

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

name: String

The name of the object.

pub struct MetadataHashValue

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

lower: u64

64 bits of a 128-bit hash value.

upper: u64

Another 64 bits of a 128-bit hash value.

Variants

pub variant DescriptorType

The type of a filesystem object referenced by a descriptor.

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

BlockDevice

The descriptor refers to a block device inode.

CharacterDevice

The descriptor refers to a character device inode.

Directory

The descriptor refers to a directory inode.

Fifo

The descriptor refers to a named pipe.

The file refers to a symbolic link inode.

RegularFile

The descriptor refers to a regular file inode.

Socket

The descriptor refers to a socket.

Other(Option<String>)

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

pub variant NewTimestamp

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

NoChange

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(Instant)

Set the timestamp to the given value.

pub variant ErrorCode

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.

Access

Permission denied, similar to EACCES in POSIX.

Already

Connection already in progress, similar to EALREADY in POSIX.

BadDescriptor

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.

FileTooLarge

File too large, similar to EFBIG in POSIX.

IllegalByteSequence

Illegal byte sequence, similar to EILSEQ in POSIX.

InProgress

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.

IsDirectory

Is a directory, similar to EISDIR in POSIX.

Loop

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

Too many links, similar to EMLINK in POSIX.

MessageSize

Message too large, similar to EMSGSIZE in POSIX.

NameTooLong

Filename too long, similar to ENAMETOOLONG in POSIX.

NoDevice

No such device, similar to ENODEV in POSIX.

NoEntry

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

NoLock

No locks available, similar to ENOLCK in POSIX.

InsufficientMemory

Not enough space, similar to ENOMEM in POSIX.

InsufficientSpace

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

NotDirectory

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

NotEmpty

Directory not empty, similar to ENOTEMPTY in POSIX.

NotRecoverable

State not recoverable, similar to ENOTRECOVERABLE in POSIX.

Unsupported

Not supported, similar to ENOTSUP and ENOSYS in POSIX.

NoTty

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

NoSuchDevice

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.

NotPermitted

Operation not permitted, similar to EPERM in POSIX.

Pipe

Broken pipe, similar to EPIPE in POSIX.

ReadOnly

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

InvalidSeek

Invalid seek, similar to ESPIPE in POSIX.

TextFileBusy

Text file busy, similar to ETXTBSY in POSIX.

CrossDevice

Cross-device link, similar to EXDEV in POSIX.

Other(Option<String>)

A catch-all for errors not captured by the existing variants. Implementations can use this to extend the error type without breaking existing code.

Enums

pub enum Advice

File or memory access pattern advisory information.

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.

WillNeed

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

DontNeed

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

NoReuse

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

Flags

pub flags DescriptorFlags

Descriptor flags.

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

Read

Read mode: Data can be read.

Write

Write mode: Data can be written to.

FileIntegritySync

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.

DataIntegritySync

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.

RequestedWriteSync

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.

MutateDirectory

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.

pub flags PathFlags

Flags determining the method of how paths are resolved.

SymlinkFollow

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

pub flags OpenFlags

Open flags used by open-at.

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.

wasi:http

Effects

pub interface 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.

async fn handle(request: Request) -> AsyncCall<Result<Response, ErrorCode>>

This function may be called with either an incoming request read from the network or a request synthesized or forwarded by another component.

pub interface Client

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.

async fn send(request: Request) -> AsyncCall<Result<Response, ErrorCode>>

This function may be used to either send an outgoing request over the network or to forward it to another component.

Resources

pub 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, 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-names and field-values 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.

Implementations may impose limits on individual field values and on total aggregate field section size. Operations that would exceed these limits fail with header-error.size-exceeded

fn new() -> Fields

Construct an empty HTTP Fields.

The resulting fields is mutable.

fn from_list(entries: List<[FieldName, FieldValue]>) -> Result<Fields, HeaderError>

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, if a header was forbidden, or if the entries would exceed an implementation size limit.

fn get(&self, name: FieldName) -> List<FieldValue>

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.

fn has(&self, name: FieldName) -> bool

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

fn set(&self, name: FieldName, value: List<FieldValue>) -> Result<(), HeaderError>

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.size-exceeded if the name or values would exceed an implementation-defined size limit.

fn delete(&self, name: FieldName) -> Result<(), HeaderError>

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.

fn get_and_delete(&self, name: FieldName) -> Result<List<FieldValue>, HeaderError>

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.

fn append(&self, name: FieldName, value: FieldValue) -> Result<(), HeaderError>

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.size-exceeded if the value would exceed an implementation-defined size limit.

fn copy_all(&self) -> List<[FieldName, FieldValue]>

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.

fn clone(&self) -> Fields

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.

pub resource Request

Represents an HTTP Request.

fn new(headers: Headers, contents: Option<Stream<u8>>, trailers: Future<Result<Option<Trailers>, ErrorCode>>, options: Option<RequestOptions>) -> [Request, Future<Result<(), ErrorCode>>]

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.

fn get_method(&self) -> Method

Get the Method for the Request.

fn set_method(&self, method: Method) -> Result<(), ()>

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

fn get_path_with_query(&self) -> Option<String>

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

fn set_path_with_query(&self, path_with_query: Option<String>) -> Result<(), ()>

Set the combination of the HTTP Path and Query for the Request. When none, this represents an empty Path and empty Query. Fails is the string given is not a syntactically valid path and query uri component.

fn get_scheme(&self) -> Option<Scheme>

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

fn set_scheme(&self, scheme: Option<Scheme>) -> Result<(), ()>

Set the HTTP Related Scheme for the Request. When none, the implementation may choose an appropriate default scheme. Fails if the string given is not a syntactically valid uri scheme.

fn get_authority(&self) -> Option<String>

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.

fn set_authority(&self, authority: Option<String>) -> Result<(), ()>

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.

fn get_options(&self) -> Option<RequestOptions>

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.

fn get_headers(&self) -> Headers

Get the headers associated with the Request.

The returned headers resource is immutable: set, append, and delete operations will fail with header-error.immutable.

fn consume_body(this: Request, res: Future<Result<(), ErrorCode>>) -> [Stream<u8>, Future<Result<Option<Trailers>, ErrorCode>>]

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.

pub resource RequestOptions

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.

fn new() -> RequestOptions

Construct a default request-options value.

fn get_connect_timeout(&self) -> Option<Duration>

The timeout for the initial connect to the HTTP Server.

fn set_connect_timeout(&self, duration: Option<Duration>) -> Result<(), RequestOptionsError>

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.

fn get_first_byte_timeout(&self) -> Option<Duration>

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

fn set_first_byte_timeout(&self, duration: Option<Duration>) -> Result<(), RequestOptionsError>

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.

fn get_between_bytes_timeout(&self) -> Option<Duration>

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

fn set_between_bytes_timeout(&self, duration: Option<Duration>) -> Result<(), RequestOptionsError>

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.

fn clone(&self) -> RequestOptions

Make a deep copy of the request-options. The resulting request-options is mutable.

pub resource Response

Represents an HTTP Response.

fn new(headers: Headers, contents: Option<Stream<u8>>, trailers: Future<Result<Option<Trailers>, ErrorCode>>) -> [Response, Future<Result<(), ErrorCode>>]

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.

fn get_status_code(&self) -> StatusCode

Get the HTTP Status Code for the Response.

fn set_status_code(&self, status_code: StatusCode) -> Result<(), ()>

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

fn get_headers(&self) -> Headers

Get the headers associated with the Response.

The returned headers resource is immutable: set, append, and delete operations will fail with header-error.immutable.

fn consume_body(this: Response, res: Future<Result<(), ErrorCode>>) -> [Stream<u8>, Future<Result<Option<Trailers>, ErrorCode>>]

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.

Types

pub type FieldName = String

pub type FieldValue = List<u8>

pub type Headers = Fields

pub type Trailers = Fields

pub type StatusCode = u16

Structs

pub struct DnsErrorPayload

Defines the case payload type for DNS-error above:

rcode: Option<String>
info_code: Option<u16>

pub struct TlsAlertReceivedPayload

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

alert_id: Option<u8>
alert_message: Option<String>

pub struct FieldSizePayload

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

field_name: Option<String>
field_size: Option<u32>

Variants

pub variant Method

This type corresponds to HTTP standard Methods.

Get
Post
Put
Delete
Connect
Options
Trace
Patch
Other(String)

pub variant Scheme

This type corresponds to HTTP standard Related Schemes.

Http
Https
Other(String)

pub variant ErrorCode

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

DnsTimeout
DnsError(DnsErrorPayload)
DestinationNotFound
DestinationUnavailable
DestinationIpProhibited
DestinationIpUnroutable
ConnectionRefused
ConnectionTerminated
ConnectionTimeout
ConnectionReadTimeout
ConnectionWriteTimeout
ConnectionLimitReached
TlsProtocolError
TlsCertificateError
TlsAlertReceived(TlsAlertReceivedPayload)
HttpRequestDenied
HttpRequestLengthRequired
HttpRequestBodySize(Option<u64>)
HttpRequestMethodInvalid
HttpRequestUriInvalid
HttpRequestUriTooLong
HttpRequestHeaderSectionSize(Option<u32>)
HttpRequestHeaderSize(Option<FieldSizePayload>)
HttpRequestTrailerSectionSize(Option<u32>)
HttpRequestTrailerSize(FieldSizePayload)
HttpResponseIncomplete
HttpResponseHeaderSectionSize(Option<u32>)
HttpResponseHeaderSize(FieldSizePayload)
HttpResponseBodySize(Option<u64>)
HttpResponseTrailerSectionSize(Option<u32>)
HttpResponseTrailerSize(FieldSizePayload)
HttpResponseTransferCoding(Option<String>)
HttpResponseContentCoding(Option<String>)
HttpResponseTimeout
HttpUpgradeFailed
HttpProtocolError
LoopDetected
ConfigurationError
InternalError(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.

pub variant HeaderError

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

InvalidSyntax

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.

SizeExceeded

This error indicates that the operation would exceed an implementation-defined limit on field sizes. This may apply to an individual field-value, a single field-name plus all its values, or the total aggregate size of all fields.

Other(Option<String>)

This is a catch-all error for anything that doesn't fit cleanly into a more specific case. Implementations can use this to extend the error type without breaking existing code. 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.

pub variant RequestOptionsError

This type enumerates the different kinds of errors that may occur when setting fields of a request-options resource.

NotSupported

Indicates the specified field is not supported by this implementation.

Immutable

Indicates that the operation on the request-options was not permitted because it is immutable.

Other(Option<String>)

This is a catch-all error for anything that doesn't fit cleanly into a more specific case. Implementations can use this to extend the error type without breaking existing code. 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.

wasi:clocks

Effects

pub interface MonotonicClock

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.

fn now() -> Mark

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.

fn get_resolution() -> Duration

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

async fn wait_until(when: Mark) -> AsyncCall<()>

Wait until the specified mark has occurred.

async fn wait_for(how_long: Duration) -> AsyncCall<()>

Wait for the specified duration to elapse.

pub interface SystemClock

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.

fn now() -> Instant

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.

fn get_resolution() -> Duration

Query the resolution of the clock. Returns the smallest duration of time that the implementation permits distinguishing.

pub interface Timezone

fn iana_id() -> Option<String>

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.

fn utc_offset(when: Instant) -> Option<i64>

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.

fn to_debug_string() -> String

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.

Types

pub type Duration = u64

pub type Mark = u64

Structs

pub struct Instant

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

seconds: i64
nanoseconds: u32

wasi:random

Effects

pub interface InsecureSeed

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

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

fn get_insecure_seed() -> [u64, u64]

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.

pub interface Insecure

The insecure interface for insecure pseudo-random numbers.

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

fn get_insecure_random_bytes(max_len: u64) -> List<u8>

Return up to max-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.

Implementations MAY return fewer bytes than requested (a short read). Callers that require exactly max-len bytes MUST call this function in a loop until the desired number of bytes has been accumulated. Implementations MUST return at least 1 byte when max-len is greater than zero. When max-len is zero, implementations MUST return an empty list without trapping.

fn get_insecure_random_u64() -> u64

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.

pub interface Random

WASI Random is a random data API.

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

fn get_random_bytes(max_len: u64) -> List<u8>

Return up to max-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.

Implementations MAY return fewer bytes than requested (a short read). Callers that require exactly max-len bytes MUST call this function in a loop until the desired number of bytes has been accumulated. Implementations MUST return at least 1 byte when max-len is greater than zero. When max-len is zero, implementations MUST return an empty list without trapping.

This function must always return fresh data. Deterministic environments must omit this function, rather than implementing it with deterministic data.

fn get_random_u64() -> u64

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.

wasi:sockets

Effects

pub interface IpNameLookup

async fn resolve_addresses(name: String) -> AsyncCall<Result<List<IpAddress>, ErrorCode>>

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.

References:

Resources

pub resource TcpSocket

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, listening, connecting or connected)

WASI uses shared ownership semantics: the tcp-socket handle and all derived stream and future values reference a single underlying OS socket:

The OS socket is closed only after the last handle is dropped. This model has observable effects; for example, it affects when the local port binding is released.

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.

fn create(address_family: IpAddressFamily) -> Result<TcpSocket, ErrorCode>

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.

Typical errors

References

fn bind(&self, local_address: IpSocketAddress) -> Result<(), ErrorCode>

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

Implementors note

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

References

async fn connect(&self, remote_address: IpSocketAddress) -> AsyncCall<Result<(), ErrorCode>>

Connect to a remote endpoint.

On success, the socket is transitioned into the connected state and 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.

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

References

fn listen(&self) -> Result<Stream<TcpSocket>, ErrorCode>

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:

Typical errors

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:

In either case, the stream returned by this listen method remains operational.

WASI requires listen to perform an implicit bind if the socket has not already been bound. Not all platforms (notably Windows) exhibit this behavior out of the box. On platforms that require it, the WASI implementation can emulate this behavior by performing the bind itself if the guest hasn't already done so.

References

fn send(&self, data: Stream<u8>) -> Future<Result<(), ErrorCode>>

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

References

fn receive(&self) -> [Stream<u8>, Future<Result<(), ErrorCode>>]

Read data from peer.

Returns a stream of data sent by the peer. The implementation drops the stream once no more data is available. At that point, the returned future resolves to:

receive may be called only once per socket. Subsequent calls return a closed stream and a future resolved to err(invalid-state).

If the caller is not expecting to receive any more data from the peer, they should 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

References

fn get_local_address(&self) -> Result<IpSocketAddress, ErrorCode>

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

References

fn get_remote_address(&self) -> Result<IpSocketAddress, ErrorCode>

Get the remote address.

Typical errors

References

fn get_is_listening(&self) -> bool

Whether the socket is in the listening state.

Equivalent to the SO_ACCEPTCONN socket option.

fn get_address_family(&self) -> IpAddressFamily

Whether this is a IPv4 or IPv6 socket.

This is the value passed to the constructor.

Equivalent to the SO_DOMAIN socket option.

fn set_listen_backlog_size(&self, value: u64) -> Result<(), ErrorCode>

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

fn get_keep_alive_enabled(&self) -> Result<bool, ErrorCode>

Enables or disables keepalive.

The keepalive behavior can be adjusted using:

Equivalent to the SO_KEEPALIVE socket option.

fn set_keep_alive_enabled(&self, value: bool) -> Result<(), ErrorCode>
fn get_keep_alive_idle_time(&self) -> Result<Duration, ErrorCode>

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. All other values are accepted without error, but may be clamped or rounded. As a result, the value read back from this setting may differ from the value that was set.

Equivalent to the TCP_KEEPIDLE socket option. (TCP_KEEPALIVE on MacOS)

Typical errors

fn set_keep_alive_idle_time(&self, value: Duration) -> Result<(), ErrorCode>
fn get_keep_alive_interval(&self) -> Result<Duration, ErrorCode>

The time between keepalive packets.

If the provided value is 0, an invalid-argument error is returned. All other values are accepted without error, but may be clamped or rounded. As a result, the value read back from this setting may differ from the value that was set.

Equivalent to the TCP_KEEPINTVL socket option.

Typical errors

fn set_keep_alive_interval(&self, value: Duration) -> Result<(), ErrorCode>
fn get_keep_alive_count(&self) -> Result<u32, ErrorCode>

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. All other values are accepted without error, but may be clamped or rounded. As a result, the value read back from this setting may differ from the value that was set.

Equivalent to the TCP_KEEPCNT socket option.

Typical errors

fn set_keep_alive_count(&self, value: u32) -> Result<(), ErrorCode>
fn get_hop_limit(&self) -> Result<u8, ErrorCode>

Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options.

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

Typical errors

fn set_hop_limit(&self, value: u8) -> Result<(), ErrorCode>
fn get_receive_buffer_size(&self) -> Result<u64, ErrorCode>

Kernel buffer space reserved for sending/receiving on this socket. Implementations usually treat this as a cap the buffer can grow to, rather than allocating the full amount immediately.

If the provided value is 0, an invalid-argument error is returned. All other values are accepted without error, but may be clamped or rounded. As a result, the value read back from this setting may differ from the value that was set.

This is only a performance hint. The implementation may ignore it or tweak it based on real traffic patterns. Linux and macOS appear to behave differently depending on whether a buffer size was explicitly set. When set, they tend to honor it; when not set, they dynamically adjust the buffer size as the connection progresses. This is especially noticeable when comparing the values from before and after connection establishment.

Equivalent to the SO_RCVBUF and SO_SNDBUF socket options.

Typical errors

fn set_receive_buffer_size(&self, value: u64) -> Result<(), ErrorCode>
fn get_send_buffer_size(&self) -> Result<u64, ErrorCode>
fn set_send_buffer_size(&self, value: u64) -> Result<(), ErrorCode>

pub resource UdpSocket

A UDP socket handle.

fn create(address_family: IpAddressFamily) -> Result<UdpSocket, ErrorCode>

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:

fn bind(&self, local_address: IpSocketAddress) -> Result<(), ErrorCode>

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

References

fn connect(&self, remote_address: IpSocketAddress) -> Result<(), ErrorCode>

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:

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

Implementors note

If the socket is already connected, some platforms (e.g. Linux) require a disconnect before connecting to a different peer address.

References

fn disconnect(&self) -> Result<(), ErrorCode>

Dissociate this socket from its peer address.

After calling this method, send & receive are free to communicate with any remote address again.

The POSIX equivalent of this is calling connect with an AF_UNSPEC address.

Typical errors

References

async fn send(&self, data: List<u8>, remote_address: Option<IpSocketAddress>) -> AsyncCall<Result<(), ErrorCode>>

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.

If the socket has not been explicitly bound, it will be implicitly bound to a random free port.

Implementations may trap if the data length exceeds 64 KiB.

Typical errors

Implementors note

WASI requires send to perform an implicit bind if the socket has not been bound. Not all platforms (notably Windows) exhibit this behavior natively. On such platforms, the WASI implementation should emulate it by performing the bind if the guest has not already done so.

References

async fn receive(&self) -> AsyncCall<Result<[List<u8>, IpSocketAddress], ErrorCode>>

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

References

fn get_local_address(&self) -> Result<IpSocketAddress, ErrorCode>

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

References

fn get_remote_address(&self) -> Result<IpSocketAddress, ErrorCode>

Get the address the socket is currently "connected" to.

Typical errors

References

fn get_address_family(&self) -> IpAddressFamily

Whether this is a IPv4 or IPv6 socket.

This is the value passed to the constructor.

Equivalent to the SO_DOMAIN socket option.

fn get_unicast_hop_limit(&self) -> Result<u8, ErrorCode>

Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options.

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

Typical errors

fn set_unicast_hop_limit(&self, value: u8) -> Result<(), ErrorCode>
fn get_receive_buffer_size(&self) -> Result<u64, ErrorCode>

Kernel buffer space reserved for sending/receiving on this socket. Implementations usually treat this as a cap the buffer can grow to, rather than allocating the full amount immediately.

If the provided value is 0, an invalid-argument error is returned. All other values are accepted without error, but may be clamped or rounded. As a result, the value read back from this setting may differ from the value that was set.

Equivalent to the SO_RCVBUF and SO_SNDBUF socket options.

Typical errors

fn set_receive_buffer_size(&self, value: u64) -> Result<(), ErrorCode>
fn get_send_buffer_size(&self) -> Result<u64, ErrorCode>
fn set_send_buffer_size(&self, value: u64) -> Result<(), ErrorCode>

Types

pub type Ipv4Address = [u8, u8, u8, u8]

pub type Ipv6Address = [u16, u16, u16, u16, u16, u16, u16, u16]

Structs

pub struct Ipv4SocketAddress

port: u16

sin_port

address: Ipv4Address

sin_addr

pub struct Ipv6SocketAddress

port: u16

sin6_port

flow_info: u32

sin6_flowinfo

address: Ipv6Address

sin6_addr

scope_id: u32

sin6_scope_id

Variants

pub variant ErrorCode

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.

AccessDenied

Access denied.

POSIX equivalent: EACCES, EPERM

NotSupported

The operation is not supported.

POSIX equivalent: EOPNOTSUPP, ENOPROTOOPT, EPFNOSUPPORT, EPROTONOSUPPORT, ESOCKTNOSUPPORT

InvalidArgument

One of the arguments is invalid.

POSIX equivalent: EINVAL, EDESTADDRREQ, EAFNOSUPPORT

OutOfMemory

Not enough memory to complete the operation.

POSIX equivalent: ENOMEM, ENOBUFS

Timeout

The operation timed out before it could finish completely.

POSIX equivalent: ETIMEDOUT

InvalidState

The operation is not valid in the socket's current state.

AddressNotBindable

The local address is not available.

POSIX equivalent: EADDRNOTAVAIL

AddressInUse

A bind operation failed because the provided address is already in use or because there are no ephemeral ports available.

POSIX equivalent: EADDRINUSE

RemoteUnreachable

The remote address is not reachable.

POSIX equivalent: EHOSTUNREACH, EHOSTDOWN, ENETDOWN, ENETUNREACH, ENONET

ConnectionRefused

The connection was forcefully rejected.

POSIX equivalent: ECONNREFUSED

ConnectionBroken

A write failed because the connection was broken.

POSIX equivalent: EPIPE

ConnectionReset

The connection was reset.

POSIX equivalent: ECONNRESET

ConnectionAborted

The connection was aborted.

POSIX equivalent: ECONNABORTED

DatagramTooLarge

The size of a datagram sent to a UDP socket exceeded the maximum supported size.

POSIX equivalent: EMSGSIZE

Other(Option<String>)

A catch-all for errors not captured by the existing variants. Implementations can use this to extend the error type without breaking existing code.

pub variant IpAddress

Ipv4(Ipv4Address)
Ipv6(Ipv6Address)

pub variant IpSocketAddress

Ipv4(Ipv4SocketAddress)
Ipv6(Ipv6SocketAddress)

pub variant ErrorCode

Lookup error codes.

AccessDenied

Access denied.

POSIX equivalent: EACCES, EPERM

InvalidArgument

name is a syntactically invalid domain name or IP address.

POSIX equivalent: EINVAL

NameUnresolvable

Name does not exist or has no suitable associated IP addresses.

POSIX equivalent: EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY

TemporaryResolverFailure

A temporary failure in name resolution occurred.

POSIX equivalent: EAI_AGAIN

PermanentResolverFailure

A permanent failure in name resolution occurred.

POSIX equivalent: EAI_FAIL

Other(Option<String>)

A catch-all for errors not captured by the existing variants. Implementations can use this to extend the error type without breaking existing code.

Enums

pub enum IpAddressFamily

Ipv4

Similar to AF_INET in POSIX.

Ipv6

Similar to AF_INET6 in POSIX.

wasi:tls

Resources

pub resource Error

fn to_debug_string(&self) -> String

pub resource Connector

fn new() -> Connector
fn send(&self, cleartext: Stream<u8>) -> [Stream<u8>, Future<Result<(), Error>>]

Set up the encryption stream transform. This takes an unprotected cleartext application data stream and returns an encrypted data stream, ready to be sent out over the network. Closing the cleartext stream will cause a close_notify packet to be emitted on the returned output stream.

fn receive(&self, ciphertext: Stream<u8>) -> [Stream<u8>, Future<Result<(), Error>>]

Set up the decryption stream transform. This takes an encrypted data stream, as received via e.g. the network, and returns a decrypted application data stream.

async fn connect(this: Connector, server_name: String) -> AsyncCall<Result<(), Error>>

Perform the handshake. The send & receive streams must be set up before calling this method.