Files
makronix/docs/reference/dtchat-upstream.txt
T
lotherk 712d066c09 dtchat: record upstream API findings (T0.2)
Adds docs/reference/dtchat-upstream.txt with the quoted sources for libtls, libstrophe, TDLib, whatsmeow, DNS-SD, Opus, VP8, XMPP and the media crypto. Corrects the ADR: TDLib does expose call signalling (createCall/acceptCall/sendCallSignalingData/discardCall), but the media stack is the separate tgcalls; whatsmeow lists Calls as not implemented. libstrophe 0.12.3 has no MUC module; xmpp_run_once exists. DNS-SD uses txtvers, not v.
2026-11-16 16:08:02 +00:00

428 lines
18 KiB
Plaintext

# dtchat -- upstream documentation, read 2026-11-16
Read for T0.2 of the dtchat plan (tasksd `mcde/dtchat`, `t0321`). Quotes
are verbatim from the source named above them; the location is the section,
function or file line. Each section ends with what the quote settles for
dtchat. Everything was fetched on 2026-11-16.
Sources were fetched to `/tmp/opencode/dtchat-docs/` for the duration of the
work; the quotes below are the parts the implementation relies on. A later
reader who needs the full text fetches the URL again.
---
## 1. libtls (OpenBSD manual pages; `security/libretls` in pkgsrc)
Source: <https://man.openbsd.org/tls_read.3>, `tls_read(3)`, RETURN VALUES:
> The `tls_read()`, `tls_write()`, `tls_handshake()`, and `tls_close()`
> functions also have two special return values:
>
> `TLS_WANT_POLLIN`
> The underlying read file descriptor needs to be readable in
> order to continue.
>
> `TLS_WANT_POLLOUT`
> The underlying write file descriptor needs to be writeable in
> order to continue.
>
> In the case of blocking file descriptors, the same function call should
> be repeated immediately. In the case of non-blocking file descriptors,
> the same function call should be repeated when the required condition
> has been met.
Source: <https://man.openbsd.org/tls_connect.3>, DESCRIPTION:
> An already existing socket can be upgraded to a secure connection by
> calling `tls_connect_socket()`.
Source: <https://man.openbsd.org/tls_accept_socket.3>, DESCRIPTION:
> a server can accept a new client connection by calling
> `tls_accept_socket()` on an already established socket connection.
Source: <https://man.openbsd.org/tls_peer_cert_hash.3>,
`tls_conn_version(3)`, DESCRIPTION:
> `tls_peer_cert_hash()` returns a string corresponding to a hash of the
> raw peer certificate from `ctx` prefixed by a hash name followed by a
> colon. The hash currently used is SHA256, though this could change in
> the future.
Source: <https://man.openbsd.org/tls_config_verify.3>, DESCRIPTION:
> `tls_config_insecure_noverifycert()` disables certificate verification
> and OCSP validation.
> `tls_config_verify()` reenables server name and certificate verification.
**Settles:** the core's TLS layer is `poll(2)`-driven: a non-blocking socket
is connected by the core, then upgraded with `tls_connect_socket` (client)
or `tls_accept_socket` (server); `tls_read`/`tls_write` return
`TLS_WANT_POLLIN`/`TLS_WANT_POLLOUT`, which map directly to the poll loop.
Remote IRC/XMPP uses the default verification. Local peers use
`tls_config_insecure_noverifycert` + `tls_config_insecure_noverifyname`
and compare `tls_peer_cert_hash()` with the stored SHA-256 pin (TOFU).
Note: `tls_init(3)` says "/* -ltls -lssl -lcrypto */". libtls is a pkgsrc
package (`security/libretls`) on both systems; the NetBSD base has OpenSSL,
not libtls (see `docs/reference/dtchat-architecture.txt`).
---
## 2. libstrophe 0.12.3
Source: <https://strophe.im/libstrophe/doc/0.12.3/group___event_loop.html>,
"Event loop", Detailed Description:
> More complex programs will have their own event loops, and should ensure
> that `xmpp_run_once()` is called regularly from there.
`xmpp_run_once()`:
> This function will run send any data that has been queued by `xmpp_send`
> and related functions and run through the Strophe even loop a single
> time, and will not wait more than `timeout` milliseconds for events.
Source: <https://strophe.im/libstrophe/doc/0.12.3/group___t_l_s.html>,
SSL/TLS specific functionality:
> `void xmpp_conn_set_cafile(xmpp_conn_t *const conn, const char *path)`
> `void xmpp_conn_set_certfail_handler(xmpp_conn_t *const conn,
> xmpp_certfail_handler hndl)`
Source: GitHub API listing of `strophe/libstrophe` `src/`, 2026-11-16:
`auth.c`, `common.h`, `compression.c`, `conn.c`, `ctx.c`, `event.c`,
`handler.c`, `jid.c`, `md5.c`, `parser_expat.c`, `parser_libxml2.c`,
`resolver.c`, `sasl.c`, `scram.c`, `sha*.c`, `sock.c`, `stanza.c`,
`tls*.c`, `util.c`, `uuid.c` -- **there is no `muc.c`.**
The API index (`modules.html`) has no MUC module either.
**Settles:** the XMPP adapter is a `poll` loop that calls
`xmpp_run_once(ctx, timeout_ms)` from the adapter's event loop; TLS
verification uses `xmpp_conn_set_cafile` (system CA file) and the TLS
functions, with `xmpp_conn_is_secured()` after connect. libstrophe 0.12.3
has **no MUC client**: joining a room, members, subject and private
messages are built from the stanza API. This corrects the plan's
"xmpp_muc, falls vorhanden" -- it is not there, so `muc.c` in
`programs/dtchat-xmpp` owns it.
---
## 3. TDLib (current `td_api.tl` and `td_json_client.h`)
Source: <https://raw.githubusercontent.com/tdlib/td/master/td/telegram/td_json_client.h>,
file comment:
> The main TDLib interface is asynchronous. To match requests with a
> corresponding response, the field `"@extra"` can be added to the request
> object. The corresponding response will have an `"@extra"` field with
> exactly the same value.
> New updates and responses to requests can be received through
> `td_receive` from any thread after the first request has been sent to the
> client instance. This function must not be called simultaneously from
> two different threads.
Source: <https://raw.githubusercontent.com/tdlib/td/master/td/generate/scheme/td_api.tl>,
lines 15511-15526, 7734 (2026-11-16):
> `createCall user_id:int53 protocol:callProtocol is_video:Bool = CallId;`
>
> `acceptCall call_id:int32 protocol:callProtocol = Ok;`
>
> `sendCallSignalingData call_id:int32 data:bytes = Ok;`
>
> `discardCall call_id:int32 is_disconnected:Bool invite_link:string duration:int32 is_video:Bool connection_id:int64 = Ok;`
>
> `callStateReady protocol:callProtocol servers:vector<callServer> config:string encryption_key:bytes emojis:vector<string> allow_p2p:Bool is_group_call_supported:Bool custom_parameters:string = CallState;`
**Correction to the earlier ADR:** TDLib *does* expose Telegram call
signalling (`createCall`, `acceptCall`, `sendCallSignalingData`,
`discardCall`, group-call functions). What it does not contain is the
media stack: `callStateReady` hands the client `servers`, `config` and
`encryption_key`, and the client has to run the RTP/WebRTC side. Telegram
Desktop uses the separate `tgcalls` library for that. Therefore the
statement "TDLib has no call API" is wrong; the correct statement is
"TDLib has signalling, the media stack is a separate C++/WebRTC project
(`tgcalls`), which dtchat v1 does not implement." The UI still shows no
Telegram call button in v1; a later phase could add it on top of TDLib +
tgcalls.
**Settles:** the Telegram adapter owns one TDLib client, calls `td_send`
from the adapter's thread and `td_receive(timeout)` from exactly one
receive thread; request matching uses `@extra` (the adapter's own ids).
Calls are out of scope for v1 with a precise reason, not a false one.
---
## 4. whatsmeow (Go, WhatsApp web multidevice)
Source: <https://github.com/tulir/whatsmeow>, README, 2026-11-16:
> whatsmeow is a Go library for the WhatsApp web multidevice API.
> Things that are not yet implemented:
>
> * Sending broadcast list messages (this is not supported on WhatsApp web
> either)
>
> * Calls
Source: <https://pkg.go.dev/go.mau.fi/whatsmeow>, package documentation:
> `func (cli *Client) GetQRChannel(ctx context.Context) (<-chan
> QRChannelItem, error)`
> `ErrQRAlreadyConnected = errors.New("GetQRChannel must be called before
> connecting")`
**Settles:** the WhatsApp adapter is a Go helper with the standard
`GetQRChannel` + `Connect` pairing; the QR bitmap goes to the UI through
the `request`/`qr` message. **No WhatsApp calls** -- whatsmeow says so
explicitly. The adapter is unofficial and stays a separate package.
---
## 5. DNS-SD (RFC 6763) and mDNS (RFC 6762)
Source: RFC 6763, <https://www.rfc-editor.org/rfc/rfc6763.txt>, Section
4.1:
> The result of this PTR lookup for the name "<Service>.<Domain>" is a set
> of zero or more PTR records giving Service Instance Names of the form:
>
> Service Instance Name = <Instance> . <Service> . <Domain>
Section 6.1:
> The format of each constituent string within the DNS TXT record is a
> single length byte, followed by 0-255 bytes of text data.
Section 6.3:
> DNS-SD uses DNS TXT records to store arbitrary key/value pairs conveying
> additional information about the named service. Each key/value pair is
> encoded as its own constituent string within the DNS TXT record, in the
> form "key=value" (without the quotation marks).
> If an implementation sees unknown keys in a service TXT record, it MUST
> silently ignore them.
> The target host name and TCP (or UDP) port number of the service are
> given in the SRV record. This information -- target host name and port
> number -- MUST NOT be duplicated using key/value attributes in the TXT
> record.
Section 6.7, "Version Tag":
> It is recommended that authors defining DNS-SD profiles include an
> attribute of the form "txtvers=x", where "x" is a decimal version number
> in US-ASCII [RFC20] text (e.g., "txtvers=1" or "txtvers=8"), in their
> definition, and require it to be the first key/value pair in the TXT
> record.
> If there is a need to indicate which version number(s) of the
> application protocol the service implements, the recommended key for
> this is "protovers".
Source: RFC 6762, <https://www.rfc-editor.org/rfc/rfc6762.txt>, Section 8:
> Whenever a Multicast DNS responder starts up, wakes up from sleep,
> receives an indication of a network interface "Link Change" event, or
> has any other reason to believe that its network connectivity may have
> changed in some relevant way, it MUST perform the two startup steps
> below: Probing (Section 8.1) and Announcing (Section 8.3).
Source: Apple `mDNSResponder`, `mDNSShared/dns_sd.h`, 2026-11-16:
> The application MUST NOT directly read from or write to this socket.
> Access to the socket is provided so that it can be used as a kqueue
> event source, a CFRunLoop event source, in a select() loop, etc. When
> the underlying event management subsystem ... indicates to the client
> that data is available for reading on the socket, the client should call
> `DNSServiceProcessResult()`, which will extract the daemon's reply from
> the socket, and pass it to the appropriate application callback.
> `DNSServiceErrorType DNSSD_API DNSServiceRegister(... const char
> *regtype, const char *domain, const char *host, uint16_t port, uint16_t
> txtLen, const void *txtRecord, ...)`
**Settles:** the service type is `_dtchat._tcp`; the instance name is the
display name; the SRV record carries host and port (the core does not put
them in TXT); TXT carries `txtvers=1` as its first pair, then
`protovers=1`, `id=<hex>`, `nm=<display name>`, `cap=...`, `fp=...`;
unknown keys are ignored. The daemon (mdnsd on NetBSD, Avahi on Linux)
does probing/announcing; `libdns_sd`'s `DNSServiceRefSockFD()` +
`DNSServiceProcessResult()` fit the core's `poll` loop. Because the
daemon owns probing, the core must not implement its own mDNS responder.
---
## 6. Opus (RFC 6716 and libopus)
Source: RFC 6716, <https://www.rfc-editor.org/rfc/rfc6716.txt>, Section
2.1.4:
> Opus can encode frames of 2.5, 5, 10, 20, 40, or 60 ms. It can also
> combine multiple frames into packets of up to 120 ms. For real-time
> applications, sending fewer packets per second reduces the bitrate,
> since it reduces the overhead from IP, UDP, and RTP headers. However,
> it increases latency and sensitivity to packet losses, as losing one
> packet constitutes a loss of a bigger chunk of audio. Increasing the
> frame duration also slightly improves coding efficiency, but the gain
> becomes small for frame sizes above 20 ms. For this reason, 20 ms
> frames are a good choice for most applications.
Section 2.1.7:
> Another mechanism providing robustness against packet loss is the in-band
> Forward Error Correction (FEC). Packets that are determined to contain
> perceptually important speech information, such as onsets or transients,
> are encoded again at a lower bitrate and this re-encoded information is
> added to a subsequent packet.
Source: `xiph/opus`, `include/opus.h`, `opus_decoder_init`:
> `@param [in] Fs <tt>opus_int32</tt>: Sampling rate to decode to (Hz).
> This must be one of 8000, 12000, 16000, 24000, or 48000.`
`opus_decode`:
> `@param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to
> indicate packet loss`
> In the case of PLC (data==NULL) or FEC (decode_fec=1), then frame_size
> needs to be exactly the duration of audio that is missing, otherwise the
> decoder will not be in the optimal state to decode the next incoming
> packet.
Source: `include/opus_defines.h`, `OPUS_SET_INBAND_FEC`:
> 1: Inband FEC enabled. If the packet loss rate is sufficiently high,
> Opus will automatically switch to SILK even at high rates to enable use
> of that FEC.
**Settles:** 48 kHz mono, 20 ms (960 samples), 24 kbit/s target,
complexity 5, `OPUS_SET_INBAND_FEC(1)`, `OPUS_SET_PACKET_LOSS_PERC(10)`;
lost packets are decoded with `opus_decode(dec, NULL, 0, pcm, 960, 0)`.
---
## 7. VP8 (RFC 6386 and libvpx)
Source: RFC 6386, <https://www.rfc-editor.org/rfc/rfc6386.txt>, Section 2:
> VP8 works exclusively with an 8-bit YUV 4:2:0 image format.
Section 2:
> Internally, VP8 decomposes each output frame into an array of
> macroblocks. A macroblock is a square array of pixels whose Y dimensions
> are 16x16 and whose U and V dimensions are 8x8.
Source: `webmproject/libvpx`, `vpx/vpx_encoder.h`, `vpx_codec_enc_cfg_t`:
`g_w`, `g_h`, `g_timebase`, `g_error_resilient`, `g_lag_in_frames`,
`rc_target_bitrate`. `vpx/vp8cx.h`: `VP8E_SET_CPUUSED`,
`VP8E_SET_TOKEN_PARTITIONS`.
**Settles:** capture and scaling produce I420; the encoder is configured
with `g_w=640`, `g_h=360`, `g_timebase=1/15`, `rc_target_bitrate=500`,
`g_lag_in_frames=0`, `g_error_resilient=1`, `VP8E_SET_CPUUSED` high for
realtime; a keyframe every 2 s and on request.
---
## 8. XMPP core (RFC 6120), for the adapter's TLS/SASL floor
Source: RFC 6120, <https://www.rfc-editor.org/rfc/rfc6120.txt>, Section
5.2:
> Support for STARTTLS is REQUIRED in XMPP client and server
> implementations. An administrator of a given deployment MAY specify
> that TLS is mandatory-to-negotiate for client-to-server communication,
> server-to-server communication, or both. An initiating entity SHOULD
> use TLS to secure its stream with the receiving entity before proceeding
> with SASL authentication.
Section 6.2:
> Support for SASL negotiation is REQUIRED in XMPP client and server
> implementations.
**Settles:** the XMPP adapter refuses a connection that does not offer
TLS before SASL; libstrophe performs STARTTLS and SASL, the adapter only
verifies `xmpp_conn_is_secured()` and surfaces a clear error otherwise.
---
## 9. Crypto (X25519, HKDF, ChaCha20-Poly1305)
Source: RFC 7748, <https://www.rfc-editor.org/rfc/rfc7748.txt>, Section
6.1:
> Alice generates 32 random bytes in a[0] to a[31] and transmits K_A =
> X25519(a, 9) to Bob ... Using their generated values and the received
> input, Alice computes X25519(a, K_B) and Bob computes X25519(b, K_A).
>
> Both now share K = X25519(a, X25519(b, 9)) = X25519(b, X25519(a, 9)) as
> a shared secret. Both MAY check, without leaking extra information
> about the value of K, whether K is the all-zero value and abort if so
> (see below).
Source: RFC 5869, <https://www.rfc-editor.org/rfc/rfc5869.txt>, Section 2:
> HKDF follows the "extract-then-expand" paradigm, where the KDF logically
> consists of two modules.
Section 2.2:
> `PRK = HMAC-Hash(salt, IKM)`
Source: RFC 8439, <https://www.rfc-editor.org/rfc/rfc8439.txt>, Section
2.8:
> `AEAD_CHACHA20_POLY1305` is an authenticated encryption with additional
> data algorithm. The inputs to `AEAD_CHACHA20_POLY1305` are:
>
> * A 256-bit key
> * A 96-bit nonce -- different for each invocation with the same key
> * An arbitrary length plaintext
> * Arbitrary length additional authenticated data (AAD)
**Settles:** the per-call X25519 shared secret is checked for all-zero;
the media key is `HKDF-SHA256(shared, salt=SHA256(transcript),
info="dtchat media v1 a->b")`; the 96-bit nonce is the 4-byte session id
followed by an 8-byte packet counter, never reused with the same key; the
16-byte media header is the AAD.
---
## 10. What this changes in the plan
| Finding | Consequence |
|---|---|
| TDLib **has** call signalling (`createCall`, `acceptCall`, `sendCallSignalingData`, `discardCall`) | The ADR sentence "TDLib has no call API" was wrong; correct it. Telegram calls are still out of v1, because the media stack is the separate `tgcalls` (C++/WebRTC), not TDLib. |
| whatsmeow README lists "Calls" as not implemented | No WhatsApp call button; the UI gets this from `caps`. |
| libstrophe 0.12.3 has no `muc.c` | `programs/dtchat-xmpp/muc.c` implements MUC with stanzas; no `xmpp_muc` dependency. |
| `xmpp_run_once()` exists in 0.12.3 | The XMPP adapter uses `poll` + `xmpp_run_once(ctx, timeout_ms)`; no extra thread and no `xmpp_run` blocking loop. |
| `tls_read`/`tls_write` return `TLS_WANT_POLLIN`/`TLS_WANT_POLLOUT` | `dc_tls.c` is non-blocking and fits the core's `poll` loop; no thread per connection. |
| `tls_peer_cert_hash()` is SHA-256 over the certificate | The TOFU pin is exactly this string; no separate pin computation. |
| DNS-SD TXT is key=value and unknown keys are ignored; the version key is `txtvers` | `_dtchat._tcp` TXT is `txtvers=1` first, then `protovers=1`, `id=...`, `nm=...`, `cap=...`, `fp=...`; SRV carries host/port. |
| `DNSServiceRefSockFD()` + `DNSServiceProcessResult()` | The McdeSys discovery API can hand one fd to the core's `poll`; the daemon does probing. |
| Opus 20 ms, 48 kHz, FEC and PLC | The media layer's fixed frame and loss handling. |
## 11. Not read yet (later tasks)
- IRC: RFC 1459/2812, IRCv3 `cap`, `sasl`, `server-time`, `away-notify`
(Phase 3, T3.2/T3.3).
- XMPP MUC, carbons, MAM, stream management details (Phase 4, T4.1-T4.5).
- TDLib build on NetBSD, `tdjson` linking, authentication states
(T0.7, then T8).
- whatsmeow QR flow and session store in practice (T0.8, then T9).
- Avahi's `libdns_sd` compatibility shim vs. `avahi-client` (T0.4).
- `uvideo(4)`/V4L2 capture (Phase 7, T7.1).
<!-- License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. -->