Skip to content

Getting Started

Pummelchen edited this page Sep 17, 2026 · 26 revisions

Getting Started

Two libraries live in this repository and they are built and used independently. Pick the one you need:

Library Use it when Entry point
Swift package You are writing a macOS app or service in Swift and want the async client/server API. repository-root Package.swift
C99 library You want a portable C library to link into your own program, or the three CLI tools. C99/CMakeLists.txt

Loopback and the development certificate. Both libraries ship a built-in self-signed development certificate that is refused on any non-loopback bind address. It exists to let a client and a server meet on localhost, 127.0.0.1 or ::1. To serve anything reachable by a real client you must supply a real certificate, and a client must validate it (--trust system in the C99 tools, the default trustPolicy in Swift). A self-signed certificate cannot be validated by a peer for a routable name, so binding a development identity publicly is a startup error, not a warning.

Swift

Requirements

  • macOS 26 or later
  • Xcode 27 or later
  • Swift 6.4 or later (both manifests declare swift-tools-version: 6.4 and Swift language mode 6)

Add the package

.package(
    url: "https://github.com/Pummelchen/WebTransport.git",
    exact: "1.5.0"
)

Add the WebTransport product to your application target. The repository-root Package.swift is the supported integration point; the lower-level products (WebTransportNetworkRuntime, WebTransportHTTP3Core, WebTransportQUICCore, WebTransportTLSCore, WebTransportCryptoApple, WebTransportUDPApple) are published too, for protocol work.

Minimal client

import Foundation
import WebTransport

let client = WebTransportClient(configuration: WebTransportClientConfiguration(
    authority: "example.com",
    path: "/wt",
    origin: "https://example.com",
    availableProtocols: ["demo.v1"]
))

let session = try await client.connect(
    to: WebTransportEndpoint(host: "example.com", port: 443)
)

let stream = try await session.openBidirectionalStream()
try await stream.send(Data("hello".utf8), endOfStream: true)
let response = try await stream.receive()
try await session.close()

trustPolicy defaults to .systemTrust, so the server's certificate is validated against the platform trust store. For a loopback server that uses the development certificate, pass trustPolicy: .localDevelopmentSelfSigned; it is accepted only for localhost, 127.0.0.1 and ::1.

Minimal server

import WebTransport

let server = WebTransportServer(configuration: WebTransportServerConfiguration(
    authority: "localhost",
    path: "/wt",
    supportedProtocols: ["demo.v1"]
))

let listener = try await server.listen(
    on: WebTransportEndpoint(host: "127.0.0.1", port: 4433)
)
defer { listener.shutdown() }

let session = try await listener.acceptSession()
let stream = try await session.acceptBidirectionalStream()
let request = try await stream.receive()
try await stream.send(request, endOfStream: true)
try await session.close()

Other things the session offers:

Call What it does
session.openBidirectionalStream() Open a stream you initiate.
session.acceptBidirectionalStream(maximumInitialBytes:) Accept a peer-initiated bidirectional stream.
session.acceptUnidirectionalStream(maximumInitialBytes:) Accept a peer-initiated unidirectional stream. Receive-only: WebTransportUnidirectionalStream has receive(maximumBytes:) and no send.
session.sendDatagram(_:) / session.receiveDatagram() Unreliable messages, when the peer negotiated datagramsAvailable.
session.exportKeyingMaterial(applicationLabel:applicationContext:outputByteCount:) Session-bound TLS exporter material.
session.drain() / session.close(applicationErrorCode:reason:) Graceful drain and close.

Supply a server identity

Loopback development can use the generated certificate. Anything reachable by a real client needs a real identity:

WebTransportServerIdentity case Use
.developmentSelfSigned (default) Loopback only. Refused on any non-loopback bind.
.pkcs12(data:passphrase:) A PKCS#12 bundle holding the leaf certificate, its chain and the private key. Usually the simplest path.
.certificateChain(chainDER:privateKeyDER:keyKind:) An explicit chain plus a private key in Apple's encoding.

Two platform constraints are easy to hit; both are described in full in Known Limitations:

  • macOS cannot build an identity from a certificate whose SubjectPublicKeyInfo carries explicit EC curve parameters. The system /usr/bin/openssl on macOS is LibreSSL 3.3.6, which writes that form. Generate the certificate with OpenSSL 3.x, or convert the key with openssl ec -in key.pem -param_enc named_curve -out key-named.pem. RSA identities are unaffected.
  • .certificateChain's privateKeyDER must be the bytes SecKeyCopyExternalRepresentation returns for the private key (97 bytes for EC P-256), not a public point and not SEC1/PKCS#8 DER. A PKCS#12 bundle avoids this.

