ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
Discovery Service (ACDS)

🔍 ascii-chat Discovery Service for session management and NAT traversal More...

Topics

 ACDS Client
 Client-side session discovery, authentication, and signaling API.
 ACDS Server
 🌐 Discovery server TCP connection manager
 ACDS Database
 💾 SQLite-based session management
 ACDS Signaling
 🎬 WebRTC SDP/ICE signaling relay
 ACDS Identity
 🔑 Ed25519 identity key management
 ACDS Session Strings
 🏷️ Human-friendly session string generation

Enumerations

enum  acds_session_type_t { SESSION_TYPE_DIRECT_TCP = 0 , SESSION_TYPE_WEBRTC = 1 }
 Session connection type. More...

ACDS Discovery Mode Messages (Host Negotiation & Migration)

enum  acip_nat_type_t {
  ACIP_NAT_TYPE_OPEN = 0 , ACIP_NAT_TYPE_FULL_CONE = 1 , ACIP_NAT_TYPE_RESTRICTED = 2 , ACIP_NAT_TYPE_PORT_RESTRICTED = 3 ,
  ACIP_NAT_TYPE_SYMMETRIC = 4
}
 NAT type classification for host selection. More...
enum  acip_connection_type_t { ACIP_CONNECTION_TYPE_DIRECT_PUBLIC = 0 , ACIP_CONNECTION_TYPE_UPNP = 1 , ACIP_CONNECTION_TYPE_STUN = 2 , ACIP_CONNECTION_TYPE_TURN = 3 }
 Connection type for host announcement. More...
 acip_nat_quality_t
 acip_host_announcement_t
 acip_host_designated_t
 acip_host_lost_t
 acip_future_host_elected_t

ACDS Error Handling

enum  acip_error_code_t {
  ACIP_ERROR_NONE = 0 , ACIP_ERROR_SESSION_NOT_FOUND = 1 , ACIP_ERROR_SESSION_FULL = 2 , ACIP_ERROR_INVALID_PASSWORD = 3 ,
  ACIP_ERROR_INVALID_SIGNATURE = 4 , ACIP_ERROR_RATE_LIMITED = 5 , ACIP_ERROR_STRING_TAKEN = 6 , ACIP_ERROR_STRING_INVALID = 7 ,
  ACIP_ERROR_INTERNAL = 255
}
 ACIP error codes. More...
 acip_error_t
 acip_bandwidth_test_t
 acip_bandwidth_result_t
 acip_broadcast_ack_t

ACDS Session Management Messages

 acip_session_create_t
 acip_session_created_t
 acip_session_lookup_t
 acip_session_info_t
 acip_session_join_t
 acip_session_joined_t
 acip_participant_joined_t
 acip_participant_left_t
 acip_session_leave_t
 acip_session_end_t
 acip_session_reconnect_t
struct __attribute__ ((packed))
 SESSION_CREATE (PACKET_TYPE_ACIP_SESSION_CREATE) - Create new session.
typedef int32_t vec_t __attribute__((vector_size(4 *4)))
 SESSION_CREATED (PACKET_TYPE_ACIP_SESSION_CREATED) - Session created response.

ACDS WebRTC Signaling Messages

 acip_webrtc_sdp_t
 acip_webrtc_ice_t

ACDS String Reservation Messages (Future)

 acip_string_reserve_t
 acip_string_reserved_t
 acip_string_renew_t
 acip_string_release_t

ACDS Ring Consensus Protocol (New P2P Design)

NEW ARCHITECTURE: Proactive future host election every 5 minutes. Participants form a virtual ring and rotate who collects NAT data. Every 5 minutes, a new "quorum leader" emerges with complete knowledge and elects the future host. This pre-elected host is announced to all participants so they know who will take over if current host dies.

Benefits:

  • No election delay when host dies (future host already known)
  • Fresh NAT data every 5 minutes (not stale)
  • Automatic rotation ensures fair load (each participant gets a turn)
  • Ring topology enables P2P coordination without central ACDS
 acip_participant_list_t
 acip_participant_entry_t
 acip_ring_collect_t

ACDS Protocol Constants

#define ACIP_SESSION_EXPIRATION_MS   (24ULL * 60 * 60 * 1000)
 Maximum session string length (e.g., "swift-river-mountain" = 20 chars).
#define ACIP_DISCOVERY_DEFAULT_PORT   OPT_ACDS_PORT_INT_DEFAULT
 Discovery server default port (use OPT_ACDS_PORT_INT_DEFAULT from options.h).
#define ACIP_HOST_DEFAULT_PORT   OPT_PORT_INT_DEFAULT
 Default port for discovery mode hosts (use OPT_PORT_INT_DEFAULT from options.h).
#define ACDS_OFFICIAL_SERVER_HOSTNAME   "discovery-service.ascii-chat.com"
 Official ACDS server hostname (automatic HTTPS key trust).

Detailed Description

🔍 ascii-chat Discovery Service for session management and NAT traversal

ACDS enables clients to discover servers using memorable session strings, provides WebRTC signaling for P2P connections, and handles NAT traversal.

This module defines the binary message formats for the ACIP discovery protocol. All messages use packed structs sent over TCP using the existing ACIP packet infrastructure (packet_header_t + payload).

ACDS Protocol Specification

Protocol Overview

  • Transport: TCP (port 27225 default, configurable)
  • Format: Binary ACIP packets (NOT JSON/HTTP)
  • Packet Structure: packet_header_t (22 bytes) + payload
  • Payload Format: Packed C structs with explicit size fields
  • Byte Order: Little-endian (host byte order on x86/ARM)
  • String Encoding: UTF-8, null-terminated where specified
  • Timestamps: Unix milliseconds (uint64_t)
  • Identifiers: UUIDs as 16-byte binary (not ASCII strings)
  • Packet Type Range: 6000-6199 (session management, discovery, host election)

Packet Header Format (22 bytes)

Offset Size Field Value/Description
------ ---- ----- -----------------
0 8 magic 0xA5C11C4A1 ("ASCIICHAT" in hex)
8 2 type 6000-6199 (ACIP packet type enum)
10 4 length Payload length (0-2097152 bytes)
14 4 crc32 CRC32 of payload bytes only
18 4 client_id Client identifier (0 if not assigned)
------
Total: 22 bytes + payload_length bytes

Version Information

  • ACDS Protocol Version: 1.0
  • ACIP Protocol Version: 1.0
  • Release Date: January 2026
  • Status: Production
  • Backward Compatibility: Version 1.0 is locked to 1.0 (no negotiation)

Session Lifecycle

Creation Phase:

  1. Client sends SESSION_CREATE (host public key + signature)
  2. Server generates session_id, expires_at (now + 24hrs)
  3. Server returns SESSION_CREATED (session_id, session_string, STUN/TURN servers)

Discovery Phase:

  1. Client sends SESSION_LOOKUP (session_string)
  2. Server returns SESSION_INFO (metadata, but NOT server IP/port)

Join Phase:

  1. Client sends SESSION_JOIN (credentials: password or Ed25519 signature)
  2. Server verifies credentials in database
  3. Server returns SESSION_JOINED (server IP/port, TURN credentials)
  4. Server broadcasts PARTICIPANT_JOINED to all session members

P2P Negotiation (Discovery mode only):

  1. Participants exchange WEBRTC_SDP (offers/answers)
  2. Participants exchange WEBRTC_ICE (candidates)
  3. Peers discover NAT quality, elect host, establish P2P connection

Disconnect Phase:

  1. Client sends SESSION_LEAVE
  2. Server removes participant from roster
  3. Server broadcasts PARTICIPANT_LEFT to remaining members
  4. Server sends SESSION_END when last participant leaves

Authentication Methods

  • Password: Argon2id hash (128 bytes) stored server-side
  • Ed25519: Client signs (type || timestamp || payload) with private key
  • Replay Protection: Timestamp validation (±5 minute window)

Field Meanings

  • session_id: UUID (16 bytes) generated by server, globally unique
  • session_string: Human-readable identifier (e.g., "swift-river-mountain")
  • participant_id: UUID per session member, tracks individuals
  • capabilities: Bitfield (bit 0=video, bit 1=audio)
  • session_type: 0=DIRECT_TCP (host IP revealed), 1=WEBRTC (P2P mesh)

PROTOCOL DESIGN:

  • Raw TCP transport (port 27225 default)
  • Binary ACIP packets (NOT JSON)
  • Reuses existing crypto handshake (CRYPTO_KEY_EXCHANGE_*, CRYPTO_AUTH_*)
  • Ed25519 identity signatures for session authentication
  • Ephemeral sessions (24-hour expiration)

MESSAGE STRUCTURE:

All ACDS messages follow the standard ACIP packet structure:

  • Header: packet_header_t (magic, type, length, CRC32, client_id)
  • Payload: Message-specific packed struct (defined here)

INTEGRATION WITH OTHER MODULES:

  • network/acip/protocol.h: Defines ACIP packet types (6000-6199)
  • network/packet.h: Provides packet_header_t infrastructure (header, CRC, etc.)
  • src/acds/: ACDS server implementation
  • lib/network/acip/: Protocol handlers and transports
Note
All structures are packed with attribute((packed)) for wire format.
Payload sizes include both fixed and variable-length portions.
String fields are null-terminated UTF-8 (not length-prefixed)
UUID fields are 16 bytes of raw binary data (not ASCII strings)
All numeric fields are little-endian
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
January 2026
Version
1.0 (ACIP/ACDS Protocol Specification)

ascii-chat Discovery Service (ACDS)

Overview

Welcome to ACDS—the magic that makes ascii-chat "just work" without dealing with networking headaches!

The Problem: Running a video chat server should be as easy as starting a Zoom call. But networking is complicated:

  • Port forwarding: Most home routers block incoming connections, requiring manual router configuration
  • IP addresses: You need to know your public IP and communicate it to friends—tedious and error-prone
  • NAT traversal: Symmetric NAT makes peer-to-peer connections nearly impossible without help
  • Firewalls: Corporate and university networks often block non-standard ports

The ACDS Solution: Instead of dealing with IP addresses and ports, you get:

Three-word session strings like purple-mountain-lake that uniquely identify your session. Share those three words and people can join—no IP addresses, no port forwarding, no network configuration.

ACDS transforms ascii-chat from a LAN-only toy into a production-ready video conferencing system that works anywhere, for anyone.

Implementation: src/discovery-service/, src/discovery/, and lib/discovery/.

What makes ACDS powerful?

  • Human-friendly: Share "happy-sunset-ocean" instead of "73.251.42.118:27224"
  • NAT traversal support: Supplies signaling and ICE configuration; peers determine whether direct, STUN, or TURN connectivity succeeds
  • Transport-aware setup: Stores and relays the endpoint metadata needed to establish TCP, WebSocket, WebTransport, or WebRTC connections
  • mDNS for local: Zero-config on LANs—no internet/server required
  • Privacy-first: ACDS never sees your media—only exchanges connection metadata
  • Open protocol: Run your own ACDS server for complete privacy

Architecture

Core Components

ACDS consists of several tightly integrated components:

Discovery Server

Files: src/discovery-service/main.c, src/discovery-service/server.c

The main ACDS server that:

  • Listens for TCP connections on port 27225 (default)
  • Handles session creation, lookup, and join requests
  • Relays WebRTC signaling (SDP offers/answers, ICE candidates)
  • Manages rate limiting to prevent abuse
  • Runs cleanup threads for expired sessions

Execution Model:

  • The shared network_server_t drives listeners and connection callbacks.
  • Packet callbacks run serially per connection outside backend event loops.
  • Cleanup and rate-limit maintenance retain their own background work where the implementation requires it; ACDS does not create one receive thread per client.

