From 97ea9fabd2e523685ab899696421aee216ac3caa Mon Sep 17 00:00:00 2001 From: eric Date: Thu, 10 Sep 2026 11:56:24 +0800 Subject: [PATCH] feat(plugin-abi): declare the C ABI that a host and its plugins share Plugins are dynamic libraries, and the boundary between them and leaf has to be something both sides can name without agreeing on a compiler. This crate is that boundary and nothing else: dependency-free, no_std, every repr(C) type and constant in one place, with include/leaf_plugin_abi.h as the single C declaration for plugins that are not written in Rust. A plugin exports a descriptor naming its ABI version, its struct sizes, optional stream and datagram engines, and whether it embeds a language runtime. abi_major must match exactly; abi_minor is informational and never gates loading. Each struct freezes a REQUIRED_SIZE prefix for its major version, and peers validate against that rather than their own sizeof, so an old plugin runs on a newer host and the reverse. The contract is written next to the declarations, because the parts that matter are the ones a signature cannot state: what each object's lifetime is, that instances move between threads and calls never overlap, that no call may block -- the readiness callback is what makes that workable -- and that decode_packet reports how much input it consumed, which is the only way a codec can be driven over a transport with no message boundaries. A parity test compiles a C probe and compares sizeof, offsetof and every constant against the Rust definitions, so the two declarations cannot drift unnoticed. --- Cargo.toml | 1 + leaf-plugin-abi/Cargo.toml | 9 + leaf-plugin-abi/include/leaf_plugin_abi.h | 383 +++++++++++++ leaf-plugin-abi/src/lib.rs | 640 ++++++++++++++++++++++ leaf-plugin-abi/tests/descriptor_flags.rs | 72 +++ leaf-plugin-abi/tests/header_parity.rs | 319 +++++++++++ 6 files changed, 1424 insertions(+) create mode 100644 leaf-plugin-abi/Cargo.toml create mode 100644 leaf-plugin-abi/include/leaf_plugin_abi.h create mode 100644 leaf-plugin-abi/src/lib.rs create mode 100644 leaf-plugin-abi/tests/descriptor_flags.rs create mode 100644 leaf-plugin-abi/tests/header_parity.rs diff --git a/Cargo.toml b/Cargo.toml index fa6ace8..33473d0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,7 @@ [workspace] members = [ "leaf", + "leaf-plugin-abi", "leaf-cli", "leaf-ffi", "leaf-plugins/shadowsocks", diff --git a/leaf-plugin-abi/Cargo.toml b/leaf-plugin-abi/Cargo.toml new file mode 100644 index 0000000..46183df --- /dev/null +++ b/leaf-plugin-abi/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "leaf-plugin-abi" +version = "0.1.0" +edition = "2021" +description = "The C ABI shared between the leaf plugin host and out-of-tree plugins" + +[lib] +# Intentionally dependency-free: plugins must be able to depend on the ABI +# without pulling in the proxy engine. diff --git a/leaf-plugin-abi/include/leaf_plugin_abi.h b/leaf-plugin-abi/include/leaf_plugin_abi.h new file mode 100644 index 0000000..6ae7f41 --- /dev/null +++ b/leaf-plugin-abi/include/leaf_plugin_abi.h @@ -0,0 +1,383 @@ +/* + * The C ABI shared between the leaf plugin host and out-of-tree plugins. + * + * This header is the canonical C declaration of the ABI. The Rust mirror lives + * in leaf-plugin-abi/src/lib.rs and the two are checked against each other by + * leaf-plugin-abi/tests/header_parity.rs. Do not copy this file into a plugin + * tree; include it instead, e.g. from cgo: + * + * #cgo CFLAGS: -I${SRCDIR}/../../leaf-plugin-abi/include + * + * The full contract -- object lifetimes, threading and the ban on blocking -- + * is documented on the Rust mirror. In short: + * + * - The descriptor, the vtables it points to and its strings are static and + * live as long as the library is loaded. + * - EngineCreateArgs, and the HostCallbacks struct it points to, are valid + * only for the create_instance call; copy what you need. + * - The host_ctx and the log/wake function pointers copied out of + * HostCallbacks stay valid until destroy_instance returns, so no call to + * them may be in flight, or start, once it has. + * - Every other buffer is valid only for the call it was passed to, and + * output buffers belong to the host. + * - The host makes no two calls on one instance at once, but successive + * calls may come from different threads. log and wake are re-entrant and + * callable from any thread; the host never calls back into the plugin + * from them. + * - Engine calls run on the host's async executor: return promptly, never + * sleep, do I/O or wait on another thread. Use + * LEAF_STREAM_ENGINE_STATE_BLOCKED and wake instead. Only + * destroy_instance may block, and only briefly. + * - Never panic, abort or unwind across the boundary; return a status code. + */ + +#ifndef LEAF_PLUGIN_ABI_H +#define LEAF_PLUGIN_ABI_H + +#include +#include + +/* A host loads a plugin only when the major versions match exactly; every + * breaking change bumps LEAF_PLUGIN_ABI_MAJOR. Minor versions are additive and + * never participate in the compatibility decision -- a peer discovers which + * trailing fields exist from each struct's `size` field, not from this number. */ +#define LEAF_PLUGIN_ABI_MAJOR 2 +/* 1 added PluginDescriptor::flags. */ +#define LEAF_PLUGIN_ABI_MINOR 1 +/* Status codes. Every entry that returns leaf_engine_status_t returns OK or one + * of the negative values, with detail left for get_last_error. + * + * INVALID_ARGUMENT -- a side, address kind or similar the engine does not + * implement; the host treats it as fatal. + * BUFFER_TOO_SMALL -- the output buffer was too small. The engine must have + * consumed nothing, so the host can grow the buffer and + * retry the same input; it does so a bounded number of + * times before giving up on the engine. + * UNSUPPORTED -- not implemented at all; retrying cannot help. + * PLUGIN_FAILURE -- the engine failed for its own reasons. The host turns + * it into an I/O error and tears the connection down. */ +#define LEAF_ENGINE_STATUS_OK 0 +#define LEAF_ENGINE_STATUS_INVALID_ARGUMENT -1 +#define LEAF_ENGINE_STATUS_BUFFER_TOO_SMALL -2 +#define LEAF_ENGINE_STATUS_UNSUPPORTED -3 +#define LEAF_ENGINE_STATUS_PLUGIN_FAILURE -4 +/* Levels for leaf_host_log_fn. They mirror the host's own levels, so a message + * logged above the level the host is configured for is dropped. */ +#define LEAF_LOG_LEVEL_ERROR 1 +#define LEAF_LOG_LEVEL_WARN 2 +#define LEAF_LOG_LEVEL_INFO 3 +#define LEAF_LOG_LEVEL_DEBUG 4 +#define LEAF_LOG_LEVEL_TRACE 5 +/* How to read PluginAddress.data: the four octets of an IPv4 address, the + * sixteen octets of an IPv6 address, or a domain name as UTF-8 without a + * trailing NUL, which the host rejects if empty. PluginAddress.port is a plain + * uint16_t in host byte order for all three. */ +#define LEAF_ADDRESS_KIND_IPV4 1 +#define LEAF_ADDRESS_KIND_IPV6 2 +#define LEAF_ADDRESS_KIND_DOMAIN 3 +/* Which direction a datagram size hint is about, or is being performed: + * ENCODE is encode_packet, DECODE is decode_packet. */ +#define LEAF_DATAGRAM_DIRECTION_ENCODE 1 +#define LEAF_DATAGRAM_DIRECTION_DECODE 2 +/* What the host carries a datagram engine's frames over. RELIABLE puts it on + * top of the stream transport the chain already established, and the engine + * frames each datagram itself -- which is why decode_packet has `consumed`. + * UNRELIABLE gets one whole frame per call in each direction. Either way the + * outbound's host/port settings are required. */ +#define LEAF_DATAGRAM_TRANSPORT_TYPE_RELIABLE 1 +#define LEAF_DATAGRAM_TRANSPORT_TYPE_UNRELIABLE 2 +/* What stream the host hands a stream engine. PROXY_TCP is a TCP connection to + * the host/port in the outbound's settings, which must be configured; DIRECT is + * a connection straight to the session's destination; NEXT is whatever the + * previous outbound in the chain produced, as a TLS engine wants. DIRECT and + * NEXT require that no host/port be configured. */ +#define LEAF_STREAM_CONNECT_TYPE_PROXY_TCP 1 +#define LEAF_STREAM_CONNECT_TYPE_DIRECT 2 +#define LEAF_STREAM_CONNECT_TYPE_NEXT 3 +/* The two sides of a stream engine: APP is the plaintext the proxy carries, NET + * is the encoded bytes on the socket. */ +#define LEAF_STREAM_SIDE_APP 1 +#define LEAF_STREAM_SIDE_NET 2 +/* State flags reported by poll_state. + * + * WANT_APP_INPUT -- room for more application input. Advisory; a short + * `consumed` from push is the authoritative signal. + * WANT_NET_INPUT -- waiting on bytes from the peer. This, not BLOCKED, is + * what an engine reports while it waits for the other end. + * HAS_APP_OUTPUT -- decoded bytes are ready to pull for the application. A + * pull that then produces nothing is believed over the + * flag. + * HAS_NET_OUTPUT -- bytes are ready to pull for the socket. Set it during a + * handshake too: the host keeps this side moving even + * while the application is only reading. + * HANDSHAKING -- informational; the handshake is not finished. + * ESTABLISHED -- informational; application data is flowing. + * PEER_CLOSED -- the peer closed. Once the engine has no application + * output left, the host reports end of stream. + * FATAL -- the engine is unusable and the host fails the + * connection, whatever the call that reported it + * returned. */ +#define LEAF_STREAM_ENGINE_STATE_WANT_APP_INPUT (1U << 0) +#define LEAF_STREAM_ENGINE_STATE_WANT_NET_INPUT (1U << 1) +#define LEAF_STREAM_ENGINE_STATE_HAS_APP_OUTPUT (1U << 2) +#define LEAF_STREAM_ENGINE_STATE_HAS_NET_OUTPUT (1U << 3) +#define LEAF_STREAM_ENGINE_STATE_HANDSHAKING (1U << 4) +#define LEAF_STREAM_ENGINE_STATE_ESTABLISHED (1U << 5) +#define LEAF_STREAM_ENGINE_STATE_PEER_CLOSED (1U << 6) +#define LEAF_STREAM_ENGINE_STATE_FATAL (1U << 7) +/* The engine cannot make progress from anything the host can hand it right now + * and will call leaf_host_wake_fn once that changes. An engine merely waiting + * for the peer reports LEAF_STREAM_ENGINE_STATE_WANT_NET_INPUT instead. */ +#define LEAF_STREAM_ENGINE_STATE_BLOCKED (1U << 8) +/* Passed to close: APP means the application has finished writing, so the + * engine should emit whatever its protocol uses to say so; NET means the socket + * reached end of file and nothing more will arrive from the peer. */ +#define LEAF_STREAM_ENGINE_CLOSE_APP (1U << 0) +#define LEAF_STREAM_ENGINE_CLOSE_NET (1U << 1) + +#if defined(_WIN32) +#define LEAF_PLUGIN_EXPORT __declspec(dllexport) +#else +#define LEAF_PLUGIN_EXPORT +#endif + +typedef int32_t leaf_engine_status_t; +typedef uint32_t leaf_log_level_t; +typedef uint16_t leaf_address_kind_t; +typedef uint32_t leaf_datagram_direction_t; +typedef uint32_t leaf_datagram_transport_type_t; +typedef uint32_t leaf_stream_connect_type_t; +typedef uint32_t leaf_stream_side_t; +typedef uint32_t leaf_stream_state_flags_t; +typedef uint32_t leaf_stream_close_flags_t; +/* The get_last_error entry of both vtables writes the engine's own status code + * through `code` and a UTF-8 message, without a trailing NUL, into `output`. + * The host asks twice: once with a NULL `output` and an `output_cap` of 0, to + * learn the length from `written`, and again with a buffer that size -- so the + * message must survive being read twice. `instance` is NULL when + * create_instance returned NULL and there is no instance to ask, so an engine + * that wants to explain a failed creation must keep that message somewhere + * reachable without one. A non-zero return means the engine has nothing to say + * and the host falls back to the status code of the call that failed. */ + +typedef void (*leaf_host_log_fn)( + void* host_ctx, + leaf_log_level_t level, + const char* target, + const uint8_t* message, + size_t message_len); +/* Called by an engine that reported LEAF_STREAM_ENGINE_STATE_BLOCKED once it + * can make progress again. Callable from any thread at any time between + * create_instance being entered and destroy_instance returning, including from + * inside another engine call. The host never calls back into the plugin from + * it, and a call made while the host is not waiting is harmless. */ +typedef void (*leaf_host_wake_fn)(void* host_ctx); + +typedef struct { + size_t size; + /* The host loads the plugin only if abi_major matches its own exactly; + * abi_minor is informational. */ + uint32_t abi_major; + uint32_t abi_minor; + /* Name and version, for logs and diagnostics. */ + const char* name; + const char* version; + /* Either vtable may be NULL -- a UDP-only protocol has no stream engine to + * export -- but a plugin that exports neither is rejected. One that exports + * both makes an outbound carrying TCP through the stream engine and UDP + * through the datagram one; one that exports a single engine makes an + * outbound that only handles that kind of traffic. */ + const struct StreamEnginePlugin* stream; + const struct DatagramEnginePlugin* datagram; + /* Properties of the plugin as a library rather than of either engine; see + * LEAF_PLUGIN_FLAG_* below. Added in minor 1: a plugin built against minor + * 0 does not provide this field and the host reads it back as zero, which + * is what a plugin with nothing to declare would have written anyway. Bits + * the host does not know are ignored. */ + uint64_t flags; +} PluginDescriptor; + +/* This plugin embeds a language runtime and must never be unmapped. A Go + * c-shared build is the standard case: the threads such a runtime starts are + * not something the host can hold a reference to, and they go on running code + * in the library after everything the host does hold has gone. A host that + * honours this keeps the library mapped for the life of the process. */ +#define LEAF_PLUGIN_FLAG_EMBEDS_RUNTIME ((uint64_t)1 << 0) + +typedef struct { + size_t size; + leaf_host_log_fn log; + /* May be NULL, in which case an engine must not report + * LEAF_STREAM_ENGINE_STATE_BLOCKED: there would be no way to un-block it. */ + leaf_host_wake_fn wake; + void* host_ctx; +} HostCallbacks; + +typedef struct { + /* One of LEAF_ADDRESS_KIND_*, which says how to read `data`. `port` is in + * host byte order. */ + leaf_address_kind_t kind; + uint16_t port; + const uint8_t* data; + size_t data_len; +} PluginAddress; + +typedef struct EngineCreateArgs { + size_t size; + /* The outbound's `args` setting, verbatim and NUL-terminated. Its shape is + * the plugin's own business -- the host never looks inside. */ + const char* plugin_args; + /* Where the session is ultimately headed, which is what a protocol engine + * encodes into its header. Not the server the host connected to. */ + const PluginAddress* destination; + /* Never NULL, and borrowed only for this call. */ + const HostCallbacks* host_callbacks; + /* The host's own ABI version, so a plugin built against a newer minor + * version can tell what the host will actually understand. */ + uint32_t host_abi_major; + uint32_t host_abi_minor; +} EngineCreateArgs; + +/* A stream engine instance is a byte-stream codec with two sides, APP and NET. + * The host owns all the I/O and drives the instance in a loop: read poll_state, + * push what it asks for, pull what it offers, repeat. The engine never touches + * a socket and never blocks. Every entry below is required -- the host refuses + * to load a plugin that leaves one NULL. */ +typedef struct StreamEnginePlugin { + size_t size; + /* One of LEAF_STREAM_CONNECT_TYPE_*, read once at load time, so it is a + * property of the plugin rather than of an instance. */ + leaf_stream_connect_type_t connect_type; + /* Returns NULL on failure, leaving the reason for get_last_error, which the + * host then calls with a NULL instance. */ + void* (*create_instance)(const EngineCreateArgs* args); + /* Must not return until no log or wake call the plugin makes can still be + * in flight. The one entry that may block, and only briefly. */ + void (*destroy_instance)(void* instance); + /* Reports what the engine wants next as a bitmask of + * LEAF_STREAM_ENGINE_STATE_*. Called between every other operation, so it + * must be cheap and must not itself advance the protocol. */ + leaf_engine_status_t (*poll_state)( + void* instance, + leaf_stream_state_flags_t* state_flags); + /* Takes input for one side and reports how much through `consumed`. A short + * or zero `consumed` is backpressure, not failure: the host keeps the rest + * and offers it again. `consumed` must never exceed input_len. */ + leaf_engine_status_t (*push)( + void* instance, + leaf_stream_side_t side, + const uint8_t* input, + size_t input_len, + size_t* consumed); + /* Writes output for one side and reports how much through `produced`. Zero + * means nothing more is available right now, even if poll_state advertised + * output; filling the buffer invites the host to call again. `produced` + * must never exceed output_cap. */ + leaf_engine_status_t (*pull)( + void* instance, + leaf_stream_side_t side, + uint8_t* output, + size_t output_cap, + size_t* produced); + /* Tells the engine one or both sides are finished, as a bitmask of + * LEAF_STREAM_ENGINE_CLOSE_*. The engine may still have output afterwards, + * such as a close notify record, and the host still drains it. */ + leaf_engine_status_t (*close)(void* instance, leaf_stream_close_flags_t close_flags); + leaf_engine_status_t (*get_last_error)( + void* instance, + leaf_engine_status_t* code, + uint8_t* output, + size_t output_cap, + size_t* written); + /* How big a buffer the engine wants for a pull on this side, and how many + * pulls of that size the host should make in a row before going back to the + * socket. Both are advisory and clamped by the host, so a wild hint costs + * efficiency rather than memory. */ + size_t (*suggest_output_size)(void* instance, leaf_stream_side_t side); + size_t (*suggest_output_batch)(void* instance, leaf_stream_side_t side); +} StreamEnginePlugin; + +/* A datagram engine instance is a packet codec: one datagram and its address in, + * wire bytes out, and back. As with the stream vtable the host owns the + * transport, and every entry below is required for the plugin to load. */ +typedef struct DatagramEnginePlugin { + size_t size; + /* One of LEAF_DATAGRAM_TRANSPORT_TYPE_*, read once at load time. */ + leaf_datagram_transport_type_t transport_type; + /* Both behave as their stream vtable counterparts do. */ + void* (*create_instance)(const EngineCreateArgs* args); + void (*destroy_instance)(void* instance); + /* Encodes one datagram for `target`, reporting the length through + * `produced`, which must never exceed output_cap. Returning + * LEAF_ENGINE_STATUS_BUFFER_TOO_SMALL makes the host grow the buffer and + * retry the same datagram, so a conservative max_output_size costs an extra + * call rather than the packet. */ + leaf_engine_status_t (*encode_packet)( + void* instance, + const uint8_t* payload, + size_t payload_len, + const PluginAddress* target, + uint8_t* output, + size_t output_cap, + size_t* produced); + /* Decodes at most one datagram out of `input`. + * + * Reliable transports carry framed datagrams over a byte stream, so a + * single read can hand the engine a partial frame or several frames at + * once. `consumed` is how the engine reports which of those happened: + * + * consumed == 0 && payload_len == 0 -- incomplete frame; the host reads + * more bytes and calls again with the frame still at the front. + * consumed > 0 && payload_len == 0 -- a frame carrying no datagram, such + * as a keepalive, was consumed; the host drops it and calls again. + * consumed > 0 && payload_len > 0 -- one datagram was decoded. + * + * `consumed` must never exceed `input_len`. On + * LEAF_ENGINE_STATUS_BUFFER_TOO_SMALL the engine must consume nothing, so + * the host can retry the same input with a larger output buffer. + * + * Unreliable transports get one whole frame per call and consume all of + * it. */ + leaf_engine_status_t (*decode_packet)( + void* instance, + const uint8_t* input, + size_t input_len, + size_t* consumed, + uint8_t* payload_out, + size_t payload_cap, + size_t* payload_len, + PluginAddress* address_out); + /* The buffer size the engine wants for an input of input_len bytes in that + * direction, and the largest address it can write into the PluginAddress + * buffer the host supplies to decode_packet. Both advisory and clamped; the + * host grows the output buffer anyway on + * LEAF_ENGINE_STATUS_BUFFER_TOO_SMALL. */ + size_t (*max_output_size)(void* instance, size_t input_len, leaf_datagram_direction_t direction); + size_t (*max_address_size)(void* instance, leaf_datagram_direction_t direction); + leaf_engine_status_t (*get_last_error)( + void* instance, + leaf_engine_status_t* code, + uint8_t* output, + size_t output_cap, + size_t* written); +} DatagramEnginePlugin; + +/* The prefix every conforming peer must provide, frozen for the lifetime of + * LEAF_PLUGIN_ABI_MAJOR. Appending a field must not change these. */ +#define LEAF_REQUIRED_SIZE(type, last_field) \ + (offsetof(type, last_field) + sizeof(((type*)0)->last_field)) + +#define LEAF_PLUGIN_DESCRIPTOR_REQUIRED_SIZE \ + LEAF_REQUIRED_SIZE(PluginDescriptor, datagram) +#define LEAF_HOST_CALLBACKS_REQUIRED_SIZE \ + LEAF_REQUIRED_SIZE(HostCallbacks, host_ctx) +#define LEAF_ENGINE_CREATE_ARGS_REQUIRED_SIZE \ + LEAF_REQUIRED_SIZE(EngineCreateArgs, host_abi_minor) +#define LEAF_STREAM_ENGINE_PLUGIN_REQUIRED_SIZE \ + LEAF_REQUIRED_SIZE(StreamEnginePlugin, suggest_output_batch) +#define LEAF_DATAGRAM_ENGINE_PLUGIN_REQUIRED_SIZE \ + LEAF_REQUIRED_SIZE(DatagramEnginePlugin, get_last_error) + +LEAF_PLUGIN_EXPORT const PluginDescriptor* leaf_plugin_get_descriptor(void); + +#endif /* LEAF_PLUGIN_ABI_H */ diff --git a/leaf-plugin-abi/src/lib.rs b/leaf-plugin-abi/src/lib.rs new file mode 100644 index 0000000..4e5ef9f --- /dev/null +++ b/leaf-plugin-abi/src/lib.rs @@ -0,0 +1,640 @@ +//! The C ABI shared between the leaf plugin host and out-of-tree plugins. +//! +//! This crate is intentionally free of dependencies and of `std`, so that a +//! plugin can depend on the ABI without linking a second copy of the proxy +//! engine into the process. The canonical C declaration of everything defined +//! here lives in `include/leaf_plugin_abi.h`; the two are kept in sync by +//! `tests/header_parity.rs`. +//! +//! # Object lifetimes +//! +//! | Object | Valid for | +//! | --- | --- | +//! | [`PluginDescriptor`], the vtables it points to, and its `name` / `version` strings | from library load until unload; static and immutable | +//! | [`EngineCreateArgs`] and its `plugin_args`, `destination` and the [`HostCallbacks`] **struct** | the `create_instance` call only -- a plugin must copy anything it needs | +//! | `host_ctx` and the `log` / `wake` **function pointers** copied out of [`HostCallbacks`] | from `create_instance` being entered until `destroy_instance` returns; `host_ctx` is opaque and must never be dereferenced | +//! | input buffers passed to `push`, `encode_packet`, `decode_packet` | that call only | +//! | output buffers passed to `pull`, `encode_packet`, `decode_packet`, `get_last_error` | that call only; owned by the host | +//! | the [`PluginAddress`] `decode_packet` fills in | that call only; the host supplies `data`, the engine writes into it and sets `data_len`, and must not replace the pointer | +//! +//! Because the callbacks stay valid until `destroy_instance` **returns**, a +//! plugin that calls them from its own threads has to make sure none is in +//! flight, and none can start, by the time it returns from `destroy_instance`. +//! +//! # Threading +//! +//! * The host never makes two calls on the same instance at the same time, but +//! successive calls may come from different threads, so an instance must not +//! be tied to one. +//! * `destroy_instance` never overlaps another call on that instance. +//! * Instances are independent of each other, and +//! `leaf_plugin_get_descriptor` must be pure and safe to call concurrently. +//! * `log` and `wake` are re-entrant and callable from any thread, including +//! from inside another engine call. The host never calls back into the +//! plugin from either. +//! +//! # Blocking +//! +//! Engine calls run on the host's async executor threads, so they must return +//! promptly: no sleeping, no I/O, no waiting on another thread. Work that +//! cannot be finished immediately is what +//! [`STREAM_ENGINE_STATE_BLOCKED`] and the `wake` callback are for. +//! +//! `destroy_instance` is the one exception; it may block briefly to join the +//! plugin's own threads, as the lifetime rules above require. +//! +//! A plugin must not panic, abort or unwind across the boundary. Failures are +//! reported as a status code, with detail available from `get_last_error`. The +//! host runs its own callbacks behind a panic barrier, but that only covers the +//! host's frames: an unwind out of an engine call still has nowhere to go. +//! +//! # What the host validates +//! +//! The host defends against a plugin that is wrong, not one that is hostile: a +//! plugin runs in the host process with the host's privileges, and nothing here +//! changes that. What it does reject, rather than trust, is a `consumed` larger +//! than the input, a `produced` larger than the output buffer, an address +//! longer than the buffer it was given, a swapped-out address pointer, and an +//! address that could not be put back on the wire. Every size an engine +//! reports -- including the length `get_last_error` asks for and the length +//! passed to `log` -- is clamped before the host acts on it, and text an engine +//! supplies has its control characters escaped before it reaches a log. +//! +//! Nor does the host scan a NUL-terminated string an engine hands it any +//! further than its own cap: a `log` target that never terminates costs a +//! truncated target, and the descriptor's `name` and `version` must terminate +//! within 256 bytes or the plugin is refused. Truncation happens on the bytes, +//! not on characters, so a multi-byte character straddling the cut is replaced +//! rather than fatal. +//! +//! `host_ctx` is a handle the host looks up, not a pointer into its memory, so +//! an engine that calls `log` or `wake` after `destroy_instance` has returned +//! -- a contract violation, but a plausible one for a plugin with threads of +//! its own -- loses the call instead of corrupting the host. Do not rely on it: +//! the wakeup is gone either way. +//! +//! What remains on trust, because the host cannot check it: the truthfulness of +//! each struct's `size` field, that the structs are suitably aligned, that the +//! vtable entries are real functions, and that an engine writes no more than +//! the `produced` and `consumed` it goes on to report. +//! +//! Before any of that, the host has to be willing to open the file at all: a +//! bare library name is refused rather than looked up along the loader's search +//! path, as is a library anyone on the machine can rewrite, and an outbound may +//! pin the sha256 the file has to have. +//! +//! # A note on runtimes with their own threads +//! +//! A plugin that embeds a language runtime, such as a Go `c-shared` build, +//! makes a host thread that calls into it unable to exit cleanly while the +//! plugin is loaded: the runtime's thread-exit hook does not return. Long-lived +//! executor threads satisfy this in practice; short-lived ones do not. +//! +//! Such a plugin must also set [`PLUGIN_FLAG_EMBEDS_RUNTIME`], because the +//! host would otherwise unmap it. Everything the host holds a plugin library +//! for -- a handler, a live stream, a datagram session -- it can count; the +//! threads a runtime starts for itself it cannot, and they keep running code +//! in the library after the last thing the host counted has gone. Unmapping +//! then takes the code out from under them. The flag is the plugin saying that +//! it cannot be unmapped, and the host answers by keeping it mapped for the +//! life of the process. +//! +//! Two such plugins in one process is two runtimes in one process, which the +//! runtimes' own projects generally decline to guarantee -- Go's, the one this +//! repository ships plugins for, treats it as a configuration it does not +//! support rather than one it has broken. In practice each runtime keeps to +//! itself: on Windows a fault is claimed by whichever runtime's module the +//! faulting instruction is in, and on the platforms where signal handlers are +//! process-wide the same question is settled by forwarding. The host therefore +//! allows it, warns once when a process ends up holding more than one, and +//! tests it under fault rather than assuming either way. + +#![no_std] + +use core::ffi::{c_char, c_void}; +use core::mem::{size_of, MaybeUninit}; + +/// The symbol every plugin must export, as a NUL-terminated name suitable for +/// `dlsym`/`GetProcAddress`. +pub const PLUGIN_DESCRIPTOR_SYMBOL: &[u8] = b"leaf_plugin_get_descriptor\0"; + +/// The major ABI version implemented by this crate. +/// +/// A host loads a plugin only when the major versions match exactly. Every +/// breaking change bumps it. +pub const PLUGIN_ABI_MAJOR: u32 = 2; + +/// The minor ABI version implemented by this crate. +/// +/// Minor versions are additive within a major version and never participate in +/// the compatibility decision: a peer discovers which trailing fields actually +/// exist from the `size` field of each struct, not from this number, which is +/// informational only. Appending a field bumps it. +/// +/// 1 added [`PluginDescriptor::flags`]. +pub const PLUGIN_ABI_MINOR: u32 = 1; + +/// [`PluginDescriptor::flags`]: this plugin embeds a language runtime and must +/// never be unmapped. +/// +/// A Go `c-shared` build is the standard case. See the note on runtimes with +/// their own threads above for why the host cannot work this out for itself, +/// and what it does about it. +pub const PLUGIN_FLAG_EMBEDS_RUNTIME: u64 = 1 << 0; + +/// The call succeeded. Every vtable entry that returns a status returns this or +/// one of the negative values below, with detail left for `get_last_error`. +pub const ENGINE_STATUS_OK: i32 = 0; +/// The call carried something the engine cannot accept, such as a `side` or an +/// address kind it does not implement. The host treats it as fatal. +pub const ENGINE_STATUS_INVALID_ARGUMENT: i32 = -1; +/// The output buffer was too small for what the call had to produce. The engine +/// must have consumed nothing, so that the host can retry the same input with a +/// larger buffer; it grows the buffer a bounded number of times before giving +/// up on the engine. +pub const ENGINE_STATUS_BUFFER_TOO_SMALL: i32 = -2; +/// The engine does not implement this operation at all, so retrying cannot +/// help. +pub const ENGINE_STATUS_UNSUPPORTED: i32 = -3; +/// The engine failed for a reason of its own. The host turns it into an I/O +/// error and tears the connection down. +pub const ENGINE_STATUS_PLUGIN_FAILURE: i32 = -4; + +/// Levels accepted by [`PluginHostLogFn`]. They mirror the host's own levels, +/// so a message logged above the level the host is configured for is dropped. +pub const LOG_LEVEL_ERROR: u32 = 1; +/// See [`LOG_LEVEL_ERROR`]. +pub const LOG_LEVEL_WARN: u32 = 2; +/// See [`LOG_LEVEL_ERROR`]. +pub const LOG_LEVEL_INFO: u32 = 3; +/// See [`LOG_LEVEL_ERROR`]. +pub const LOG_LEVEL_DEBUG: u32 = 4; +/// See [`LOG_LEVEL_ERROR`]. +pub const LOG_LEVEL_TRACE: u32 = 5; + +/// [`PluginAddress::data`] holds the four octets of an IPv4 address, in network +/// order. `port` is a plain `u16` in host order, as it is for every kind. +pub const ADDRESS_KIND_IPV4: u16 = 1; +/// [`PluginAddress::data`] holds the sixteen octets of an IPv6 address, in +/// network order. +pub const ADDRESS_KIND_IPV6: u16 = 2; +/// [`PluginAddress::data`] holds a domain name as UTF-8, without a trailing +/// NUL. The host rejects an empty one, and one longer than 255 bytes: that is +/// all the length byte in the wire formats it re-encodes the address into has +/// room for. +pub const ADDRESS_KIND_DOMAIN: u16 = 3; + +/// The host is asking about, or performing, the outbound direction: +/// `encode_packet`, turning one of the application's datagrams into wire bytes. +pub const DATAGRAM_DIRECTION_ENCODE: u32 = 1; +/// The host is asking about, or performing, the inbound direction: +/// `decode_packet`, turning wire bytes back into a datagram. +pub const DATAGRAM_DIRECTION_DECODE: u32 = 2; + +/// The engine's datagrams ride a byte stream, so the host puts the datagram +/// engine on top of the stream transport the chain already established and the +/// engine frames each datagram itself. One read can carry a partial frame or +/// several, which is what `decode_packet`'s `consumed` exists for. +pub const DATAGRAM_TRANSPORT_TYPE_RELIABLE: u32 = 1; +/// The engine's datagrams ride a datagram transport, one whole frame per call +/// in each direction. +/// +/// Either transport type makes the outbound's `host`/`port` settings required: +/// a datagram engine always talks to a configured server. +pub const DATAGRAM_TRANSPORT_TYPE_UNRELIABLE: u32 = 2; + +/// The engine speaks a proxy protocol, so the host connects a TCP socket to the +/// `host`/`port` in the outbound's settings and hands the engine that stream. +/// Both must be configured. +pub const STREAM_CONNECT_TYPE_PROXY_TCP: u32 = 1; +/// The host connects straight to the session's destination and hands the engine +/// that stream. The outbound's settings must not carry a `host`/`port`. +pub const STREAM_CONNECT_TYPE_DIRECT: u32 = 2; +/// The engine is a transport layered on whatever the previous outbound in the +/// chain produced, as TLS is; the host hands it that stream. The outbound's +/// settings must not carry a `host`/`port`. +pub const STREAM_CONNECT_TYPE_NEXT: u32 = 3; + +/// The application side of a stream engine: plaintext going to and coming from +/// whatever the proxy is carrying. +pub const STREAM_SIDE_APP: u32 = 1; +/// The network side of a stream engine: encoded bytes going to and coming from +/// the socket. +pub const STREAM_SIDE_NET: u32 = 2; + +/// The engine can take more application input; the host may `push` with +/// [`STREAM_SIDE_APP`]. Advisory -- `push` reporting a short `consumed` is the +/// authoritative signal. +pub const STREAM_ENGINE_STATE_WANT_APP_INPUT: u32 = 1 << 0; +/// The engine is waiting on bytes from the peer; the host reads the socket and +/// pushes with [`STREAM_SIDE_NET`]. This, not +/// [`STREAM_ENGINE_STATE_BLOCKED`], is what an engine reports while it waits +/// for the other end. +pub const STREAM_ENGINE_STATE_WANT_NET_INPUT: u32 = 1 << 1; +/// The engine has decoded bytes for the application; the host `pull`s with +/// [`STREAM_SIDE_APP`]. A `pull` that then produces nothing is believed over +/// the flag, so an engine that leaves it set with nothing to give only costs a +/// wasted call. +pub const STREAM_ENGINE_STATE_HAS_APP_OUTPUT: u32 = 1 << 2; +/// The engine has bytes for the socket; the host `pull`s with +/// [`STREAM_SIDE_NET`] and writes them. Set it during a handshake too: the host +/// keeps this side moving even while the application is only reading. +pub const STREAM_ENGINE_STATE_HAS_NET_OUTPUT: u32 = 1 << 3; +/// The engine has not finished its handshake. Informational; the host drives it +/// from the other flags either way. +pub const STREAM_ENGINE_STATE_HANDSHAKING: u32 = 1 << 4; +/// The handshake is done and the engine is carrying application data. +/// Informational. +pub const STREAM_ENGINE_STATE_ESTABLISHED: u32 = 1 << 5; +/// The peer closed its side. Once the engine has no application output left, +/// the host reports end of stream to the application. +pub const STREAM_ENGINE_STATE_PEER_CLOSED: u32 = 1 << 6; +/// The engine is unusable. The host fails the connection as soon as it sees +/// this, whatever the call that reported it returned. +pub const STREAM_ENGINE_STATE_FATAL: u32 = 1 << 7; +/// The engine cannot make progress from anything the host can hand it right +/// now, and will call [`PluginHostWakeFn`] once that changes. +/// +/// This is what an engine reports when it is waiting on work of its own rather +/// than on the peer: more input would not help, so the host stops polling and +/// waits to be woken. An engine that is merely waiting for the peer reports +/// [`STREAM_ENGINE_STATE_WANT_NET_INPUT`] instead. +pub const STREAM_ENGINE_STATE_BLOCKED: u32 = 1 << 8; + +/// Passed to `close`: the application has finished writing, so the engine +/// should emit whatever its protocol uses to say so. +pub const STREAM_ENGINE_CLOSE_APP: u32 = 1 << 0; +/// Passed to `close`: the socket reached end of file, so nothing more will +/// arrive from the peer. +pub const STREAM_ENGINE_CLOSE_NET: u32 = 1 << 1; + +/// `leaf_plugin_get_descriptor`. +pub type PluginDescriptorFn = unsafe extern "C" fn() -> *const PluginDescriptor; + +/// The `get_last_error` entry shared by both engine vtables. +/// +/// Signature: `(instance, code_out, output, output_cap, written_out)`. The +/// engine writes its own status code through `code_out` and a UTF-8 message, +/// without a trailing NUL, into `output`. +/// +/// The host asks twice: once with a null `output` and `output_cap` of zero, to +/// learn the length from `written_out`, and again with a buffer that size. So +/// `written_out` is the length the message needs when the buffer is too small, +/// and the length actually written otherwise, and the message must survive +/// being read twice. +/// +/// `instance` is null when `create_instance` returned null and there is no +/// instance to ask, so an engine that wants to report why a creation failed has +/// to keep that message somewhere reachable without one, such as a thread-local. +/// A non-zero return means the engine has nothing to say, and the host falls +/// back to the status code of the call that failed. +pub type PluginLastErrorFn = + unsafe extern "C" fn(*mut c_void, *mut i32, *mut u8, usize, *mut usize) -> i32; + +/// The host-provided logging callback. +pub type PluginHostLogFn = unsafe extern "C" fn(*mut c_void, u32, *const c_char, *const u8, usize); + +/// The host-provided readiness callback. +/// +/// An engine that reports [`STREAM_ENGINE_STATE_BLOCKED`] calls this once it +/// can make progress again. It may be called from any thread and at any time +/// between `create_instance` being entered and `destroy_instance` returning, +/// including from inside another engine call. The host never calls back into +/// the plugin from it, and a call made while the host is not waiting is +/// harmless. A call made after `destroy_instance` has returned is still a +/// contract violation, but the host drops it rather than acting on it. +pub type PluginHostWakeFn = unsafe extern "C" fn(*mut c_void); + +/// The root object returned by `leaf_plugin_get_descriptor`. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct PluginDescriptor { + /// `sizeof` this struct as the plugin built it. See [`AbiStruct`] for what + /// the host does with it. + pub size: usize, + /// [`PLUGIN_ABI_MAJOR`] the plugin was built against. The host loads the + /// plugin only if it matches its own exactly. + pub abi_major: u32, + /// [`PLUGIN_ABI_MINOR`] the plugin was built against. Informational. + pub abi_minor: u32, + /// The plugin's name, for logs and diagnostics. NUL-terminated, static. + pub name: *const c_char, + /// The plugin's own version, for logs and diagnostics. NUL-terminated, + /// static. + pub version: *const c_char, + /// The stream vtable, or null if the plugin has no stream engine -- a + /// UDP-only protocol has nothing to put here. + pub stream: *const StreamEnginePlugin, + /// The datagram vtable, or null if the plugin has no datagram engine. + /// + /// A plugin that exports neither is rejected. One that exports both is + /// registered for both, and the outbound then carries TCP through the + /// stream engine and UDP through this one; one that exports a single engine + /// makes an outbound that only handles that kind of traffic. + pub datagram: *const DatagramEnginePlugin, + /// Properties of the plugin as a library, rather than of either engine. + /// + /// Currently only [`PLUGIN_FLAG_EMBEDS_RUNTIME`]. A plugin built against an + /// older minor version does not provide this field at all and it reads back + /// as zero, which is what a plugin with nothing to declare would have + /// written anyway. The host ignores bits it does not know, so a plugin may + /// set a flag from a later minor version without being refused by an older + /// host -- it simply will not be honoured, which is why a flag may only + /// ever ask for treatment that is safe to omit for a plugin that never + /// asked. + pub flags: u64, +} + +// SAFETY: Plugin descriptors are exported as process-lifetime immutable static +// data. The raw pointers are required for C ABI compatibility and are only +// expected to point to immutable NUL-terminated strings and static vtables. +unsafe impl Sync for PluginDescriptor {} + +/// Callbacks the host offers to an engine instance. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct HostCallbacks { + /// `sizeof` this struct as the host built it. + pub size: usize, + /// Writes a message into the host's log. May be `None`, in which case the + /// plugin has nowhere to log. + pub log: Option, + /// May be `None`, in which case an engine must not report + /// [`STREAM_ENGINE_STATE_BLOCKED`]: there would be no way to un-block it. + pub wake: Option, + /// Passed back as the first argument of `log` and `wake`. + /// + /// Entirely opaque: it is a handle the host resolves, not necessarily a + /// pointer to anything, so a plugin must pass it back unchanged and must + /// never dereference it. Valid for as long as those function pointers are. + pub host_ctx: *mut c_void, +} + +/// A network address passed across the boundary. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct PluginAddress { + /// One of the `ADDRESS_KIND_*` values, which says how to read `data`. + pub kind: u16, + /// The port, in host byte order. + pub port: u16, + /// The address bytes, whose meaning depends on `kind`. + pub data: *const u8, + /// How many bytes `data` holds. + pub data_len: usize, +} + +/// Arguments passed to both `create_instance` entries. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct EngineCreateArgs { + /// `sizeof` this struct as the host built it. + pub size: usize, + /// The outbound's `args` setting, verbatim and NUL-terminated. Its shape is + /// the plugin's own business -- the host never looks inside. + pub plugin_args: *const c_char, + /// Where the session is ultimately headed, which is what a protocol engine + /// encodes into its header. Not the server the host connected to. + pub destination: *const PluginAddress, + /// The callbacks this instance may use. Never null; the struct itself is + /// borrowed only for this call. + pub host_callbacks: *const HostCallbacks, + /// The host's own ABI version, so a plugin built against a newer minor + /// version can tell what the host will actually understand. + pub host_abi_major: u32, + pub host_abi_minor: u32, +} + +/// The stream engine vtable. +/// +/// An instance is a byte-stream codec with two sides, [`STREAM_SIDE_APP`] and +/// [`STREAM_SIDE_NET`]. The host owns all the I/O and drives the instance in a +/// loop: read `poll_state`, `push` what that asks for, `pull` what it offers, +/// and repeat. The engine never touches a socket and never blocks. +/// +/// Every entry here is required: the host refuses to load a plugin whose stream +/// vtable leaves one null. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct StreamEnginePlugin { + pub size: usize, + /// One of the `STREAM_CONNECT_TYPE_*` values, saying what stream the host + /// should hand this engine. Read once at load time, so it is a property of + /// the plugin rather than of an instance. + pub connect_type: u32, + /// Creates an instance, or returns null and leaves the reason in + /// `get_last_error`, which the host then calls with a null instance. + pub create_instance: Option *mut c_void>, + /// Destroys an instance. Never overlaps another call on it, and must not + /// return until no `log` or `wake` call the plugin makes can still be in + /// flight; this is the one entry that may block, and only briefly. + pub destroy_instance: Option, + /// Reports what the engine wants next, as a bitmask of the + /// `STREAM_ENGINE_STATE_*` flags written through the out-parameter. + /// + /// The host calls this between every other operation, so it must be cheap + /// and must not itself advance the protocol. + pub poll_state: Option i32>, + /// Hands the engine input for one side and reports how much of it was taken + /// through `consumed`. + /// + /// A short or zero `consumed` is backpressure, not failure: the host keeps + /// the rest and offers it again. `consumed` must never exceed `input_len`; + /// the host rejects a plugin that says otherwise. + pub push: Option i32>, + /// Takes output for one side into the host's buffer and reports how much + /// through `produced`. + /// + /// `produced == 0` means nothing more is available right now, even if + /// `poll_state` advertised output; the host believes the bytes over the + /// flag. Filling the buffer completely invites the host to call again. + /// `produced` must never exceed `output_cap`. + pub pull: Option i32>, + /// Tells the engine that one or both sides are finished, as a bitmask of + /// the `STREAM_ENGINE_CLOSE_*` flags. + /// + /// The engine may still have output to hand over afterwards -- a close + /// notify record, a final frame -- and the host still drains it. + pub close: Option i32>, + pub get_last_error: Option, + /// How big a buffer the engine would like for a `pull` on this side. The + /// host clamps the answer to a sane range, so a wild hint costs efficiency + /// rather than memory. + pub suggest_output_size: Option usize>, + /// How many `pull` calls of that size the host should make in a row before + /// going back to the socket. Also clamped. + pub suggest_output_batch: Option usize>, +} + +/// The datagram engine vtable. +/// +/// An instance is a packet codec: one datagram and its address in, wire bytes +/// out, and back. As with the stream vtable the host owns the transport, and +/// every entry here is required for the plugin to load. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct DatagramEnginePlugin { + pub size: usize, + /// One of the `DATAGRAM_TRANSPORT_TYPE_*` values, saying what the host + /// should carry these datagrams over. Read once at load time. + pub transport_type: u32, + /// Creates an instance, or returns null and leaves the reason in + /// `get_last_error`, which the host then calls with a null instance. + pub create_instance: Option *mut c_void>, + /// Destroys an instance, under the same rules as the stream vtable's entry. + pub destroy_instance: Option, + /// Encodes one datagram for `target` into `output`, reporting the length + /// through `produced`. + /// + /// Returning [`ENGINE_STATUS_BUFFER_TOO_SMALL`] makes the host grow the + /// buffer and retry the same datagram, a bounded number of times, so a + /// conservative `max_output_size` costs an extra call rather than the + /// packet. `produced` must never exceed `output_cap`. + pub encode_packet: Option< + unsafe extern "C" fn( + *mut c_void, + *const u8, + usize, + *const PluginAddress, + *mut u8, + usize, + *mut usize, + ) -> i32, + >, + /// Decodes at most one datagram out of `input`. + /// + /// Reliable transports carry framed datagrams over a byte stream, so a + /// single read can hand the engine a partial frame or several frames at + /// once. `consumed` is how the engine reports which of those happened: + /// + /// * `consumed == 0 && produced == 0` -- the input holds an incomplete + /// frame. The host reads more bytes and calls again with the frame's + /// bytes still at the front of the buffer. + /// * `consumed > 0 && produced == 0` -- a frame that carries no datagram, + /// such as a keepalive, was consumed. The host drops those bytes and + /// calls again. + /// * `consumed > 0 && produced > 0` -- one datagram was decoded. + /// + /// `consumed` must never exceed `input_len`. On + /// [`ENGINE_STATUS_BUFFER_TOO_SMALL`] the engine must consume nothing, so + /// that the host can retry the same input with a larger output buffer. + /// + /// Unreliable transports get one whole frame per call and always consume + /// all of it. + pub decode_packet: Option< + unsafe extern "C" fn( + *mut c_void, + *const u8, + usize, + *mut usize, + *mut u8, + usize, + *mut usize, + *mut PluginAddress, + ) -> i32, + >, + /// The buffer size the engine wants for an input of `input_len` bytes in + /// the given `DATAGRAM_DIRECTION_*` direction. Advisory and clamped by the + /// host, which grows the buffer anyway on + /// [`ENGINE_STATUS_BUFFER_TOO_SMALL`]. + pub max_output_size: Option usize>, + /// The largest address the engine can write into the [`PluginAddress`] + /// buffer the host supplies to `decode_packet`. Also clamped. + pub max_address_size: Option usize>, + pub get_last_error: Option, +} + +mod sealed { + pub trait Sealed {} +} + +/// A `size`-prefixed ABI struct exchanged across the boundary. +/// +/// Both peers declare how many bytes of the struct they actually wrote in its +/// leading `size` field. The receiver requires at least [`Self::REQUIRED_SIZE`] +/// bytes -- the prefix frozen when this major version was published, which +/// never grows -- and treats anything beyond that as present only if `size` +/// covers it. That is what lets an old plugin run against a newer host that has +/// appended fields, and a newer plugin run against an older host that will +/// ignore the tail. +/// +/// # Safety +/// +/// Implementors must be `#[repr(C)]` and must have no bit pattern of all zeros +/// that is invalid, so that a short struct can be zero-extended by +/// [`read_struct_prefix`]. +pub unsafe trait AbiStruct: Copy + sealed::Sealed { + /// The prefix every conforming peer must provide. Frozen for the lifetime + /// of [`PLUGIN_ABI_MAJOR`]: appending a field must not change it. + const REQUIRED_SIZE: usize; + /// Human-readable name used in diagnostics. + const NAME: &'static str; +} + +macro_rules! impl_abi_struct { + ($t:ty, $name:literal, last = $field:ident : $field_ty:ty) => { + impl sealed::Sealed for $t {} + // SAFETY: `$t` is `#[repr(C)]` and is built only from integers, raw + // pointers and `Option`, for each of which an all-zero + // bit pattern is a valid value (null pointer, `None`, zero). + unsafe impl AbiStruct for $t { + const REQUIRED_SIZE: usize = core::mem::offset_of!($t, $field) + size_of::<$field_ty>(); + const NAME: &'static str = $name; + } + }; +} + +// `datagram` and not `flags`: the required prefix is frozen for the lifetime +// of the major version, so a field appended in a minor version must never +// enlarge it. Moving this on would refuse every plugin built before that +// minor. +impl_abi_struct!( + PluginDescriptor, + "descriptor", + last = datagram: *const DatagramEnginePlugin +); +impl_abi_struct!(HostCallbacks, "host callbacks", last = host_ctx: *mut c_void); +impl_abi_struct!( + EngineCreateArgs, + "engine create args", + last = host_abi_minor: u32 +); +impl_abi_struct!( + StreamEnginePlugin, + "stream engine", + last = suggest_output_batch: Option usize> +); +impl_abi_struct!( + DatagramEnginePlugin, + "datagram engine", + last = get_last_error: Option +); + +/// Copies a peer-provided ABI struct out of `ptr`, zero-extending it when the +/// peer is older and wrote fewer bytes than this build knows about, and +/// ignoring the tail when the peer is newer and wrote more. +/// +/// Fields the peer did not provide read back as `None`, null or zero, so a +/// caller checks for those exactly as it would for a field a peer chose not to +/// populate. +/// +/// # Safety +/// +/// `ptr` must be non-null and point to at least `declared_size` readable bytes, +/// and `declared_size` must be the value the peer wrote into the struct's +/// leading `size` field. Callers must reject `declared_size < +/// T::REQUIRED_SIZE` before calling. +pub unsafe fn read_struct_prefix(ptr: *const T, declared_size: usize) -> T { + debug_assert!(!ptr.is_null()); + debug_assert!(declared_size >= T::REQUIRED_SIZE); + let readable = if declared_size < size_of::() { + declared_size + } else { + size_of::() + }; + let mut out = MaybeUninit::::zeroed(); + core::ptr::copy_nonoverlapping(ptr.cast::(), out.as_mut_ptr().cast::(), readable); + // SAFETY: `AbiStruct` guarantees an all-zero `T` is valid, and the bytes the + // peer did provide have been copied over that zeroed value. + out.assume_init() +} diff --git a/leaf-plugin-abi/tests/descriptor_flags.rs b/leaf-plugin-abi/tests/descriptor_flags.rs new file mode 100644 index 0000000..4df34ab --- /dev/null +++ b/leaf-plugin-abi/tests/descriptor_flags.rs @@ -0,0 +1,72 @@ +//! `PluginDescriptor::flags` was appended in minor 1, and the whole point of +//! appending rather than inserting is that a plugin built before it still +//! loads. These are the two things that has to mean. + +use std::mem::{offset_of, size_of}; + +use leaf_plugin_abi::*; + +/// A descriptor as a plugin built against minor 0 writes it: no `flags` field +/// at all, and a `size` that says so. +fn minor_zero_descriptor() -> PluginDescriptor { + PluginDescriptor { + size: PluginDescriptor::REQUIRED_SIZE, + abi_major: PLUGIN_ABI_MAJOR, + abi_minor: 0, + name: c"old-plugin".as_ptr(), + version: c"0.1.0".as_ptr(), + stream: core::ptr::null(), + datagram: core::ptr::null(), + // Whatever this build happens to leave here is exactly what the host + // must not read, because the plugin's `size` says it is not there. + flags: PLUGIN_FLAG_EMBEDS_RUNTIME, + } +} + +/// The required prefix is frozen for the lifetime of the major version. +/// +/// If someone moves `impl_abi_struct!` on to `flags`, this fails -- which is +/// the point. Doing so would refuse every plugin built against minor 0, whose +/// descriptor is smaller than the prefix would then demand. +#[test] +fn appending_flags_did_not_enlarge_the_required_prefix() { + let frozen = offset_of!(PluginDescriptor, datagram) + size_of::<*const DatagramEnginePlugin>(); + assert_eq!( + PluginDescriptor::REQUIRED_SIZE, + frozen, + "the required prefix must end at `datagram`, not at a field appended later" + ); + assert!( + size_of::() > PluginDescriptor::REQUIRED_SIZE, + "this test is meaningless unless the struct has grown past the prefix" + ); +} + +/// A plugin that predates the field reads back as one that did not set it, +/// rather than as whatever bytes happened to follow its descriptor. +#[test] +fn a_minor_zero_descriptor_reads_back_with_no_flags() { + let descriptor = minor_zero_descriptor(); + // SAFETY: `descriptor` is a live `PluginDescriptor`, and `declared_size` is + // the value in its own `size` field, which is at least `REQUIRED_SIZE`. + let read = unsafe { read_struct_prefix(&descriptor as *const PluginDescriptor, descriptor.size) }; + assert_eq!( + read.flags, 0, + "a field the plugin's `size` excludes must read back zero, not the memory after it" + ); + assert_eq!(read.abi_minor, 0); + assert!(read.stream.is_null()); +} + +/// And a plugin that does set it is believed. +#[test] +fn a_full_descriptor_carries_its_flags_through() { + let descriptor = PluginDescriptor { + size: size_of::(), + abi_minor: PLUGIN_ABI_MINOR, + ..minor_zero_descriptor() + }; + // SAFETY: as above. + let read = unsafe { read_struct_prefix(&descriptor as *const PluginDescriptor, descriptor.size) }; + assert_eq!(read.flags & PLUGIN_FLAG_EMBEDS_RUNTIME, PLUGIN_FLAG_EMBEDS_RUNTIME); +} diff --git a/leaf-plugin-abi/tests/header_parity.rs b/leaf-plugin-abi/tests/header_parity.rs new file mode 100644 index 0000000..c274c50 --- /dev/null +++ b/leaf-plugin-abi/tests/header_parity.rs @@ -0,0 +1,319 @@ +//! Checks that `include/leaf_plugin_abi.h` and `src/lib.rs` describe the same +//! ABI. Without this the C and Rust declarations drift silently, which is +//! exactly the failure mode a shared ABI crate exists to prevent. + +use std::collections::BTreeMap; +use std::mem::{offset_of, size_of}; +use std::path::PathBuf; +use std::process::Command; + +use leaf_plugin_abi::*; + +const C_PROBE: &str = r#" +#include +#include +#include "leaf_plugin_abi.h" + +#define P_SIZE(s) printf("size:%s=%zu\n", #s, sizeof(s)) +#define P_OFF(s, f) printf("off:%s.%s=%zu\n", #s, #f, offsetof(s, f)) +#define P_CONST(c) printf("const:%s=%lld\n", #c, (long long)(c)) + +int main(void) { + P_SIZE(PluginDescriptor); + P_OFF(PluginDescriptor, size); + P_OFF(PluginDescriptor, abi_major); + P_OFF(PluginDescriptor, abi_minor); + P_OFF(PluginDescriptor, name); + P_OFF(PluginDescriptor, version); + P_OFF(PluginDescriptor, stream); + P_OFF(PluginDescriptor, datagram); + P_OFF(PluginDescriptor, flags); + + P_SIZE(HostCallbacks); + P_OFF(HostCallbacks, size); + P_OFF(HostCallbacks, log); + P_OFF(HostCallbacks, wake); + P_OFF(HostCallbacks, host_ctx); + + P_SIZE(PluginAddress); + P_OFF(PluginAddress, kind); + P_OFF(PluginAddress, port); + P_OFF(PluginAddress, data); + P_OFF(PluginAddress, data_len); + + P_SIZE(EngineCreateArgs); + P_OFF(EngineCreateArgs, size); + P_OFF(EngineCreateArgs, plugin_args); + P_OFF(EngineCreateArgs, destination); + P_OFF(EngineCreateArgs, host_callbacks); + P_OFF(EngineCreateArgs, host_abi_major); + P_OFF(EngineCreateArgs, host_abi_minor); + + P_SIZE(StreamEnginePlugin); + P_OFF(StreamEnginePlugin, size); + P_OFF(StreamEnginePlugin, connect_type); + P_OFF(StreamEnginePlugin, create_instance); + P_OFF(StreamEnginePlugin, destroy_instance); + P_OFF(StreamEnginePlugin, poll_state); + P_OFF(StreamEnginePlugin, push); + P_OFF(StreamEnginePlugin, pull); + P_OFF(StreamEnginePlugin, close); + P_OFF(StreamEnginePlugin, get_last_error); + P_OFF(StreamEnginePlugin, suggest_output_size); + P_OFF(StreamEnginePlugin, suggest_output_batch); + + P_SIZE(DatagramEnginePlugin); + P_OFF(DatagramEnginePlugin, size); + P_OFF(DatagramEnginePlugin, transport_type); + P_OFF(DatagramEnginePlugin, create_instance); + P_OFF(DatagramEnginePlugin, destroy_instance); + P_OFF(DatagramEnginePlugin, encode_packet); + P_OFF(DatagramEnginePlugin, decode_packet); + P_OFF(DatagramEnginePlugin, max_output_size); + P_OFF(DatagramEnginePlugin, max_address_size); + P_OFF(DatagramEnginePlugin, get_last_error); + + P_CONST(LEAF_PLUGIN_ABI_MAJOR); + P_CONST(LEAF_PLUGIN_ABI_MINOR); + P_CONST(LEAF_PLUGIN_DESCRIPTOR_REQUIRED_SIZE); + P_CONST(LEAF_HOST_CALLBACKS_REQUIRED_SIZE); + P_CONST(LEAF_ENGINE_CREATE_ARGS_REQUIRED_SIZE); + P_CONST(LEAF_STREAM_ENGINE_PLUGIN_REQUIRED_SIZE); + P_CONST(LEAF_DATAGRAM_ENGINE_PLUGIN_REQUIRED_SIZE); + P_CONST(LEAF_ENGINE_STATUS_OK); + P_CONST(LEAF_ENGINE_STATUS_INVALID_ARGUMENT); + P_CONST(LEAF_ENGINE_STATUS_BUFFER_TOO_SMALL); + P_CONST(LEAF_ENGINE_STATUS_UNSUPPORTED); + P_CONST(LEAF_ENGINE_STATUS_PLUGIN_FAILURE); + P_CONST(LEAF_LOG_LEVEL_ERROR); + P_CONST(LEAF_LOG_LEVEL_WARN); + P_CONST(LEAF_LOG_LEVEL_INFO); + P_CONST(LEAF_LOG_LEVEL_DEBUG); + P_CONST(LEAF_LOG_LEVEL_TRACE); + P_CONST(LEAF_ADDRESS_KIND_IPV4); + P_CONST(LEAF_ADDRESS_KIND_IPV6); + P_CONST(LEAF_ADDRESS_KIND_DOMAIN); + P_CONST(LEAF_DATAGRAM_DIRECTION_ENCODE); + P_CONST(LEAF_DATAGRAM_DIRECTION_DECODE); + P_CONST(LEAF_DATAGRAM_TRANSPORT_TYPE_RELIABLE); + P_CONST(LEAF_DATAGRAM_TRANSPORT_TYPE_UNRELIABLE); + P_CONST(LEAF_STREAM_CONNECT_TYPE_PROXY_TCP); + P_CONST(LEAF_STREAM_CONNECT_TYPE_DIRECT); + P_CONST(LEAF_STREAM_CONNECT_TYPE_NEXT); + P_CONST(LEAF_STREAM_SIDE_APP); + P_CONST(LEAF_STREAM_SIDE_NET); + P_CONST(LEAF_STREAM_ENGINE_STATE_WANT_APP_INPUT); + P_CONST(LEAF_STREAM_ENGINE_STATE_WANT_NET_INPUT); + P_CONST(LEAF_STREAM_ENGINE_STATE_HAS_APP_OUTPUT); + P_CONST(LEAF_STREAM_ENGINE_STATE_HAS_NET_OUTPUT); + P_CONST(LEAF_STREAM_ENGINE_STATE_HANDSHAKING); + P_CONST(LEAF_STREAM_ENGINE_STATE_ESTABLISHED); + P_CONST(LEAF_STREAM_ENGINE_STATE_PEER_CLOSED); + P_CONST(LEAF_STREAM_ENGINE_STATE_FATAL); + P_CONST(LEAF_STREAM_ENGINE_STATE_BLOCKED); + P_CONST(LEAF_STREAM_ENGINE_CLOSE_APP); + P_CONST(LEAF_STREAM_ENGINE_CLOSE_NET); + P_CONST(LEAF_PLUGIN_FLAG_EMBEDS_RUNTIME); + return 0; +} +"#; + +fn c_compiler() -> String { + std::env::var("CC").unwrap_or_else(|_| "cc".to_string()) +} + +/// Compiles and runs the C probe, returning every `key=value` pair it printed. +fn c_layout() -> BTreeMap { + let tmp = PathBuf::from(env!("CARGO_TARGET_TMPDIR")); + std::fs::create_dir_all(&tmp).expect("create tmp dir"); + let src = tmp.join("leaf_plugin_abi_probe.c"); + let bin = tmp.join("leaf_plugin_abi_probe"); + std::fs::write(&src, C_PROBE).expect("write probe source"); + + let include = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("include"); + let cc = c_compiler(); + let status = Command::new(&cc) + .arg("-std=c11") + .arg("-Wall") + .arg("-Werror") + .arg("-I") + .arg(&include) + .arg("-o") + .arg(&bin) + .arg(&src) + .status() + .unwrap_or_else(|err| panic!("failed to run C compiler [{}]: {}", cc, err)); + assert!(status.success(), "C probe failed to compile with [{}]", cc); + + let output = Command::new(&bin).output().expect("run probe"); + assert!(output.status.success(), "C probe exited with failure"); + String::from_utf8(output.stdout) + .expect("probe output is utf-8") + .lines() + .filter_map(|line| line.split_once('=')) + .map(|(key, value)| (key.to_string(), value.parse().expect("probe value"))) + .collect() +} + +#[test] +fn c_header_matches_rust_definitions() { + let c = c_layout(); + let mut rust: BTreeMap = BTreeMap::new(); + + macro_rules! size { + ($t:ty) => { + rust.insert(format!("size:{}", stringify!($t)), size_of::<$t>() as i64); + }; + } + macro_rules! off { + ($t:ty, $($f:ident),+ $(,)?) => {$( + rust.insert( + format!("off:{}.{}", stringify!($t), stringify!($f)), + offset_of!($t, $f) as i64, + ); + )+}; + } + macro_rules! konst { + ($($c:ident => $name:literal),+ $(,)?) => {$( + rust.insert(format!("const:{}", $name), $c as i64); + )+}; + } + + size!(PluginDescriptor); + off!( + PluginDescriptor, + size, + abi_major, + abi_minor, + name, + version, + stream, + datagram, + flags + ); + size!(HostCallbacks); + off!(HostCallbacks, size, log, wake, host_ctx); + size!(PluginAddress); + off!(PluginAddress, kind, port, data, data_len); + size!(EngineCreateArgs); + off!( + EngineCreateArgs, + size, + plugin_args, + destination, + host_callbacks, + host_abi_major, + host_abi_minor, + ); + size!(StreamEnginePlugin); + off!( + StreamEnginePlugin, + size, + connect_type, + create_instance, + destroy_instance, + poll_state, + push, + pull, + close, + get_last_error, + suggest_output_size, + suggest_output_batch, + ); + size!(DatagramEnginePlugin); + off!( + DatagramEnginePlugin, + size, + transport_type, + create_instance, + destroy_instance, + encode_packet, + decode_packet, + max_output_size, + max_address_size, + get_last_error, + ); + + konst! { + PLUGIN_ABI_MAJOR => "LEAF_PLUGIN_ABI_MAJOR", + PLUGIN_ABI_MINOR => "LEAF_PLUGIN_ABI_MINOR", + ENGINE_STATUS_OK => "LEAF_ENGINE_STATUS_OK", + ENGINE_STATUS_INVALID_ARGUMENT => "LEAF_ENGINE_STATUS_INVALID_ARGUMENT", + ENGINE_STATUS_BUFFER_TOO_SMALL => "LEAF_ENGINE_STATUS_BUFFER_TOO_SMALL", + ENGINE_STATUS_UNSUPPORTED => "LEAF_ENGINE_STATUS_UNSUPPORTED", + ENGINE_STATUS_PLUGIN_FAILURE => "LEAF_ENGINE_STATUS_PLUGIN_FAILURE", + LOG_LEVEL_ERROR => "LEAF_LOG_LEVEL_ERROR", + LOG_LEVEL_WARN => "LEAF_LOG_LEVEL_WARN", + LOG_LEVEL_INFO => "LEAF_LOG_LEVEL_INFO", + LOG_LEVEL_DEBUG => "LEAF_LOG_LEVEL_DEBUG", + LOG_LEVEL_TRACE => "LEAF_LOG_LEVEL_TRACE", + ADDRESS_KIND_IPV4 => "LEAF_ADDRESS_KIND_IPV4", + ADDRESS_KIND_IPV6 => "LEAF_ADDRESS_KIND_IPV6", + ADDRESS_KIND_DOMAIN => "LEAF_ADDRESS_KIND_DOMAIN", + DATAGRAM_DIRECTION_ENCODE => "LEAF_DATAGRAM_DIRECTION_ENCODE", + DATAGRAM_DIRECTION_DECODE => "LEAF_DATAGRAM_DIRECTION_DECODE", + DATAGRAM_TRANSPORT_TYPE_RELIABLE => "LEAF_DATAGRAM_TRANSPORT_TYPE_RELIABLE", + DATAGRAM_TRANSPORT_TYPE_UNRELIABLE => "LEAF_DATAGRAM_TRANSPORT_TYPE_UNRELIABLE", + STREAM_CONNECT_TYPE_PROXY_TCP => "LEAF_STREAM_CONNECT_TYPE_PROXY_TCP", + STREAM_CONNECT_TYPE_DIRECT => "LEAF_STREAM_CONNECT_TYPE_DIRECT", + STREAM_CONNECT_TYPE_NEXT => "LEAF_STREAM_CONNECT_TYPE_NEXT", + STREAM_SIDE_APP => "LEAF_STREAM_SIDE_APP", + STREAM_SIDE_NET => "LEAF_STREAM_SIDE_NET", + STREAM_ENGINE_STATE_WANT_APP_INPUT => "LEAF_STREAM_ENGINE_STATE_WANT_APP_INPUT", + STREAM_ENGINE_STATE_WANT_NET_INPUT => "LEAF_STREAM_ENGINE_STATE_WANT_NET_INPUT", + STREAM_ENGINE_STATE_HAS_APP_OUTPUT => "LEAF_STREAM_ENGINE_STATE_HAS_APP_OUTPUT", + STREAM_ENGINE_STATE_HAS_NET_OUTPUT => "LEAF_STREAM_ENGINE_STATE_HAS_NET_OUTPUT", + STREAM_ENGINE_STATE_HANDSHAKING => "LEAF_STREAM_ENGINE_STATE_HANDSHAKING", + STREAM_ENGINE_STATE_ESTABLISHED => "LEAF_STREAM_ENGINE_STATE_ESTABLISHED", + STREAM_ENGINE_STATE_PEER_CLOSED => "LEAF_STREAM_ENGINE_STATE_PEER_CLOSED", + STREAM_ENGINE_STATE_FATAL => "LEAF_STREAM_ENGINE_STATE_FATAL", + STREAM_ENGINE_STATE_BLOCKED => "LEAF_STREAM_ENGINE_STATE_BLOCKED", + STREAM_ENGINE_CLOSE_APP => "LEAF_STREAM_ENGINE_CLOSE_APP", + STREAM_ENGINE_CLOSE_NET => "LEAF_STREAM_ENGINE_CLOSE_NET", + PLUGIN_FLAG_EMBEDS_RUNTIME => "LEAF_PLUGIN_FLAG_EMBEDS_RUNTIME", + } + + for (name, required) in [ + ( + "LEAF_PLUGIN_DESCRIPTOR_REQUIRED_SIZE", + PluginDescriptor::REQUIRED_SIZE, + ), + ( + "LEAF_HOST_CALLBACKS_REQUIRED_SIZE", + HostCallbacks::REQUIRED_SIZE, + ), + ( + "LEAF_ENGINE_CREATE_ARGS_REQUIRED_SIZE", + EngineCreateArgs::REQUIRED_SIZE, + ), + ( + "LEAF_STREAM_ENGINE_PLUGIN_REQUIRED_SIZE", + StreamEnginePlugin::REQUIRED_SIZE, + ), + ( + "LEAF_DATAGRAM_ENGINE_PLUGIN_REQUIRED_SIZE", + DatagramEnginePlugin::REQUIRED_SIZE, + ), + ] { + rust.insert(format!("const:{name}"), required as i64); + } + + let mut mismatches = Vec::new(); + for (key, rust_value) in &rust { + match c.get(key) { + Some(c_value) if c_value == rust_value => {} + Some(c_value) => mismatches.push(format!("{key}: C={c_value} Rust={rust_value}")), + None => mismatches.push(format!("{key}: missing from the C header probe")), + } + } + for key in c.keys() { + if !rust.contains_key(key) { + mismatches.push(format!("{key}: missing from the Rust definitions")); + } + } + assert!( + mismatches.is_empty(), + "C header and Rust ABI definitions disagree:\n {}", + mismatches.join("\n ") + ); +}