Serving a browser additionally needs settingsValidation: .interoperable. The default is .draft16Strict, which rejects peers still on earlier revisions.

Build, test and run

From the repository root:

swift build
swift test
swift run WebTransportClient --scenario all
swift run WebTransportServer --scenario all

A passing client run ends:

SUMMARY WebTransportClient: passed=40 failed=0 skipped=0 total=40

The two Release scenarios read Package.swift and Swift/build-release-apple-silicon.sh from the working directory. Outside a checkout they are reported as skipped, and the run ends SUMMARY … passed=38 failed=0 skipped=2 total=40 with exit status 3 (nothing failed, two scenarios could not be attempted).

--scenario accepts one name or a comma-separated list; --list prints every name; --help prints the catalog and the exit statuses; --json and --verbose change the report.

Run a real client and server

The two CLI peers also speak to each other over a real socket. Start a loopback server:

swift run WebTransportServer --listen 127.0.0.1:4433 --transport packet
network packet session listening: 127.0.0.1:4433
network packet session certificate-sha256: XbZ2etPocaN39O9rawa6QA2OEuALPX3TXrsWGlvCCwk=

Connect from another terminal:

swift run WebTransportClient --connect 127.0.0.1:4433 --transport packet --trust local-self-signed
network packet session connected: local=127.0.0.1:50185 remote=127.0.0.1:44341 session=established exchange=auto message="webtransport-network-session"

Use [::1]:4433 for IPv6 loopback. The client flags for this mode are --connect, --message, --timeout-ms, --transport packet|frame, --authority, --path, --origin, --protocol, --trust system|local-self-signed, --settings-validation and --exchange auto|stream|datagram; the server flags are --listen, --timeout-ms, --transport, --max-sessions, --authority, --path, --origin, --protocol, --identity-pkcs12, --identity-passphrase and --settings-validation. Both accept --flag value and --flag=value. The server has no --trust flag.

C99

Requirements

  • CMake 3.28 or later, Ninja
  • OpenSSL 3.0 (find_package(OpenSSL 3.0 REQUIRED); any other crypto backend is a configure-time FATAL_ERROR)
  • A C99 compiler. Clang, GCC and mingw-w64 are exercised in CI; MSVC is not.

Build and test

C99/scripts/build-and-test.sh              # Debug, into C99/out/<platform>/build
C99/scripts/build-and-test.sh --release    # into C99/out/<platform>/build-release
C99/scripts/build-and-test.sh --sanitize   # ASan + UBSan, into build-sanitize
C99/scripts/build-and-test.sh --all        # all three, in that order

The script prints the build and then the test run; a clean Debug run ends:

100% tests passed out of 97

The identical loop by hand, as CI runs it:

cmake -S C99 -B C99/out/ci/build -G Ninja \
  -DCMAKE_BUILD_TYPE=Debug -DWEBTRANSPORT_C99_BUILD_APPS=ON
cmake --build C99/out/ci/build
ctest --test-dir C99/out/ci/build --output-on-failure

The three CLI tools land in C99/out/ci/build/apps/. Note that the script and the by-hand invocation write to different directories: C99/out/<platform>/build versus C99/out/ci/build.

Link the library

Build and install into a prefix of your choice:

cmake -S C99 -B /tmp/wt-build -G Ninja \
  -DCMAKE_BUILD_TYPE=Release \
  -DCMAKE_INSTALL_PREFIX=/tmp/wt-prefix \
  -DWEBTRANSPORT_C99_BUILD_APPS=ON
cmake --build /tmp/wt-build
cmake --install /tmp/wt-build

That produces libwebtransport.a (static) and libwebtransport.<version>.dylib / .so (shared) with a find_package(webtransport_c99) CMake package. Both options are on by default; -DBUILD_SHARED_LIBS=OFF drops the shared library and -DWEBTRANSPORT_C99_BUILD_STATIC=OFF drops the static one. At least one must stay on.

A consumer's CMakeLists.txt:

cmake_minimum_required(VERSION 3.28)
project(my_app C)

find_package(webtransport_c99 REQUIRED)

add_executable(my_app main.c)
target_link_libraries(my_app PRIVATE WebTransport::static)   # or WebTransport::shared
cmake -S . -B build -G Ninja -DCMAKE_PREFIX_PATH=/tmp/wt-prefix
cmake --build build

WebTransport::static is the static archive; the installed CMake package declares its OpenSSL 3.0 dependency (through find_dependency) when the static library is installed, so the consumer does not have to name it. WebTransport::shared is the shared library, which links OpenSSL privately. Installing the tools also puts wt-client-c99, wt-server-c99 and wt-conformance-c99 in <prefix>/bin.

Call the public API