Key Functions:

// Initialize ACDS server
// Run server (blocking until shutdown)
asciichat_error_t acds_server_run(acds_server_t *server);
// Graceful shutdown
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
void acds_server_shutdown(acds_server_t *server)
Shutdown discovery server.
asciichat_error_t acds_server_init(acds_server_t *server, const acds_config_t *config)
acds server is intentionally a small, concrete record. Fields such as network_server,...
Discovery server configuration.
Discovery server state.

Session Database

File: lib/acds/database.c, lib/acds/database.h

SQLite-based session storage:

  • Sessions table: session_id, session_string, host_pubkey, password_hash, participants, capabilities
  • Participants table: participant_id, session_id, identity_pubkey, joined_at
  • Rate events table: IP address, event type, timestamp for rate limiting
  • WAL mode: Write-Ahead Logging for concurrent read performance

Database Schema:

CREATE TABLE sessions (
session_id BLOB PRIMARY KEY,
session_string TEXT UNIQUE NOT NULL,
host_pubkey BLOB NOT NULL,
password_hash TEXT,
max_participants INTEGER DEFAULT 4,
current_participants INTEGER DEFAULT 0,
capabilities INTEGER DEFAULT 3, -- video + audio
has_password INTEGER DEFAULT 0,
expose_ip_publicly INTEGER DEFAULT 0,
session_type INTEGER DEFAULT 0, -- DirectTCP or WebRTC
server_address TEXT,
server_port INTEGER DEFAULT 0,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE TABLE participants (
participant_id BLOB PRIMARY KEY,
session_id BLOB NOT NULL,
identity_pubkey BLOB NOT NULL,
joined_at INTEGER NOT NULL,
FOREIGN KEY (session_id) REFERENCES sessions(session_id) ON DELETE CASCADE
);

Key Functions:

// Database lifecycle
asciichat_error_t database_init(const char *db_path, sqlite3 **db);
void database_close(sqlite3 *db);
// Session operations
const acds_config_t *config, acip_session_created_t *resp);
asciichat_error_t database_session_lookup(sqlite3 *db, const char *session_string,
const acds_config_t *config, acip_session_info_t *resp);
const acds_config_t *config, acip_session_joined_t *resp);
const uint8_t participant_id[16]);
// Maintenance
asciichat_error_t database_session_lookup(sqlite3 *db, const char *session_string, const acds_config_t *config, acip_session_info_t *resp)
Lookup session by string.
asciichat_error_t database_session_join(sqlite3 *db, const acip_session_join_t *req, const acds_config_t *config, acip_session_joined_t *resp)
Join existing session.
asciichat_error_t database_session_leave(sqlite3 *db, const uint8_t session_id[16], const uint8_t participant_id[16])
Leave session.
void database_close(sqlite3 *db)
Close database.
asciichat_error_t database_session_create(sqlite3 *db, const acip_session_create_t *req, const acds_config_t *config, acip_session_created_t *resp)
Create new session.
asciichat_error_t database_init(const char *db_path, sqlite3 **db)
Initialize database and create schema.
void database_session_cleanup_expired(sqlite3 *db)
Clean up inactive sessions.
unsigned char uint8_t
acip_session_join_t
Definition acds.h:408
acip_session_joined_t
Definition acds.h:479
acip_session_created_t
Definition acds.h:274
acip_session_create_t
Definition acds.h:226
acip_session_info_t
Definition acds.h:360
uint8_t session_id[SESSION_ID_SIZE]
uint8_t participant_id[SESSION_ID_SIZE]

WebRTC Signaling

File: src/acds/signaling.c, src/acds/signaling.h

Pure relay server for WebRTC signaling—no media processing:

  • Relays SDP offers/answers between participants
  • Relays ICE candidates for P2P connection establishment
  • Supports unicast (to specific participant) and broadcast (to all in session)
  • Uses participant_id → socket mapping from TCP server registry

Key Functions:

// Relay SDP offer/answer
const acip_webrtc_sdp_t *sdp, size_t total_packet_len);
// Relay ICE candidate
const acip_webrtc_ice_t *ice, size_t total_packet_len);
// Broadcast to all participants in session
const uint8_t session_id[16], packet_type_t packet_type,
const void *packet, size_t packet_len);
acip_webrtc_ice_t
Definition acds.h:655
acip_webrtc_sdp_t
Definition acds.h:609
packet_type_t
Network protocol packet type enumeration.
Definition packet.h:315
struct tcp_server tcp_server_t
asciichat_error_t signaling_relay_ice(sqlite3 *db, network_server_t *network_server, const acip_webrtc_ice_t *ice, size_t total_packet_len)
Relay ICE candidate to recipient.
Definition signaling.c:174
asciichat_error_t signaling_relay_sdp(sqlite3 *db, network_server_t *network_server, const acip_webrtc_sdp_t *sdp, size_t total_packet_len)
Relay SDP offer/answer to recipient.
Definition signaling.c:132
asciichat_error_t signaling_broadcast(sqlite3 *db, network_server_t *network_server, const uint8_t session_id[SESSION_ID_SIZE], packet_type_t packet_type, const void *packet, size_t packet_len, const uint8_t *exclude_participant_id)
Broadcast packet to all session participants.
Definition signaling.c:213
The useful part of tcp server is in event_loop, listen_socket, listen_socket6, running: together they...

Identity Management

File: lib/acds/identity.c, lib/acds/identity.h

Ed25519 identity key management for ACDS server:

  • Auto-generates identity key on first run
  • Loads existing key from the configured discovery identity path
  • Computes SHA256 fingerprint for display
  • Cross-platform key storage (Unix and Windows paths)

Key Functions:

// Key lifecycle
asciichat_error_t acds_identity_generate(uint8_t public_key[32], uint8_t secret_key[64]);
asciichat_error_t acds_identity_load(const char *path, uint8_t public_key[32], uint8_t secret_key[64]);
asciichat_error_t acds_identity_save(const char *path, const uint8_t public_key[32],
const uint8_t secret_key[64]);
// Display
void acds_identity_fingerprint(const uint8_t public_key[32], char fingerprint[65]);
asciichat_error_t acds_identity_default_path(char *path_out, size_t path_size);
asciichat_error_t acds_identity_load(const char *path, uint8_t public_key[32], uint8_t secret_key[64])
Load identity from file.
Definition identity.c:36
void acds_identity_fingerprint(const uint8_t public_key[32], char fingerprint[(32 *2+1)])
Compute SHA256 fingerprint of public key.
Definition identity.c:131
asciichat_error_t acds_identity_default_path(char *path_out, size_t path_size)
Get default identity file path for current platform.
Definition identity.c:151
asciichat_error_t acds_identity_save(const char *path, const uint8_t public_key[32], const uint8_t secret_key[64])
Save identity to file.
Definition identity.c:88
asciichat_error_t acds_identity_generate(uint8_t public_key[32], uint8_t secret_key[64])
Generate new Ed25519 keypair.
Definition identity.c:22

Session Strings

File: lib/acds/strings.c, lib/acds/strings.h

Human-friendly session identifier generation:

  • Format: adjective-noun-noun (e.g., bright-forest-river)
  • ~100 adjectives, ~100 nouns = 1,000,000+ unique combinations
  • Cryptographically random selection via libsodium
  • Easy to speak, remember, and type without errors

Key Functions:

// Initialize generator (requires sodium_init())
// Generate random session string
asciichat_error_t acds_string_generate(char *output, size_t output_size);
// Validate session string (format + dictionary)
bool is_session_string(const char *str);
asciichat_error_t acds_string_init(void)
Initialize session string system with cached word validation.
bool is_session_string(const char *str)
Check if a string is a valid session string.
asciichat_error_t acds_string_generate(char *output, size_t output_size)
Generate random session string.

Validation Rules (enforced by is_session_string()):

  • Only lowercase ASCII letters and hyphens allowed
  • Exactly 2 hyphens separating 3 words (adjective-noun-noun format)
  • First word must be a valid adjective from wordlist (2500 adjectives)
  • Second and third words must be valid nouns from wordlist (5000 nouns)
  • Each word is 2-12 characters
  • No consecutive hyphens
  • Cannot start or end with hyphen
  • Length 5-47 characters

Protocol

Packet Flow

ACDS uses the ACIP (ascii-chat Internet Protocol) packet format over TCP.

Session Creation Flow:

Server ACDS
| |
|--- ACIP_SESSION_CREATE --------------->| (identity, capabilities, max_participants)
| | [Rate limit check]
| | [Signature verification (optional)]
| | [IP reachability check (Direct TCP)]
| | [Generate session_string]
|<-- ACIP_SESSION_CREATED ---------------| (session_string, STUN/TURN servers)
| |

Session Join Flow:

Client ACDS
| |
|--- ACIP_SESSION_LOOKUP --------------->| (session_string)
| | [Rate limit check]
|<-- ACIP_SESSION_INFO ------------------| (found, capabilities, has_password)
| |
|--- ACIP_SESSION_JOIN ----------------->| (session_string, identity, password)
| | [Rate limit check]
| | [Signature verification (optional)]
| | [Password verification (if required)]
|<-- ACIP_SESSION_JOINED ----------------| (participant_id, server_address, TURN creds)
| |

WebRTC Signaling Flow:

Client A ACDS Client B
| | |
|--- WEBRTC_SDP ------>| | (SDP offer)
| |--- WEBRTC_SDP ---->| (relay to recipient)
| | |
| |<-- WEBRTC_SDP ----| (SDP answer)
|<-- WEBRTC_SDP -------| | (relay to sender)
| | |
|--- WEBRTC_ICE ------>| | (ICE candidates)
| |--- WEBRTC_ICE --->| (relay)
| | |

Packet Types

ACDS handles these ACIP packet types:

Packet Type Direction Description
ACIP_SESSION_CREATE Client→ACDS Create new session
ACIP_SESSION_CREATED ACDS→Client Session created response
ACIP_SESSION_LOOKUP Client→ACDS Query session info
ACIP_SESSION_INFO ACDS→Client Session info response
ACIP_SESSION_JOIN Client→ACDS Join existing session
ACIP_SESSION_JOINED ACDS→Client Join response with connection info
ACIP_SESSION_LEAVE Client→ACDS Leave session
ACIP_WEBRTC_SDP Client↔ACDS SDP offer/answer relay
ACIP_WEBRTC_ICE Client↔ACDS ICE candidate relay
ACIP_ERROR ACDS→Client Error response

NAT Traversal Technologies

ACDS leverages multiple NAT traversal techniques to maximize connectivity:

UPnP (Universal Plug and Play)

  • Automatic port forwarding via miniupnpc library
  • Enables direct TCP connections (lowest latency)
  • Opt in with --port-forwarding in server, discovery-service, client, or discovery modes
  • Maps active TCP and WebSocket listeners to the gateway-selected LAN address
  • Maps a reserved UDP port for each native WebRTC peer before ICE gathering
  • Requests a one-hour lease, renews halfway through the granted lease, and removes mappings on clean shutdown
  • Reports disabled, discovering, mapped, or unavailable status in the logs
  • Loopback-only and IPv6-only listeners do not request IPv4 mappings

A mapping is not an external reachability test. Double NAT, CGNAT, or a host firewall may still prevent incoming connections. Conversely, mapping failure does not prevent direct connections through an existing manual forwarding rule. The discovery service itself still needs a reachable TCP/WebSocket endpoint; it does not gain a WebRTC fallback merely because router mapping failed. Private-WAN mappings remain locally usable but do not select Direct TCP for discovery; those sessions retain WebRTC setup. Quality probes made before discovery host selection do not modify the router. Listener mappings share the server lifecycle; UDP mappings belong to their WebRTC peer connection and are removed when it closes. Native WebRTC binds its ICE socket to the mapped IPv4 interface and port. STUN discovers and advertises that endpoint; normal ICE checks still select the connection path. Mapping failure leaves normal ICE/STUN/TURN available. Relay-only peers skip mapping. Browser peers do not create router mappings themselves. Recreate the peer connection after changing networks.

