libwebsockets Documentation

repository·main·Indexed 26 days ago

https://github.com/warmcat/libwebsockets

A high-performance, C-based networking library providing client and server implementations for HTTP/3, WebSockets, MQTT, and WebRTC. Designed for portability from embedded RTOS to cloud environments, it includes features for ABI compatibility tracking, a mcufont encoder/decoder, GPIO button controllers, and a generic display management API (lws_display_t) with integrated power state management.

Tokens
144.8K
Snippets
426
Records
974
Agent score
90%

What's inside libwebsockets

  1. Overview of the minimal secure streams server

    main

    This application demonstrates a TLS + WebSocket (WS) server running on https://localhost:7681 using Libwebsockets' Secure Streams feature.

    Key characteristics:

    • Policy Configuration: Server operation logic is defined via a JSON policy located in main.c.
    • Client Interaction: When visited in a modern browser, the server serves HTML and JavaScript. The JavaScript establishes a WebSocket connection back to the server, which then transmits an incrementing number every 100ms.
    • Secure Streams: The server utilizes Secure Streams to manage the TLS and protocol transitions.
  2. Overview of minimal secure streams threads example

    main

    This example demonstrates low-level secure stream handling and thread synchronization in libwebsockets:

    • Threaded Service Cancellation: Creates a separate thread that calls lws_cancel_service() at 10Hz.
    • Secure Stream Events: Verifies that the Secure Stream receives the LWSSSCS_EVENT_WAIT_CANCELLED state following each lws_cancel_service() call.
    • Shared Data Protection: Demonstrates how to safely protect a shared data area between external threads and the libwebsockets event loop thread to communicate instructions to the service loop.
    • Automatic Exit: The application exits with a 0 return code after 3 seconds if the expected number of messages were received.
  3. Overview of lws-cert-dist-server plugin

    main

    The lws-cert-dist-server is a server-side protocol plugin designed for certificate distribution systems. It uses Mutual TLS (mTLS) to authenticate clients and securely distributes TLS certificates (fullchain and private key) to authorized clients over a WebSocket connection.

    Key capabilities include:

    • mTLS Authentication: Uses the Common Name (CN) from the client's certificate to identify the requesting subdomain.
    • Automated Updates: If LWS_WITH_DIR is enabled, the server watches the local PKI directory and automatically pushes updated certificates to connected clients when files on disk change.
  4. Overview of lws_display_list

    main

    lws_display_list is a modernized 1970s-style Display List of graphic primitives. It uses an lws_dll2 list of Display List Objects (DLOs) to describe a logical scene.

    Key characteristics:

    • Memory Efficiency: It rasterizes the list one line at a time from top to bottom, meaning no backing framebuffer is required.
    • Automatic Cleanup: DLOs are destroyed as they go out of scope during rasterization, freeing resources immediately.
    • Resolution Independence: Memory scales with scene complexity (number of DLOs) rather than output resolution, making it suitable for 32-bpp rendering on constrained devices.

    Supported DLO Primitives:

    • Filled rectangles (with individually controllable rounded corners)
    • PNGs (1:1 orientation, transparency supported)
    • JPEGs (1:1 orientation)
    • UTF-8 text areas (using compressed, antialiased mcufonts)
  5. Overview of lws-dht-dnssec-monitor

    main
    The lws-dht-dnssec-monitor plugin automates the lifecycle of authoritative DNS zones. It works by scanning a centralized JSON configuration directory to discover managed domains, automatically generating missing ZSK or KSK DNSSEC keys, and detecting changes in upstream .zone files. When a change is detected, it merges active ACME zones, signs the zone, and publishes the resulting JWS payloads into the libwebsockets DHT for propagation. It is designed to work with lws-acme-client for multi-certificate management.
  6. Overview of the lws-webrtc plugin

    main
    The lws-webrtc plugin provides a shared WebRTC signaling and media transport layer within libwebsockets. It manages the entire WebRTC lifecycle including WebSocket signaling, DTLS negotiation, SRTP keying, and RTP packetization for audio and video. It acts as an ICE-lite server by processing STUN binding requests to establish connectivity.
  7. Overview of JOSE support in libwebsockets

    main

    libwebsockets provides lightweight APIs for performing cryptographic operations on JSON objects, independent of the TLS backend in use. It supports the following JOSE (JSON Object Signing and Encryption) standards:

    • JWS (RFC7515): JSON Web Signatures
    • JWE (RFC7516): JSON Web Encryption
    • JWK (RFC7517): JSON Web Keys
    • JWA (RFC7518): JSON Web Algorithms

    JSON parsing for these operations is handled by the lws lejp stream parser.

  8. Overview of the lws-ssh-base plugin

    main

    lws-ssh-base is a protocol plugin for libwebsockets that implements an abstract, generic SSH server. It is designed with a small footprint (suitable for ESP32) and high security (valgrind and Coverity clean).

    Key Characteristics:

    • Abstract Base Class: It handles crypto, protocol sequencing, and the state machine, but leaves IO and specific behaviors (like shell spawning or user authentication) to the user via an ops struct.
    • Security-First: It does not perform dangerous defaults like checking ~/.ssh/authorized_keys or spawning system shells unless you explicitly implement those in your callbacks.
    • Crypto: Automatically uses mbedTLS or OpenSSL depending on how libwebsockets was built. It implements:
      • KEX: curve25519-sha256@libssh.org
      • Server host key: ssh-rsa (4096b)
      • Encryption: chacha20-poly1305@openssh.com
  9. Overview of the lws-rtc-camera plugin

    main

    The lws-rtc-camera plugin provides WebRTC camera integration for libwebsockets. It manages V4L2 device capture, multimedia encoding, and secure routing to an lws-webrtc-mixer endpoint. It provides a simple operational API to trigger complex multimedia pipelines dynamically.

    Security Requirement: This plugin requires the protocol_lws_auth_device_client plugin to be enabled. The authentication plugin manages the RFC 8628 Device Authorization Flow to pair headless cameras with the mixer and acquire the access tokens required by protocol_lws_rtc_camera during attachment.

  10. Overview of LWS System Message Distribution (SMD)

    main

    LWS System Message Distribution (SMD) is a mechanism for independent system components to communicate events and state changes quickly. It is designed for short payloads (less than 384 bytes), making it suitable for JSON or small binary data.

    Key features:

    • Cross-platform: Works across Windows, RTOS, and Linux.
    • Local & Remote: Messages are delivered to all participants on the same lws_context by default, but can be broadcast between different processes using Secure Streams proxying.
    • Thread-safe: Registering as a participant and sending messages are thread-safe operations.
    • Non-recursive: Messages are delivered no sooner than the next event loop iteration to ensure modest stack usage.
    • Filtering: Participants use a bitfield (Message Class) to filter which messages they receive.
  11. Overview of the minimal secure streams example

    main

    This example demonstrates how to use libwebsockets Secure Streams to perform an HTTPS GET request. The application connects to https://warmcat.com and reads index.html.

    Key components of this example include:

    • Context and Stream Setup: Handled in minimal-secure-streams.c, which sets up the context and opens a secure stream of type "mintest".
    • State and Payload Handling: The handler for state changes and payloads for the "mintest" stream is implemented in ss-myss.c.
    • Connection Policy: The protocol and connection details for the "mintest" stream are defined in policy-database.c.
  12. Overview of lws_struct for JSON and SQLite serialization

    main

    lws_struct is a lightweight utility for serializing and deserializing C structs to and from JSON and sqlite3.

    Key features include:

    • Metadata-driven: You define a metadata array describing struct members once, then use generic APIs for serialization/deserialization.
    • Complex Data Types: Supports flat structs, single child struct pointers, and unbounded arrays or linked-lists (using lws_dll2).
    • C Type Support: Supports bool, char, int, long, and long long (both signed and unsigned).
    • String Handling: Supports both char * (pointer to separate content) and fixed-length char [] (inline content). Large strings are managed via a temporary lwsac of chained chunks to minimize heap fragmentation.
    • Memory Management: Deserialization allocates into an lwsac. This allows for efficient memory usage with minimal heap allocations. When the struct is no longer needed, a single call to free the lwsac releases all associated memory without needing to traverse the struct members.