One header, webtransport/webtransport.h, carries the consumer surface: the status model, the bounded buffer/cursor/writer helpers, the version calls, and the session API in webtransport/api/. This program is the repository's own package consumer (C99/tests/package/main.c) and is built and run on every platform by CTest:

#include <stdio.h>
#include <string.h>

#include "webtransport/webtransport.h"

int main(void) {
  wt_buf_t buf = wt_buf_init(NULL);
  wt_cursor_t cursor;
  uint8_t bytes[4];
  wt_writer_t writer;

  if (wt_buf_append(&buf, "\x01\x02\x03", 3U) != WT_OK) return 1;
  cursor = wt_buf_cursor(&buf);
  if (wt_cursor_u8(&cursor) != 0x01U) return 1;
  if (wt_cursor_u16(&cursor) != 0x0203U) return 1;

  writer = wt_writer_init(bytes, sizeof(bytes));
  wt_writer_u32(&writer, 0x01020304U);
  if (!wt_writer_ok(&writer)) return 1;

  printf("webtransport-c99 %s (%s)\n", wt_version_string(), wt_protocol_draft());
  wt_buf_free(&buf);
  return 0;
}
webtransport-c99 1.5.0 (draft-ietf-webtrans-http3-16)

The session API is a handle plus explicit feed calls; there is no wt_session_run and the library never calls a callback from a thread of its own:

wt_endpoint_config_t endpoint = wt_endpoint_config_default();
wt_session_config_t config;
wt_session_callbacks_t callbacks = {0};
wt_session_t *session = NULL;

endpoint.role = WT_ENDPOINT_ROLE_CLIENT;
endpoint.host = "localhost";
endpoint.port = 4433U;
endpoint.path = "/wt";

if (wt_endpoint_config_check(&endpoint) != WT_OK) return 1;
if (wt_endpoint_session_config(&endpoint, 4U, &config) != WT_OK) return 1;  /* session_id = 4 */
if (wt_session_create(&config, NULL, &session) != WT_OK) return 1;         /* NULL = default allocator */

callbacks.context = NULL;
callbacks.on_datagram = on_datagram;   /* your function */
/* leave the callbacks you do not use NULL: no callback means the event is accepted and discarded. */
if (wt_session_set_callbacks(session, &callbacks) != WT_OK) return 1;

wt_session_destroy(session, NULL);     /* the same allocator used at create */

Key consumer symbols: wt_session_create / wt_session_destroy, wt_session_set_callbacks, wt_session_established, wt_session_on_stream_opened, wt_session_on_stream_data, wt_session_on_stream_reset, wt_session_on_datagram, wt_session_on_capsule, wt_session_write_drain, wt_session_write_close, wt_session_state, wt_session_id, wt_session_last_error, wt_session_flow_configure, wt_endpoint_config_default, wt_endpoint_session_config, wt_version_string, wt_protocol_draft, wt_status_name. For driving a real socket, the installed library exposes the runtime seam wt_runtime_session_pump, wt_runtime_session_start_client, wt_runtime_session_start_server and wt_runtime_session_handshake_done in webtransport/runtime/session.h.

The three CLI tools

The tools are built at C99/out/<platform>/build/apps/ (or C99/out/ci/build/apps/), and installed to <prefix>/bin; the examples below assume that directory is on PATH.

All three share one option parser: --transport accepts only packet, --trust accepts system or local-development, --exchange accepts stream or datagram, --timeout-ms defaults to 5000, and --json prints the report as one object. --help and --version exit 0. An unsupported value exits 2 and names what it refused. --trust local-development is refused unless the address is localhost, 127.0.0.1 or [::1].

Server (one peer per run; exits non-zero if no session completes):

wt-server-c99 --listen 127.0.0.1:4433 --exchange stream --message pong \
  --timeout-ms 10000 --json

Client:

wt-client-c99 --connect 127.0.0.1:4433 --exchange stream --message ping \
  --trust local-development --timeout-ms 10000 --json

A datagram exchange against the same server (--exchange datagram on both sides) reports:

{"role":"client","status":"ok","established":true,"connectAccepted":true,"responseStatus":200,"receivedBytes":5,"receivedDatagram":true, ...}
{"role":"server","status":"ok","boundPort":44331,"established":true,"connectAccepted":true,"receivedBytes":5,"receivedDatagram":true, ...}

Conformance tool — two endpoints in one process over IPv4 and IPv6:

wt-conformance-c99 --scenario all
57 scenario(s): 57 passed, 0 failed, 0 unsupported

A machine without an IPv6 loopback reports that scenario as unsupported and exits 3. The tool's exit statuses are 0 (nothing failed), 1 (a scenario failed) and 3 (nothing failed, something was not attempted).

Clone this wiki locally