NAT-PMP (NAT Port Mapping Protocol)

  • Apple's alternative to UPnP
  • Common on Apple routers and some enterprise equipment
  • Also enables direct TCP connections
  • Supported via libnatpmp integration

WebRTC (ICE/STUN/TURN)

  • STUN: Discovers public IP/port mapping through NAT
  • ICE: Negotiates P2P connection through NAT using candidate gathering
  • TURN: Provides relay fallback when P2P fails (when configured and reachable)
  • WebRTC DataChannels provide reliable data transfer

Connection Priority: Transport negotiation chooses a compatible endpoint. ACDS does not promise a fixed priority or that TURN is reachable; direct connectivity, ICE/STUN, and TURN are inputs to the negotiated result.

mDNS Support (Local Network Discovery)

ACDS also supports mDNS (multicast DNS) for local network discovery:

# Server announces on local network
ascii-chat server --mdns
# Client discovers servers automatically
ascii-chat client --mdns

How it works:

  • ACDS server advertises as _ascii-chat-discovery-service._tcp.local
  • Clients can discover ACDS servers on the LAN without knowing their IP
  • Zero-configuration for local sessions
  • No internet connectivity required

Security

Identity Verification

ACDS supports optional Ed25519 identity verification:

Server Identity (--require-server-identity):

  • Servers must sign their SESSION_CREATE request with Ed25519
  • Prevents impersonation attacks
  • Signature covers: timestamp, capabilities, max_participants

Client Identity (--require-client-identity):

  • Clients must sign their SESSION_JOIN request with Ed25519
  • Enables client whitelisting
  • Signature covers: timestamp, session_string

Timestamp Validation:

  • All signed requests include Unix timestamp
  • 5-minute window for replay attack protection
  • Prevents captured requests from being replayed later

Privacy Protection

IP Address Protection:

  • By default, server IP is NOT revealed to clients
  • IP revealed only when:
    • Password authentication succeeds, OR
    • Server explicitly opts in with expose_ip_publicly flag
  • Prevents IP harvesting attacks

ACDS Never Sees Media:

  • Only exchanges connection metadata (IPs, ports, session strings)
  • All media flows directly between peers using ACIP encryption
  • ACDS doesn't decrypt, proxy, or store media content

Rate Limiting

ACDS implements rate limiting to prevent abuse:

  • SESSION_CREATE: Max 10 per hour per IP
  • SESSION_LOOKUP: Max 60 per minute per IP
  • SESSION_JOIN: Max 30 per minute per IP
  • Events stored in SQLite with automatic cleanup (1 hour retention)
  • Rate limit exceeded returns ACIP_ERROR packet

Configuration

Command-Line Options

Run ascii-chat discovery-service --help (or ascii-chat acds --help) for the complete option list:

Network Options:

  • -p --port PORT: TCP listen port (default: 27225)
  • [address] [address]: IPv4 and/or IPv6 bind addresses (default: 127.0.0.1 ::1)

Database & Identity:

  • -d --database PATH: SQLite database file path (default: ~/.ascii-chat/discovery.db)
  • -k --key PATH: Ed25519 identity key file path (default: ~/.ascii-chat/discovery_identity)

Security Policies:

  • -S --require-server-identity: Require servers to provide signed identity
  • -C --require-client-identity: Require clients to provide signed identity
  • -V --require-server-verify: Require servers to verify client identity during handshake
  • -c --require-client-verify: Require clients to verify server identity during handshake

WebRTC Configuration:

  • --stun-servers LIST: Comma-separated STUN server URLs
  • --turn-servers LIST: Comma-separated TURN server URLs
  • --turn-username USER: Username for TURN server authentication
  • --turn-credential PASS: Credential/password for TURN server authentication
  • --turn-secret SECRET: Shared secret for dynamic TURN credential generation (HMAC-SHA1)
  • --port-forwarding: Enable UPnP/NAT-PMP for automatic router port mapping

Usage Examples

# Run the discovery service on all interfaces
ascii-chat discovery-service 0.0.0.0 :: --port 27225
# Run with custom database and identity key
ascii-chat discovery-service --database /var/lib/acds/sessions.db --key /etc/acds/identity.key
# Run with strict identity requirements
ascii-chat discovery-service --require-server-identity --require-client-identity
# Run with debug logging
ascii-chat -V --log-level debug discovery-service --port 27225
# Run with custom STUN/TURN servers
ascii-chat discovery-service \
--stun-servers "stun:stun.example.com:3478,stun:stun.l.google.com:19302" \
--turn-servers "turn:turn.example.com:3478" \
--turn-username myuser --turn-credential mypassword

Integration with Client and Server

Server Integration

When starting an ascii-chat server with ACDS registration:

# Server registers with ACDS and gets a session string
ascii-chat server --acds --acds-server acds.example.com --acds-port 27225
# Server displays session string for users to share
# "Session: happy-sunset-ocean"

Server Registration Process:

  1. Server sends ACIP_SESSION_CREATE to ACDS
  2. ACDS generates unique session_string and stores session info
  3. ACDS returns session_string and STUN/TURN servers
  4. Server displays session_string to user
  5. Server maintains keepalive with ACDS

Client Integration

When connecting to an ascii-chat server via ACDS:

# Client looks up session and connects
ascii-chat client happy-sunset-ocean
# Or with explicit ACDS server
ascii-chat client happy-sunset-ocean --acds-server acds.example.com

Client Connection Process:

  1. Client sends ACIP_SESSION_LOOKUP to ACDS
  2. If session found, client sends ACIP_SESSION_JOIN
  3. ACDS returns server address/port (if allowed) or TURN credentials
  4. Client attempts connection:
    • Direct TCP to server_address:server_port (if available)
    • WebRTC P2P via ICE/STUN (if direct fails)
    • TURN relay (fallback)

Error Handling

ACDS returns standardized error codes via ACIP_ERROR packets:

Error Code Meaning
ERROR_SESSION_NOT_FOUND Invalid session string
ERROR_SESSION_FULL Session at max capacity
ERROR_INVALID_PASSWORD Password verification failed
ERROR_CRYPTO_VERIFICATION Signature verification failed
ERROR_RATE_LIMITED Too many requests from IP
ERROR_INVALID_PARAM Malformed request

ACDS Deployment & Operation

Official ACDS Infrastructure

The official ACDS infrastructure consists of two components:

  1. discovery.ascii-chat.com - Public key distribution website (HTTPS)
  2. discovery-service.ascii-chat.com:27225 - ACDS server (TCP)

Public Key Distribution via HTTPS (discovery.ascii-chat.com):

  • SSH Ed25519 public key: https://discovery.ascii-chat.com/key.pub (OpenSSH format)
  • GPG public key: https://discovery.ascii-chat.com/key.gpg (GPG export format)
  • Both key types are provided as a convenience - clients can use either
  • Keys served over HTTPS for integrity and authenticity
  • HTML landing page displays key fingerprints and usage instructions
  • Plaintext rendering allows users to verify keys manually before downloading

ACDS Server (discovery-service.ascii-chat.com:27225):

  • Default ACDS server address built into ascii-chat client
  • Handles session creation, lookup, join, and WebRTC signaling
  • Operates transparently - no manual configuration needed
  • Uses the Ed25519 keys published at discovery.ascii-chat.com

Client Trust Model:

  • ascii-chat client automatically trusts keys downloaded from discovery.ascii-chat.com over HTTPS
  • Connects to discovery-service.ascii-chat.com:27225 by default for ACDS operations
  • Keys are cached locally and trusted for subsequent connections
  • User verification required if ACDS keys ever change (prevents MITM attacks)
  • Alternative: Users can manually specify ACDS server and keys via command-line flags

Default Behavior (no flags needed):

# Client automatically uses discovery-service.ascii-chat.com:27225
# and trusts keys from discovery.ascii-chat.com
ascii-chat client happy-sunset-ocean
# Or explicitly specify ACDS server and key
ascii-chat client happy-sunset-ocean \
--acds-server discovery-service.ascii-chat.com \
--acds-key https://discovery.ascii-chat.com/key.pub

Manual Key Specification (optional):

# Download and verify SSH key
curl -O https://discovery.ascii-chat.com/key.pub
ssh-keygen -lf key.pub # Verify fingerprint
# Use local key file
ascii-chat client happy-sunset-ocean \
--acds-key ~/.config/ascii-chat/acds_known_keys/discovery.ascii-chat.com.pub

Running Your Own ACDS Server

If you want to run your own ACDS instance for privacy or custom deployments, you should follow the same pattern as the official server:

Public Key Hosting via HTTPS (Required for public ACDS servers):

To make your ACDS server usable by clients, you must host at least one public key over HTTPS at a URL of your choice:

  • Host your ACDS key (SSH Ed25519 or GPG) at any HTTPS URL
  • Examples: https://your-domain.com/acds-key.pub (SSH) or https://your-domain.com/acds.gpg (GPG)
  • You can provide both SSH and GPG keys (like the official server) or just one type
  • HTTPS is required - HTTP is not acceptable for key distribution
  • Serve keys as plaintext so users can verify them in their browser
  • Provide an HTML landing page with key fingerprints and usage instructions

Why HTTPS Key Hosting is Critical:

For third-party ACDS servers, ascii-chat clients will not work unless they can:

  1. Download your public key from your HTTPS URL, OR
  2. Be manually configured with your public key file via --acds-key flag

Note: The official discovery.ascii-chat.com server is special-cased in the client - it automatically trusts keys downloaded from that domain over HTTPS. Your ACDS server will require explicit client configuration.

Client Configuration for Custom ACDS:

Clients connecting to your ACDS server must explicitly trust your key:

# Method 1: Download SSH key from your HTTPS endpoint (recommended)
ascii-chat client session-name \
--acds-server acds.example.com \
--acds-key https://acds.example.com/acds-key.pub
# Or download GPG key from your HTTPS endpoint
ascii-chat client session-name \
--acds-server acds.example.com \
--acds-key https://acds.example.com/acds.gpg
# Method 2: Distribute key file to users manually
ascii-chat client session-name \
--acds-server acds.example.com \
--acds-key /path/to/acds-example-com.pub

IMPORTANT: Without the --acds-key flag, ascii-chat will not connect to third-party ACDS servers. Only the official discovery.ascii-chat.com server has automatic HTTPS key trust built into the client.

Best Practices

For Public ACDS Operators:

  • Host at least one public key (SSH or GPG) over HTTPS - this is mandatory for clients to use your server
  • You can provide both SSH and GPG keys (like discovery.ascii-chat.com) or just one type
  • Serve keys as plaintext for easy browser verification
  • Display key fingerprints on your HTML landing page
  • Document the --acds-key https://your-domain.com/path/to/key flag usage for your server
  • Clients must explicitly configure your key - only discovery.ascii-chat.com has automatic trust
  • Enable identity requirements for production (--require-server-identity, --require-client-identity)
  • Monitor rate limit events for abuse detection
  • Configure appropriate STUN/TURN servers for your region
  • Regular database backups (SQLite file)
  • Consider key rotation policies (with advance user notification)

For Private ACDS Operators (Corporate/Organizational):

  • Distribute ACDS public key via internal documentation or HTTPS
  • Require client/server identity verification (--require-*-identity flags)
  • Run ACDS on internal network (no public internet exposure)
  • Use mDNS for local network discovery where appropriate
  • Implement monitoring and alerting for session activity

For Server Hosts:

  • Enable --port-forwarding for automatic port forwarding
  • Use identity keys for server authentication
  • Consider password-protecting sensitive sessions
  • Don't expose IP publicly unless necessary

For Clients:

  • Verify server identity when possible (--server-key)
  • Use identity keys for authenticated sessions
  • Prefer local mDNS discovery on trusted networks

Service Lifecycle

The ACDS server follows a well-defined lifecycle with distinct phases:

Initialization Phase

Entry Point: acds_main() in src/discovery-service/main.c

Initialization sequence:

  1. Signal Handling: Register SIGINT/SIGTERM handlers for graceful shutdown
  2. Global Context: Initialize the server, transport, and optional UPnP/mDNS contexts
  3. Server Initialization: Call acds_server_init()
    • Load or generate Ed25519 identity keys (stored in ~/.ascii-chat/discovery_identity)
    • Open SQLite database (~/.ascii-chat/discovery.db by default)
    • Create database schema if missing
    • Initialize rate limiter
    • Create the shared network_server_t and its configured listeners
    • Enable UPnP/NAT-PMP port mapping if requested
    • Register mDNS service if enabled
  4. Thread Pool: Create worker thread pool for background tasks
  5. Cleanup Thread: Spawn background cleanup thread
  6. Status Screen: Initialize optional discovery status UI

Running Phase

Main Loop: acds_server_run() in src/discovery-service/server.c

Server runs through the shared event-driven connection layer:

  1. Accept Loop: Let network_server_t accept and drive listeners
  2. Connection Callbacks: Deliver lifecycle and packet callbacks serially outside the backend event loop
  3. Client Processing:
    • Perform the shared crypto handshake
    • Adopt the connection's acip_transport_t
    • Process incoming ACIP packets:
      • SESSION_CREATE/LOOKUP/JOIN - routed to lib/discovery/database.c
      • WEBRTC_SDP/ICE - routed to signaling relay
      • Invalid packets rejected with error response
  4. Connection Cleanup: Stop producers, drain transport callbacks, and release client context
  5. Background Tasks:
    • Cleanup thread runs every 5 minutes
    • Removes old rate limit events from database
    • Cleans up expired sessions
    • Monitors host migrations with timeout detection

Shutdown Phase

Graceful Shutdown: Triggered by SIGINT/SIGTERM or application request

Shutdown sequence in acds_server_shutdown():

  1. Signal Main Loop: Request the shared network server to stop
  2. Stop Accepting: Stop listeners and interrupt pending backend I/O
  3. Drain Connections: Stop producers and wait for transport callbacks
  4. Stop Workers: Join the network server's backend workers
  5. Database Cleanup: Checkpoint and close SQLite database
  6. Resource Cleanup:
    • Release UPnP/NAT-PMP port mappings
    • Deregister mDNS service
    • Free thread pool and memory
  7. Status Display: Shutdown status screen UI

Persistence and Data Management

SQLite as Single Source of Truth

ACDS uses SQLite as the authoritative storage for all persistent data:

Sessions Table (sessions):

  • Indexed by 16-byte session_id (UUID)
  • Stores session metadata: string, host pubkey, capabilities, participant count, max participants
  • Tracks expiration time for automatic cleanup
  • Records whether IP is publicly exposed
  • Stores server address/port for Direct TCP connections

Participants Table (participants):

  • Indexed by 16-byte participant_id (UUID)
  • Foreign key reference to session_id
  • Cascade delete when session expires
  • Stores participant's Ed25519 identity pubkey
  • Records join timestamp

Rate Limit Events Table (rate_events):

  • Tracks request events for rate limiting (IP address, event type, timestamp)
  • Automatic cleanup removes events older than 1 hour
  • Prevents abuse through per-IP rate limiting:
    • SESSION_CREATE: 10 per hour
    • SESSION_LOOKUP: 60 per minute
    • SESSION_JOIN: 30 per minute

Database Features:

  • WAL (Write-Ahead Logging) mode for concurrent read performance
  • Synchronous writes for data integrity
  • Automatic schema migration on first run
  • Efficient queries with proper indexing

Multi-Key Session Creation

ACDS supports multi-key session creation - servers can register with multiple identity keys (e.g., SSH + GPG) in a single session.

Protocol (defined in server.h):

  1. Client sends SESSION_CREATE with first key
    • ACDS generates session_id and stores in pending_session
    • Client enters multi-key creation state: in_multikey_session_create = true
  2. Client sends SESSION_CREATE with second key
    • Key added to pending_session_keys[] array
    • Duplicate detection prevents adding same key twice
  3. Client sends SESSION_CREATE with zero key (empty key field)
    • Finalizes session creation
    • All keys in pending_session_keys[] written to database
    • Session exits multi-key state

Implementation (acds_client_data_t in server.h):

  • in_multikey_session_create: State flag
  • pending_session: Session data from first CREATE request
  • pending_session_keys[]: Array of Ed25519 public keys (up to MAX_IDENTITY_KEYS)
  • num_pending_keys: Count of keys received so far

Restrictions During Multi-Key Creation:

  • Only PING/PONG packets allowed (other commands rejected)
  • Prevents interleaving with other session operations
  • Timeout after 5 minutes automatically clears pending state

Host Migration Management

ACDS tracks host migration events when a session changes its host server.

Migration Tracking (migration_context_t in server.h):

  • session_id: Session undergoing migration
  • migration_start_ns: When migration started (nanoseconds)
  • Array of up to 32 concurrent migrations

Migration Process:

  1. Host picks a future host (every 5 minutes proactively)
  2. Host notifies ACDS of pending migration
  3. New host connects to ACDS and takes over session
  4. ACDS updates database with new host
  5. Migration context tracked until completion
  6. Timeout (configurable, typically 30 seconds) marks migration as failed
  7. database_session_clear_host() clears host on timeout

Cleanup Thread Monitoring (monitor_host_migrations()):

Peer Discovery Integration

ACDS provides both server-side discovery service and integrates with client-side peer discovery:

Server-Side Discovery Service

The ACDS server (src/discovery-service/) enables:

  1. Session Registration: Servers register via SESSION_CREATE
  2. Session Lookup: Clients find servers via SESSION_LOOKUP/SESSION_INFO
  3. Session Join: Clients join via SESSION_JOIN
  4. Fallback Coordination: ACDS provides STUN/TURN servers for WebRTC fallback
  5. Metadata Relay: Participants can relay SDP/ICE through ACDS

Client-Side Discovery Integration

ascii-chat clients use ACDS for:

  1. Session String Resolution: Convert "happy-sunset-ocean" → session metadata
  2. NAT Traversal: Obtain STUN/TURN servers from ACDS
  3. Signaling Relay: Optional relay of WebRTC signaling through ACDS
  4. Address Resolution: Get server address (if allowed) for Direct TCP

Client Connection Sequence:

Client ACDS Server
| | |
|--- SESSION_LOOKUP->| |
|<-- SESSION_INFO ---| |
|--- SESSION_JOIN --->| |
| |-- [identity check]-|
|<-- SESSION_JOINED -| |
|<-- STUN/TURN list -| |
| | |
|-- Try Direct TCP ------->| (if addr provided)
|-- Try WebRTC P2P ------->| (via ICE/STUN)
|-- Try TURN relay ------->| (fallback)

mDNS Local Discovery

ACDS also integrates with mDNS for local network discovery:

  • Server registers as _ascii-chat-discovery-service._tcp.local
  • Clients can discover servers without knowing their IP
  • Useful for LANs where no internet connectivity is available
  • Zero-configuration for local sessions

Implementation Files

Source Files (src/discovery-service/):

  • main.c - ACDS entry point, signal handling, initialization, main loop
  • main.h - Configuration structures and entry point declaration
  • server.c - TCP server implementation, client handlers, migration tracking, cleanup
  • server.h - Server structures, per-client state, migration context
  • signaling.c - WebRTC SDP/ICE relay implementation
  • signaling.h - Signaling relay function declarations

Library Files (lib/discovery/):

  • database.c/h - SQLite operations, session lifecycle, rate limiting
  • session.c - Session data structure helpers
  • identity.c/h - Ed25519 key generation, loading, saving, fingerprinting
  • strings.c/h - Session string generation (adjective-noun-noun)
  • adjectives.c/nouns.c - Word lists for session string generation

Network Protocol (lib/network/acip/):

  • acds.c - ACDS packet parsing and type definitions
  • acds_handlers.c - Packet type handlers (SESSION_*, WEBRTC_*)
  • acds_client.c - Client-side ACDS protocol helpers
  • send.c - ACDS packet sending helpers
  • Transport abstraction uses lib/network/tcp/ for connection handling

Rate Limiting (lib/network/rate_limit/):

See also
Network Protocol
Cryptographic Handshake
Server Architecture
Client Architecture

Macro Definition Documentation

◆ ACDS_OFFICIAL_SERVER_HOSTNAME

#define ACDS_OFFICIAL_SERVER_HOSTNAME   "discovery-service.ascii-chat.com"

#include <include/ascii-chat/network/acip/acds.h>

Official ACDS server hostname (automatic HTTPS key trust).

Used by:

Single source of truth to avoid duplication across headers.

Definition at line 1115 of file acds.h.

◆ ACIP_DISCOVERY_DEFAULT_PORT

#define ACIP_DISCOVERY_DEFAULT_PORT   OPT_ACDS_PORT_INT_DEFAULT

#include <include/ascii-chat/network/acip/acds.h>

Discovery server default port (use OPT_ACDS_PORT_INT_DEFAULT from options.h).

Definition at line 1102 of file acds.h.

Referenced by acds_client_config_init_defaults(), client_crypto_init(), discovery_main(), and discovery_session_create().

◆ ACIP_HOST_DEFAULT_PORT

#define ACIP_HOST_DEFAULT_PORT   OPT_PORT_INT_DEFAULT

#include <include/ascii-chat/network/acip/acds.h>

Default port for discovery mode hosts (use OPT_PORT_INT_DEFAULT from options.h).

Definition at line 1105 of file acds.h.

Referenced by negotiate_determine_result().

◆ ACIP_SESSION_EXPIRATION_MS

#define ACIP_SESSION_EXPIRATION_MS   (24ULL * 60 * 60 * 1000)

#include <include/ascii-chat/network/acip/acds.h>

Maximum session string length (e.g., "swift-river-mountain" = 20 chars).

Session maximum lifetime (24 hours in milliseconds) Note: Sessions are actually cleaned up after 3 hours of inactivity (last_activity_at), but expires_at serves as an absolute maximum lifetime.

Definition at line 1099 of file acds.h.

Typedef Documentation

◆ __attribute__

struct __attribute__

#include <lib/video/ascii/simd/vector.h>

SESSION_CREATED (PACKET_TYPE_ACIP_SESSION_CREATED) - Session created response.

BROADCAST_ACK (PACKET_TYPE_ACIP_BROADCAST_ACK) - Acknowledge broadcast receipt.

Bandwidth test result packet.

Bandwidth test request packet.

ERROR (PACKET_TYPE_ACIP_ERROR) - Generic error response.

FUTURE_HOST_ELECTED (PACKET_TYPE_ACIP_FUTURE_HOST_ELECTED) - Future host announcement.

HOST_LOST (PACKET_TYPE_ACIP_HOST_LOST) - Host disconnect notification.

HOST_DESIGNATED (PACKET_TYPE_ACIP_HOST_DESIGNATED) - Host assignment.

HOST_ANNOUNCEMENT (PACKET_TYPE_ACIP_HOST_ANNOUNCEMENT) - Host declaration.

NETWORK_QUALITY (PACKET_TYPE_ACIP_NETWORK_QUALITY) - Unified quality metrics.

RING_COLLECT (PACKET_TYPE_ACIP_RING_COLLECT) - NAT quality request.

Participant entry in ring (variable-length data following PARTICIPANT_LIST).

PARTICIPANT_LIST (PACKET_TYPE_ACIP_PARTICIPANT_LIST) - Ordered ring list.

STRING_RELEASE (PACKET_TYPE_ACIP_STRING_RELEASE) - Release string reservation.

STRING_RENEW (PACKET_TYPE_ACIP_STRING_RENEW) - Renew string reservation.

STRING_RESERVED (PACKET_TYPE_ACIP_STRING_RESERVED) - String reservation response.

STRING_RESERVE (PACKET_TYPE_ACIP_STRING_RESERVE) - Reserve a session string.

WEBRTC_ICE (PACKET_TYPE_ACIP_WEBRTC_ICE) - ICE candidate relay.

WEBRTC_SDP (PACKET_TYPE_ACIP_WEBRTC_SDP) - SDP offer/answer relay.

SESSION_RECONNECT (PACKET_TYPE_ACIP_SESSION_RECONNECT) - Reconnect to session.

SESSION_END (PACKET_TYPE_ACIP_SESSION_END) - End session (host only).

SESSION_LEAVE (PACKET_TYPE_ACIP_SESSION_LEAVE) - Leave session.

PARTICIPANT_LEFT (PACKET_TYPE_ACIP_PARTICIPANT_LEFT) - Participant left notification.

PARTICIPANT_JOINED (PACKET_TYPE_ACIP_PARTICIPANT_JOINED) - New participant notification.

SESSION_JOINED (PACKET_TYPE_ACIP_SESSION_JOINED) - Session join response.

SESSION_JOIN (PACKET_TYPE_ACIP_SESSION_JOIN) - Join existing session.

SESSION_INFO (PACKET_TYPE_ACIP_SESSION_INFO) - Session info response.

SESSION_LOOKUP (PACKET_TYPE_ACIP_SESSION_LOOKUP) - Lookup session by string.

Direction: Discovery Server -> Client

Payload structure (fixed + variable):

  • Fixed part: acip_session_created_t (90 bytes)
  • Variable part: stun_server_t[stun_count] + turn_server_t[turn_count]

Packet Format

Offset Size Field Value/Description
------ ---- ----- -----------------
0 1 session_string_len Length of generated/provided string
1 48 session_string Session ID string (null-padded)
49 16 session_id UUID bytes (generated by server)
65 16 participant_id Creator's participant UUID
81 8 expires_at Unix ms (session creation + 24 hours)
89 1 stun_count Number of STUN servers (0-N)
90 1 turn_count Number of TURN servers (0-N)
------
Total: 91 bytes + STUN/TURN server data

STUN/TURN Servers: Followed by packed stun_server_t and turn_server_t structs for WebRTC P2P connectivity behind NAT.

The server responds to SESSION_CREATE with the generated session identifier, session string (either auto-generated or the provided reserved string), and optional STUN/TURN server information for WebRTC connectivity.

The creator is assigned a participant_id and is considered the session initiator (controls session settings in discovery mode).

Note
STUN server configuration (stun_server_t) is defined in networking/webrtc/stun.h
TURN server configuration (turn_server_t) is defined in networking/webrtc/turn.h

Direction: Client -> Discovery Server

Packet Format

Offset Size Field Value/Description
------ ---- ----- -----------------
0 1 session_string_len Length of query string
1 48 session_string Session ID string to lookup
------
Total: 49 bytes

The client queries for session information using the session string. Server responds with SESSION_INFO containing basic session metadata (but NOT the server connection information, which is only revealed after successful authentication via SESSION_JOIN).

Security Note: Server does NOT reveal host IP in SESSION_INFO response, preventing information leakage to non-members.

Direction: Discovery Server -> Client

Packet Format

Offset Size Field Value/Description
------ ---- ----- -----------------
0 1 found 0=not found, 1=found
1 16 session_id UUID (valid if found=1)
17 32 host_pubkey Ed25519 public key of host
49 1 capabilities Bit 0=video, Bit 1=audio
50 1 max_participants Maximum allowed participants
51 1 current_participants Current count (may increase during lookup)
52 1 session_type 0=DIRECT_TCP, 1=WEBRTC
53 1 has_password 0=open, 1=password required
54 8 created_at Unix ms (session creation time)
62 8 expires_at Unix ms (24 hours after creation)
70 1 require_server_verify ACDS policy flag (host verifies guest)
71 1 require_client_verify ACDS policy flag (guest verifies host)
------
Total: 72 bytes
bool valid
Definition fft.c:29

SECURITY NOTE: Does NOT include server connection information (IP/port). Server address is only revealed after authentication via SESSION_JOIN. This prevents IP address leakage to unauthenticated clients.

Server Verification: If require_server_verify=1, host must verify client identity using Ed25519 signatures.

Direction: Client -> Discovery Server

Payload structure: acip_session_join_t (241 bytes fixed)

Packet Format

Offset Size Field Value/Description
------ ---- ----- -----------------
0 1 session_string_len Length of session string
1 48 session_string Session ID to join
49 32 identity_pubkey Client's Ed25519 public key
81 64 signature Ed25519(type || timestamp || session_string)
145 8 timestamp Unix ms (replay protection, ±5min window)
153 1 has_password 0=no password, 1=password provided
154 128 password Cleartext password (TLS protects wire)
------
Total: 282 bytes

Authentication Methods:

  • Identity Signature: Client signs (type || timestamp || session_string) with Ed25519
  • Password: Optional additional requirement, stored as Argon2id hash on server
  • Replay Protection: Timestamp must be within ±5 minute window of server time

Response: Server verifies credentials and responds with SESSION_JOINED containing server IP:port and TURN credentials.

The client requests to join an existing session, providing identity proof via Ed25519 signature and optionally a password. Server responds with SESSION_JOINED containing server connection information upon successful authentication.

Direction: Discovery Server -> Client

Packet Format (Variable Length)

Offset Size Field Value/Description
------ ---- ----- -----------------
0 1 success 0=failed, 1=joined
1 1 error_code Error code if success=0
2 128 error_message Human-readable error (null-terminated)
130 16 participant_id Client's new UUID (if success=1)
146 16 session_id Session UUID
162 16 initiator_id Session creator's UUID
178 1 host_established 0=negotiate, 1=host exists
179 16 host_id Host's UUID (if host_established=1)
195 1 peer_count Number of peers (if host_established=0)
196 N*16 peer_ids[] Variable: peer UUIDs (N*16 bytes)
(196+N*16) 1 session_type 0=DIRECT_TCP, 1=WEBRTC (if success=1)
(197+N*16) 64 server_address Host IP/hostname (if success=1)
(261+N*16) 2 server_port Host TCP port (if success=1)
(263+N*16) 128 turn_username TURN auth user (if session_type=WEBRTC)
(391+N*16) 128 turn_password TURN auth pass (if session_type=WEBRTC)
------
Total: 519+ bytes (variable based on peer_count)

CRITICAL SECURITY: Server connection information (IP/port) is ONLY revealed after successful authentication (password verification or identity verification). This prevents IP address leakage to unauthenticated clients who only know the session string.

HOST NEGOTIATION: When host_established == 0, the joiner must negotiate with existing peers to determine who becomes the host. When host_established == 1, the joiner can connect directly to the established host.

TURN Credentials: RFC 5766 time-limited credentials for NAT traversal. Format: "timestamp:session_id" and HMAC-SHA1(secret, username).

Direction: Discovery Server -> Existing Participants

Sent to all existing participants when a new participant joins the session. In discovery mode, this triggers NAT quality exchange and host negotiation between the new joiner and existing participants.

Direction: Discovery Server -> Remaining Participants

Sent to remaining participants when someone leaves the session (gracefully or timeout). If the leaving participant was the host, this triggers host migration.

Direction: Client -> Discovery Server

The client gracefully leaves a session, allowing the server to update participant count and potentially notify other participants.

Direction: Host -> Discovery Server

The session host terminates the session, preventing new joins and notifying all participants. Requires signature proof of host identity.

Direction: Client -> Discovery Server

The client reconnects to a session after disconnection, using stored participant ID and identity proof to resume participation.

Direction: Bidirectional (relayed through discovery server)

Payload structure (fixed + variable):

  • Fixed: acip_webrtc_sdp_t (50 bytes minimum)
  • Variable: sdp_data (SDP string, null-terminated)

Packet Format

Offset Size Field Value/Description
------ ---- ----- -----------------
0 16 session_id Session UUID
16 16 from_id Sender's participant UUID
32 16 to_id Recipient's participant UUID (or all if broadcast)
48 2 sdp_len Length of SDP data (0-2MB)
50 N sdp_data UTF-8 SDP string (null-terminated)
------
Total: 50 + sdp_len bytes

SDP Format: RFC 4566 Session Description Protocol

  • Offer: Media offer with local capabilities
  • Answer: Media answer matching peer capabilities
  • Both include ICE ufrag/pwd for candidate exchange

WebRTC session description protocol messages are relayed through the discovery server to facilitate peer-to-peer connection establishment.

Direction: Bidirectional (relayed through discovery server)

Payload structure (fixed + variable):

  • Fixed: acip_webrtc_ice_t (50 bytes minimum)
  • Variable: candidate (ICE candidate string, null-terminated)

Packet Format

Offset Size Field Value/Description
------ ---- ----- -----------------
0 16 session_id Session UUID
16 16 sender_id Sender's participant UUID
32 16 recipient_id Recipient's participant UUID
48 2 candidate_len Length of ICE candidate (0-512)
50 N candidate UTF-8 ICE candidate (null-terminated)
------
Total: 50 + candidate_len bytes

ICE Candidate Format: RFC 5245 Interactive Connectivity Establishment

  • Example: "candidate:1 1 udp 2122260223 192.168.1.100 54321 typ host"
  • Contains: foundation, component, transport, priority, address, port, type
  • Relayed candidate: includes related-address/port for NAT-mapped endpoints

Candidate Types:

  • host: Local machine (non-NATted)
  • srflx: Server reflexive (STUN-discovered)
  • prflx: Peer reflexive (discovered via STUN from peer)
  • relay: TURN-relayed candidate

WebRTC ICE candidates are relayed through the discovery server to facilitate NAT traversal during peer-to-peer connection establishment.

Direction: Client -> Discovery Server

FUTURE FEATURE: Reserve a memorable session string for future use, preventing others from using it for a specified duration.

Direction: Discovery Server -> Client

FUTURE FEATURE: Confirms successful string reservation or reports error.

Direction: Client -> Discovery Server

FUTURE FEATURE: Extends an existing string reservation before expiration.

Direction: Client -> Discovery Server

FUTURE FEATURE: Voluntarily releases a reserved string before expiration.

Direction: ACDS -> All Participants

Broadcast by ACDS after session join or when participant joins/leaves. Lists all participants in deterministic ring order (by join time or participant ID). Participants use this to determine:

  • My position in the ring
  • Who is next in ring (for NAT collection)
  • Who is quorum leader this round (last in rotation)

Follows acip_participant_list_t in packet payload. Array of num_participants entries.

Direction: Previous Participant -> Next Participant (via direct connection)

Sent during ring rotation to request NAT quality from next participant. Forms the "spoke" of the ring, where one participant collects from all others.

During each 5-minute round:

  • Participant[0] connects to Participant[1], gets NAT data
  • Participant[1] connects to Participant[2], gets NAT data
  • ... (continues around ring)
  • Participant[N-1] has all NAT data, runs election, announces future host

Direction: Participant -> Others (via ring collection, WebRTC signaling, or direct P2P)

NEW DESIGN: Unified packet for all network quality metrics, replacing separate NAT_QUALITY, HOST_LOST NAT fields, etc. Used in three contexts:

  1. Initial Negotiation (during host selection before session established)
    • Exchanged between first two participants to determine initial host
  2. Ring Collection (proactive, every 5 minutes)
    • Quorum leader collects from all participants for future host election
    • Fresh NAT data ensures optimal host selection
    • Participants know future host before current host dies
  3. Migration Recovery (if current host dies unexpectedly)
    • Participants exchange fresh NETWORK_QUALITY if pre-elected future host unavailable
    • Enables fallback re-election

Direction: Participant -> ACDS

Sent by the participant who won host negotiation to announce they are starting the server. ACDS stores this and includes it in future SESSION_JOINED responses.

Direction: ACDS -> All Participants

Sent by ACDS after receiving HOST_ANNOUNCEMENT to notify all participants who the host is and where to connect.

Direction: Participant -> ACDS

Lightweight notification that a participant detected the host disconnected. NAT quality data is NOT included - migration participants use pre-elected future host instead of re-electing. If future host unavailable, participants can request fresh NETWORK_QUALITY exchange for re-election if needed.

NEW P2P DESIGN: This is now just a notification for ACDS bookkeeping. Actual migration happens peer-to-peer without ACDS involvement - participants connect to pre-elected future host immediately upon detection.

Direction: Quorum Leader -> ACDS -> All Participants

NEW P2P DESIGN: Sent proactively by quorum leader after completing ring consensus (every 5 minutes or when new participant joins). Announces to all participants who will become host if current host dies.

Key Insight: Future host is PRE-ELECTED and stored by everyone. When current host dies, participants don't need to elect - they immediately:

  • Future host: starts hosting (already know they will)
  • Others: connect to future host (address already stored)
  • Total failover time: <500ms (no election!)

This packet is broadcast by ACDS after receiving it from quorum leader, ensuring all participants know the migration plan before host dies.

Direction: Discovery Server -> Client

Generic error response used when no specific response packet type exists. Contains error code and human-readable message.

Sent by client to ACDS to request bandwidth measurement. Client sends this packet followed by test payload data. ACDS measures receive time and calculates upload speed.

Sent by ACDS to client with measured bandwidth results. Includes upload speed (measured by ACDS), download speed (echo test), RTT, jitter, and packet loss metrics.

Direction: Client -> ACDS

Sent by clients to acknowledge receipt of critical broadcast messages (e.g., HOST_DESIGNATED, FUTURE_HOST_ELECTED). ACDS tracks ACKs and retries broadcasts to clients that haven't acknowledged.

< Length of session string (e.g., 20 for "swift-river-mountain")

< Null-padded session string

< UUID as bytes (not string)

< Creator's participant ID (they are a participant too)

< Unix ms (created_at + 24 hours)

< Number of STUN servers

< Number of TURN servers

Definition at line 42 of file vector.h.

Enumeration Type Documentation

◆ acds_session_type_t

#include <include/ascii-chat/network/acip/acds.h>

Session connection type.

Determines how clients connect to the session host:

  • DIRECT_TCP: Clients connect directly to server IP:port (default, requires public IP)
  • WEBRTC: Clients use WebRTC P2P mesh with STUN/TURN (works behind NAT)
Enumerator
SESSION_TYPE_DIRECT_TCP 

Direct TCP connection to server IP:port (default).

SESSION_TYPE_WEBRTC 

WebRTC P2P mesh with STUN/TURN relay.

Definition at line 149 of file acds.h.

149 {
acds_session_type_t
Session connection type.
Definition acds.h:149
@ SESSION_TYPE_WEBRTC
WebRTC P2P mesh with STUN/TURN relay.
Definition acds.h:151
@ SESSION_TYPE_DIRECT_TCP
Direct TCP connection to server IP:port (default).
Definition acds.h:150

◆ acip_connection_type_t

#include <include/ascii-chat/network/acip/acds.h>

Connection type for host announcement.

Enumerator
ACIP_CONNECTION_TYPE_DIRECT_PUBLIC 

Direct public IP connection.

ACIP_CONNECTION_TYPE_UPNP 

UPnP/NAT-PMP port mapping.

ACIP_CONNECTION_TYPE_STUN 

STUN hole-punching.

ACIP_CONNECTION_TYPE_TURN 

TURN relay (fallback).

Definition at line 842 of file acds.h.

842 {
acip_connection_type_t
Connection type for host announcement.
Definition acds.h:842
@ ACIP_CONNECTION_TYPE_TURN
TURN relay (fallback).
Definition acds.h:846
@ ACIP_CONNECTION_TYPE_UPNP
UPnP/NAT-PMP port mapping.
Definition acds.h:844
@ ACIP_CONNECTION_TYPE_DIRECT_PUBLIC
Direct public IP connection.
Definition acds.h:843
@ ACIP_CONNECTION_TYPE_STUN
STUN hole-punching.
Definition acds.h:845

◆ acip_error_code_t

#include <include/ascii-chat/network/acip/acds.h>

ACIP error codes.

Standard error codes returned in ACIP error responses.

Enumerator
ACIP_ERROR_NONE 

No error (success).

ACIP_ERROR_SESSION_NOT_FOUND 

Session does not exist.

ACIP_ERROR_SESSION_FULL 

Session has reached max participants.

ACIP_ERROR_INVALID_PASSWORD 

Password verification failed.

ACIP_ERROR_INVALID_SIGNATURE 

Identity signature invalid.

ACIP_ERROR_RATE_LIMITED 

Too many requests from this IP.

ACIP_ERROR_STRING_TAKEN 

Requested string already reserved.

ACIP_ERROR_STRING_INVALID 

String format invalid.

ACIP_ERROR_INTERNAL 

Internal server error.

Definition at line 1073 of file acds.h.

1073 {
1074 ACIP_ERROR_NONE = 0,
1082 ACIP_ERROR_INTERNAL = 255
acip_error_code_t
ACIP error codes.
Definition acds.h:1073
@ ACIP_ERROR_RATE_LIMITED
Too many requests from this IP.
Definition acds.h:1079
@ ACIP_ERROR_STRING_TAKEN
Requested string already reserved.
Definition acds.h:1080
@ ACIP_ERROR_STRING_INVALID
String format invalid.
Definition acds.h:1081
@ ACIP_ERROR_INTERNAL
Internal server error.
Definition acds.h:1082
@ ACIP_ERROR_INVALID_PASSWORD
Password verification failed.
Definition acds.h:1077
@ ACIP_ERROR_SESSION_NOT_FOUND
Session does not exist.
Definition acds.h:1075
@ ACIP_ERROR_SESSION_FULL
Session has reached max participants.
Definition acds.h:1076
@ ACIP_ERROR_INVALID_SIGNATURE
Identity signature invalid.
Definition acds.h:1078
@ ACIP_ERROR_NONE
No error (success).
Definition acds.h:1074

◆ acip_nat_type_t

#include <include/ascii-chat/network/acip/acds.h>

NAT type classification for host selection.

Enumerator
ACIP_NAT_TYPE_OPEN 

No NAT (public IP).

ACIP_NAT_TYPE_FULL_CONE 

Full cone NAT (easiest to traverse).

ACIP_NAT_TYPE_RESTRICTED 

Address-restricted cone NAT.

ACIP_NAT_TYPE_PORT_RESTRICTED 

Port-restricted cone NAT.

ACIP_NAT_TYPE_SYMMETRIC 

Symmetric NAT (hardest, requires TURN).

Definition at line 830 of file acds.h.

830 {
acip_nat_type_t
NAT type classification for host selection.
Definition acds.h:830
@ ACIP_NAT_TYPE_RESTRICTED
Address-restricted cone NAT.
Definition acds.h:833
@ ACIP_NAT_TYPE_SYMMETRIC
Symmetric NAT (hardest, requires TURN).
Definition acds.h:835
@ ACIP_NAT_TYPE_FULL_CONE
Full cone NAT (easiest to traverse).
Definition acds.h:832
@ ACIP_NAT_TYPE_OPEN
No NAT (public IP).
Definition acds.h:831
@ ACIP_NAT_TYPE_PORT_RESTRICTED
Port-restricted cone NAT.
Definition acds.h:834

Function Documentation

◆ __attribute__()

struct __attribute__ ( (packed) )

#include <include/ascii-chat/network/acip/acds.h>

SESSION_CREATE (PACKET_TYPE_ACIP_SESSION_CREATE) - Create new session.

BROADCAST_ACK (PACKET_TYPE_ACIP_BROADCAST_ACK) - Acknowledge broadcast receipt.

Bandwidth test result packet.

Bandwidth test request packet.

ERROR (PACKET_TYPE_ACIP_ERROR) - Generic error response.

FUTURE_HOST_ELECTED (PACKET_TYPE_ACIP_FUTURE_HOST_ELECTED) - Future host announcement.

HOST_LOST (PACKET_TYPE_ACIP_HOST_LOST) - Host disconnect notification.

HOST_DESIGNATED (PACKET_TYPE_ACIP_HOST_DESIGNATED) - Host assignment.

HOST_ANNOUNCEMENT (PACKET_TYPE_ACIP_HOST_ANNOUNCEMENT) - Host declaration.

NETWORK_QUALITY (PACKET_TYPE_ACIP_NETWORK_QUALITY) - Unified quality metrics.

RING_COLLECT (PACKET_TYPE_ACIP_RING_COLLECT) - NAT quality request.

Participant entry in ring (variable-length data following PARTICIPANT_LIST).

PARTICIPANT_LIST (PACKET_TYPE_ACIP_PARTICIPANT_LIST) - Ordered ring list.

STRING_RELEASE (PACKET_TYPE_ACIP_STRING_RELEASE) - Release string reservation.

STRING_RENEW (PACKET_TYPE_ACIP_STRING_RENEW) - Renew string reservation.

STRING_RESERVED (PACKET_TYPE_ACIP_STRING_RESERVED) - String reservation response.

STRING_RESERVE (PACKET_TYPE_ACIP_STRING_RESERVE) - Reserve a session string.

WEBRTC_ICE (PACKET_TYPE_ACIP_WEBRTC_ICE) - ICE candidate relay.

WEBRTC_SDP (PACKET_TYPE_ACIP_WEBRTC_SDP) - SDP offer/answer relay.

SESSION_RECONNECT (PACKET_TYPE_ACIP_SESSION_RECONNECT) - Reconnect to session.

SESSION_END (PACKET_TYPE_ACIP_SESSION_END) - End session (host only).

SESSION_LEAVE (PACKET_TYPE_ACIP_SESSION_LEAVE) - Leave session.

PARTICIPANT_LEFT (PACKET_TYPE_ACIP_PARTICIPANT_LEFT) - Participant left notification.

PARTICIPANT_JOINED (PACKET_TYPE_ACIP_PARTICIPANT_JOINED) - New participant notification.

SESSION_JOINED (PACKET_TYPE_ACIP_SESSION_JOINED) - Session join response.

SESSION_JOIN (PACKET_TYPE_ACIP_SESSION_JOIN) - Join existing session.

SESSION_INFO (PACKET_TYPE_ACIP_SESSION_INFO) - Session info response.

SESSION_LOOKUP (PACKET_TYPE_ACIP_SESSION_LOOKUP) - Lookup session by string.

SESSION_CREATED (PACKET_TYPE_ACIP_SESSION_CREATED) - Session created response.

Direction: Client -> Discovery Server

Payload structure (fixed + variable):

  • Fixed part: acip_session_create_t (295 bytes minimum)
  • Variable part: reserved_string (if reserved_string_len > 0, max 47 bytes)

Packet Format

Offset Size Field Value/Description
------ ---- ----- -----------------
0 32 identity_pubkey Ed25519 public key (host identity)
32 64 signature Ed25519(type || timestamp || capabilities)
96 8 timestamp Unix milliseconds (replay protection)
104 1 capabilities Bit 0=video, Bit 1=audio
105 1 max_participants 1-128 allowed concurrent participants
106 1 session_type 0=DIRECT_TCP, 1=WEBRTC
107 1 has_password 0=no password, 1=password protected
108 128 password_hash Argon2id hash (if has_password=1)
236 1 expose_ip_publicly 0=require verify, 1=allow public IP
237 1 reserved_string_len 0=auto-generate, >0=use provided
238 1 total_keys Total number of keys in multi-key sequence (0=single key mode)
239 1 key_index Index of this key in sequence (0-based, only valid if total_keys > 0)
240 64 server_address IPv4/IPv6/hostname (null-terminated)
304 2 server_port TCP port for client connection
------
Total: 306 bytes + reserved_string (if len > 0, max 47 bytes)

The client requests creation of a new session with specific capabilities, optionally providing a pre-reserved session string. The server responds with SESSION_CREATED containing the session identifier.

Host Responsibility: The creator becomes the session host (participant_id) and controls session settings in discovery mode.

Direction: Discovery Server -> Client

Payload structure (fixed + variable):

  • Fixed part: acip_session_created_t (90 bytes)
  • Variable part: stun_server_t[stun_count] + turn_server_t[turn_count]

Packet Format

Offset Size Field Value/Description
------ ---- ----- -----------------
0 1 session_string_len Length of generated/provided string
1 48 session_string Session ID string (null-padded)
49 16 session_id UUID bytes (generated by server)
65 16 participant_id Creator's participant UUID
81 8 expires_at Unix ms (session creation + 24 hours)
89 1 stun_count Number of STUN servers (0-N)
90 1 turn_count Number of TURN servers (0-N)
------
Total: 91 bytes + STUN/TURN server data

STUN/TURN Servers: Followed by packed stun_server_t and turn_server_t structs for WebRTC P2P connectivity behind NAT.

The server responds to SESSION_CREATE with the generated session identifier, session string (either auto-generated or the provided reserved string), and optional STUN/TURN server information for WebRTC connectivity.

The creator is assigned a participant_id and is considered the session initiator (controls session settings in discovery mode).

Note
STUN server configuration (stun_server_t) is defined in networking/webrtc/stun.h
TURN server configuration (turn_server_t) is defined in networking/webrtc/turn.h

Direction: Client -> Discovery Server

Packet Format

Offset Size Field Value/Description
------ ---- ----- -----------------
0 1 session_string_len Length of query string
1 48 session_string Session ID string to lookup
------
Total: 49 bytes

The client queries for session information using the session string. Server responds with SESSION_INFO containing basic session metadata (but NOT the server connection information, which is only revealed after successful authentication via SESSION_JOIN).

Security Note: Server does NOT reveal host IP in SESSION_INFO response, preventing information leakage to non-members.

Direction: Discovery Server -> Client

Packet Format

Offset Size Field Value/Description
------ ---- ----- -----------------
0 1 found 0=not found, 1=found
1 16 session_id UUID (valid if found=1)
17 32 host_pubkey Ed25519 public key of host
49 1 capabilities Bit 0=video, Bit 1=audio
50 1 max_participants Maximum allowed participants
51 1 current_participants Current count (may increase during lookup)
52 1 session_type 0=DIRECT_TCP, 1=WEBRTC
53 1 has_password 0=open, 1=password required
54 8 created_at Unix ms (session creation time)
62 8 expires_at Unix ms (24 hours after creation)
70 1 require_server_verify ACDS policy flag (host verifies guest)
71 1 require_client_verify ACDS policy flag (guest verifies host)
------
Total: 72 bytes

SECURITY NOTE: Does NOT include server connection information (IP/port). Server address is only revealed after authentication via SESSION_JOIN. This prevents IP address leakage to unauthenticated clients.

Server Verification: If require_server_verify=1, host must verify client identity using Ed25519 signatures.

Direction: Client -> Discovery Server

Payload structure: acip_session_join_t (241 bytes fixed)

Packet Format

Offset Size Field Value/Description
------ ---- ----- -----------------
0 1 session_string_len Length of session string
1 48 session_string Session ID to join
49 32 identity_pubkey Client's Ed25519 public key
81 64 signature Ed25519(type || timestamp || session_string)
145 8 timestamp Unix ms (replay protection, ±5min window)
153 1 has_password 0=no password, 1=password provided
154 128 password Cleartext password (TLS protects wire)
------
Total: 282 bytes

Authentication Methods:

  • Identity Signature: Client signs (type || timestamp || session_string) with Ed25519
  • Password: Optional additional requirement, stored as Argon2id hash on server
  • Replay Protection: Timestamp must be within ±5 minute window of server time

Response: Server verifies credentials and responds with SESSION_JOINED containing server IP:port and TURN credentials.

The client requests to join an existing session, providing identity proof via Ed25519 signature and optionally a password. Server responds with SESSION_JOINED containing server connection information upon successful authentication.

Direction: Discovery Server -> Client

Packet Format (Variable Length)

Offset Size Field Value/Description
------ ---- ----- -----------------
0 1 success 0=failed, 1=joined
1 1 error_code Error code if success=0
2 128 error_message Human-readable error (null-terminated)
130 16 participant_id Client's new UUID (if success=1)
146 16 session_id Session UUID
162 16 initiator_id Session creator's UUID
178 1 host_established 0=negotiate, 1=host exists
179 16 host_id Host's UUID (if host_established=1)
195 1 peer_count Number of peers (if host_established=0)
196 N*16 peer_ids[] Variable: peer UUIDs (N*16 bytes)
(196+N*16) 1 session_type 0=DIRECT_TCP, 1=WEBRTC (if success=1)
(197+N*16) 64 server_address Host IP/hostname (if success=1)
(261+N*16) 2 server_port Host TCP port (if success=1)
(263+N*16) 128 turn_username TURN auth user (if session_type=WEBRTC)
(391+N*16) 128 turn_password TURN auth pass (if session_type=WEBRTC)
------
Total: 519+ bytes (variable based on peer_count)

CRITICAL SECURITY: Server connection information (IP/port) is ONLY revealed after successful authentication (password verification or identity verification). This prevents IP address leakage to unauthenticated clients who only know the session string.

HOST NEGOTIATION: When host_established == 0, the joiner must negotiate with existing peers to determine who becomes the host. When host_established == 1, the joiner can connect directly to the established host.

TURN Credentials: RFC 5766 time-limited credentials for NAT traversal. Format: "timestamp:session_id" and HMAC-SHA1(secret, username).

Direction: Discovery Server -> Existing Participants

Sent to all existing participants when a new participant joins the session. In discovery mode, this triggers NAT quality exchange and host negotiation between the new joiner and existing participants.

Direction: Discovery Server -> Remaining Participants

Sent to remaining participants when someone leaves the session (gracefully or timeout). If the leaving participant was the host, this triggers host migration.

Direction: Client -> Discovery Server

The client gracefully leaves a session, allowing the server to update participant count and potentially notify other participants.

Direction: Host -> Discovery Server

The session host terminates the session, preventing new joins and notifying all participants. Requires signature proof of host identity.

Direction: Client -> Discovery Server

The client reconnects to a session after disconnection, using stored participant ID and identity proof to resume participation.

Direction: Bidirectional (relayed through discovery server)

Payload structure (fixed + variable):

  • Fixed: acip_webrtc_sdp_t (50 bytes minimum)
  • Variable: sdp_data (SDP string, null-terminated)

Packet Format

Offset Size Field Value/Description
------ ---- ----- -----------------
0 16 session_id Session UUID
16 16 from_id Sender's participant UUID
32 16 to_id Recipient's participant UUID (or all if broadcast)
48 2 sdp_len Length of SDP data (0-2MB)
50 N sdp_data UTF-8 SDP string (null-terminated)
------
Total: 50 + sdp_len bytes

SDP Format: RFC 4566 Session Description Protocol

  • Offer: Media offer with local capabilities
  • Answer: Media answer matching peer capabilities
  • Both include ICE ufrag/pwd for candidate exchange

WebRTC session description protocol messages are relayed through the discovery server to facilitate peer-to-peer connection establishment.

Direction: Bidirectional (relayed through discovery server)

Payload structure (fixed + variable):

  • Fixed: acip_webrtc_ice_t (50 bytes minimum)
  • Variable: candidate (ICE candidate string, null-terminated)

Packet Format

Offset Size Field Value/Description
------ ---- ----- -----------------
0 16 session_id Session UUID
16 16 sender_id Sender's participant UUID
32 16 recipient_id Recipient's participant UUID
48 2 candidate_len Length of ICE candidate (0-512)
50 N candidate UTF-8 ICE candidate (null-terminated)
------
Total: 50 + candidate_len bytes

ICE Candidate Format: RFC 5245 Interactive Connectivity Establishment

  • Example: "candidate:1 1 udp 2122260223 192.168.1.100 54321 typ host"
  • Contains: foundation, component, transport, priority, address, port, type
  • Relayed candidate: includes related-address/port for NAT-mapped endpoints

Candidate Types:

  • host: Local machine (non-NATted)
  • srflx: Server reflexive (STUN-discovered)
  • prflx: Peer reflexive (discovered via STUN from peer)
  • relay: TURN-relayed candidate

WebRTC ICE candidates are relayed through the discovery server to facilitate NAT traversal during peer-to-peer connection establishment.

Direction: Client -> Discovery Server

FUTURE FEATURE: Reserve a memorable session string for future use, preventing others from using it for a specified duration.

Direction: Discovery Server -> Client

FUTURE FEATURE: Confirms successful string reservation or reports error.

Direction: Client -> Discovery Server

FUTURE FEATURE: Extends an existing string reservation before expiration.

Direction: Client -> Discovery Server

FUTURE FEATURE: Voluntarily releases a reserved string before expiration.

Direction: ACDS -> All Participants

Broadcast by ACDS after session join or when participant joins/leaves. Lists all participants in deterministic ring order (by join time or participant ID). Participants use this to determine:

  • My position in the ring
  • Who is next in ring (for NAT collection)
  • Who is quorum leader this round (last in rotation)

Follows acip_participant_list_t in packet payload. Array of num_participants entries.

Direction: Previous Participant -> Next Participant (via direct connection)

Sent during ring rotation to request NAT quality from next participant. Forms the "spoke" of the ring, where one participant collects from all others.

During each 5-minute round:

  • Participant[0] connects to Participant[1], gets NAT data
  • Participant[1] connects to Participant[2], gets NAT data
  • ... (continues around ring)
  • Participant[N-1] has all NAT data, runs election, announces future host

Direction: Participant -> Others (via ring collection, WebRTC signaling, or direct P2P)

NEW DESIGN: Unified packet for all network quality metrics, replacing separate NAT_QUALITY, HOST_LOST NAT fields, etc. Used in three contexts:

  1. Initial Negotiation (during host selection before session established)
    • Exchanged between first two participants to determine initial host
  2. Ring Collection (proactive, every 5 minutes)
    • Quorum leader collects from all participants for future host election
    • Fresh NAT data ensures optimal host selection
    • Participants know future host before current host dies
  3. Migration Recovery (if current host dies unexpectedly)
    • Participants exchange fresh NETWORK_QUALITY if pre-elected future host unavailable
    • Enables fallback re-election

Direction: Participant -> ACDS

Sent by the participant who won host negotiation to announce they are starting the server. ACDS stores this and includes it in future SESSION_JOINED responses.

Direction: ACDS -> All Participants

Sent by ACDS after receiving HOST_ANNOUNCEMENT to notify all participants who the host is and where to connect.

Direction: Participant -> ACDS

Lightweight notification that a participant detected the host disconnected. NAT quality data is NOT included - migration participants use pre-elected future host instead of re-electing. If future host unavailable, participants can request fresh NETWORK_QUALITY exchange for re-election if needed.

NEW P2P DESIGN: This is now just a notification for ACDS bookkeeping. Actual migration happens peer-to-peer without ACDS involvement - participants connect to pre-elected future host immediately upon detection.

Direction: Quorum Leader -> ACDS -> All Participants

NEW P2P DESIGN: Sent proactively by quorum leader after completing ring consensus (every 5 minutes or when new participant joins). Announces to all participants who will become host if current host dies.

Key Insight: Future host is PRE-ELECTED and stored by everyone. When current host dies, participants don't need to elect - they immediately:

  • Future host: starts hosting (already know they will)
  • Others: connect to future host (address already stored)
  • Total failover time: <500ms (no election!)

This packet is broadcast by ACDS after receiving it from quorum leader, ensuring all participants know the migration plan before host dies.

Direction: Discovery Server -> Client

Generic error response used when no specific response packet type exists. Contains error code and human-readable message.

Sent by client to ACDS to request bandwidth measurement. Client sends this packet followed by test payload data. ACDS measures receive time and calculates upload speed.

Sent by ACDS to client with measured bandwidth results. Includes upload speed (measured by ACDS), download speed (echo test), RTT, jitter, and packet loss metrics.

Direction: Client -> ACDS

Sent by clients to acknowledge receipt of critical broadcast messages (e.g., HOST_DESIGNATED, FUTURE_HOST_ELECTED). ACDS tracks ACKs and retries broadcasts to clients that haven't acknowledged.

< Ed25519 public key of session host

< Signs: type || timestamp || capabilities

< Unix ms (replay protection)

< Bit 0: video, Bit 1: audio

< 1-128 participants allowed

< acds_session_type_t: 0=DIRECT_TCP (default), 1=WEBRTC

< 0 = no password, 1 = password protected

< Argon2id hash (only if has_password == 1)

< 0 = require verification, 1 = allow public IP disclosure (explicit –acds-expose-ip opt-in)

< 0 = auto-generate, >0 = use provided string

< Total number of keys to transmit (0 = single key mode, legacy)

< Index of this key in the sequence (0-based), only valid if total_keys > 0

< IPv4/IPv6 address or hostname (null-terminated)

< Port number for client connection

< Length of session string (e.g., 20 for "swift-river-mountain")

< Null-padded session string

< UUID as bytes (not string)

< Creator's participant ID (they are a participant too)

< Unix ms (created_at + 24 hours)

< Number of STUN servers

< Number of TURN servers

< 0 = not found, 1 = found

< Valid only if found == 1

< Host's Ed25519 public key

< Session capabilities

< acds_session_type_t: 0=DIRECT_TCP, 1=WEBRTC

< 1 = password required to join

< Unix ms

< Unix ms

< ACDS policy: server must verify client identity

< ACDS policy: client must verify server identity

< Joiner's Ed25519 public key

< Signs: type || timestamp || session_string

< Unix ms

< Cleartext password (TLS protects transport)

< 0 = failed, 1 = joined

< Error code if success == 0

< Human-readable error

< UUID for this participant (valid if success == 1)

< Session UUID

< Who created the session (controls settings)

< 0 = no host yet (negotiate), 1 = host exists (connect directly)

< Host's participant ID (valid if host_established == 1)

< Number of other participants to negotiate with

< acds_session_type_t: 0=DIRECT_TCP, 1=WEBRTC

< IPv4/IPv6 address or hostname (null-terminated)

< Port number for client connection

< Format: "{timestamp}:{session_id}"

< Base64-encoded HMAC-SHA1(secret, username)

< Session UUID

< UUID of the new participant

< Ed25519 public key of new participant

< Total participants including new one

< Session UUID

< UUID of participant who left

< 1 if the leaving participant was the host

< Participants remaining in session

< Host proves ownership

< Prove identity

< Session UUID

< Participant UUID

< All zeros = broadcast to all

< 0 = offer, 1 = answer

< Length of SDP data

< How long to reserve (1-365)

< Unix ms

< Number of participants in session

< Participant's address (for direct connection)

< Participant's listening port

< acip_connection_type_t

< Who is requesting

< Who is requested

< Which 5-minute round (for detection of stale requests)

< STUN reflexive == local IP

< UPnP/NAT-PMP port mapping works

< Port we mapped (network byte order)

< acip_nat_type_t classification

< Same subnet as peer (mDNS/ARP)

< RTT to STUN server in nanoseconds

< Upload bandwidth in Kbps (from ACDS test)

< Download bandwidth in Kbps (informational)

< Latency to ACDS server in nanoseconds

< Packet timing variance in nanoseconds

< Packet loss percentage (0-100)

< Our public IP (if has_public_ip or upnp)

< Our public port

< Bitmask: 1=host, 2=srflx, 4=relay

< My participant ID

< Where clients should connect

< Port

< acip_connection_type_t

< Handoff generation in network byte order; one for initial host

< Committed handoff round in network byte order; zero for initial host

< acip_connection_type_t

< Handoff generation in network byte order; one for initial host

< Committed handoff round in network byte order; zero for initial host

< Who is reporting

< The host that disconnected

< 0=unknown, 1=timeout, 2=tcp_reset, 3=graceful

< When disconnect was detected (Unix ms)

< Who will host if current host dies

< Where to connect when needed

< Port number

< acip_connection_type_t (DIRECT, UPNP, STUN, TURN)

< Which 5-minute round this was elected in

< Error code (see acip_error_code_t)

< Human-readable error

< Session identifier

< Participant identifier

< Size of test payload (typically 64KB)

< Timestamp when client sent packet

< Upload bandwidth in kilobits/sec

< Download bandwidth in kilobits/sec

< Round-trip time in nanoseconds

< Packet timing variance in nanoseconds

< Packet loss percentage (0-100)

< Session UUID

< Participant acknowledging

< ID of broadcast being acknowledged

< Type of packet being acknowledged

Definition at line 1 of file acds.h.

200 {
201 uint8_t identity_pubkey[ED25519_PUBLIC_KEY_SIZE];
203 uint64_t timestamp;
204
205 uint8_t capabilities;
206 uint8_t max_participants;
207 uint8_t session_type;
208
209 uint8_t has_password;
210 uint8_t password_hash[ACIP_PASSWORD_HASH_SIZE];
211 uint8_t expose_ip_publicly;
213
214 uint8_t reserved_string_len;
215 // char reserved_string[]; ///< Variable length, follows if len > 0
216
217 // Multi-key protocol: tracks which key in sequence this is
218 uint8_t total_keys;
219 uint8_t key_index;
220
221 // Server connection information (where clients should connect)
222 // For DIRECT_TCP: server_address and server_port specify where to connect
223 // For WEBRTC: these fields are ignored, signaling happens through ACDS
224 char server_address[ACIP_ADDRESS_SIZE];
225 uint16_t server_port;
#define ACIP_ADDRESS_SIZE
Definition acds_sizes.h:11
#define ACIP_PASSWORD_HASH_SIZE
Definition acds_sizes.h:13
unsigned short uint16_t
unsigned long long uint64_t
#define ED25519_SIGNATURE_SIZE
Ed25519 signature size in bytes.
Definition sizes.h:41
#define ED25519_PUBLIC_KEY_SIZE
Ed25519 public key size in bytes.
Definition sizes.h:37

Variable Documentation

◆ acip_bandwidth_result_t

acip_bandwidth_result_t

#include <include/ascii-chat/network/acip/acds.h>

Definition at line 1046 of file acds.h.

◆ acip_bandwidth_test_t

acip_bandwidth_test_t

#include <include/ascii-chat/network/acip/acds.h>

Definition at line 1029 of file acds.h.

◆ acip_broadcast_ack_t

acip_broadcast_ack_t

#include <include/ascii-chat/network/acip/acds.h>

Definition at line 1064 of file acds.h.

◆ acip_error_t

◆ acip_future_host_elected_t

acip_future_host_elected_t

#include <include/ascii-chat/network/acip/acds.h>

Definition at line 990 of file acds.h.

◆ acip_host_announcement_t

acip_host_announcement_t

◆ acip_host_designated_t

acip_host_designated_t

#include <include/ascii-chat/network/acip/acds.h>

Definition at line 937 of file acds.h.

◆ acip_host_lost_t

acip_host_lost_t

◆ acip_nat_quality_t

acip_nat_quality_t

#include <include/ascii-chat/network/acip/acds.h>

Definition at line 896 of file acds.h.

◆ acip_participant_entry_t

acip_participant_entry_t

#include <include/ascii-chat/network/acip/acds.h>

Definition at line 793 of file acds.h.

◆ acip_participant_joined_t

acip_participant_joined_t

#include <include/ascii-chat/network/acip/acds.h>

Definition at line 497 of file acds.h.

◆ acip_participant_left_t

acip_participant_left_t

#include <include/ascii-chat/network/acip/acds.h>

Definition at line 514 of file acds.h.

◆ acip_participant_list_t

acip_participant_list_t

#include <include/ascii-chat/network/acip/acds.h>

Definition at line 779 of file acds.h.

◆ acip_ring_collect_t

acip_ring_collect_t

#include <include/ascii-chat/network/acip/acds.h>

Definition at line 816 of file acds.h.

◆ acip_session_create_t

◆ acip_session_created_t

◆ acip_session_end_t

acip_session_end_t

#include <include/ascii-chat/network/acip/acds.h>

Definition at line 544 of file acds.h.

◆ acip_session_info_t

acip_session_info_t

#include <include/ascii-chat/network/acip/acds.h>

Definition at line 360 of file acds.h.

Referenced by acip_send_session_info(), and database_session_lookup().

◆ acip_session_join_t

acip_session_join_t

◆ acip_session_joined_t

acip_session_joined_t

#include <include/ascii-chat/network/acip/acds.h>

Definition at line 479 of file acds.h.

Referenced by acip_send_session_joined(), and database_session_join().

◆ acip_session_leave_t

acip_session_leave_t

#include <include/ascii-chat/network/acip/acds.h>

Definition at line 529 of file acds.h.

Referenced by acds_protocol_leave(), and discovery_session_stop().

◆ acip_session_lookup_t

acip_session_lookup_t

#include <include/ascii-chat/network/acip/acds.h>

Definition at line 309 of file acds.h.

Referenced by acds_protocol_lookup().

◆ acip_session_reconnect_t

acip_session_reconnect_t

#include <include/ascii-chat/network/acip/acds.h>

Definition at line 560 of file acds.h.

◆ acip_string_release_t

acip_string_release_t

#include <include/ascii-chat/network/acip/acds.h>

Definition at line 733 of file acds.h.

◆ acip_string_renew_t

acip_string_renew_t

#include <include/ascii-chat/network/acip/acds.h>

Definition at line 716 of file acds.h.

◆ acip_string_reserve_t

acip_string_reserve_t

#include <include/ascii-chat/network/acip/acds.h>

Definition at line 682 of file acds.h.

◆ acip_string_reserved_t

acip_string_reserved_t

#include <include/ascii-chat/network/acip/acds.h>

Definition at line 698 of file acds.h.

◆ acip_webrtc_ice_t

acip_webrtc_ice_t

◆ acip_webrtc_sdp_t

acip_webrtc_sdp_t