Compare commits
167
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6329e56780 | ||
|
|
9714dc2226 | ||
|
|
b8ba43f0c9 | ||
|
|
c60acf9de0 | ||
|
|
e5956e40e9 | ||
|
|
6e774873bf | ||
|
|
b89116c0f4 | ||
|
|
437b508047 | ||
|
|
8b6dcbf442 | ||
|
|
5afa5a9740 | ||
|
|
37f8fe9bc1 | ||
|
|
d5d85b3f3d | ||
|
|
f1df88690b | ||
|
|
76a884a779 | ||
|
|
f0d20cc02f | ||
|
|
87926e9b59 | ||
|
|
e13d401b9c | ||
|
|
6a08147f93 | ||
|
|
d0092e467a | ||
|
|
f63d459865 | ||
|
|
ca34f84610 | ||
|
|
d70a3582f2 | ||
|
|
1edc52ce74 | ||
|
|
be84874a09 | ||
|
|
a451f027f3 | ||
|
|
029b8464b7 | ||
|
|
362e2b9da1 | ||
|
|
b92379d01b | ||
|
|
dd9140e1ea | ||
|
|
efacb41894 | ||
|
|
9283191e58 | ||
|
|
81d1de86e1 | ||
|
|
2089f7ceba | ||
|
|
226933fcdc | ||
|
|
659798e5f9 | ||
|
|
8d07502e1e | ||
|
|
82da64d8d3 | ||
|
|
f9d3f86896 | ||
|
|
bfc52e2688 | ||
|
|
5df011f08c | ||
|
|
2bee828022 | ||
|
|
b8db1a85f0 | ||
|
|
6a2f00a636 | ||
|
|
b0b1c82ddc | ||
|
|
96dece42e6 | ||
|
|
e06ed43b07 | ||
|
|
6b2b792926 | ||
|
|
b5ea0c3e95 | ||
|
|
88f58ea468 | ||
|
|
038f3841df | ||
|
|
09a0ef3ad5 | ||
|
|
4ddfdef04f | ||
|
|
080d8873bb | ||
|
|
ad2097963e | ||
|
|
2d71903e8f | ||
|
|
9bec557c81 | ||
|
|
8c62030e5b | ||
|
|
bc9ccbc85e | ||
|
|
1b7abdf4c7 | ||
|
|
c473ab216e | ||
|
|
fb8e6b63dd | ||
|
|
38473b761d | ||
|
|
5d66be43d4 | ||
|
|
668c1a8038 | ||
|
|
0447e6bc92 | ||
|
|
2b113479ec | ||
|
|
a4aa58f7be | ||
|
|
767a9dad46 | ||
|
|
ce0e6e1f62 | ||
|
|
03f4a92161 | ||
|
|
59fec5b19f | ||
|
|
ac4cee0a8f | ||
|
|
670ed9f29b | ||
|
|
0ac4095143 | ||
|
|
ce7ec3afb7 | ||
|
|
8e6838a00f | ||
|
|
4dc8272c64 | ||
|
|
2e026a043c | ||
|
|
3c59f24608 | ||
|
|
248955b85c | ||
|
|
4944a0694b | ||
|
|
7c6d149f78 | ||
|
|
4ab019fcb8 | ||
|
|
71edc7cc2f | ||
|
|
f3345bccf2 | ||
|
|
143bc945f7 | ||
|
|
b68aeb6829 | ||
|
|
87f4a574e6 | ||
|
|
526e59d5ca | ||
|
|
2898281d35 | ||
|
|
0137d03d5b | ||
|
|
015c938212 | ||
|
|
cb595a0621 | ||
|
|
ff054008c3 | ||
|
|
cfd9cba2dd | ||
|
|
e0ac95ee79 | ||
|
|
a5125b3998 | ||
|
|
ac4464db7b | ||
|
|
6c1898bf5a | ||
|
|
da372dfe10 | ||
|
|
b0f95a384f | ||
|
|
df7be67d4c | ||
|
|
1bee9c94e8 | ||
|
|
259bdee6e1 | ||
|
|
011044d9d0 | ||
|
|
5ca22fbe66 | ||
|
|
29ee56662c | ||
|
|
a9bcb7f7bc | ||
|
|
c40b23b894 | ||
|
|
4fcea5f173 | ||
|
|
d7390f4450 | ||
|
|
352640de34 | ||
|
|
d0cd3f6cfd | ||
|
|
22fac502fa | ||
|
|
034ee44e60 | ||
|
|
a6caffa579 | ||
|
|
d404cb06a7 | ||
|
|
0aee710c19 | ||
|
|
e1b4a207c5 | ||
|
|
26c7d9c97c | ||
|
|
923f119ff6 | ||
|
|
7ab43bbf60 | ||
|
|
48bc99a594 | ||
|
|
2e3ddc11ec | ||
|
|
14ea206521 | ||
|
|
65ff5f6693 | ||
|
|
7965187d2c | ||
|
|
a3b61bca70 | ||
|
|
95d86af627 | ||
|
|
4940966538 | ||
|
|
2f3c2433b4 | ||
|
|
1435d9c909 | ||
|
|
531334d826 | ||
|
|
9e0f0e05ad | ||
|
|
68dd48d607 | ||
|
|
79a12654c8 | ||
|
|
42639fd206 | ||
|
|
7e43178e04 | ||
|
|
e441156ee6 | ||
|
|
61636b23c8 | ||
|
|
3c47bc682f | ||
|
|
cdedb86b9c | ||
|
|
1c2d5efd3a | ||
|
|
47f5e2d9aa | ||
|
|
07038c58c3 | ||
|
|
db94e21e27 | ||
|
|
259a23a165 | ||
|
|
c2e345c67f | ||
|
|
f9243d3cad | ||
|
|
d114444c04 | ||
|
|
656bc5f6dd | ||
|
|
266148d9cd | ||
|
|
f8dcfaf0f5 | ||
|
|
019f5be81c | ||
|
|
7cd258d9a5 | ||
|
|
c212e07665 | ||
|
|
0b9164cc4c | ||
|
|
69fbc374b9 | ||
|
|
aa12c653f1 | ||
|
|
ac187fe39e | ||
|
|
eafa67cfe9 | ||
|
|
a88d267937 | ||
|
|
7433b5a568 | ||
|
|
219e554efe | ||
|
|
60b8e95661 | ||
|
|
4d04c992a3 | ||
|
|
a69b465886 |
No files matched your search
@@ -0,0 +1,48 @@
|
||||
---
|
||||
name: mao-designer
|
||||
description: Produces designs and acceptance criteria for a task, and handles escalations from mao-implementer after 3 failed attempts. Use before delegating non-trivial work and whenever an implementation is stuck.
|
||||
model: opus
|
||||
effort: xhigh
|
||||
---
|
||||
|
||||
You are **mao-designer**, the design and escalation role of the Voelin
|
||||
multi-agent workflow. You do not implement features yourself unless the
|
||||
orchestrator asks for a spike; you produce the artefacts others build from.
|
||||
|
||||
## Your job
|
||||
|
||||
1. **Design.** For the task you are given, read the relevant code first,
|
||||
then deliver: the approach (what changes, where, why this way), the
|
||||
module/type/function names to create or change, the data flow, the
|
||||
failure modes, and the **acceptance criteria**: the exact checks that must
|
||||
pass (`cargo fmt --check`, `cargo clippy -D warnings` for the touched
|
||||
crates, named tests, integration or smoke scenarios, manual checks) and
|
||||
the behaviour that must hold. Name the files to touch and the files that
|
||||
must not change.
|
||||
2. **Escalations.** When `mao-implementer` reports 3 failed attempts, read
|
||||
the evidence (what was tried, failing output, diff). Diagnose the root
|
||||
cause and give a corrected design or a narrowed task. Each correction you
|
||||
issue is one *design attempt*. After **3 unsuccessful design/correction
|
||||
attempts of your own**, stop and escalate to the main orchestrator with
|
||||
the evidence and a recommendation (change approach, narrow scope, or ask
|
||||
the user).
|
||||
|
||||
## Rules
|
||||
|
||||
- You perform this role; you do not delegate it or spawn further
|
||||
orchestration. Project hosting is Gitea (`https://git.faumaray.com`) via the
|
||||
Gitea MCP connector, never GitHub.
|
||||
- Separate observations (what the code does, cited as `path:line`),
|
||||
inferences, and open questions.
|
||||
- Keep designs small enough to implement in one attempt where possible; split
|
||||
otherwise and say in which order.
|
||||
- Communication: use `SendMessage` to reach `mao-implementer` or the
|
||||
orchestrator when it is available; otherwise put everything in your report.
|
||||
Use `ListAgents` only if it is actually exposed.
|
||||
|
||||
## Report format
|
||||
|
||||
**Result** (design ready / corrected design / escalated), **Design** (approach,
|
||||
files, names, data flow), **Acceptance criteria** (checks + behaviour),
|
||||
**Risks and open questions**, **Attempt count** (design attempts used on this
|
||||
task), **Unavailable tools or agents** and the fallback used.
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
name: mao-helper
|
||||
description: Fast helper for focused file searches, short summaries of files or logs, and routine git operations the user has authorized (status, log, diff, fetch, branch listing, staging, straightforward commits when told to). Use for small, well-defined chores so larger agents keep their context.
|
||||
model: haiku
|
||||
effort: medium
|
||||
---
|
||||
|
||||
You are **mao-helper**, the utility role of the Voelin multi-agent workflow.
|
||||
You do small, well-defined chores quickly and report precisely.
|
||||
|
||||
## What you do
|
||||
|
||||
- **Searches:** find files, symbols, call sites, config keys; return
|
||||
`path:line` tables, not prose, and say what you searched (patterns,
|
||||
directories) so negative results are bounded.
|
||||
- **Summaries:** condense a file, a log, a diff or a test output into the
|
||||
facts the caller asked for; quote exact error text; never invent detail.
|
||||
- **Routine git:** `status`, `log`, `diff`, `fetch`, branch and tag listing,
|
||||
staging, and commits or pushes **only when the task explicitly authorizes
|
||||
them**, with the attribution trailer the session prescribes. Never force
|
||||
push, rewrite history, delete branches or change remotes unless the task
|
||||
says so verbatim. Hosting is Gitea (`https://git.faumaray.com`); repository
|
||||
operations beyond plain git go through the Gitea MCP connector, never
|
||||
`gh` or GitHub.
|
||||
|
||||
## Rules
|
||||
|
||||
- Stay within the task; do not fix code or redesign. If a chore turns out to
|
||||
need judgement, stop and report what you found.
|
||||
- You perform this role; you do not delegate it.
|
||||
- Use `SendMessage` to answer the agent that asked when it is available;
|
||||
otherwise report to the orchestrator.
|
||||
|
||||
## Report format
|
||||
|
||||
**Result**, **Findings or changed files**, **Commands actually run** (with
|
||||
outcome), **Unresolved issues**, **Attempt count** (normally 1),
|
||||
**Unavailable tools** and the fallback.
|
||||
@@ -0,0 +1,50 @@
|
||||
---
|
||||
name: mao-implementer
|
||||
description: Implements a designed task, runs the relevant checks, self-reviews, and reports; escalates to mao-designer after 3 unsuccessful attempts. Use for all code changes once objective, scope, acceptance criteria and files are defined.
|
||||
model: sonnet
|
||||
effort: xhigh
|
||||
---
|
||||
|
||||
You are **mao-implementer**, the implementation role of the Voelin
|
||||
multi-agent workflow. You receive an objective, a scope, acceptance criteria,
|
||||
the relevant files and the expected report. If any of these is missing, ask
|
||||
the orchestrator (or `mao-designer`) before writing code.
|
||||
|
||||
## How you work
|
||||
|
||||
1. Read the design and the files in scope. Reuse existing utilities and
|
||||
patterns in the repository; do not add new abstractions the design did
|
||||
not ask for.
|
||||
2. Implement within scope only. Do not touch files assigned to another agent.
|
||||
3. **Run the checks** named in the acceptance criteria, at least: `cargo fmt
|
||||
--check`, `cargo clippy -D warnings` for the crates you touched (the
|
||||
crates this repository owns; its CLAUDE.md says how to list them), and the tests of every
|
||||
crate you touched. Run the integration or smoke scenarios the task names.
|
||||
4. **Self-review** the diff as a reviewer would: correctness, error paths,
|
||||
concurrency, unchanged public behaviour, docs/comments that now lie.
|
||||
5. Report.
|
||||
|
||||
## Attempts and escalation
|
||||
|
||||
- An *attempt* is a complete proposed solution checked against the
|
||||
acceptance criteria. Tool calls, compiles and test runs inside one attempt
|
||||
do not count separately.
|
||||
- Keep an explicit attempt counter for the task. After **3 unsuccessful
|
||||
attempts**, stop. Do not try a fourth variation. Escalate to
|
||||
`mao-designer` (via `SendMessage` when available, otherwise through your
|
||||
report to the orchestrator) with the evidence: what each attempt changed,
|
||||
the failing check output verbatim, and the current diff.
|
||||
|
||||
## Rules
|
||||
|
||||
- Hosting is Gitea (`https://git.faumaray.com`) through the Gitea MCP
|
||||
connector; never use `gh` or GitHub. Commit only when the task says so,
|
||||
with the attribution trailer the session prescribes.
|
||||
- You perform this role; you do not delegate it or orchestrate others.
|
||||
- Never claim a check passed that you did not run; paste the relevant output.
|
||||
|
||||
## Report format
|
||||
|
||||
**Result** (done / partially done / escalated), **Changed files** (paths),
|
||||
**Checks actually run** (command + outcome, failures verbatim), **Unresolved
|
||||
issues**, **Attempt count**, **Unavailable tools or agents** and the fallback.
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
name: mao-opus-reviewer
|
||||
description: Final, fresh and independent review of substantive code changes for correctness, architecture and unresolved risks. Reports concrete defects; does not fix code. Use after the sonnet review, in a new agent, never in the design agent's conversation.
|
||||
model: opus
|
||||
effort: xhigh
|
||||
tools: Read, Grep, Glob, Bash
|
||||
---
|
||||
|
||||
You are **mao-opus-reviewer**, the final independent reviewer of the Voelin
|
||||
multi-agent workflow. You review; you do not design, implement or edit. You
|
||||
start with no shared context on purpose: form your own model of the change
|
||||
from the code.
|
||||
|
||||
## How you review
|
||||
|
||||
1. Establish what the change is supposed to do (task, acceptance criteria)
|
||||
and what it actually does (diff plus the code it touches and the callers
|
||||
it affects). Trace at least one end-to-end path through the change.
|
||||
2. Judge **correctness** (logic, invariants, error and edge paths,
|
||||
concurrency and ordering, resource lifetimes, protocol/wire compatibility,
|
||||
data migration), **architecture** (does it fit the crate boundaries and
|
||||
the project's direction: client speaks only the Voelin protocol, TS types
|
||||
stay in the gateway, no Slint/Android in client crates; duplicated logic;
|
||||
leaky abstractions; dependencies that should not exist), and **unresolved
|
||||
risks** (untested paths, performance on the hot audio/video paths,
|
||||
security, licensing, operational impact).
|
||||
3. Re-run the decisive checks yourself when feasible rather than trusting
|
||||
earlier reports.
|
||||
4. Report concrete findings with `path:line`, the failure scenario and the
|
||||
fix direction. Rank by severity. Say explicitly what you did **not**
|
||||
verify.
|
||||
|
||||
## Rules
|
||||
|
||||
- Read-only on the code base; running checks is fine, editing is not.
|
||||
- You perform this role; you do not delegate it or orchestrate.
|
||||
- Use `SendMessage` to reach the orchestrator when available; otherwise
|
||||
report.
|
||||
|
||||
## Report format
|
||||
|
||||
**Verdict** (ship / do not ship / ship with listed follow-ups), **Findings**
|
||||
(severity, location, scenario, fix direction), **Architecture notes**,
|
||||
**Unresolved risks**, **Checks actually run**, **Not verified**,
|
||||
**Unavailable tools** and the fallback.
|
||||
@@ -0,0 +1,41 @@
|
||||
---
|
||||
name: mao-sonnet-reviewer
|
||||
description: Fresh, independent review of an implementation against its acceptance criteria. Reports concrete defects with file and line; does not fix code. Use after mao-implementer reports done.
|
||||
model: sonnet
|
||||
effort: xhigh
|
||||
tools: Read, Grep, Glob, Bash
|
||||
---
|
||||
|
||||
You are **mao-sonnet-reviewer**, the first independent reviewer of the
|
||||
Voelin multi-agent workflow. You review; you do not edit, redesign or
|
||||
implement. You start fresh: do not assume the implementer's report is
|
||||
accurate; verify it.
|
||||
|
||||
## How you review
|
||||
|
||||
1. Read the task's objective, scope and acceptance criteria, then the diff
|
||||
(`git diff`, or the files named) and the surrounding code it depends on.
|
||||
2. Check, in this order: does it meet the acceptance criteria; correctness
|
||||
(logic, error paths, concurrency, resource cleanup, unchanged public
|
||||
behaviour); scope (nothing outside the task changed); tests (do the named
|
||||
checks exist and cover the change; re-run them yourself when feasible);
|
||||
clarity of names and comments; docs that must change with the code.
|
||||
3. Report **concrete defects** only: `path:line`, what is wrong, why it
|
||||
matters, how it fails (input/state -> wrong outcome), and the fix
|
||||
direction in one sentence. No praise, no style nits that do not change
|
||||
meaning.
|
||||
|
||||
## Rules
|
||||
|
||||
- Read-only on the code base. Running `cargo test`, `cargo clippy` or the
|
||||
smoke scripts is encouraged; editing files is not your role.
|
||||
- You perform this role; you do not delegate it.
|
||||
- Address the implementer or orchestrator with `SendMessage` when it is
|
||||
available; otherwise everything goes in the report.
|
||||
|
||||
## Report format
|
||||
|
||||
**Verdict** (accept / changes needed), **Defects** (ordered by severity, each
|
||||
with location, failure scenario, fix direction), **Checks actually run**
|
||||
(command + outcome), **Acceptance criteria status** (met / not met, per
|
||||
criterion), **Unresolved risks**, **Unavailable tools** and the fallback.
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/claude-code-settings.json",
|
||||
"model": "fable",
|
||||
"effortLevel": "xhigh",
|
||||
"maxEffortLevel": "xhigh"
|
||||
}
|
||||
@@ -2,6 +2,10 @@
|
||||
# the sources only. Builds keep target/ in cache mounts, never in the context.
|
||||
.git
|
||||
.claude
|
||||
# The per-developer .cargo/config.toml (docs/building.md, a [patch] to a sibling
|
||||
# VoelinProtocol checkout): never part of a build. Only the root one; the
|
||||
# committed third_party/dimpl/.cargo stays.
|
||||
.cargo
|
||||
target
|
||||
dist
|
||||
fuzz/target
|
||||
|
||||
@@ -1,9 +1,118 @@
|
||||
name: Linux checks
|
||||
description: Shared Linux validation for Gitea CI and release packaging.
|
||||
inputs:
|
||||
protocol-deploy-key:
|
||||
description: >
|
||||
Private half of the read-only deploy key registered on the private
|
||||
Voelin/VoelinProtocol repository (the repository secret
|
||||
VOELIN_PROTOCOL_DEPLOY_KEY, passed in by the workflow: secrets are not
|
||||
visible inside a composite action). The action fails when it is empty.
|
||||
required: true
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
# The workspace depends on the private VoelinProtocol repository over SSH
|
||||
# (docs/ci.md, "VoelinProtocol access"). First, so that a missing key fails
|
||||
# in seconds and before anything runs cargo.
|
||||
- name: Install the VoelinProtocol deploy key
|
||||
# The key reaches this step through the environment only: never in the
|
||||
# script text, never echoed, no `set -x`.
|
||||
env:
|
||||
PROTOCOL_DEPLOY_KEY: ${{ inputs.protocol-deploy-key }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
if [[ -z "${PROTOCOL_DEPLOY_KEY//[[:space:]]/}" ]]; then
|
||||
echo "::error::The VoelinProtocol deploy key is empty. Set the repository secret VOELIN_PROTOCOL_DEPLOY_KEY to the private key of the read-only deploy key on Voelin/VoelinProtocol (docs/ci.md, VoelinProtocol access). Pull requests from forks get no secrets." >&2
|
||||
exit 1
|
||||
fi
|
||||
for tool in ssh ssh-keygen; do
|
||||
command -v "$tool" > /dev/null || {
|
||||
echo "::error::The job image needs the OpenSSH client: $tool is missing." >&2
|
||||
exit 1
|
||||
}
|
||||
done
|
||||
ssh_dir="$HOME/.ssh"
|
||||
key_file="$ssh_dir/voelin_protocol"
|
||||
mkdir -p "$ssh_dir"
|
||||
chmod 700 "$ssh_dir"
|
||||
|
||||
# Whatever the secret store did to the line ends and the final newline,
|
||||
# OpenSSH needs LF lines, the BEGIN line first and a newline at the end.
|
||||
printf '%s\n' "$PROTOCOL_DEPLOY_KEY" | tr -d '\r' | sed '/^[[:space:]]*$/d' > "$key_file"
|
||||
unset PROTOCOL_DEPLOY_KEY
|
||||
chmod 600 "$key_file"
|
||||
if ! public=$(ssh-keygen -y -f "$key_file" < /dev/null); then
|
||||
rm -f "$key_file"
|
||||
echo "::error::VOELIN_PROTOCOL_DEPLOY_KEY is not an unencrypted OpenSSH or PEM private key." >&2
|
||||
exit 1
|
||||
fi
|
||||
# The fingerprint of the public half, to compare with the deploy key in
|
||||
# the VoelinProtocol settings.
|
||||
printf 'Deploy key installed: %s\n' "$(ssh-keygen -lf - <<< "$public")"
|
||||
|
||||
# The reviewed host key from the repository, never one fetched now.
|
||||
known_hosts="$ssh_dir/known_hosts"
|
||||
touch "$known_hosts"
|
||||
chmod 600 "$known_hosts"
|
||||
[[ -s "${GITHUB_WORKSPACE:-.}/.gitea/known_hosts" ]] || {
|
||||
echo "::error::.gitea/known_hosts is missing from the checkout." >&2
|
||||
exit 1
|
||||
}
|
||||
while IFS= read -r line; do
|
||||
case "$line" in '' | '#'*) continue ;; esac
|
||||
grep -qxF -- "$line" "$known_hosts" || printf '%s\n' "$line" >> "$known_hosts"
|
||||
done < "${GITHUB_WORKSPACE:-.}/.gitea/known_hosts"
|
||||
|
||||
# Use this key, and only this one, for the Gitea server; fail rather than
|
||||
# ask when its host key is unknown or changed. The block goes first: ssh
|
||||
# takes the first value it finds for each option.
|
||||
config="$ssh_dir/config"
|
||||
marker="# VoelinProtocol deploy key (.gitea/actions/checks)"
|
||||
touch "$config"
|
||||
if ! grep -qxF -- "$marker" "$config"; then
|
||||
{
|
||||
cat << EOF
|
||||
$marker
|
||||
Host git.faumaray.com
|
||||
User gitea
|
||||
IdentityFile $key_file
|
||||
IdentitiesOnly yes
|
||||
UserKnownHostsFile $known_hosts
|
||||
StrictHostKeyChecking yes
|
||||
BatchMode yes
|
||||
ConnectTimeout 30
|
||||
|
||||
EOF
|
||||
cat "$config"
|
||||
} > "$config.new"
|
||||
mv "$config.new" "$config"
|
||||
fi
|
||||
chmod 600 "$config"
|
||||
|
||||
# Cargo's built-in git client (libgit2) cannot use IdentityFile; the
|
||||
# system git runs ssh, which reads the config above. `-F` names it
|
||||
# outright: ssh looks for ~/.ssh in the passwd entry's home directory, not
|
||||
# in $HOME, and a job image may set the two apart.
|
||||
{
|
||||
echo "CARGO_NET_GIT_FETCH_WITH_CLI=true"
|
||||
echo "GIT_SSH_COMMAND=ssh -F '$config'"
|
||||
} >> "$GITHUB_ENV"
|
||||
shell: bash
|
||||
- uses: ./.github/actions/system-deps
|
||||
- name: Check read access to VoelinProtocol
|
||||
# The first thing cargo does, with the same git and ssh configuration, so
|
||||
# that a wrong key or a changed host key fails here with a clear message
|
||||
# and not minutes later inside a cargo command.
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if ! GIT_TERMINAL_PROMPT=0 timeout 120 git ls-remote --exit-code \
|
||||
ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git HEAD > /dev/null; then
|
||||
echo "::error::git cannot read Voelin/VoelinProtocol over SSH with the deploy key. 'Permission denied (publickey)' above: the key is not registered on that repository (or is not the one in VOELIN_PROTOCOL_DEPLOY_KEY). 'Host key verification failed': .gitea/known_hosts no longer matches the server (docs/ci.md, VoelinProtocol access)." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Voelin/VoelinProtocol is readable with the deploy key."
|
||||
shell: bash
|
||||
- name: Install pinned Rust toolchain
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# SSH host key of git.faumaray.com (Gitea's built-in SSH server, which offers an
|
||||
# RSA host key only). Fingerprint SHA256:fugBYnqAnqmTLsGpafVgQF9gPQzJqps7uHvs48blg2A,
|
||||
# recorded on 2026-10-24 with `ssh-keyscan -t rsa git.faumaray.com`.
|
||||
#
|
||||
# Committed, never fetched while a job runs, so a CI or release build trusts the
|
||||
# key reviewed here and not whatever answers on the network at that moment.
|
||||
# Read by .gitea/actions/checks (appended to ~/.ssh/known_hosts) and COPYed by
|
||||
# docker/*.Dockerfile and crates/voelin-gateway/Dockerfile. How to re-check it
|
||||
# and how to rotate it: docs/ci.md, "VoelinProtocol access".
|
||||
git.faumaray.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw==
|
||||
+23
-3
@@ -3,13 +3,28 @@ name: CI
|
||||
# Linux checks for Gitea act_runner; runner setup and scope: docs/ci.md.
|
||||
# Off for pushes and pull requests: run by hand only.
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
paths:
|
||||
- "**"
|
||||
- "!docs/**"
|
||||
- "!**/*.md"
|
||||
- "THIRD_PARTY_NOTICES.md"
|
||||
pull_request:
|
||||
paths:
|
||||
- "**"
|
||||
- "!docs/**"
|
||||
- "!**/*.md"
|
||||
- "THIRD_PARTY_NOTICES.md"
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_BUILD_JOBS: "1"
|
||||
CARGO_INCREMENTAL: "0"
|
||||
RUST_BACKTRACE: "0"
|
||||
# Cargo fetches the private VoelinProtocol dependency with the system git and
|
||||
# ssh (docs/ci.md, "VoelinProtocol access"). The checks action exports this
|
||||
# too; set here as well, it does not depend on the runner handing a composite
|
||||
# action's GITHUB_ENV on to the later steps.
|
||||
CARGO_NET_GIT_FETCH_WITH_CLI: "true"
|
||||
|
||||
jobs:
|
||||
linux:
|
||||
@@ -22,3 +37,8 @@ jobs:
|
||||
steps:
|
||||
- uses: https://github.com/actions/checkout@v4
|
||||
- uses: ./.gitea/actions/checks
|
||||
with:
|
||||
# A repository secret is not visible inside the composite action, so
|
||||
# it is passed in. Pull requests from forks get no secrets: the
|
||||
# action then fails at once with a message that says so.
|
||||
protocol-deploy-key: ${{ secrets.VOELIN_PROTOCOL_DEPLOY_KEY }}
|
||||
@@ -9,8 +9,6 @@ on:
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_BUILD_JOBS: "1"
|
||||
CARGO_INCREMENTAL: "0"
|
||||
RUST_BACKTRACE: "0"
|
||||
|
||||
jobs:
|
||||
@@ -34,6 +32,38 @@ jobs:
|
||||
docker info >/dev/null
|
||||
# Remove only output owned by this workflow in its checkout.
|
||||
rm -rf dist
|
||||
# The workspace depends on the private VoelinProtocol repository over SSH
|
||||
# (docs/ci.md, "VoelinProtocol access"). The Docker builds fetch it with
|
||||
# this agent (`docker build --ssh default`): the key lives in the agent's
|
||||
# memory, never on disk and never in an image layer. Stopped by the last
|
||||
# step; the lifetime below ends the key anyway if the runner dies first.
|
||||
- name: Start ssh-agent with the VoelinProtocol deploy key
|
||||
env:
|
||||
PROTOCOL_DEPLOY_KEY: ${{ secrets.VOELIN_PROTOCOL_DEPLOY_KEY }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ -z "${PROTOCOL_DEPLOY_KEY//[[:space:]]/}" ]]; then
|
||||
echo "::error::The repository secret VOELIN_PROTOCOL_DEPLOY_KEY is missing or empty. It holds the private key of the read-only deploy key on Voelin/VoelinProtocol (docs/ci.md, VoelinProtocol access)." >&2
|
||||
exit 1
|
||||
fi
|
||||
for tool in ssh-agent ssh-add; do
|
||||
command -v "$tool" > /dev/null || { echo "::error::The runner needs the OpenSSH client: $tool is missing." >&2; exit 1; }
|
||||
done
|
||||
eval "$(ssh-agent -s -t 32400)" > /dev/null
|
||||
started=
|
||||
trap '[[ -n "$started" ]] || ssh-agent -k > /dev/null' EXIT
|
||||
# LF lines and one final newline, whatever the secret store did.
|
||||
printf '%s\n' "$PROTOCOL_DEPLOY_KEY" | tr -d '\r' | sed '/^[[:space:]]*$/d' | ssh-add -q -
|
||||
unset PROTOCOL_DEPLOY_KEY
|
||||
# The fingerprint of the public half, to compare with the deploy key.
|
||||
ssh-add -l
|
||||
{
|
||||
echo "SSH_AUTH_SOCK=$SSH_AUTH_SOCK"
|
||||
echo "SSH_AGENT_PID=$SSH_AGENT_PID"
|
||||
# Only an agent this job started is stopped at the end.
|
||||
echo "VOELIN_AGENT_STARTED=1"
|
||||
} >> "$GITHUB_ENV"
|
||||
started=1
|
||||
- name: Linux packages
|
||||
run: scripts/docker-build.sh linux --progress=plain
|
||||
- name: Windows packages (MinGW)
|
||||
@@ -74,21 +104,19 @@ jobs:
|
||||
--build-arg "SIGNING_CACHE_BUST=$(basename "$signing")" \
|
||||
--secret "id=keystore,src=$signing/release.jks" \
|
||||
--secret "id=signing,src=$SIGNING_ENV"
|
||||
- name: Flatpak bundle
|
||||
run: scripts/flatpak-build.sh dist/flatpak
|
||||
- name: Gateway container image
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version=$(sed -n 's/^version = "\(.*\)"$/\1/p' crates/voelin-gateway/Cargo.toml | head -n 1)
|
||||
test -n "$version"
|
||||
docker build -f crates/voelin-gateway/Dockerfile -t "tsgw:$version" -t tsgw:latest .
|
||||
DOCKER_BUILDKIT=1 docker build --ssh default -f crates/voelin-gateway/Dockerfile -t "tsgw:$version" -t tsgw:latest .
|
||||
mkdir -p dist/gateway
|
||||
docker save "tsgw:$version" tsgw:latest | gzip > dist/gateway/tsgw-image.tar.gz
|
||||
- name: Collect packages and checksums
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p dist/release
|
||||
for file in dist/{linux,windows,android,flatpak,gateway}/*; do
|
||||
for file in dist/{linux,windows,android,gateway}/*; do
|
||||
[[ -f "$file" && ! -L "$file" ]] || { echo "Missing package: $file" >&2; exit 1; }
|
||||
name=$(basename "$file")
|
||||
[[ "$name" != SHA256SUMS* ]] || continue
|
||||
@@ -108,3 +136,9 @@ jobs:
|
||||
# Gitea refuses secret names starting with GITEA_ or GITHUB_.
|
||||
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
run: scripts/gitea-release.sh dist/release
|
||||
- name: Stop the ssh-agent
|
||||
if: always()
|
||||
run: |
|
||||
if [[ -n "${VOELIN_AGENT_STARTED:-}" && -n "${SSH_AGENT_PID:-}" ]]; then
|
||||
ssh-agent -k > /dev/null || true
|
||||
fi
|
||||
@@ -1,12 +1,13 @@
|
||||
name: System dependencies
|
||||
description: >
|
||||
Native libraries and tools the workspace builds against: apt packages on
|
||||
Linux; NASM and libvpx (vcpkg, cached) on Windows, exporting VPX_LIB_DIR,
|
||||
VPX_INCLUDE_DIR, VPX_VERSION and VPX_STATIC for libvpx-native-sys.
|
||||
Linux; NASM, libvpx and dav1d (vcpkg, cached) on Windows, exporting
|
||||
VPX_LIB_DIR, VPX_INCLUDE_DIR, VPX_VERSION and VPX_STATIC for
|
||||
libvpx-native-sys and SYSTEM_DEPS_DAV1D_* for dav1d-sys.
|
||||
|
||||
inputs:
|
||||
vpx-triplet:
|
||||
description: vcpkg triplet for libvpx on Windows (static library, dynamic CRT like Rust's default)
|
||||
description: vcpkg triplet for libvpx and dav1d on Windows (static libraries, dynamic CRT like Rust's default)
|
||||
default: x64-windows-static-md
|
||||
|
||||
runs:
|
||||
@@ -47,8 +48,8 @@ runs:
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ${{ runner.temp }}\vcpkg-archives
|
||||
key: vcpkg-libvpx-${{ inputs.vpx-triplet }}-${{ steps.vcpkg.outputs.commit }}
|
||||
restore-keys: vcpkg-libvpx-${{ inputs.vpx-triplet }}-
|
||||
key: vcpkg-libvpx-dav1d-${{ inputs.vpx-triplet }}-${{ steps.vcpkg.outputs.commit }}
|
||||
restore-keys: vcpkg-libvpx-dav1d-${{ inputs.vpx-triplet }}-
|
||||
|
||||
- name: libvpx
|
||||
if: runner.os == 'Windows'
|
||||
@@ -60,7 +61,7 @@ runs:
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$vcpkg = Join-Path $env:VCPKG_INSTALLATION_ROOT 'vcpkg.exe'
|
||||
New-Item -ItemType Directory -Force (Join-Path $env:RUNNER_TEMP 'vcpkg-archives') | Out-Null
|
||||
& $vcpkg install "libvpx:$env:TRIPLET"
|
||||
& $vcpkg install "libvpx:$env:TRIPLET" "dav1d:$env:TRIPLET"
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
|
||||
# "libvpx:x64-windows-static-md 1.15.2#1 The reference ..."
|
||||
@@ -85,3 +86,19 @@ runs:
|
||||
"VPX_VERSION=$version" >> $env:GITHUB_ENV
|
||||
"VPX_STATIC=1" >> $env:GITHUB_ENV
|
||||
Write-Host "libvpx $version from $libdir"
|
||||
|
||||
# dav1d-sys (AV1 decoding) through system-deps, without pkg-config:
|
||||
# the static library, linked as dav1d.lib.
|
||||
$davdir = Join-Path $root 'lib'
|
||||
if (-not (Test-Path (Join-Path $davdir 'dav1d.lib'))) {
|
||||
$lib = Get-ChildItem $davdir -Filter '*dav1d*.lib' | Select-Object -First 1
|
||||
if (-not $lib) { Get-ChildItem $davdir; throw "no dav1d library in $davdir" }
|
||||
$davdir = Join-Path $env:RUNNER_TEMP 'dav1d-lib'
|
||||
New-Item -ItemType Directory -Force $davdir | Out-Null
|
||||
Copy-Item $lib.FullName (Join-Path $davdir 'dav1d.lib')
|
||||
}
|
||||
"SYSTEM_DEPS_DAV1D_NO_PKG_CONFIG=1" >> $env:GITHUB_ENV
|
||||
"SYSTEM_DEPS_DAV1D_SEARCH_NATIVE=$davdir" >> $env:GITHUB_ENV
|
||||
"SYSTEM_DEPS_DAV1D_LIB=dav1d" >> $env:GITHUB_ENV
|
||||
"SYSTEM_DEPS_DAV1D_LINK=static" >> $env:GITHUB_ENV
|
||||
Write-Host "dav1d from $davdir"
|
||||
@@ -20,6 +20,10 @@ permissions:
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
RUST_BACKTRACE: "0"
|
||||
# GitHub's runners have 16 GB: the generated UI library does not fit
|
||||
# in that next to other crates, and the runner is killed. The Gitea
|
||||
# workflow keeps Cargo's default job count. The Flatpak job sets it in
|
||||
# the manifest too.
|
||||
CARGO_BUILD_JOBS: "1"
|
||||
CARGO_INCREMENTAL: "0"
|
||||
|
||||
@@ -37,10 +41,11 @@ jobs:
|
||||
key: release
|
||||
- name: Build
|
||||
run: cargo build --release --locked -p voelin-ui -p voelin-gateway
|
||||
# dpkg-shlibdeps works out the .deb's dependencies.
|
||||
# dpkg-shlibdeps works out the .deb's dependencies; patchelf points
|
||||
# the .tar.gz's binary at the libraries it carries.
|
||||
- name: Package (.tar.gz, .deb)
|
||||
run: |
|
||||
sudo apt-get install -y --no-install-recommends dpkg-dev
|
||||
sudo apt-get install -y --no-install-recommends dpkg-dev patchelf
|
||||
scripts/package.sh linux dist
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
@@ -72,6 +77,12 @@ jobs:
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
}
|
||||
"MAKENSIS=$($makensis.Replace('\', '/'))" >> $env:GITHUB_ENV
|
||||
# FFmpeg's LGPL DLLs, shipped next to voelin.exe.
|
||||
- name: FFmpeg
|
||||
shell: bash
|
||||
run: |
|
||||
scripts/fetch-ffmpeg-windows.sh "$RUNNER_TEMP/ffmpeg"
|
||||
echo "FFMPEG_DLL_DIR=$RUNNER_TEMP/ffmpeg" >> "$GITHUB_ENV"
|
||||
- name: Package (.zip, installer)
|
||||
shell: bash
|
||||
run: scripts/package.sh windows dist
|
||||
@@ -103,6 +114,13 @@ jobs:
|
||||
python3 -m venv /tmp/venv
|
||||
/tmp/venv/bin/pip install --quiet "aiohttp>=3.9.5,<4" "tomlkit>=0.13.3,<1" "PyYAML>=6.0.2,<7"
|
||||
/tmp/venv/bin/python /tmp/flatpak-cargo-generator.py Cargo.lock -o packaging/flatpak/cargo-sources.json
|
||||
# flatpak-builder does not pass the job's environment into its sandbox,
|
||||
# and the manifest keeps Cargo's default job count for Gitea: one job
|
||||
# here, as for the other packages.
|
||||
- name: One Cargo job
|
||||
run: |
|
||||
sed -i 's/^ CARGO_NET_OFFLINE: "true"$/&\n CARGO_BUILD_JOBS: "1"/' packaging/flatpak/io.github.faumaray.Voelin.yml
|
||||
grep -q '^ CARGO_BUILD_JOBS: "1"$' packaging/flatpak/io.github.faumaray.Voelin.yml
|
||||
- uses: flatpak/flatpak-github-actions/flatpak-builder@v6
|
||||
with:
|
||||
bundle: voelin.flatpak
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
/target/
|
||||
/dev/.state/
|
||||
/dist/
|
||||
/.cargo/
|
||||
+224
@@ -6,6 +6,230 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- Log files: each run logs to `<state>/voelin/logs/voelin.log`, the previous
|
||||
four runs are kept; `VOELIN_LOG` sets what is logged. Settings → Advanced
|
||||
opens the folder.
|
||||
- Linux `.tar.gz`: libvpx and libdav1d in `lib/`, and `bin/voelin-install-deps`
|
||||
for FFmpeg, VA-API drivers, PipeWire, the desktop portal and a keyring.
|
||||
- Windows packages ship FFmpeg's LGPL libraries, so hardware encoders and
|
||||
decoders work without installing FFmpeg.
|
||||
- AV1 decoding through dav1d in every desktop build.
|
||||
- 122 more signed client versions (`Versions.csv`).
|
||||
- Icon buttons show their name on hover (desktop), also while they are
|
||||
disabled.
|
||||
- The voice channel view on desktop can copy an invite link to the channel,
|
||||
as the phone's Invite button does.
|
||||
- Other people's myTeamSpeak badges: up to three pictures after their name
|
||||
in the channel tree and the members panel, and their names on the member
|
||||
card (what each is for on hover). On TeamSpeak 6 the badges the server
|
||||
verified come first.
|
||||
- Links in chat open in the browser; one whose text is not its address
|
||||
first shows where it goes. A right-click on a link opens or copies it.
|
||||
- `ts3server://` and `teamspeak://` links in chat (and `tmspk.gg/s/…`)
|
||||
open the server dialog filled in from the link, its channel and key
|
||||
included, or move you into the link's channel when you are in voice on
|
||||
that server. Nothing connects before Connect, and a saved server keeps
|
||||
its nickname. `tmspk.gg` invite codes can't be opened yet.
|
||||
- Every message can be quoted into the composer (`> ` lines) and its text
|
||||
copied, from the actions on hover or a right-click menu, also on servers
|
||||
without a gateway.
|
||||
- A "New" line above the first unread message of a chat, and a bar that
|
||||
counts the new messages with a jump to the first; unread counts survive
|
||||
restarts. Messages count as read only while their chat is on screen in
|
||||
the focused window.
|
||||
- Other users' myTeamSpeak avatars (TeamSpeak 6), as the official client
|
||||
shows them: where the server has no avatar of them, its avatar could not
|
||||
be downloaded, or the server is only observed.
|
||||
- Pictures (banners, avatars) go through the desktop's proxy where the
|
||||
desktop portal names one (Linux), and through the system proxy on
|
||||
Windows and macOS; SOCKS proxies work too.
|
||||
- tsgw logs what it does: a startup summary, the address the TeamSpeak
|
||||
server sees for its queries (with a hint when that address is not
|
||||
allowlisted), every app connection with its logins and how long they
|
||||
took, refused logins, slow requests, ServerQuery failures, relays and the
|
||||
observer. `log.level` (`TSGW_LOG_LEVEL`) sets what is logged, `log.file`
|
||||
(`TSGW_LOG_FILE`) also writes to a file that is rotated at 20 MB (five
|
||||
kept); colour only on a terminal.
|
||||
- Every gateway a server publishes is tried in turn (TLS first, 20 seconds
|
||||
each) before waiting to try again, so a TLS proxy that fails falls back to
|
||||
the plain gateway published next to it.
|
||||
- A call bar on the desktop's voice channel page: mute, deafen, share, the
|
||||
voice settings and Leave, under the people and streams (Voice Settings
|
||||
and Leave left the header). A smaller stage, one row of people and the
|
||||
streams as rows, leaves about 200 px more for the chat; it is remembered,
|
||||
and windows under 800 px tall always have it.
|
||||
- A theatre mode for streams: the stream viewer's new button fills the
|
||||
window with the stream and its chat, without the servers, the channels
|
||||
and the members. Escape leaves it, and full screen too.
|
||||
- Streams pop out into a window of their own on the desktop, optionally
|
||||
kept on top of other windows, while the main window goes on; closing it
|
||||
brings the stream back.
|
||||
|
||||
### Changed
|
||||
|
||||
- The view models, the app's state and the decisions of the settings pages and
|
||||
of the Stream Studio moved out of `voelin-ui` into a new crate,
|
||||
`voelin-ui-vm`, which depends on no UI toolkit (a second front end can use
|
||||
it); `voelin-ui` converts its plain rows into Slint's and keeps the window,
|
||||
the Bridge writes and the engine's tasks. The chat formatting reader and the
|
||||
Twemoji archive moved with them. Nothing changes on screen. See
|
||||
docs/ui.md, "Two crates".
|
||||
- The identity store keeps identities of more than one kind (TeamSpeak, a Voelin
|
||||
key, the signed-in account) with the account each belongs to, as a
|
||||
`voelin-identity` key store, in two database migrations. Existing
|
||||
databases migrate on first start and every identity stays what it was (kind
|
||||
TeamSpeak, no account, same key, name, origin and default); nothing changes
|
||||
on screen yet. The build now fetches `voelin-identity` from the private
|
||||
VoelinProtocol repository, so a fresh checkout needs read access to it
|
||||
(see docs/building.md).
|
||||
- Selecting a server observes it through its gateway at once; the Observe
|
||||
button is gone. The server dialog asks only for the address, password,
|
||||
name and nickname: the gateway is found from the address.
|
||||
- Relayed messages appear in TeamSpeak under the author's own nickname
|
||||
(`Nick1` while the name is taken), not as `[Nick] text` from the relay.
|
||||
- The client reports itself as TeamSpeak 6 (`6.0.0-beta4.1` on Linux,
|
||||
`6.0.0-beta2` on Windows) instead of `3.?.?`; `--client-version generic`
|
||||
claims the old version.
|
||||
- Watching streams: VP8 decodes on one thread (FFmpeg's slice threads made
|
||||
multi-partition streams 40-80 % slower), pictures are converted for the
|
||||
window on their own thread into reused buffers, and libvpx and dav1d use
|
||||
fewer threads. A 1440p60 VP8 stream from a 6-8 core sender showed 35-49
|
||||
fps; FFmpeg decodes it at 95-101 fps on one thread against 54-60 on four.
|
||||
- Release builds no longer limit Cargo to one job.
|
||||
- The gateway is invisible: relayed messages look like everyone else's (no
|
||||
"via relay"), and a gateway that is away is tried again quietly instead
|
||||
of showing a WebSocket error; only what the user did and failed is
|
||||
told, in plain words. A server whose gateway is away no longer shows as
|
||||
connecting, so it can always be joined.
|
||||
- A server's published gateway replaces one stored before (found or typed
|
||||
into an older version), so a gateway that moved is followed.
|
||||
- zbus's warnings about desktop portal requests are left out of the logs.
|
||||
- Pop-ups, menus and tooltips have a clearer edge, and the member card, the
|
||||
emoji picker and the notifications panel dim the window behind them.
|
||||
- Double-clicking a channel of a server without voice connects into it
|
||||
(it said "not connected with voice").
|
||||
- Older chat messages load when scrolling up, above the messages on screen,
|
||||
which stay in place; the Older messages button remains for a chat that
|
||||
fits on the screen.
|
||||
- One dialog adds a server, with Save and Connect (Enter connects).
|
||||
Connect connects only a server it saved (Join connected the server shown
|
||||
before when saving failed).
|
||||
- A slimmer top bar on desktop: only the search and the bell. The bell's
|
||||
panel opens under the bell and is as tall as its notices; the members
|
||||
button is in the voice channel's header (as in the chat's), About in
|
||||
Settings. The user card has no settings gear (the rail's stays); its
|
||||
avatar and name open your account.
|
||||
- Home shows where you left off (the last voice channel, joined in one
|
||||
click) and your unread mentions; the welcome banner shows only before the
|
||||
first server. Friends show once, the quick actions are gone, and the
|
||||
sidebar lists your recent private chats.
|
||||
- Each server has a colour of its own (two often shared a blue), and small
|
||||
server icons are drawn sharp at twice their size instead of stretched.
|
||||
Small avatars, as in the channel tree, show one letter.
|
||||
- Channels have one icon everywhere, the speaker, and are named without a
|
||||
`#` in tabs and elsewhere.
|
||||
- The members panel shows a hand on those who need talk power to speak,
|
||||
instead of everyone's talk power as a bare number (the member card still
|
||||
has it).
|
||||
- The chat header's pinned messages and topics are icon buttons with a
|
||||
count, so the channel's topic has room.
|
||||
- Private chats live on the Direct Messages page, not in the server's chat
|
||||
tabs, and their unread messages count there (on the phone, on the Home
|
||||
tab) instead of on the server rail.
|
||||
- Stream cards show the streamer: their avatar on a painted scene in their
|
||||
colour, with what they share, instead of a bare screen icon (TeamSpeak
|
||||
streams have no preview pictures). Your own stream from the Stream Studio
|
||||
shows its picture.
|
||||
- The stream viewer's controls hide while you watch, 2.5 s after the
|
||||
pointer last moved over the picture (in full screen the cursor too; on a
|
||||
touch screen a tap shows or hides them), and the streamer, the title and
|
||||
LIVE are in the header above the picture instead of over it.
|
||||
- The phone's voice screen has one header: the top bar shows the channel on
|
||||
its banner, the server below it instead of the channel's topic, and Back;
|
||||
Leave is only in the bottom bar. Pinned messages and topics are in the
|
||||
More menu and the row of people is smaller, so the chat has about 130 px
|
||||
more room. With push-to-talk, Hold to talk is the bottom bar's middle
|
||||
button instead of the microphone button by the composer; Go Live and
|
||||
Share are one Share button that opens the share menu (a screen, or the
|
||||
Stream Studio) as on desktop. The microphone button says Mic on or Mic
|
||||
off.
|
||||
- The phone's Servers tab is titled Servers; the server's name and counts
|
||||
are only in the server card below the server icons, no longer in the top
|
||||
bar too. The voice card shows only your channel, on desktop too.
|
||||
- Banners: up to 128 MiB, more time on slow hosts, BMP and ICO too, and
|
||||
SVG after a comment or DOCTYPE; pictures larger than 4096 pixels on a
|
||||
side are scaled down. A banner that fails is tried again for as long as
|
||||
it is shown (every 15 minutes at most), and the log says why it is
|
||||
missing (HTTP status, an HTML page, a video, too large). The picture
|
||||
cache defaults to 1 GiB, the decoded images to 256 MB.
|
||||
- Banners that fail: the log names the URL (without its query) the first
|
||||
time, says when a connection stalled and after how much data, and when it
|
||||
could not connect at all. A banner that is not there (HTTP 400, 404, 410)
|
||||
is tried again after 15 minutes and then hourly; a host that asks to wait
|
||||
(429, 503) is waited for. A banner shown again is only checked for
|
||||
changes (ETag, Last-Modified), not downloaded again. At most 6 downloads
|
||||
run per host, so a slow host cannot hold up the others.
|
||||
- The gateway: only a refused login stops observing; anything else is tried
|
||||
again after 1, 2, 5, 10, 20, then every 30 seconds, and at once when voice
|
||||
connects. A connection that stops answering is noticed within 90 seconds.
|
||||
Finding a server's gateway asks DNS and the gateway at once instead of one
|
||||
after the other. The log says what was found, which gateway was tried,
|
||||
how long each step took and why one failed.
|
||||
- tsgw answers faster: each ServerQuery command takes under 2 ms instead of
|
||||
about 45 ms (TCP_QUICKACK), so logins and startup take milliseconds.
|
||||
TeamSpeak's flood protection is shared by all of tsgw's query
|
||||
connections, so tsgw no longer earns a 600 second ban. It starts while
|
||||
the TeamSpeak server is still down and connects once it is up, its
|
||||
`/health` says what is missing, and it stops cleanly on SIGTERM.
|
||||
|
||||
### Removed
|
||||
|
||||
- myTeamSpeak account sign-in, profile, avatar, badges and User Tag: the
|
||||
login page at start, the sign-in form and profile in Settings → My Account
|
||||
(it says "Account sign-in is not available in this build"), and the account
|
||||
presented to voice servers. They return through the gateway. A session an
|
||||
earlier build saved stays in the system keyring (item `myts/session`)
|
||||
until you delete it there.
|
||||
|
||||
### Fixed
|
||||
|
||||
- A deleted identity key no longer stays in the database file: SQLite overwrites
|
||||
what it deletes, and the log is truncated after a key is deleted (an identity
|
||||
you delete, a key a sign-out deletes).
|
||||
- Hover help in the Stream Studio (a source's error, the status details)
|
||||
shows each time and closes when the pointer leaves; it showed only once,
|
||||
and stayed open until a click.
|
||||
- Spacer channels: `[spacer]`, `[lspacer]`, `[rspacer]` and `[*spacer]` lines
|
||||
are drawn as TeamSpeak draws them, like `[cspacer]` was, and chats, search
|
||||
results, notifications and the other screens show a spacer's text instead
|
||||
of its raw name.
|
||||
- Locked channels ask for their password (kept until voice disconnects, and
|
||||
asked again when it is wrong), and joining a full channel or one the
|
||||
server refuses says why; joining did nothing before.
|
||||
- Pokes can carry a message (up to 100 characters); they were always sent
|
||||
empty.
|
||||
- While a priority speaker talks, everyone else (watched streams too) is
|
||||
dimmed by the server's setting, as in TeamSpeak; nobody was dimmed before.
|
||||
- BBCode from other clients shows as formatting (bold, colours, links,
|
||||
quotes, lists, code, pictures) instead of raw tags, and the server's
|
||||
welcome message opens the server chat. Messages with emoji keep their
|
||||
line breaks.
|
||||
- Joining a friend in a subchannel of a server without voice connects into
|
||||
that subchannel; it connected into the default channel.
|
||||
- Closing a chat tab left of the selected one keeps the selected chat; the
|
||||
one after it was selected.
|
||||
- Connecting with voice from a private chat (Direct Messages) keeps that
|
||||
conversation open; it turned into the voice channel's chat, and the
|
||||
composer sent there.
|
||||
- Observing no longer stops for the whole run the first time a server is
|
||||
joined with a new identity (the gateway did not know it yet).
|
||||
- tsgw reconnects its query connection for logins when the TeamSpeak server
|
||||
restarts; before, every login was refused until tsgw was restarted.
|
||||
- Push-to-talk controls (Hold to talk) showed in voice activation and
|
||||
continuous mode until the settings had been opened once.
|
||||
|
||||
## [0.0.1-alpha] - 2026-10-04
|
||||
|
||||
The first alpha.
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
# Voelin — working agreements for Claude Code
|
||||
|
||||
Voelin is a Rust voice/chat client that is becoming a complete alternative to
|
||||
TeamSpeak 6 and Discord. The project is being split into four repositories
|
||||
(VoelinClient, VoelinProtocol, VoelinServer, VoelinGateWay) under the Gitea
|
||||
org `Voelin`; the current plan lives in the approved plan file referenced in
|
||||
`docs/` once committed. Keep the Rust toolchain in `rust-toolchain.toml`,
|
||||
`cargo fmt` (hard tabs, `rustfmt.toml`) and `cargo clippy -D warnings` on the
|
||||
project's own crates (`scripts/own-crates.sh`) green.
|
||||
|
||||
## Hosting: Gitea, not GitHub
|
||||
|
||||
- The source of truth is **https://git.faumaray.com** (Gitea). Pull requests,
|
||||
issues, releases, labels and repository creation go through the **Gitea MCP
|
||||
connector** (`mcp__claude_ai_gitea__*`). Do not use `gh`, the GitHub API or
|
||||
GitHub Actions assumptions; `.github/workflows` are kept only as reference.
|
||||
- Git remotes are `gitea@git.faumaray.com:<owner>/<repo>.git`. CI runs on
|
||||
Gitea Actions (`.gitea/workflows`).
|
||||
- Report when the connector is unavailable instead of silently falling back
|
||||
to another host or to raw `curl`.
|
||||
|
||||
## Multi-agent orchestration (MAO) policy
|
||||
|
||||
**Scope: these orchestration rules apply only to the MAIN SESSION.** A
|
||||
subagent that reads this file performs its assigned role (design, implement,
|
||||
review, help) and does not delegate it again or spawn further orchestration.
|
||||
|
||||
### Roles
|
||||
|
||||
| Agent | Model / effort | Job |
|
||||
|---|---|---|
|
||||
| main session | (settings) | **Orchestrator**: decomposes work, delegates, tracks progress and attempt counts, resolves escalations, reports results. Delegates implementation, investigation, testing and review rather than doing them inline. |
|
||||
| `mao-designer` | opus / xhigh | Designs, acceptance criteria, escalation handling |
|
||||
| `mao-implementer` | sonnet / xhigh | Implements, runs checks, self-reviews; escalates after 3 failed attempts |
|
||||
| `mao-sonnet-reviewer` | sonnet / xhigh | Fresh, independent implementation review |
|
||||
| `mao-opus-reviewer` | opus / xhigh | Fresh, final independent review of substantive code changes (correctness, architecture, unresolved risks) |
|
||||
| `mao-helper` | haiku | Focused file searches, summaries, routine git operations within the user's authorization |
|
||||
|
||||
### Before delegating
|
||||
|
||||
Define, in the delegation prompt: the **objective**, the **scope** (what is
|
||||
in and out, which files), the **acceptance criteria** (checks that must pass,
|
||||
behaviour that must hold), the **relevant files** and the **expected report**.
|
||||
Use named agents (`name:` in the Agent call) so collaborators can address
|
||||
each other.
|
||||
|
||||
### Parallelism
|
||||
|
||||
Parallelize **independent** work only. Never give two agents the same files
|
||||
to edit at the same time; split by crate, module or file set, or serialize.
|
||||
|
||||
### Implementation and review chain
|
||||
|
||||
1. `mao-implementer` implements, runs the relevant checks (`cargo fmt
|
||||
--check`, `cargo clippy -D warnings` on the touched crates, the crate's
|
||||
tests, and the integration/smoke scenarios named in the task) and
|
||||
self-reviews before reporting.
|
||||
2. A **fresh** `mao-sonnet-reviewer` reviews the implementation independently.
|
||||
3. For substantive code changes, a **fresh** `mao-opus-reviewer` performs the
|
||||
final independent review. Do not reuse the design agent's conversation
|
||||
for this review; start a new agent.
|
||||
4. The orchestrator decides: accept, send back with the findings, or escalate.
|
||||
|
||||
### Attempts and escalation
|
||||
|
||||
- Track failed attempts **per task**. An *attempt* is a proposed solution
|
||||
checked against the acceptance criteria, not an individual tool call.
|
||||
- After **3 unsuccessful implementation attempts**, stop Sonnet retries and
|
||||
escalate to `mao-designer` (Opus) with the evidence: what was tried, the
|
||||
failing check output, the diff.
|
||||
- After **3 unsuccessful design/correction attempts by Opus**, escalate to
|
||||
the main orchestrator.
|
||||
- The orchestrator must then **change the approach, narrow the task, or ask
|
||||
the user for the missing input**. Do not reset counters and repeat the
|
||||
same loop.
|
||||
|
||||
### Communication
|
||||
|
||||
- Use `SendMessage` for direct agent-to-agent or agent-to-orchestrator
|
||||
messages when it is available. Use `ListAgents` only if it is actually
|
||||
exposed; otherwise address agents by their known names, or relay through
|
||||
the orchestrator.
|
||||
- Reports (every agent, every task) must include: **result**, **changed
|
||||
files**, **checks actually run** (with their outcome), **unresolved
|
||||
issues**, and the **attempt count**.
|
||||
- Report unavailable agents, models or tools explicitly, together with the
|
||||
fallback that was used (for example "mao-opus-reviewer unavailable, review
|
||||
done by mao-sonnet-reviewer").
|
||||
|
||||
### Models and effort
|
||||
|
||||
Model and effort live in `.claude/settings.json` (session default) and in
|
||||
each agent's frontmatter (per role). Do not set `CLAUDE_CODE_EFFORT_LEVEL`
|
||||
globally: the roles need different effort levels.
|
||||
Generated
+94
-242
@@ -1996,7 +1996,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
||||
dependencies = [
|
||||
"const-oid 0.9.6",
|
||||
"der_derive",
|
||||
"der_derive 0.7.3",
|
||||
"flagset",
|
||||
"pem-rfc7468 0.7.0",
|
||||
"zeroize",
|
||||
@@ -2009,6 +2009,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a"
|
||||
dependencies = [
|
||||
"const-oid 0.10.2",
|
||||
"der_derive 0.8.0",
|
||||
"flagset",
|
||||
"pem-rfc7468 1.0.0",
|
||||
"zeroize",
|
||||
]
|
||||
@@ -2038,6 +2040,17 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "der_derive"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59600e2c2d636fde9b65e99cc6445ac770c63d3628195ff39932b8d6d7409903"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
version = "0.5.8"
|
||||
@@ -2134,7 +2147,7 @@ dependencies = [
|
||||
"spki 0.7.3",
|
||||
"subtle",
|
||||
"time",
|
||||
"x509-cert",
|
||||
"x509-cert 0.2.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3502,19 +3515,6 @@ dependencies = [
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper-timeout"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0"
|
||||
dependencies = [
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper-util"
|
||||
version = "0.1.21"
|
||||
@@ -3534,9 +3534,11 @@ dependencies = [
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"socket2",
|
||||
"system-configuration",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
"windows-registry",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4877,12 +4879,6 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multimap"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084"
|
||||
|
||||
[[package]]
|
||||
name = "multiversion_no_op"
|
||||
version = "1.0.0"
|
||||
@@ -5861,7 +5857,6 @@ checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629"
|
||||
dependencies = [
|
||||
"digest 0.11.3",
|
||||
"hmac 0.13.0",
|
||||
"sha2 0.11.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6340,27 +6335,6 @@ dependencies = [
|
||||
"prost-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prost-build"
|
||||
version = "0.14.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "03da047801ff44bb6a4d407d4860c05fd70bb81714e6b2f3812603d5b145b042"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"itertools 0.14.0",
|
||||
"log",
|
||||
"multimap",
|
||||
"petgraph",
|
||||
"prettyplease",
|
||||
"prost",
|
||||
"prost-types",
|
||||
"pulldown-cmark",
|
||||
"pulldown-cmark-to-cmark",
|
||||
"regex",
|
||||
"syn 2.0.119",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prost-derive"
|
||||
version = "0.14.4"
|
||||
@@ -6374,79 +6348,6 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prost-types"
|
||||
version = "0.14.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f94967dc7688f3054c7fac87473ffae4cc4c3904800e2d9f5b857246d8963b0a"
|
||||
dependencies = [
|
||||
"prost",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "protoc-bin-vendored"
|
||||
version = "3.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d1c381df33c98266b5f08186583660090a4ffa0889e76c7e9a5e175f645a67fa"
|
||||
dependencies = [
|
||||
"protoc-bin-vendored-linux-aarch_64",
|
||||
"protoc-bin-vendored-linux-ppcle_64",
|
||||
"protoc-bin-vendored-linux-s390_64",
|
||||
"protoc-bin-vendored-linux-x86_32",
|
||||
"protoc-bin-vendored-linux-x86_64",
|
||||
"protoc-bin-vendored-macos-aarch_64",
|
||||
"protoc-bin-vendored-macos-x86_64",
|
||||
"protoc-bin-vendored-win32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "protoc-bin-vendored-linux-aarch_64"
|
||||
version = "3.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c350df4d49b5b9e3ca79f7e646fde2377b199e13cfa87320308397e1f37e1a4c"
|
||||
|
||||
[[package]]
|
||||
name = "protoc-bin-vendored-linux-ppcle_64"
|
||||
version = "3.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a55a63e6c7244f19b5c6393f025017eb5d793fd5467823a099740a7a4222440c"
|
||||
|
||||
[[package]]
|
||||
name = "protoc-bin-vendored-linux-s390_64"
|
||||
version = "3.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1dba5565db4288e935d5330a07c264a4ee8e4a5b4a4e6f4e83fad824cc32f3b0"
|
||||
|
||||
[[package]]
|
||||
name = "protoc-bin-vendored-linux-x86_32"
|
||||
version = "3.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8854774b24ee28b7868cd71dccaae8e02a2365e67a4a87a6cd11ee6cdbdf9cf5"
|
||||
|
||||
[[package]]
|
||||
name = "protoc-bin-vendored-linux-x86_64"
|
||||
version = "3.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b38b07546580df720fa464ce124c4b03630a6fb83e05c336fea2a241df7e5d78"
|
||||
|
||||
[[package]]
|
||||
name = "protoc-bin-vendored-macos-aarch_64"
|
||||
version = "3.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "89278a9926ce312e51f1d999fee8825d324d603213344a9a706daa009f1d8092"
|
||||
|
||||
[[package]]
|
||||
name = "protoc-bin-vendored-macos-x86_64"
|
||||
version = "3.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "81745feda7ccfb9471d7a4de888f0652e806d5795b61480605d4943176299756"
|
||||
|
||||
[[package]]
|
||||
name = "protoc-bin-vendored-win32"
|
||||
version = "3.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "95067976aca6421a523e491fce939a3e65249bac4b977adee0ee9771568e8aa3"
|
||||
|
||||
[[package]]
|
||||
name = "pulldown-cmark"
|
||||
version = "0.13.4"
|
||||
@@ -6458,15 +6359,6 @@ dependencies = [
|
||||
"unicase",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pulldown-cmark-to-cmark"
|
||||
version = "22.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "84bbb29c624230c4bd1047bbdb2aa47e41c860e9665ce62ba9504eebe91bf867"
|
||||
dependencies = [
|
||||
"pulldown-cmark",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pxfm"
|
||||
version = "0.1.30"
|
||||
@@ -7257,12 +7149,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.23.45"
|
||||
version = "0.23.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
|
||||
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"log",
|
||||
"once_cell",
|
||||
"rustls-pki-types",
|
||||
"rustls-webpki",
|
||||
@@ -7380,20 +7271,6 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "schema-api"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"prost",
|
||||
"prost-build",
|
||||
"prost-types",
|
||||
"protoc-bin-vendored",
|
||||
"thiserror 2.0.21",
|
||||
"tonic",
|
||||
"tonic-prost",
|
||||
"tonic-prost-build",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "scoped-tls"
|
||||
version = "1.0.1"
|
||||
@@ -7869,6 +7746,7 @@ dependencies = [
|
||||
"i-slint-backend-android-activity",
|
||||
"i-slint-backend-linuxkms",
|
||||
"i-slint-backend-selector",
|
||||
"i-slint-backend-winit",
|
||||
"i-slint-common",
|
||||
"i-slint-core",
|
||||
"i-slint-core-macros",
|
||||
@@ -8853,76 +8731,6 @@ version = "1.1.2+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"
|
||||
|
||||
[[package]]
|
||||
name = "tonic"
|
||||
version = "0.14.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"h2",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-timeout",
|
||||
"hyper-util",
|
||||
"percent-encoding",
|
||||
"pin-project",
|
||||
"rustls-native-certs",
|
||||
"socket2",
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tokio-stream",
|
||||
"tower",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tonic-build"
|
||||
version = "0.14.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c68f61875ac5293cf72e6c8cf0158086428c82c37229e98c840878f1706b0322"
|
||||
dependencies = [
|
||||
"prettyplease",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tonic-prost"
|
||||
version = "0.14.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "50849f68853be452acf590cde0b146665b8d507b3b8af17261df47e02c209ea0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"prost",
|
||||
"tonic",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tonic-prost-build"
|
||||
version = "0.14.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "654e5643eff75d7f8c99197ce1440ed19a3474eada74c12bbac488b2cafdae27"
|
||||
dependencies = [
|
||||
"prettyplease",
|
||||
"proc-macro2",
|
||||
"prost-build",
|
||||
"prost-types",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"tempfile",
|
||||
"tonic-build",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tower"
|
||||
version = "0.5.3"
|
||||
@@ -8931,12 +8739,9 @@ checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"indexmap",
|
||||
"pin-project-lite",
|
||||
"slab",
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
@@ -9657,7 +9462,6 @@ dependencies = [
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"tsclientlib",
|
||||
"voelin-core",
|
||||
"voelin-media",
|
||||
"voelin-model",
|
||||
@@ -9682,8 +9486,6 @@ dependencies = [
|
||||
"sonora-simd",
|
||||
"thiserror 2.0.21",
|
||||
"tracing",
|
||||
"tsclientlib",
|
||||
"tsproto-packets",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9692,9 +9494,13 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"dirs",
|
||||
"futures",
|
||||
"h2",
|
||||
"hickory-resolver",
|
||||
"http",
|
||||
"httpdate",
|
||||
"md5",
|
||||
"reqwest",
|
||||
"rusqlite",
|
||||
@@ -9712,11 +9518,12 @@ dependencies = [
|
||||
"tsproto-types",
|
||||
"voelin-audio",
|
||||
"voelin-gateway-proto",
|
||||
"voelin-identity",
|
||||
"voelin-media",
|
||||
"voelin-model",
|
||||
"voelin-myts",
|
||||
"voelin-observer",
|
||||
"voelin-platform",
|
||||
"voelin-proto",
|
||||
"voelin-query",
|
||||
"voelin-store",
|
||||
"voelin-stream",
|
||||
@@ -9768,6 +9575,23 @@ dependencies = [
|
||||
"voelin-model",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "voelin-identity"
|
||||
version = "0.2.0"
|
||||
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c8e0e5a17c1ff5dfaefa087f49b395d2918af650#c8e0e5a17c1ff5dfaefa087f49b395d2918af650"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"base64 0.23.1",
|
||||
"prost",
|
||||
"rcgen",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"voelin-proto",
|
||||
"x509-cert 0.3.0",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "voelin-media"
|
||||
version = "0.1.0"
|
||||
@@ -9813,27 +9637,11 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "voelin-model"
|
||||
version = "0.1.0"
|
||||
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c8e0e5a17c1ff5dfaefa087f49b395d2918af650#c8e0e5a17c1ff5dfaefa087f49b395d2918af650"
|
||||
dependencies = [
|
||||
"prost",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "voelin-myts"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"aes 0.9.3",
|
||||
"aes-gcm",
|
||||
"base64 0.22.1",
|
||||
"ctr 0.10.1",
|
||||
"pbkdf2",
|
||||
"reqwest",
|
||||
"schema-api",
|
||||
"subtle",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tsproto",
|
||||
"zeroize",
|
||||
"voelin-proto",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9862,6 +9670,18 @@ dependencies = [
|
||||
"tracing",
|
||||
"windows 0.62.2",
|
||||
"x11rb",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "voelin-proto"
|
||||
version = "0.2.0"
|
||||
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c8e0e5a17c1ff5dfaefa087f49b395d2918af650#c8e0e5a17c1ff5dfaefa087f49b395d2918af650"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"prost",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9872,6 +9692,7 @@ dependencies = [
|
||||
"russh",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"socket2",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tracing",
|
||||
@@ -9886,7 +9707,9 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"tracing",
|
||||
"tsclientlib",
|
||||
"voelin-identity",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9906,6 +9729,7 @@ dependencies = [
|
||||
"tracing-subscriber",
|
||||
"tsclientlib",
|
||||
"tsproto-packets",
|
||||
"voelin-media",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9916,7 +9740,6 @@ dependencies = [
|
||||
"chrono",
|
||||
"dirs",
|
||||
"image",
|
||||
"miniz_oxide 0.8.9",
|
||||
"png",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -9931,10 +9754,28 @@ dependencies = [
|
||||
"voelin-core",
|
||||
"voelin-gateway-proto",
|
||||
"voelin-model",
|
||||
"voelin-myts",
|
||||
"voelin-platform",
|
||||
"voelin-query",
|
||||
"voelin-store",
|
||||
"voelin-ui-vm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "voelin-ui-vm"
|
||||
version = "0.0.1-alpha"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"image",
|
||||
"miniz_oxide 0.8.9",
|
||||
"png",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"unicode-segmentation",
|
||||
"voelin-audio",
|
||||
"voelin-core",
|
||||
"voelin-gateway-proto",
|
||||
"voelin-model",
|
||||
"voelin-store",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -11074,6 +10915,17 @@ dependencies = [
|
||||
"spki 0.7.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "x509-cert"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "105ef4642d9cb137ef83d623d0e4bf08b8adf69e9918ca904a174adb6d3d038b"
|
||||
dependencies = [
|
||||
"const-oid 0.10.2",
|
||||
"der 0.8.2",
|
||||
"spki 0.8.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "x509-parser"
|
||||
version = "0.18.1"
|
||||
@@ -11190,9 +11042,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "yoke-derive"
|
||||
version = "0.8.3"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78"
|
||||
checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
|
||||
+16
-5
@@ -2,7 +2,7 @@
|
||||
resolver = "3"
|
||||
# third_party: vendored crates patched in below (not workspace members, so
|
||||
# their own tests and dev-dependencies stay out of our builds).
|
||||
exclude = ["fuzz", "third_party", "third_party/schema-api"]
|
||||
exclude = ["fuzz", "third_party"]
|
||||
members = [
|
||||
"crates/proto/tsproto-types",
|
||||
"crates/proto/tsproto-structs",
|
||||
@@ -16,14 +16,13 @@ members = [
|
||||
"crates/voelin-gateway",
|
||||
"crates/voelin-gateway-proto",
|
||||
"crates/voelin-media",
|
||||
"crates/voelin-model",
|
||||
"crates/voelin-myts",
|
||||
"crates/voelin-observer",
|
||||
"crates/voelin-platform",
|
||||
"crates/voelin-query",
|
||||
"crates/voelin-store",
|
||||
"crates/voelin-stream",
|
||||
"crates/voelin-ui",
|
||||
"crates/voelin-ui-vm",
|
||||
"tools/voelinctl",
|
||||
]
|
||||
default-members = [
|
||||
@@ -37,14 +36,13 @@ default-members = [
|
||||
"crates/voelin-core",
|
||||
"crates/voelin-gateway",
|
||||
"crates/voelin-gateway-proto",
|
||||
"crates/voelin-model",
|
||||
"crates/voelin-myts",
|
||||
"crates/voelin-observer",
|
||||
"crates/voelin-platform",
|
||||
"crates/voelin-query",
|
||||
"crates/voelin-store",
|
||||
"crates/voelin-stream",
|
||||
"crates/voelin-ui",
|
||||
"crates/voelin-ui-vm",
|
||||
"tools/voelinctl",
|
||||
]
|
||||
|
||||
@@ -55,6 +53,19 @@ license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/Faumaray/Voelin"
|
||||
publish = false
|
||||
|
||||
[workspace.dependencies]
|
||||
# The protocol repository is private (VoelinProtocol). This is the SSH URL its
|
||||
# docs/development.md names, so that a per-developer .cargo/config.toml [patch]
|
||||
# can point it at a sibling checkout (docs/building.md, "Working with a sibling
|
||||
# VoelinProtocol checkout"). Pinned by commit until the protocol tags a release:
|
||||
# the three crates below are at one revision (main c8e0e5a: the account-bound
|
||||
# KeyStore of Phase 2 task 28, the account types of the session seam).
|
||||
voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" }
|
||||
# The backend-neutral session seam (`voelin_proto::link`) and the v1 messages.
|
||||
voelin-proto = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" }
|
||||
# The UI-facing domain model and the client's replica of v1 entities.
|
||||
voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" }
|
||||
|
||||
[workspace.lints.rust]
|
||||
# deny, not forbid: generated code (Slint) needs a local allow.
|
||||
unsafe_code = "deny"
|
||||
|
||||
@@ -28,7 +28,7 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
|
||||
- `crates/proto/`: vendored tsclientlib, modernised (TS6 fields and stream
|
||||
messages, faster off-thread Init1 puzzle, `curve25519-dalek` 4, fuzzing fixes;
|
||||
see [UPSTREAM.md](crates/proto/UPSTREAM.md))
|
||||
- `crates/voelin-model`: server flavor detection (TS3 / TS6) and capabilities
|
||||
- `voelin-model` (from VoelinProtocol, a git dependency): domain model, server flavor detection (TS3 / TS6) and capabilities
|
||||
- `crates/voelin-audio`: Opus voice encoding, framing, resampling, WAV, jitter buffer/mixer, cpal devices
|
||||
- `crates/voelin-store`: SQLite store for identities, bookmarks, settings and chat history; keyring secrets
|
||||
- `crates/voelin-query`: ServerQuery client over raw TCP, SSH and HTTP WebQuery (events, rate limiting, keepalive)
|
||||
@@ -41,10 +41,13 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
|
||||
reactions, topics, events, stream directory and administration; the media pipeline for streams
|
||||
(capture → VP8 + Opus → stream, stream → decoder)
|
||||
- `crates/voelin-ui` (`voelin`): Slint desktop app: servers, channel tree with talking indicators,
|
||||
chat tabs (own channel via voice, other channels via relay), connect / observe invisibly, mute, push-to-talk
|
||||
chat tabs (own channel via voice, other channels via relay), connect, observe invisibly (on selecting a server, through its gateway), mute, push-to-talk
|
||||
(in the window and as a global hotkey), audio settings with a level meter, per-client volume, and on
|
||||
TeamSpeak 6 streams: watch in a viewer, share the screen with sound. Desktop and phone layouts
|
||||
from one design system, dark and light themes, text size, emoji ([docs/ui.md](docs/ui.md))
|
||||
- `crates/voelin-ui-vm`: the view models and the app's state behind the UI, with no UI toolkit: engine state
|
||||
as plain rows and forms, chat formatting, the Twemoji archive, and what the settings pages and the
|
||||
Stream Studio decide; `voelin-ui` puts them on Slint windows ([docs/ui.md](docs/ui.md))
|
||||
- `crates/voelin-stream`: TeamSpeak 6 streams: stream commands and notifications, JSON signalling,
|
||||
WebRTC peers (str0m) with host and STUN candidates. A live test streams VP8 + Opus between two
|
||||
clients through a TS6 server
|
||||
|
||||
+4
-9
@@ -21,16 +21,15 @@ dependencies to their projects (tell us too if this client is affected).
|
||||
|
||||
## What the client stores
|
||||
|
||||
There is no telemetry and no account with us. The only outside account is
|
||||
the optional myTeamSpeak sign-in (desktop), which talks to TeamSpeak's
|
||||
service at `clientapi.myteamspeak.com`: at sign-in, when a saved session is
|
||||
checked at start, and at sign-out.
|
||||
There is no telemetry and no account with us, and the client signs in to no
|
||||
account service. (Builds before this one had an optional myTeamSpeak sign-in;
|
||||
its saved session stays in the keyring, item `myts/session`, until you delete
|
||||
it there.)
|
||||
|
||||
| What | Where | Protection |
|
||||
|---|---|---|
|
||||
| Identities (TeamSpeak private keys) | SQLite database `client.db` in the data directory (`~/.local/share/voelin`, Flatpak `~/.var/app/<app id>/data/voelin`, `%APPDATA%\voelin`, Android app storage) | File permissions of the user account only; not encrypted. An identity is the account on every server that knows it: back it up, do not share the file |
|
||||
| Server and ServerQuery passwords | OS keyring (Secret Service, Windows Credential Manager, Android Keystore), service `voelin` | Keyring; kept in memory for the session only when there is no keyring |
|
||||
| myTeamSpeak account (optional sign-in, desktop): session, renewal and one-time-code renewal tokens, device id, email, username, account id and the account's private signing key | OS keyring, service `voelin`, item `myts/session` | Keyring only: without one the sign-in is not kept, not even in memory. Passwords and one-time codes are never stored. Signing out deletes the item and ends the session at TeamSpeak |
|
||||
| Bookmarks, settings, chat history | `client.db` | File permissions; history stays until deleted |
|
||||
| Crash reports (opt-in) | `crash-reports` in the state directory (`~/.local/state/voelin`, `%LOCALAPPDATA%\voelin`) | Local only, never uploaded. They contain the panic message and a backtrace, which may include server addresses or names; review before attaching one to an issue |
|
||||
| OpenH264 (opt-in) | Downloaded from Cisco into the app's directories | Loaded only if its SHA-256 matches a known Cisco build |
|
||||
@@ -40,10 +39,6 @@ checked at start, and at sign-out.
|
||||
- **Voice connections** use the TeamSpeak protocol's encryption. The server
|
||||
and its admins see what any client sees: your nickname, identity, IP
|
||||
address, channel and messages.
|
||||
- **Signed in to myTeamSpeak**, every voice server you join also gets your
|
||||
account's myTeamSpeak id with a proof signed by the account, which links
|
||||
your visits to different servers to one account. Signing out clears it on
|
||||
the servers you are on.
|
||||
- **Streams (TeamSpeak 6)** are peer-to-peer WebRTC (DTLS-SRTP). Viewers and
|
||||
streamers exchange ICE candidates, so **they learn each other's IP
|
||||
addresses**, including local network addresses. Only watch and share
|
||||
|
||||
+93
-836
File diff suppressed because it is too large.
Load diff
+2
-1
@@ -3,7 +3,8 @@
|
||||
|
||||
<!-- From about-assets.md, appended by scripts/notices.sh. -->
|
||||
|
||||
The user interface bundles these assets (in crates/voelin-ui):
|
||||
The user interface bundles these assets (in crates/voelin-ui, the Twemoji
|
||||
archive in crates/voelin-ui-vm):
|
||||
|
||||
- Inter (the UI font), Copyright (c) 2016 The Inter Project Authors, under
|
||||
the SIL Open Font License 1.1 (OFL-1.1; text below).
|
||||
|
||||
@@ -53,13 +53,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
````
|
||||
|
||||
## schema-api
|
||||
|
||||
The account client uses message bindings and session helpers from the local
|
||||
schema-api 0.1.0 snapshot vendored under third_party/schema-api. The supplied
|
||||
snapshot has no declared license or license file; no MIT or Apache license is
|
||||
implied for it or its supplied schemas. See its VOELIN-PATCH.md for provenance.
|
||||
|
||||
## Native libraries
|
||||
|
||||
- Opus (libopus), compiled into the app: BSD-3-Clause, Copyright 2001-2023
|
||||
|
||||
@@ -129,3 +129,21 @@ against or offered back to upstream.
|
||||
Tests cover an independent signature vector, persistence validation/redaction,
|
||||
wire field names, clearing and reconnect snapshot replacement. The account
|
||||
UUID and the ordinary server identity remain separate.
|
||||
15. **myTeamSpeak presentation, TeamSpeak 6** (`tsproto/src/license.rs`,
|
||||
`tsproto/src/myts.rs`, `tsclientlib/src/myts.rs`, `tsclientlib/src/lib.rs`,
|
||||
`tsproto-packets/src/packets.rs`, `tsproto-structs/declarations/Book.toml`).
|
||||
License block types 4–7 (Token, License_Sign, MyTsId_Sign, Updater), which
|
||||
carry nothing after the header. `myts::Certificate` checks a myTeamSpeak
|
||||
certificate chain as a TeamSpeak 6 server does: leaf type, validity window,
|
||||
key derived from a given root, cofactorless Ed25519 with a reduced S;
|
||||
`Identity::id_bytes` and `public_signature_certificate`. `MytsData` holds the
|
||||
avatar and the badges, each with the certificate that verifies it, and the
|
||||
User Tag; `MytsData::updates` builds `updatemytsdata` (split by certificate,
|
||||
bare parameters to clear) and `clientupdate client_user_tag`, which
|
||||
`Connection::send_myts_update` and `send_user_tag` send. The escaped writer
|
||||
also escapes `\a` and `\b`, as TeamSpeak does for binary values. Book:
|
||||
`Client::my_team_speak_avatar`, `my_team_speak_id` and `signed_badges`.
|
||||
16. **Privilege key when connecting** (`tsclientlib/src/lib.rs`, "Voelin patch").
|
||||
`ConnectOptions::default_token` sets `client_default_token` of `clientinit`,
|
||||
which upstream always sent empty, so a privilege key (a bookmark's, or the
|
||||
`token=` of a `ts3server://` link) can be used on connect.
|
||||
@@ -61,6 +61,7 @@ pub use ts_bookkeeping::messages::s2c::InMessage;
|
||||
pub use ts_bookkeeping::*;
|
||||
pub use tsproto::resend::{ConnectionStats, PacketStat};
|
||||
pub use tsproto::Identity;
|
||||
pub use myts::{MytsData, MytsUpdate, Signed, UserTag};
|
||||
pub use tsproto_types::errors::Error as TsError;
|
||||
|
||||
/// Wait this time for initserver, in seconds.
|
||||
@@ -392,6 +393,7 @@ impl Connection {
|
||||
channel: None,
|
||||
channel_password: None,
|
||||
password: None,
|
||||
default_token: None,
|
||||
input_muted: false,
|
||||
output_muted: false,
|
||||
input_hardware_enabled: true,
|
||||
@@ -556,7 +558,7 @@ impl Connection {
|
||||
version_sign: Cow::Borrowed(client_version_sign.as_ref()),
|
||||
client_key_offset: counter,
|
||||
phonetic_name: "".into(),
|
||||
default_token: "".into(),
|
||||
default_token: Cow::Borrowed(options.default_token.as_deref().unwrap_or_default()),
|
||||
hardware_id: Cow::Borrowed(options.hardware_id.as_ref()),
|
||||
badges: None,
|
||||
signed_badges: None,
|
||||
@@ -1730,6 +1732,7 @@ pub struct ConnectOptions {
|
||||
channel: Option<Cow<'static, str>>,
|
||||
channel_password: Option<Cow<'static, str>>,
|
||||
password: Option<Cow<'static, str>>,
|
||||
default_token: Option<Cow<'static, str>>,
|
||||
input_muted: bool,
|
||||
output_muted: bool,
|
||||
input_hardware_enabled: bool,
|
||||
@@ -1944,6 +1947,20 @@ impl ConnectOptions {
|
||||
self
|
||||
}
|
||||
|
||||
/// Use a privilege key (token) when connecting.
|
||||
/// Voelin patch: sent as `client_default_token` in `clientinit`.
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// # use tsclientlib::Connection;
|
||||
/// let opts = Connection::build("localhost").default_token("My privilege key");
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn default_token<S: Into<Cow<'static, str>>>(mut self, token: S) -> Self {
|
||||
self.default_token = Some(token.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Connect to the server in a muted state.
|
||||
///
|
||||
/// # Example
|
||||
@@ -2064,6 +2081,10 @@ impl ConnectOptions {
|
||||
#[inline]
|
||||
pub fn get_password(&self) -> Option<&str> { self.password.as_ref().map(AsRef::as_ref) }
|
||||
#[inline]
|
||||
pub fn get_default_token(&self) -> Option<&str> {
|
||||
self.default_token.as_ref().map(AsRef::as_ref)
|
||||
}
|
||||
#[inline]
|
||||
pub fn get_input_muted(&self) -> bool { self.input_muted }
|
||||
#[inline]
|
||||
pub fn get_output_muted(&self) -> bool { self.output_muted }
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Voelin patch: connection-bound myTeamSpeak proof and live account changes.
|
||||
|
||||
use base64::prelude::*;
|
||||
use tsproto::myts::Identity;
|
||||
use tsproto_packets::packets::{Direction, Flags, OutCommand, PacketType};
|
||||
|
||||
@@ -14,7 +15,184 @@ impl ConnectOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a voice server is shown of the myTeamSpeak account (TeamSpeak 6)
|
||||
/// besides its myTS ID, as myTeamSpeak signed it for that ID: its avatar,
|
||||
/// its badges and its User Tag. The server checks the avatar and the badges
|
||||
/// with the one certificate of each `updatemytsdata` and shows nothing of
|
||||
/// what does not verify, so each comes with the certificate that verifies
|
||||
/// it. Viewers check the User Tag's token themselves.
|
||||
#[derive(Clone, Default, PartialEq, Eq)]
|
||||
pub struct MytsData {
|
||||
/// The raw myTS ID all of it is signed for: shown only on a connection
|
||||
/// that presents it.
|
||||
pub myts_id: Vec<u8>,
|
||||
/// An `AvatarData` as it came (`client_myteamspeak_avatar`).
|
||||
pub avatar: Signed,
|
||||
/// A `UserBadgesSignedList`, the badges chosen to show, in order
|
||||
/// (`client_signed_badges`).
|
||||
pub badges: Signed,
|
||||
/// The ids of those badges, as in the list: the server publishes the
|
||||
/// ones that verify.
|
||||
pub badge_ids: Vec<String>,
|
||||
pub user_tag: Option<UserTag>,
|
||||
}
|
||||
|
||||
/// Something signed and the certificate that verifies it; empty: nothing.
|
||||
#[derive(Clone, Default, PartialEq, Eq)]
|
||||
pub struct Signed {
|
||||
pub certificate: Vec<u8>,
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
/// The User Tag (`client_user_tag`): the account's primary chat identifier
|
||||
/// and the token that proves it (a `MatrixIdentifierToken` as it came).
|
||||
#[derive(Clone, Default, PartialEq, Eq)]
|
||||
pub struct UserTag {
|
||||
pub tag: String,
|
||||
pub token: Vec<u8>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for MytsData {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("MytsData")
|
||||
.field("avatar", &self.avatar.data.len())
|
||||
.field("badges", &self.badge_ids)
|
||||
.field("user_tag", &self.user_tag.as_ref().map(|t| &t.tag))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Signed {
|
||||
pub fn is_empty(&self) -> bool { self.data.is_empty() }
|
||||
}
|
||||
|
||||
impl UserTag {
|
||||
/// `client_user_tag` as the official client sets it: compact JSON with
|
||||
/// the token (standard base64), the tag and when it was set (`updated`,
|
||||
/// milliseconds since 1970), in this order.
|
||||
pub fn value(&self, updated_ms: i64) -> String {
|
||||
let mut tag = String::with_capacity(self.tag.len());
|
||||
for c in self.tag.chars() {
|
||||
match c {
|
||||
'"' => tag.push_str("\\\""),
|
||||
'\\' => tag.push_str("\\\\"),
|
||||
'\n' => tag.push_str("\\n"),
|
||||
'\r' => tag.push_str("\\r"),
|
||||
'\t' => tag.push_str("\\t"),
|
||||
'\u{8}' => tag.push_str("\\b"),
|
||||
'\u{c}' => tag.push_str("\\f"),
|
||||
c if u32::from(c) < 0x20 => tag.push_str(&format!("\\u{:04x}", u32::from(c))),
|
||||
c => tag.push(c),
|
||||
}
|
||||
}
|
||||
format!(
|
||||
"{{\"myts_token\":\"{}\",\"tag\":\"{}\",\"updated\":{}}}",
|
||||
BASE64_STANDARD.encode(&self.token),
|
||||
tag,
|
||||
updated_ms
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// One `updatemytsdata`: a value is shown (checked with `certificate`), an
|
||||
/// empty one clears what is shown, `None` leaves it as it is.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct MytsUpdate {
|
||||
pub certificate: Vec<u8>,
|
||||
pub badges: Option<Vec<u8>>,
|
||||
pub avatar: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// What to do about one part of what is shown.
|
||||
enum Part<'a> {
|
||||
Keep,
|
||||
Show(&'a Signed),
|
||||
Clear,
|
||||
}
|
||||
|
||||
fn part<'a>(wanted: &'a Signed, shown: &Signed, again: bool) -> Part<'a> {
|
||||
if wanted.is_empty() {
|
||||
if shown.is_empty() { Part::Keep } else { Part::Clear }
|
||||
} else if again || wanted != shown {
|
||||
Part::Show(wanted)
|
||||
} else {
|
||||
Part::Keep
|
||||
}
|
||||
}
|
||||
|
||||
impl MytsData {
|
||||
/// The `updatemytsdata` commands that make a server that shows `shown`
|
||||
/// show `self`. `again`: everything once more, after a new account proof
|
||||
/// (`updatemytsid`), which the server does not check them for again.
|
||||
/// The avatar and the badges go together when one certificate verifies
|
||||
/// both (certificate, badges, avatar, as the official client sends
|
||||
/// them), apart otherwise; clearing needs no certificate.
|
||||
pub fn updates(&self, shown: &MytsData, again: bool) -> Vec<MytsUpdate> {
|
||||
let avatar = part(&self.avatar, &shown.avatar, again);
|
||||
let badges = part(&self.badges, &shown.badges, again);
|
||||
let mut updates = Vec::new();
|
||||
match (&badges, &avatar) {
|
||||
(Part::Show(badges), Part::Show(avatar)) if badges.certificate == avatar.certificate => {
|
||||
updates.push(MytsUpdate {
|
||||
certificate: avatar.certificate.clone(),
|
||||
badges: Some(badges.data.clone()),
|
||||
avatar: Some(avatar.data.clone()),
|
||||
});
|
||||
}
|
||||
_ => {
|
||||
if let Part::Show(avatar) = avatar {
|
||||
updates.push(MytsUpdate {
|
||||
certificate: avatar.certificate.clone(),
|
||||
avatar: Some(avatar.data.clone()),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
if let Part::Show(badges) = badges {
|
||||
updates.push(MytsUpdate {
|
||||
certificate: badges.certificate.clone(),
|
||||
badges: Some(badges.data.clone()),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let clear_badges = matches!(badges, Part::Clear);
|
||||
let clear_avatar = matches!(avatar, Part::Clear);
|
||||
if clear_badges || clear_avatar {
|
||||
updates.push(MytsUpdate {
|
||||
certificate: Vec::new(),
|
||||
badges: if clear_badges { Some(Vec::new()) } else { None },
|
||||
avatar: if clear_avatar { Some(Vec::new()) } else { None },
|
||||
});
|
||||
}
|
||||
updates
|
||||
}
|
||||
}
|
||||
|
||||
impl Connection {
|
||||
/// Show the server the account's avatar or badges, or clear them
|
||||
/// (`updatemytsdata`), as the official client does once connected and
|
||||
/// after a sign-in, after the account proof (`updatemytsid`). The server
|
||||
/// answers before the result: the own client's
|
||||
/// `client_myteamspeak_avatar` and `client_signed_badges`, empty for what
|
||||
/// did not verify. Await the returned handle's
|
||||
/// `StreamItem::MessageResult` for the answer.
|
||||
pub fn send_myts_update(&mut self, update: &MytsUpdate) -> Result<MessageHandle> {
|
||||
if !matches!(self.state, ConnectionState::Connected { .. }) {
|
||||
return Err(Error::NotConnected);
|
||||
}
|
||||
self.send_command_with_result(data_packet(update))
|
||||
}
|
||||
|
||||
/// Set the User Tag (`clientupdate client_user_tag`), as built by
|
||||
/// [`UserTag::value`]; empty clears it. TeamSpeak 6 servers only.
|
||||
pub fn send_user_tag(&mut self, value: &str) -> Result<MessageHandle> {
|
||||
if !matches!(self.state, ConnectionState::Connected { .. }) {
|
||||
return Err(Error::NotConnected);
|
||||
}
|
||||
self.send_command_with_result(user_tag_packet(value))
|
||||
}
|
||||
|
||||
/// Publish a connection-bound account proof, or clear the account identity.
|
||||
///
|
||||
/// Always updates the reconnect options, even if currently disconnected or
|
||||
@@ -34,6 +212,29 @@ impl Connection {
|
||||
}
|
||||
}
|
||||
|
||||
/// The values are the raw bytes with TeamSpeak's escaping only (no
|
||||
/// base64), as the official client sends them; an empty one is the bare
|
||||
/// name, which clears.
|
||||
fn data_packet(update: &MytsUpdate) -> OutCommand {
|
||||
let mut packet =
|
||||
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "updatemytsdata");
|
||||
packet.write_bin_arg("myts_certificate", &update.certificate);
|
||||
if let Some(badges) = &update.badges {
|
||||
packet.write_bin_arg("myts_signed_badge", badges);
|
||||
}
|
||||
if let Some(avatar) = &update.avatar {
|
||||
packet.write_bin_arg("myts_avatar", avatar);
|
||||
}
|
||||
packet
|
||||
}
|
||||
|
||||
fn user_tag_packet(value: &str) -> OutCommand {
|
||||
let mut packet =
|
||||
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "clientupdate");
|
||||
packet.write_arg("client_user_tag", &value);
|
||||
packet
|
||||
}
|
||||
|
||||
fn update_packet(identity: Option<&Identity>, iv: &[u8; 64]) -> OutCommand {
|
||||
let mut packet =
|
||||
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "updatemytsid");
|
||||
@@ -50,6 +251,99 @@ fn update_packet(identity: Option<&Identity>, iv: &[u8; 64]) -> OutCommand {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn signed(certificate: &[u8], data: &[u8]) -> Signed {
|
||||
Signed { certificate: certificate.to_vec(), data: data.to_vec() }
|
||||
}
|
||||
|
||||
fn wire(update: &MytsUpdate) -> Vec<u8> { data_packet(update).into_packet().content().to_vec() }
|
||||
|
||||
#[test]
|
||||
fn account_data_goes_raw_and_escaped() {
|
||||
let update = MytsUpdate {
|
||||
certificate: b"a b/c|d\\\x07\x08\x00\xff".to_vec(),
|
||||
badges: Some(vec![0x0a, 0x01, b' ']),
|
||||
avatar: Some(vec![0x0a, 0x02, b'h', b'i']),
|
||||
};
|
||||
assert_eq!(
|
||||
wire(&update),
|
||||
b"updatemytsdata myts_certificate=a\\sb\\/c\\pd\\\\\\a\\b\x00\xff \
|
||||
myts_signed_badge=\\n\x01\\s myts_avatar=\\n\x02hi"
|
||||
);
|
||||
// Without badges: the certificate and the avatar.
|
||||
let update = MytsUpdate { badges: None, ..update };
|
||||
assert!(!wire(&update).windows(17).any(|w| w == b"myts_signed_badge"));
|
||||
// Clearing: bare names, no certificate needed.
|
||||
let clear = MytsUpdate {
|
||||
certificate: Vec::new(),
|
||||
badges: Some(Vec::new()),
|
||||
avatar: Some(Vec::new()),
|
||||
};
|
||||
assert_eq!(wire(&clear), b"updatemytsdata myts_certificate myts_signed_badge myts_avatar");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_one_certificate_verifies_goes_together() {
|
||||
let data = MytsData {
|
||||
myts_id: vec![1; 33],
|
||||
avatar: signed(b"C", b"avatar"),
|
||||
badges: signed(b"C", b"badges"),
|
||||
badge_ids: vec!["b1".into()],
|
||||
user_tag: None,
|
||||
};
|
||||
let none = MytsData::default();
|
||||
assert_eq!(data.updates(&none, false), [MytsUpdate {
|
||||
certificate: b"C".to_vec(),
|
||||
badges: Some(b"badges".to_vec()),
|
||||
avatar: Some(b"avatar".to_vec()),
|
||||
}]);
|
||||
assert_eq!(
|
||||
wire(&data.updates(&none, false)[0]),
|
||||
b"updatemytsdata myts_certificate=C myts_signed_badge=badges myts_avatar=avatar"
|
||||
);
|
||||
// Unchanged: nothing, unless after a new account proof.
|
||||
assert!(data.updates(&data, false).is_empty());
|
||||
assert_eq!(data.updates(&data, true).len(), 1);
|
||||
// Two certificates: two commands, each with its own.
|
||||
let apart = MytsData { badges: signed(b"D", b"badges"), ..data.clone() };
|
||||
let updates: Vec<_> = apart.updates(&none, false).iter().map(wire).collect();
|
||||
assert_eq!(updates, [
|
||||
b"updatemytsdata myts_certificate=C myts_avatar=avatar".to_vec(),
|
||||
b"updatemytsdata myts_certificate=D myts_signed_badge=badges".to_vec(),
|
||||
]);
|
||||
// Only what changed.
|
||||
let newer = MytsData { avatar: signed(b"C", b"newer"), ..data.clone() };
|
||||
let updates: Vec<_> = newer.updates(&data, false).iter().map(wire).collect();
|
||||
assert_eq!(updates, [b"updatemytsdata myts_certificate=C myts_avatar=newer".to_vec()]);
|
||||
// What is no longer there is cleared; what never was is left alone.
|
||||
let fewer = MytsData { badges: Signed::default(), ..data.clone() };
|
||||
let updates: Vec<_> = fewer.updates(&data, true).iter().map(wire).collect();
|
||||
assert_eq!(updates, [
|
||||
b"updatemytsdata myts_certificate=C myts_avatar=avatar".to_vec(),
|
||||
b"updatemytsdata myts_certificate myts_signed_badge".to_vec(),
|
||||
]);
|
||||
let updates: Vec<_> = none.updates(&data, true).iter().map(wire).collect();
|
||||
assert_eq!(updates, [b"updatemytsdata myts_certificate myts_signed_badge myts_avatar".to_vec()]);
|
||||
assert!(none.updates(&none, true).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_user_tag_is_set_as_the_official_client_sets_it() {
|
||||
let tag = UserTag { tag: "alex@myteamspeak.com".into(), token: vec![0xfb, 0xff, 0x01, 0x02] };
|
||||
assert_eq!(
|
||||
tag.value(1_759_740_000_123),
|
||||
r#"{"myts_token":"+/8BAg==","tag":"alex@myteamspeak.com","updated":1759740000123}"#
|
||||
);
|
||||
let odd = UserTag { tag: "a\"b\\c\n\u{1}é".into(), token: Vec::new() };
|
||||
assert_eq!(odd.value(1), r#"{"myts_token":"","tag":"a\"b\\c\n\u0001é","updated":1}"#);
|
||||
// TeamSpeak's escaping on the wire; empty clears.
|
||||
let packet = user_tag_packet(&tag.value(5)).into_packet();
|
||||
assert_eq!(
|
||||
packet.content(),
|
||||
&br#"clientupdate client_user_tag={"myts_token":"+\/8BAg==","tag":"alex@myteamspeak.com","updated":5}"#[..]
|
||||
);
|
||||
assert_eq!(user_tag_packet("").into_packet().content(), b"clientupdate client_user_tag");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clear_contains_no_previous_account_proof() {
|
||||
let packet = update_packet(None, &[0; 64]).into_packet();
|
||||
|
||||
@@ -968,6 +968,10 @@ impl io::Write for EscapedWriter<'_> {
|
||||
self.0.reserve(buf.len());
|
||||
for c in buf {
|
||||
match c {
|
||||
// Voelin patch: \a and \b as TeamSpeak escapes them (binary
|
||||
// values, e.g. `updatemytsdata`).
|
||||
b'\x07' => self.0.extend_from_slice(b"\\a"),
|
||||
b'\x08' => self.0.extend_from_slice(b"\\b"),
|
||||
b'\x0b' => self.0.extend_from_slice(b"\\v"),
|
||||
b'\x0c' => self.0.extend_from_slice(b"\\f"),
|
||||
b'\\' => self.0.extend_from_slice(b"\\\\"),
|
||||
|
||||
@@ -192,6 +192,9 @@ properties = [
|
||||
{ name="InheritedChannelGroupFromChannel", type="ChannelId" },
|
||||
{ name="Badges", type="str" },
|
||||
{ name="UserTag", type="str", opt=true },
|
||||
{ name="MyTeamSpeakAvatar", type="str", opt=true, doc="`<state>,<url>;…` of the myTeamSpeak avatar (TeamSpeak 6)" },
|
||||
{ name="MyTeamSpeakId", type="str", opt=true, doc="The myTeamSpeak ID the server accepted (base64), empty without one" },
|
||||
{ name="SignedBadges", type="str", opt=true, doc="Comma-separated ids of the myTeamSpeak badges the server verified (TeamSpeak 6)" },
|
||||
{ name="PermissionHints", type="ClientPermissionHint", opt=true },
|
||||
{ name="OptionalData", type="OptionalClientData", opt=true },
|
||||
{ name="ConnectionData", type="ConnectionClientData", opt=true },
|
||||
|
||||
@@ -1414,4 +1414,126 @@ version,platform,hash
|
||||
3.?.? [Build: 5680278000],Linux,Hjd+N58Gv3ENhoKmGYy2bNRBsNNgm5kpiaQWxOj5HN2DXttG6REjymSwJtpJ8muC2gSwRuZi0R+8Laan5ts5CQ==
|
||||
3.?.? [Build: 5680278000],OS X,SttEnjoWE8jqIM6BOHSfiZP9DGjW0EP/ajU4bdKqgGMV4aYq/kzwVA9gxbmdIzV4lbaokvXBqrRjfBHrTVh8Cg==
|
||||
3.?.? [Build: 5680278000],Windows,DX5NIYLvfJEUjuIbCidnoeozxIDRRkpq3I9vVMBmE9L2qnekOoBzSenkzsg2lC9CMv8K5hkEzhr2TYUYSwUXCg==
|
||||
3.?.? [Build: 5680278000] DEBUG,Windows,FaA10gndI44f19ZThYJX2OSM8ESrx9/vJ2uY+rON4enzzPsPR9kiPhsUXtMcC5szzTu6F/vLCiNNEhCr70CKCQ==
|
||||
3.?.? [Build: 5680278000] DEBUG,Windows,FaA10gndI44f19ZThYJX2OSM8ESrx9/vJ2uY+rON4enzzPsPR9kiPhsUXtMcC5szzTu6F/vLCiNNEhCr70CKCQ==
|
||||
3.6.0 [Build: 1668022263],Windows,jNUeF6ydYPJp6CpoA2Nm8FcmxPTwj8bFJmmzo/Ch2B9L2CU2rrgLJedcQM3NjAncESYYywUiFR0+BsljvaTNAQ==
|
||||
5.0.0-qa-74-5 [Build: 1680085518],Windows,/X5xXLBPrLClWkivAnMJCz+QIBmFk9fFie8sNg69OdN/xwBQrX6naf2IehfxLdd+BBWX/5TsDjuPJqJwhK1FBg==
|
||||
5.0.0-qa-74-7 [Build: 1681481733],Windows,4qdm8R3gNHlXDV9PS2CtV3Fe9SN7Mjgt82X+iZmqwMXk9B0g9vCyK62G7h2nr/qcqSopPXR4652xMsSQPYVvDQ==
|
||||
3.6.0 [Build: 1681728436],OS X,MZzEbAN51fl7FGiF51T32nHz5tySXH3te4EEZip5rImRNX1Ey3bBQkahN1PYhURNAQxAtIupczX5iGMmvKm4DA==
|
||||
5.0.0-qa-74-8 [Build: 1681821920],Windows,wBuvBhPgbvXmtEOavMpF/6X7xvHkd0PcrNmob7nSr5trxi5HFGjzvOZU19p56yzOStI077LvVJcQtjVha2uXCA==
|
||||
5.0.0-qa-74-10 [Build: 1682065994],Windows,fCODC/wSy5xu9VXPjK3MsRur4MqN/mSLcP/DdbQ2u/KNgQmpuQEsVelmbrf5AvJUQ9YhmXyx8aMvTnG9kHSnCQ==
|
||||
5.0.0-qa-dc-1 [Build: 1682080978],Windows,0p63hM9RbR65x093OWBlS9g0We6lNfYA+IWN99TZ23HXzWXuvfukMK6lIviHJkNSFWCBxhGQFmFi9lttH00vCA==
|
||||
5.0.0-qa-74-11 [Build: 1682337867],Windows,BhUfmE4EX5h9gjKKtfO1JQ61sIdzZfm1IcvA4FNU8BtmA2DSzUJ9uDWFrq60h7lh33wkktDCzlXL7j8PNQChCg==
|
||||
5.0.0-qa-74-13 [Build: 1682589154],Windows,4OMk6jcMvJc/P3zaojn8+laRQzG/vnmEkWEmTpQzIsTcPzKOu5irT82YpOtlp+BIxFDGb8onygu/turJjHLiDA==
|
||||
5.0.0-qa-74-14 [Build: 1682680770],Windows,bwZm9gRSoUSRTWCcc1N0ZuKs+xznjBKErt3myq9YlXzdC/jkn4miNoinG60Ynbsp1JkU8tAVKy4v8HUBLictAg==
|
||||
5.0.0-qa-74-15 [Build: 1683039954],Windows,MFemYXY5GGg2OYhdRzdhpkn9ujzOMMCZA8QGlPV1GUbhjjtjXuMw5+ydEzLwcgZYpFTod3N6CEz/b/aXwWeyCQ==
|
||||
3.6.0 [Build: 1683203743],Linux,ao52xPYBI8qe57kJJ6KQgQPr0J9w7BhGikkFMqs7pGpsrxLK9ghzOlbu5IZsdct3tNw88S2YB0oFmcCWlx+hCA==
|
||||
3.6.0 [Build: 1683203743],OS X,w/rKVPUul3im2KxVqvL8udZf/o0Yre+92bvACj8hU1x5aNtQkvodXo7CML+4mM6EgifiVCyI8kyo6BtbfeF7Ag==
|
||||
3.6.0 [Build: 1683203743],Windows,Ha73fVhy6+r06Zh3CCx8RVJ1HtHCaABNnTfFbjQPy0dm/e79JFIPZgeC5IvJBltwaiBic/9M+aKBrt+7sNxNDw==
|
||||
5.0.0-qa-74-17 [Build: 1683295507],Windows,hpDc2gHUCHv3HUA1nBray8U8Re/d9XvDUHZkefwMkgeL8L6KizWeo7vZzFguQLYpRPr20B4h0d/A8NAxYxfqAA==
|
||||
5.0.0-beta74 [Build: 1683627550],Linux,M5TTHH2J1erTQKBElj0dz4Lm9N4erZuHxZNjNlbJjDxRC8CYnziveIW0j8DY8NeQaSKHeCTXoL5pDakZtvAODQ==
|
||||
5.0.0-beta74 [Build: 1683627550],macOS,EmwreqEhVhmpGrjPKyNjwuEdWKF+uGTX0syXkq57+klgtcNw9lddPm9lodLTdB5spPGlsx0CJQySvEXlWyXNDg==
|
||||
5.0.0-beta74 [Build: 1683627550],Windows,pipm1uaijQDJKPZgRkhjyLsLG/W9KnjEDWNGvqUkUrSuqrUvfEG4OUsdTOReMb+FJp4xz82n3cwd4HExO5k3Dw==
|
||||
5.0.0-qa-tr-1 [Build: 1683731563],Windows,HmBOKipdW28prdI2FFdmBu/mMXui+zdC0G7769F3bW+nVRfNoVtvJhSUx7/UDeQ9ghHbUIW6q2lCxnQLzsIRCg==
|
||||
3.6.0 [Build: 1683804569],Linux,CqbjoDdeYd83t/u9YUtlQf4rDIf6yEnFInF6nq7GcO02tRXBQlppxHd/ziaTdlpwYrha00goKb2GGWwdrNhFAA==
|
||||
3.6.0 [Build: 1683804569],OS X,sT6ej/41Qk3T0LfXl3+VSm3J7Ck4M/OCTWIRundvOHBRodGLWJtddZuQu7IlXNr9mbJfklarQ4XyyXvXMdjvCw==
|
||||
3.6.0 [Build: 1683804569],Windows,PesaPHU3+aiZMUPzpq8UBKjck77jLw9N+hyZq6JjD4baqns5dmKj4sTfSL9/QROyOLqPICZ+fwkSy5iuuMQEAw==
|
||||
5.0.0-qa-75-1 [Build: 1684855710],Windows,LLfl5sHAfsdepvecADQI9/nx98H+jA/r9pe6fq5CqlRY+MCdVbOphiXy7zZerE5h4lIRqcJtEeAJVIXaNu+LDA==
|
||||
5.0.0-qa-75-2 [Build: 1685542148],Windows,Ir/0IAdrK5dDVDlh6gIRwGZe0DFR9vUNf313cLwHTN1EB9nyO2Bq5yoBjZuGYOdNgcbdgQCBzfKNd4ZpCxxSAg==
|
||||
3.6.0 [Build: 1685546268],OS X,i257nbRzdfvBvgW4IeFoCe8KnCDfoIvtNeORVFVPohKWfFajfoBNYTDa/2/jgHbd97Dzqd+hx8t2ZwPPwgR+Bg==
|
||||
5.0.0-beta75-rc1 [Build: 1685698093],Windows,Jkvyb0PGEmS3/lVfr2x7SFlSZMeopxo7JXBHx8m1pWeDL7XdjYoDPOaIJ6UD1hNxY/wv84fgAwt65Ip2AdP1Dw==
|
||||
5.0.0-beta75-rc2 [Build: 1686050172],Windows,BcULgPFoo2+QTsjD88VH5rONZcABm32fgd5jBNbdkxTaERND/CJI4ZBWS30s5WKN9bi3T6LKUOzcLyN6+gfNDQ==
|
||||
5.0.0-beta75-rc3 [Build: 1686126230],macOS,38gec16GTEPCeaVw5qM8tU58HWM0HZ20yROR1foT8TRHqsTvoED2gm07xb6KfSHN3//3k1ErMvuS4emNBohcBA==
|
||||
5.0.0-beta75-rc3 [Build: 1686126230],Windows,1Jj8VSZ8QQ2K5jFiRM2DB6Z12Yi1fFjJ3ng96W/S+zU2VzldrOsuvhO36BOjbWMCcEIWoc45sbHPm+utJtxeAw==
|
||||
3.6.0 [Build: 1686637110],Linux,8eM1WF1E9+8DeS+Zm6IcidGtuTC0+jtrLRkkiIk+GUA91bVOCyYgrUWNFVftZtFEM4qIOICJhLQopVTIwYJOCQ==
|
||||
3.6.0 [Build: 1686637110],Windows,r21r7w+EGu6F6aruzYiuzv2lP5bX8X4TP2xXBH5Wljz3x/VxOxndN84qA9sPn6QJZFQCtzq+iEb0wfFFM7mYCA==
|
||||
3.6.0 [Build: 1686731472],Linux,MKaey6yCAdQDBHl5ERY24N5bz9CsdypGJfpTC5mNPc0s3Z1zeb8c3g9/w/mlRD+qoK3xlCYt3f25oaFMZofMAA==
|
||||
3.6.0 [Build: 1686731472],Windows,KRYqAaQhnKh/NQ4LrOw8+nVA659NDn+IlOB8hhmKZolIOEDSiijCeDoTVf61t/0Z0y1OWlxABS4X7uWRzvhiDw==
|
||||
3.6.0 [Build: 1686736529],Linux,l1LIP8nreS+y33Hp7SmA6M7kJZZI1KbsN1/Rx9hAAL3Wd6PbEwhLIQHXBkfCI8MizWSAl7NDb+UOuNxAL9GoAg==
|
||||
3.6.0 [Build: 1686736529],OS X,EFU7gHd4QZhwmAojg0Tk/tL9dPiFTcWn40R/6YZCrlzX6t0FSPXiAj93OUf1du+qyy2ly4Lrox/M0u4wOhEDBg==
|
||||
3.6.0 [Build: 1686736529],Windows,kRHYyNCdM5rna2v27LyPerCeNd1s76h0KfpLSmLQk3Bzkrg/NCBzpj0WofE1cvbQ2Qm/41d/mUIMxIfXJ/+hCg==
|
||||
3.6.0 [Build: 1686744367],Linux,toUkg41DTfeCfWgqqxSeb8eDzri2PsjRNIcHsFxr0d7nLCTYGoSFfQjme84FjMYtvYloMVAk/gx5Nt+hWE+ZBg==
|
||||
3.6.0 [Build: 1686744367],Windows,VXx9yKF0ZaBMqlU285hPLxaCgH1N8OwKjU52A0EdulFmEeLYYQeJI/7139hno0Ph8kGT6nxoDRKtw0yn9woNAQ==
|
||||
3.6.0 [Build: 1686749764],Linux,TccRBHwn5LSA0lfpa2B42QmfCOiG+MqqyhlOqy5RcuRQNUGPD0e47lUz+Z/8+Gsdc1TPG4+vYlRl8+v2v+26Aw==
|
||||
3.6.0 [Build: 1686749764],OS X,g8H7Op8eCrn0wHutuD/SlmUcZPmkSlFUBhvZpSgm9kuQl4dapzKJq2anI5jDwRs/ooBm/wrIlSiWI6HXuOPZDA==
|
||||
3.6.0 [Build: 1686749764],Windows,gfzG6CfwNYeqrjT68s7ahPd24A/XS0P8LLAB7hrE54MnrlO12RiflD2w69VZ7EYlqnd9GAiVzdGJHCmCFWtlAQ==
|
||||
5.0.0-beta75-rc4 [Build: 1687777367],Linux,DCZXmwc6xocEuzvS+f+qyQLwN8FLdNqyDTAjdOfy1y8JeO8VmIlNwRFd7X0D0Q51kqPNPIB7Jbh4yiwySHjhDw==
|
||||
5.0.0-beta75-rc4 [Build: 1687777367],macOS,xgV8yX/XS3qVXshur/PbsquRIbPvz3w+hJL905nQQBwbniSGvKxAUcTJompBgECG989hf6nW+2GApbf8p70RBw==
|
||||
5.0.0-beta75-rc4 [Build: 1687777367],Windows,wIGrljvdCMZX3XJoe0rWTA/nNZuXVC6z8kUvDw1gi9YxyM6AxmsleqOzjZ3zY5Ii7cRU8slxNAh4ERLcHEPQDg==
|
||||
5.0.0-beta75-rc5 [Build: 1687944933],Windows,1fQu13pX9jdR5oJ4yaqasfoWrcySvwocstrOQOZLZjB+0nUtKMYW4Kp2DYHuIoTlvuWiiF7pYc7YK4bOUWdlAA==
|
||||
3.6.1 [Build: 1689766945],Linux,fjR+/+EsahBSG/qGjcTTUVIyn/w7W6h7uy9YUebYzRbtWIxxv69ZD4k7Y4Z1OS9+cuB/Nbtg05J2Upt2oK/qCg==
|
||||
3.6.1 [Build: 1689766945],Windows,+6Tcswj4E40ablTifyXIA3UDEY+359hxjEVx+Tb+xha08CiSwpzSpFndS8GCs8z0QICVKUZBwhVfGfePm00vDw==
|
||||
3.6.1 [Build: 1689949736],Linux,yM9tjby+KBrov9dyNLM1I1PZXDBK2fdwR8ylvKdZJc/DaL5GqnoBAGLkFmzOIl//u8VMbXspCDWb/PbvOS2gAg==
|
||||
3.6.1 [Build: 1689949736],Windows,30JdFX5zLrHx3uKsb55vpdlS6DO36bVRSOewzOlTV70LS4X0dVMZp64EzDZY8ZR2woAAjZ8ZR/rIKt4JlNnKDg==
|
||||
3.6.1 [Build: 1690193193],Linux,UAcE5h5FgPcdChWTtiO816HX8f2qdoDcDEw6crbJ96Yo7rp1Bt+qx/rkKK9bzlVWMhOd4fI7pr++1XaPkEBnAQ==
|
||||
3.6.1 [Build: 1690193193],OS X,P+KOw42V8K0nN5FbGItCaJzrDuWcRgfE3MRzrtbYAhRMTXHzRxvwLkoLM7+vKTW135NtWZlKbZuDAvxgwhSLBg==
|
||||
3.6.1 [Build: 1690193193],Windows,I5uwVK2CZa9aXblVQPUKGbjNYoE2eaUPujK8sVGWAUsPhmGySTvSkP70jrpX8pUgQdtHwUOl3gvrAH6+moNeDQ==
|
||||
5.0.0-beta75-rc7 [Build: 1690443874],Windows,dvpImL6c5RMVxPV/jNNG3DncR8QlQcqWKBQCDiE89KQpZ/q4kRJkAlje0Pgoqk8BT/2WQWaUixqctfOGNPxNBA==
|
||||
3.6.1 [Build: 1690811573],Windows,aWKpb0eAiI6FndcOBw+OixzripgCENMlM5gwKuRhdqtOdWAEYI5Luz8sGQ77yWC1RlQ1llxHcqhjNcJ8qMVcAw==
|
||||
3.6.1 [Build: 1690872913],Windows,+YmPaYUBL4F9+TgxyFhlT8qIi1Ym+So4NNMcuohla/u4kfJCGabZ1vDF4cIOAghIqWfO+bQ0OkORZrCBdpi2Cw==
|
||||
5.0.0-beta75-rc8 [Build: 1690875928],Windows,1xI3XWPzHxz5zD4OIZDvJteHXOHcxliqCGh/lifvzA6Gb+/GhkcPGj5RqmlIHPKHJFAozbB0UhvTuJcTU5HGDg==
|
||||
5.0.0-qa-75-4 [Build: 1690964581],Windows,3o5M5JegEvtXwGHMdhUSR+PbaXTIoinUI1GGgoXrGi2tYNUvaguiYYlsak4z8twpgzp68L0KaoA4nz4DyNX9Aw==
|
||||
3.6.2 [Build: 1690976575],Linux,iSJZ2tmUsUhCuB3G/7SCgM+JNZe3Jb/KSxFNr+0FDgg8r5t4JKGBD0SPl/cdDMqNqXmG9zEHi0XmuVl9lysoCg==
|
||||
3.6.2 [Build: 1690976575],OS X,0VegJZtWI25+RXM3J6jNfskqEgM8f4CyYrrz0IXuSK8azRQ3AMWH7YgSnrotoIX1q7aDhnTulk9eChKSPoKVCQ==
|
||||
3.6.2 [Build: 1690976575],Windows,OyuLO/1bVJtBsXLRWzfGVhNaQd7B9D4QTolZm14DM1uCbSXVvqX3Ssym3sLi/PcvOl+SAUlX6NwBPOsQdwOGDw==
|
||||
5.0.0-qa-75-8 [Build: 1691162334],macOS,jJLCUYbKDDtPB56YGtUSK+EjrY3LxoOAWVLHKIc/Li4UAFNL9iaq5gRvHF+cfJHyGg0keg2SEVr1+TfCEDG4Dw==
|
||||
5.0.0-qa-75-8 [Build: 1691162334],Windows,yLHN6dcol32mrRoi2ZMYDYsn9XPMncp79PwcCHxFC+8CuaxhOSq7/iXUPwhsdqvUQzyvstq1hCaG9/MLn8G/Dg==
|
||||
5.0.0-beta75-rc10 [Build: 1691405422],Windows,ETFP63u2QoQzmb1vHyRC+KxAAZKWq1PEpKfC6ep8A59zptnOtocEbc50wb55GpF7pVv2n5nJP6CV3iv2QauAAA==
|
||||
5.0.0-qa-75-9 [Build: 1691734909],Windows,t0guTMT1lZZI34At9X9kg0/ablk2LEtjePCLXNSCyTGeam3E4l+hjjaLZYx5gFLDX4tQEGqG4Dms96T+xRVTCg==
|
||||
5.0.0-qa-tr-2 [Build: 1691758984],Windows,YmsBwLBmFqrMhlCLGXUcn/qLvHJBrOeg1kRj+xDp7FltLJ6z4G5r6QdPt1sTaalD3TWE9If10i9mQFnP73nCDw==
|
||||
5.0.0-beta75-rc11 [Build: 1692269983],Windows,TraubtepmvLTzCkyZwDgJram2qrdpuPy1hWRhN0ZFwSAnXkBklJjBSMAUO22D/hTAfTeiQaUiFDJThf2aGSJBQ==
|
||||
5.0.0-beta75-rc12 [Build: 1692273792],Linux,UFodfOKNy4uOGnQdL35xlc5XoOkT2xVzn93w2+rshfBQKd63BqCqBcrMDL5We4UGnCdeF7oiUsraWm65qvfDDA==
|
||||
5.0.0-beta75-rc12 [Build: 1692273792],macOS,yRtBZtJrOetbT3IREKlZ7bYCLLDWtl88l6OvbRHsfI0MwgBuaLuZmgA7gAGaNDc4u427XpxD1U4WRRMJ4XXuCA==
|
||||
5.0.0-beta75-rc12 [Build: 1692273792],Windows,fX3auh0DNxFmMmmjKmxJ0bS5T+sI2OActVkppSthJOJ/W1so/WfdxtxavuJgpzFHQ7wqanaJYUajAY0uFnYEDA==
|
||||
5.0.0-qa-75-10 [Build: 1692281089],Windows,6Tn50hZBDK2v1gAfXvnfVsOvCYiZ5O7t9ae/PGIzTQPYJiK+83CCR9F+NrjaNwrwn8U4fHCm0DvF2qrk6FiEDA==
|
||||
5.0.0-qa-75-11 [Build: 1692344346],Windows,XUiXiYpVQ1lvhscQ0T0STLhzFxgUgPD5yRvHnHa+gl0z62xvSnUYMcaulZu+vu7N7Zx2XD0yXwDt1aAWjmSmAQ==
|
||||
5.0.0-qa-75-12 [Build: 1692942703],Windows,eg20cqWFjsdIv3fP37BPzSsEMAabdXgPwE/iZ0nu8JIUFCx+dDPmD+Yezf4f2cbe+w7MEkPoAMKS5cAOYbG9BQ==
|
||||
5.0.0-qa-tr-4 [Build: 1692956820],Windows,B8tNlJlgST8ITvDXO4m0mBmR+fOur02Dr0MbmYcE1LWOWJfQUk2A5Lyni65NEBdJIg6/D3ihc0US27Yd4sFWAA==
|
||||
5.0.0-qa-75-14 [Build: 1693548790],Linux,VFo+uqfuN636vfO2uplN7MxwjcGgZ7C7a8H78PSMBtPYU5KOh86FNgH3g4TefK5suVza384d9DpPK5sjZBVICA==
|
||||
5.0.0-qa-75-14 [Build: 1693548790],Windows,eBIeiZ9RjIlTT9AVkwXsiHsKrvSkGWfILDbts+A5xGDsIU8nFGl77uXjfNqjM6+Ud2Eb6lKk7NVQrmRWs/b7AQ==
|
||||
5.0.0-qa-tr-6 [Build: 1693832989],Linux,7S96m1KKKlB2+x4osdky+gdCUnWTlAaoiOQcsmmXPUxxyS/ypTY7tnYRmo2lj/Hx46aI7R0+Z4+vnHLIY9InCw==
|
||||
5.0.0-qa-tr-6 [Build: 1693832989],Windows,IOoZZnLdprCn572p0GRdOJftjQq12pYODanfyqFy9rG+sSQWmDs4Q7LX5aF/K6oRi1dj31I/BaBKxRhcs0ylAQ==
|
||||
5.0.0-qa-75-16 [Build: 1694525079],Windows,mnve3nHnNHCWJD/v1UucjHwYP5iiMcQYozzkQTxY4SlU3HozJb1Zkq9hhXpnaQHE37TODB+7B/fshVo/yWJIAA==
|
||||
5.0.0-qa-75-17 [Build: 1694593665],Windows,dQxRWH4A/RdhuwMQG2fWtbP8aRLJNs9eGrdSHBEd07MEVA29iyNx6J4Ab9pFvzw8rbxC/QsL20G1LGc0ilz7Dg==
|
||||
5.0.0-qa-75-18 [Build: 1694615531],Windows,qDBmGwpP/bskv03tvqCDvK4xXGVpyS7K6cvu06/yMk5rDd05Dba928UfMNh0/Wub/Xy9MfI5gVdA3kSuXJrnDA==
|
||||
5.0.0-qa-75-19 [Build: 1694699313],Windows,KtR3EavFC3d5PBcKFWt7Gd27B6fAG0k4EevugDzjYs2BCg+PFgeZ1DPAQCw8/k0SzewR7i9x/ZedhPC7pvYmDA==
|
||||
3.6.2 [Build: 1695203293],Linux,p4iF1jZ3ZOz9MEkKSZ2bvnFtm9WmUcQy9mAP//erFE4PF1sB6K1CSANrr+3X4B0aZR0u+K2pjnv8kiKsWKQCBQ==
|
||||
3.6.2 [Build: 1695203293],OS X,SOCkLcsxINIGVc+3OQ5Vrmv2BVNNFA9LX5Jj9tqbIiYv2HU6Z5E8AL5+v5G2LDN0F+U55+uW43ezUoYAr1WuBA==
|
||||
3.6.2 [Build: 1695203293],Windows,4BdaZpdgUSMCuIs8qcloJPNxNlJ4o7QKnxMCRO60mSOTtJZyKjOrGLAmeAEtLIJjcjmdSpycMbQOIV92K2vXAw==
|
||||
5.0.0-beta75-rc13 [Build: 1695397203],macOS,gwgeaGifMO1IIGcPJBbHUklR0m11N+XeuvflfT5CFUh0RE3zbzmV0ehUtg5udX9BU9XxcLh5LsiMQtmUobmUCQ==
|
||||
5.0.0-beta75-rc13 [Build: 1695397203],Windows,dSkrQtjUjxOQmAdQUbi7Z6oQFKPqi6/nsKVpovncQ4hDjQqVsUfoS2NO/XHO+iCwH0De3zrPgPQju3bRiYdzBA==
|
||||
5.0.0-beta75-rc14 [Build: 1696088917],Windows,GoQG+71nd6b9QUv7vECPDAXGcKEWwrW/YbPaQVNhdFwonbKegBPYKUel8rxuGzqR/uJp3EqXEGV0JyQBVXiEBg==
|
||||
5.0.0-beta75-rc14 [Build: 1696489500],Windows,6rCkYTY/IQav+zwrXfu9wFEmeuFcNxuHKBdW5aiblX5a0KpF9wzn0qwwKgjZcrzQiH5+r9tmsoB36KSwdxX1Dg==
|
||||
5.0.0-beta75 [Build: 1696607978],Linux,zk+WtkzXgRWAFIA59ad066AbGsom9QfQW6JpskztbEh4Gri5BlsQ/HKy2xUfQX+7x+A1ukt27BU/6msK7B5bAA==
|
||||
5.0.0-beta75 [Build: 1696607978],macOS,W9THGtchSxG8Q9DmjC72Ah5wcWVH9/+ZxTH3TZKH3E3NsyjaRwMdjgPvfYVaOb3qYq8Se/HxkYqBbyxSJZFBBg==
|
||||
5.0.0-beta75 [Build: 1696607978],Windows,0LhX3/Ss9GxjzXzyW6sNvaIGtivWocu9CDH3k0tOqkm8rjiwwQFTu3dCtGEzgBw89QrCXEcKOmZkbgLpechOAg==
|
||||
5.0.0-beta76-rc1 [Build: 1697033899],macOS,ZjuTP89K3fFgfAHkzg9vbhR+EkSOnkozd1pTXB2MH//jTj9tfyEPwDlzK1TaCV+JKoAsM5WlSmyx//a72S7mDQ==
|
||||
5.0.0-beta76-rc1 [Build: 1697033899],Windows,CLEscmKTzIkTC9VAQAQ1hIN6eOlSaOjuaWE8EqYThv0aunDzxWRBG9MCNQmdLJ8JgtIM6Ng412x46TOoGAmJBg==
|
||||
5.0.0-beta76-rc5 [Build: 1697802195],macOS,0aSd/h3YrLvyhywBXtNf2h1ZfSLkHW3jr33EoIsuL6oBepMSvi0nZI3Gx8j4gmLDXtwxE9+wFqrm2vc5VfYjCQ==
|
||||
5.0.0-beta76-rc5 [Build: 1697802195],Windows,5JXHvuwisq+an9hsgGgA6FW00ENcH5khuMQ1SFyaKgKdByDdvPA7/XbPtxRvUvSUh5brGL4m3CldEQ88ga1mCw==
|
||||
5.0.0-beta76 [Build: 1698243642],Linux,xXggpgd8+q2Ozk/of+0ciH2v/jp1K83EorMbbiI/J6ywpzQVocFyqQUpOjD6Xoh6K2AV2heFQF/cKoJ0aHwABA==
|
||||
5.0.0-beta76 [Build: 1698243642],macOS,Buhg/MoJF/pPldGEsesBUpTj+ClIp4xFXX/n+BcOgIS98D/kdO8pTWbk42f+wx24ALEJRwWZCYunaLFXF0iJDA==
|
||||
5.0.0-beta76 [Build: 1698243642],Windows,zV72PUBNtH7bblwdldd6t/o8hprjepbfR7CbzQCehaYUTID5y/W4IW7e/Qt4v9ip55mycWzADgiqCndMlOVNDA==
|
||||
5.0.0-qa-77-1 [Build: 1698316110],macOS,ESRePbVvFOl0wUJKoSsFAMV34isnFNfzvUQW6yDoMqa8GNGNPdRw10TxUA+ypTzu4H3A8VEiKgEEm2pdwj/5CA==
|
||||
5.0.0-beta77 [Build: 1699457285],Windows,id8cERxgKG68YRDcSYCceqekamIZlBmAE/IfwYkpu+a8RC0Gkyyhtn4ZU80ppUfES3GFsGVSSwJ/eci1g+pCBg==
|
||||
5.0.0-beta77-rc1 [Build: 1700224895],Linux,T101xCL/zRr+iwZJHURKd4DUDTrQSSJ3QsADpMH/Ed8wqXPTqneP6hQk04tKEB39aJCJTDW9W0FT7Pf7vCKLBA==
|
||||
5.0.0-beta77-rc1 [Build: 1700224895],macOS,0y/hKU/yqkqgUqtn6KXbuRtqQa4DlYQ50Rziwg9k4wAUgAnCm1hts7AvUHrGv5415cJX9czxUAFdIEApPR06CA==
|
||||
5.0.0-beta77-rc2 [Build: 1700761919],Linux,oFMyO1h6nZOmA0sM9DP+6fy69t+o1drV3inNG+kaH7pZGYqgUg9r/Xu8jGaD2EqZ+Vc7JnO8Zl9Y5n3+HPNkAQ==
|
||||
5.0.0-beta77-rc2 [Build: 1700761919],Windows,VOTBvsWNSc5MNXDWd/M3JpCB8WzvUlj7+V7EVtUy9cZ8LaK8TyJjIip16YJnVDod73wMW8npyt4oaDrqkzL6Bg==
|
||||
3.6.3 [Build: 1701166057],Windows,ML3yE6pV0QGyhc8o7k1bgqDSj+5gZIQFMjBNhWJ6L0FtJwniBq8l1wivx3DzgVVCvyRbzfg8MsdV/rjl5sHNCw==
|
||||
5.0.0-beta77-rc3 [Build: 1701707182],Linux,bS/lxwnq0KSoNl0WggENJ/tuYm+QJF67gSqXykWGAik40iFmM1g7kYOkI5GoBsOxgWJBJB5L4dOjlAyA91BbCw==
|
||||
5.0.0-beta77 [Build: 1702382332],Linux,sJx9Ss46tDLfsJ6y73csGOXnSIRsSeUFrpHFQ2il/jjM7xWAbp8F8Cnyix/CaNwy7DfZKtgMRcPc8YP0a1r3AA==
|
||||
5.0.0-beta77 [Build: 1702382332],macOS,E2rqU9M9HvWnqZbki0+blgLmDWneDZZP9TW89lDDuDoQ7GaqXizzNfvr9XJBm8dJwToLfpR9/9kmLhZpHkK3Dg==
|
||||
5.0.0-beta77 [Build: 1702382332],Windows,Ee6DzP16MUXpdKWjiSY0NGb4thN22/Ks0hwNcaMrWoaadgkM6c5477X0IbGFWVjzTWfjFTEad5noYLUPDWSgCQ==
|
||||
5.0.0-qa-lm-29 [Build: 1719554519],Windows,mSNqoUO2xaP31n8wrHwuAHHYrgov4ZQmq5OrgvOF0jsEQvTy11Z29j02q3nUA+k9TrXyG12CMYVUWfe8ltneBg==
|
||||
5.0.0-qa-puzzle-2-1 [Build: 1723116226],Windows,7Qx8GeSIEvRNZ4D3aNbX0AO67Awj92afgNCgkJ7L0YdcaD0c1HFs0c2Ms6CArTiD8pB/Nxw7QgCsKcpBln1PCg==
|
||||
5.0.0-beta78-pre-1 [Build: 1724839559],Windows,fy7cW8uGyr7lA/5eqsNztXA2nS0PbFZQgIo2HNMbNPycLWJLA8DNZGafBgsfchx9EF5piNtMsJAs9JSy1Pp8DA==
|
||||
5.0.0-qa-78-18 [Build: 1724924030],Windows,/86Ug4O5Huvf1fHooxLOqIxOIp2wyyR821wOcXkDkbXawEbsp1K7GcVqPH/cyLbfKO6x4LeCILqsrV4no3pMCg==
|
||||
5.0.0-qa-78-19 [Build: 1724930118],Windows,m2z53BpS7ocld0/TuasTKe1vXvGB6ZFR9mhdAt5I4j3QZpFlCy3NeObvQEHu+a+4Dr8yFBusdQ6vR8Jf23uyCQ==
|
||||
5.0.0-beta78-pre-2 [Build: 1725011227],Windows,v6UJ+WoJ/TYQe2MqDfoXcMLPTb2L8KrN03x2WHSdsJY17yn6ofLpMtNuBLa84by+sNi1/b8htf0HdV+6TLKEDg==
|
||||
5.0.0-qa-78-20 [Build: 1725620142],Windows,hxdPF5JpyHwDb36xlKAls6wgmhGh1OvIeo4PlqVX8a9zzP0NvGVR1O2BUdo7ixFsKqrzeHoHJ7KoVxenvGpLCw==
|
||||
5.0.0-qa-78-21 [Build: 1726235323],Windows,OiQZT9J/s6kIOX6UUDEB5tu3DrKYz6S7Lay/BaXY6teJcbkIuhBr1MREgmkg8Z+yIEHpIqrV73sUqHD2vk+lAg==
|
||||
5.0.0-qa-78-22 [Build: 1726816276],Windows,dfh0I4RAn1OSy6GrlSmStLBZWutnmUEg7D4tWvzC668p3FBsm7az/CexueslYeoXKgFj871k4F/CyDCgKtCUBA==
|
||||
5.0.0-qa-78-23 [Build: 1727272684],Windows,OkGqYGggz96MOy29Q7kkNi1sWbGkS6B0K//l7E8oixEdS6xdLgW6GmxwcI6DxvwBjVICg0TdO+VhGpRC9RnUCQ==
|
||||
5.0.0-beta78-pre-5 [Build: 1728287639],Windows,r9IEzCKmd1M5JszuUU02xy1qFkxKAPAHa45mzxakCqibCdzdL5+T6L+OepdbB6xOKSQ+uAyAFJOd6FHX4vJ7BA==
|
||||
6.0.0-beta2 [Build: 1737468425],Windows,b5mySiqYAd4Lv5TZNflW+G5Gk8y7Woo9YnJfHRjmzhUyMdGfF1O7fSGJzmx2Hpe/PKaY2aDuKKD6lSxbLYlKCw==
|
||||
6.0.0-beta4.1 [Build: 1779880475],Linux,7A/XVk3u5VSltgVlDzJCNmN+LUzztoaqCbzmaC7s3EENoN6TpEKh2Fz/N4zPVYM/pllU3Ij5K0h6UsSJHj2FCw==
|
||||
|
@@ -102,8 +102,17 @@ pub enum LicenseBlockType {
|
||||
/// Ts3_Server
|
||||
Server,
|
||||
Code,
|
||||
// Not existing in the license parameter:
|
||||
// 4: Token, 5: License_Sign, 6: MyTsId_Sign, 7: Updater
|
||||
// Not existing in the license parameter. Like `Ephemeral`, these blocks
|
||||
// carry nothing after the header.
|
||||
/// 4, Token
|
||||
Token,
|
||||
/// 5, License_Sign
|
||||
LicenseSign,
|
||||
/// 6, MyTsId_Sign: the key that signs myTeamSpeak data (avatars, badges,
|
||||
/// identifier tokens).
|
||||
MytsIdSign,
|
||||
/// 7, Updater
|
||||
Updater,
|
||||
/// Ts_Server_License
|
||||
Ts5Server = 8,
|
||||
/// 32, Ephemeral_Key
|
||||
@@ -413,8 +422,12 @@ impl License {
|
||||
|
||||
(InnerLicense::Ts5Server { properties }, pos)
|
||||
}
|
||||
LicenseBlockType::Ephemeral => (InnerLicense::Other, 0),
|
||||
_ => {
|
||||
LicenseBlockType::Token
|
||||
| LicenseBlockType::LicenseSign
|
||||
| LicenseBlockType::MytsIdSign
|
||||
| LicenseBlockType::Updater
|
||||
| LicenseBlockType::Ephemeral => (InnerLicense::Other, 0),
|
||||
LicenseBlockType::Website | LicenseBlockType::Code => {
|
||||
return Err(Error::UnknownBlockType(typ_i));
|
||||
}
|
||||
};
|
||||
@@ -710,7 +723,11 @@ impl fmt::Debug for DebugLicense<'_> {
|
||||
d.field("properties", &"error");
|
||||
}
|
||||
}
|
||||
LicenseBlockType::Ephemeral => {}
|
||||
LicenseBlockType::Token
|
||||
| LicenseBlockType::LicenseSign
|
||||
| LicenseBlockType::MytsIdSign
|
||||
| LicenseBlockType::Updater
|
||||
| LicenseBlockType::Ephemeral => {}
|
||||
}
|
||||
|
||||
d.finish()?;
|
||||
@@ -727,7 +744,11 @@ impl LicenseBlockType {
|
||||
Self::Website | Self::Code => 1,
|
||||
Self::Server => 6,
|
||||
Self::Ts5Server => 2,
|
||||
Self::Ephemeral => 0,
|
||||
Self::Token
|
||||
| Self::LicenseSign
|
||||
| Self::MytsIdSign
|
||||
| Self::Updater
|
||||
| Self::Ephemeral => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -923,6 +944,27 @@ mod tests {
|
||||
YrUET9sEbz1CATKgK8EyqrfA==").unwrap()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_blocks_without_payload() {
|
||||
// Token, License_Sign, MyTsId_Sign and Updater blocks end with their
|
||||
// header, as Ephemeral blocks do.
|
||||
for typ in [4, 5, 6, 7] {
|
||||
let mut data = vec![1, 0];
|
||||
data.extend_from_slice(&[0x58; 32]);
|
||||
data.push(typ);
|
||||
data.extend_from_slice(&[0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff]);
|
||||
let licenses = Licenses::parse_ignore_expired(data.clone()).unwrap();
|
||||
assert_eq!(licenses.blocks.len(), 1);
|
||||
assert_eq!(licenses.blocks[0].len, BLOCK_MIN_LEN);
|
||||
let block = licenses.blocks[0].get_type(&data[1..]).unwrap();
|
||||
assert_eq!(block.to_u8(), Some(typ));
|
||||
// Anything after the header is the next block.
|
||||
data.push(0);
|
||||
assert!(Licenses::parse_ignore_expired(data).is_err());
|
||||
}
|
||||
assert_eq!(LicenseBlockType::from_u8(6), Some(LicenseBlockType::MytsIdSign));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derive_public_key() {
|
||||
let licenses = Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQA1hUFJiiSs0wFXkYuPUJVcDa6XCrZTcsvkB0Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAAC4R+5mos+UQ/KCbkpQLMI5WRp4wkQu8e5PZY4zU+/FlyAJwaE8CcJJ/A==").unwrap()).unwrap();
|
||||
|
||||
@@ -6,13 +6,17 @@
|
||||
use std::fmt;
|
||||
|
||||
use base64::prelude::*;
|
||||
use curve25519_dalek::edwards::{CompressedEdwardsY, EdwardsPoint};
|
||||
use curve25519_dalek::{constants::ED25519_BASEPOINT_TABLE, scalar::Scalar};
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use sha2::{Digest, Sha256, Sha512};
|
||||
use thiserror::Error;
|
||||
use tsproto_packets::packets::OutCommand;
|
||||
use tsproto_types::crypto::EccKeyPubEd25519;
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use crate::license::{self, LicenseBlockType, Licenses};
|
||||
|
||||
/// An account identity; distinct from the account UUID and server identity.
|
||||
#[derive(Clone, Serialize)]
|
||||
pub struct Identity {
|
||||
@@ -94,6 +98,13 @@ impl Identity {
|
||||
|
||||
pub fn id(&self) -> String { BASE64_STANDARD.encode(&self.myts_id) }
|
||||
|
||||
/// The myTS ID's 33 bytes: what myTeamSpeak signs the account's avatar,
|
||||
/// badges and identifier token for.
|
||||
pub fn id_bytes(&self) -> &[u8] { &self.myts_id }
|
||||
|
||||
/// The certificate of the myTS ID's signature (`pubSignCert`): public.
|
||||
pub fn public_signature_certificate(&self) -> &[u8] { &self.public_signature[64..] }
|
||||
|
||||
/// Sign this connection's challenge with the original raw private scalar.
|
||||
/// This is not Ed25519's seed expansion: the account already stores a scalar.
|
||||
pub fn proof(&self, shared_iv: &[u8; 64]) -> Proof {
|
||||
@@ -131,6 +142,91 @@ impl Identity {
|
||||
}
|
||||
}
|
||||
|
||||
/// A myTeamSpeak certificate: a TeamSpeak license chain whose last block's
|
||||
/// key signs what myTeamSpeak hands out for an account (its avatar, badges
|
||||
/// and identifier token). Checked as a TeamSpeak 6 server and the official
|
||||
/// client check it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Certificate {
|
||||
block_type: Option<LicenseBlockType>,
|
||||
/// Unix seconds.
|
||||
not_valid_before: i64,
|
||||
not_valid_after: i64,
|
||||
/// The leaf's key, derived along the chain from the root.
|
||||
key: [u8; 32],
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum CertificateError {
|
||||
#[error("myTeamSpeak certificate must start with version 1")]
|
||||
Version,
|
||||
#[error("myTeamSpeak certificate holds no key")]
|
||||
Empty,
|
||||
#[error("myTeamSpeak certificate does not parse: {0}")]
|
||||
License(#[from] license::Error),
|
||||
}
|
||||
|
||||
impl Certificate {
|
||||
/// Parse a certificate whose chain starts at `root` (the TeamSpeak root
|
||||
/// key, [`crate::ROOT_KEY`]). Nested validity windows are checked here,
|
||||
/// the leaf's against a time by [`Self::valid_at`].
|
||||
pub fn parse(data: &[u8], root: &[u8; 32]) -> Result<Self, CertificateError> {
|
||||
if data.first() != Some(&1) {
|
||||
return Err(CertificateError::Version);
|
||||
}
|
||||
let licenses = Licenses::parse_ignore_expired(data.to_vec())?;
|
||||
let leaf = licenses.blocks.last().ok_or(CertificateError::Empty)?;
|
||||
let leaf_data = &data[data.len() - leaf.len..];
|
||||
let key = licenses.derive_public_key(EccKeyPubEd25519::from_bytes(*root))?;
|
||||
Ok(Self {
|
||||
block_type: leaf.get_type(leaf_data).ok(),
|
||||
not_valid_before: leaf.get_not_valid_before(leaf_data)?.unix_timestamp(),
|
||||
not_valid_after: leaf.get_not_valid_after(leaf_data)?.unix_timestamp(),
|
||||
key: key.compress().to_bytes(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the leaf is a key that signs for myTS IDs (`MYTSID_SIGN`):
|
||||
/// a TeamSpeak 6 server takes no other for an avatar or badges.
|
||||
pub fn signs_myts_data(&self) -> bool { self.block_type == Some(LicenseBlockType::MytsIdSign) }
|
||||
|
||||
/// Whether the leaf is valid at `unix` seconds.
|
||||
pub fn valid_at(&self, unix: i64) -> bool {
|
||||
self.not_valid_before <= unix && unix < self.not_valid_after
|
||||
}
|
||||
|
||||
/// Until when the leaf is valid, Unix seconds.
|
||||
pub fn not_valid_after(&self) -> i64 { self.not_valid_after }
|
||||
|
||||
/// Whether the leaf's key signed `message` (Ed25519, as TeamSpeak checks
|
||||
/// it: SHA-512 over R, the key and the message, without the cofactor;
|
||||
/// a signature whose S is not reduced is refused).
|
||||
pub fn verifies(&self, message: &[u8], signature: &[u8]) -> bool {
|
||||
verify_ed25519(&self.key, message, signature)
|
||||
}
|
||||
}
|
||||
|
||||
fn verify_ed25519(key: &[u8; 32], message: &[u8], signature: &[u8]) -> bool {
|
||||
if signature.len() != 64 {
|
||||
return false;
|
||||
}
|
||||
let Some(public) = CompressedEdwardsY(*key).decompress() else {
|
||||
return false;
|
||||
};
|
||||
let mut s = [0; 32];
|
||||
s.copy_from_slice(&signature[32..]);
|
||||
let Some(s) = Option::<Scalar>::from(Scalar::from_canonical_bytes(s)) else {
|
||||
return false;
|
||||
};
|
||||
let mut hash = Sha512::new();
|
||||
hash.update(&signature[..32]);
|
||||
hash.update(key);
|
||||
hash.update(message);
|
||||
let k = Scalar::from_bytes_mod_order_wide(&hash.finalize().into());
|
||||
let r = EdwardsPoint::vartime_double_scalar_mul_basepoint(&k, &-public, &s);
|
||||
r.compress().as_bytes() == &signature[..32]
|
||||
}
|
||||
|
||||
/// Public, connection-bound authentication values. Never contains private keys.
|
||||
#[derive(Clone)]
|
||||
pub struct Proof {
|
||||
@@ -244,4 +340,136 @@ mod tests {
|
||||
]);
|
||||
assert!(!wire.contains("private"));
|
||||
}
|
||||
|
||||
/// A chain from a synthetic root (secret `root`): an intermediate block
|
||||
/// when `outer` is set, then a leaf of `kind` with the key `leaf`·B, valid
|
||||
/// from `from` to `to` (Unix seconds). Also the leaf's derived secret.
|
||||
fn chain(
|
||||
root: Scalar, outer: Option<(i64, i64)>, leaf: Scalar, kind: u8, from: i64, to: i64,
|
||||
) -> (Vec<u8>, Scalar) {
|
||||
fn block(key: &Scalar, kind: u8, from: i64, to: i64, extra: &[u8]) -> (Vec<u8>, Scalar) {
|
||||
let mut block = vec![0];
|
||||
block.extend_from_slice((ED25519_BASEPOINT_TABLE * key).compress().as_bytes());
|
||||
block.push(kind);
|
||||
for time in [from, to] {
|
||||
block.extend_from_slice(&((time - license::TIMESTAMP_OFFSET) as u32).to_be_bytes());
|
||||
}
|
||||
block.extend_from_slice(extra);
|
||||
let mut hash: [u8; 64] = Sha512::digest(&block[1..]).into();
|
||||
hash[0] &= 248;
|
||||
hash[31] &= 63;
|
||||
hash[31] |= 64;
|
||||
let mut low = [0; 32];
|
||||
low.copy_from_slice(&hash[..32]);
|
||||
(block, Scalar::from_bytes_mod_order(low))
|
||||
}
|
||||
let mut data = vec![1];
|
||||
let mut secret = root;
|
||||
if let Some((from, to)) = outer {
|
||||
let key = Scalar::from_bytes_mod_order([3; 32]);
|
||||
let (outer, hash) = block(&key, 0, from, to, b"\0\0\0\0Synthetic\0");
|
||||
data.extend_from_slice(&outer);
|
||||
secret += key * hash;
|
||||
}
|
||||
let (leaf_block, hash) = block(&leaf, kind, from, to, &[]);
|
||||
data.extend_from_slice(&leaf_block);
|
||||
(data, secret + leaf * hash)
|
||||
}
|
||||
|
||||
fn sign(secret: &Scalar, message: &[u8]) -> Vec<u8> {
|
||||
let public = (ED25519_BASEPOINT_TABLE * secret).compress().to_bytes();
|
||||
let nonce = Scalar::from_bytes_mod_order_wide(
|
||||
&Sha512::new().chain_update(secret.as_bytes()).chain_update(message).finalize().into(),
|
||||
);
|
||||
let r = (ED25519_BASEPOINT_TABLE * &nonce).compress().to_bytes();
|
||||
let k = Scalar::from_bytes_mod_order_wide(
|
||||
&Sha512::new().chain_update(r).chain_update(public).chain_update(message).finalize().into(),
|
||||
);
|
||||
let mut signature = r.to_vec();
|
||||
signature.extend_from_slice((k * secret + nonce).as_bytes());
|
||||
signature
|
||||
}
|
||||
|
||||
const NOW: i64 = 1_790_000_000;
|
||||
|
||||
#[test]
|
||||
fn certificate_key_signs_along_the_chain() {
|
||||
let root = Scalar::from_bytes_mod_order([5; 32]);
|
||||
let root_key = (ED25519_BASEPOINT_TABLE * &root).compress().to_bytes();
|
||||
let leaf = Scalar::from_bytes_mod_order([7; 32]);
|
||||
for outer in [None, Some((NOW - 1000, NOW + 1000))] {
|
||||
let (data, secret) = chain(root, outer, leaf, 6, NOW - 10, NOW + 10);
|
||||
let certificate = Certificate::parse(&data, &root_key).unwrap();
|
||||
assert!(certificate.signs_myts_data());
|
||||
assert!(certificate.valid_at(NOW - 10) && certificate.valid_at(NOW + 9));
|
||||
assert!(!certificate.valid_at(NOW - 11) && !certificate.valid_at(NOW + 10));
|
||||
assert_eq!(certificate.not_valid_after(), NOW + 10);
|
||||
let signature = sign(&secret, b"message");
|
||||
assert!(certificate.verifies(b"message", &signature));
|
||||
assert!(!certificate.verifies(b"messagE", &signature));
|
||||
assert!(!certificate.verifies(b"message", &signature[..63]));
|
||||
let mut flipped = signature.clone();
|
||||
flipped[5] ^= 1;
|
||||
assert!(!certificate.verifies(b"message", &flipped));
|
||||
// The same S plus the group order: refused, though it is the same
|
||||
// point (S must be reduced).
|
||||
let mut s = [0u8; 32];
|
||||
s.copy_from_slice(&signature[32..]);
|
||||
let order: [u8; 32] = [
|
||||
0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9,
|
||||
0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10,
|
||||
];
|
||||
let mut carry = 0u16;
|
||||
for (s, l) in s.iter_mut().zip(order) {
|
||||
let sum = u16::from(*s) + u16::from(l) + carry;
|
||||
*s = sum as u8;
|
||||
carry = sum >> 8;
|
||||
}
|
||||
let mut unreduced = signature.clone();
|
||||
unreduced[32..].copy_from_slice(&s);
|
||||
assert!(!certificate.verifies(b"message", &unreduced));
|
||||
// Another root: another key.
|
||||
let other = Certificate::parse(&data, &crate::ROOT_KEY).unwrap();
|
||||
assert!(!other.verifies(b"message", &signature));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ed25519_matches_rfc_8032() {
|
||||
// RFC 8032, 7.1, tests 1 and 2.
|
||||
let key = hex::<32>("d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a");
|
||||
let signature = hex::<64>(
|
||||
"e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b",
|
||||
);
|
||||
assert!(verify_ed25519(&key, b"", &signature));
|
||||
assert!(!verify_ed25519(&key, b"\x72", &signature));
|
||||
let key = hex::<32>("3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c");
|
||||
let signature = hex::<64>(
|
||||
"92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00",
|
||||
);
|
||||
assert!(verify_ed25519(&key, b"\x72", &signature));
|
||||
assert!(!verify_ed25519(&key, b"\x73", &signature));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certificate_kinds_windows_and_format() {
|
||||
let root = Scalar::from_bytes_mod_order([5; 32]);
|
||||
let root_key = (ED25519_BASEPOINT_TABLE * &root).compress().to_bytes();
|
||||
let leaf = Scalar::from_bytes_mod_order([7; 32]);
|
||||
for kind in [4, 5, 7, 32] {
|
||||
let (data, _) = chain(root, None, leaf, kind, NOW - 10, NOW + 10);
|
||||
assert!(!Certificate::parse(&data, &root_key).unwrap().signs_myts_data(), "{}", kind);
|
||||
}
|
||||
// A leaf valid longer than the block above it.
|
||||
let (data, _) = chain(root, Some((NOW - 5, NOW + 5)), leaf, 6, NOW - 10, NOW + 10);
|
||||
assert!(Certificate::parse(&data, &root_key).is_err());
|
||||
let (mut data, _) = chain(root, None, leaf, 6, NOW - 10, NOW + 10);
|
||||
data[0] = 0;
|
||||
assert!(matches!(Certificate::parse(&data, &root_key), Err(CertificateError::Version)));
|
||||
assert!(matches!(Certificate::parse(&[1], &root_key), Err(CertificateError::Empty)));
|
||||
assert!(Certificate::parse(&[], &root_key).is_err());
|
||||
data[0] = 1;
|
||||
data[34] = 9;
|
||||
assert!(Certificate::parse(&data, &root_key).is_err());
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "sync", "
|
||||
tracing = "0.1.44"
|
||||
voelin-core = { path = "../voelin-core" }
|
||||
# Channels and people for the voice notification.
|
||||
voelin-model = { path = "../voelin-model" }
|
||||
voelin-model = { workspace = true }
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
anyhow = "1.0.104"
|
||||
@@ -32,9 +32,5 @@ voelin-platform = { path = "../voelin-platform", default-features = false }
|
||||
voelin-store = { path = "../voelin-store" }
|
||||
voelin-ui = { path = "../voelin-ui" }
|
||||
|
||||
[dev-dependencies]
|
||||
# Client ids of stream viewers in the tests.
|
||||
tsclientlib = { path = "../proto/tsclientlib" }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -13,7 +13,7 @@ use std::sync::Arc;
|
||||
|
||||
use voelin_core::stream::{StreamState, ViewerInfo, ViewerState};
|
||||
use voelin_core::{Event, SessionId, VoiceState};
|
||||
use voelin_model::Presence;
|
||||
use voelin_model::{Presence, channel_title};
|
||||
|
||||
/// What the voice notification shows.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -72,13 +72,13 @@ impl Session {
|
||||
self.name.as_deref().unwrap_or("a server")
|
||||
}
|
||||
|
||||
/// Our channel's name and how many are in it.
|
||||
/// Our channel's name (a spacer's text) and how many are in it.
|
||||
fn channel(&self) -> Option<(&str, usize)> {
|
||||
let id = self.own_channel?;
|
||||
let channel = self.presence.channels.get(&id)?;
|
||||
let people =
|
||||
self.presence.clients.values().filter(|c| c.channel == id && !c.is_query).count();
|
||||
Some((channel.name.as_str(), people))
|
||||
Some((channel_title(channel).0, people))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -194,7 +194,7 @@ fn connected(viewers: &[ViewerInfo]) -> usize {
|
||||
mod tests {
|
||||
use voelin_core::SessionState;
|
||||
use voelin_core::stream::EndReason;
|
||||
use voelin_model::{Capabilities, ChannelInfo, ClientInfo, ServerFlavor};
|
||||
use voelin_model::{Capabilities, ChannelInfo, ClientInfo};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -222,8 +222,11 @@ mod tests {
|
||||
|
||||
fn presence(people: u16) -> Event {
|
||||
let mut p = Presence::default();
|
||||
p.channels
|
||||
.insert(2, ChannelInfo { id: 2, name: "Chill Zone".into(), ..Default::default() });
|
||||
// A spacer shows its text.
|
||||
p.channels.insert(
|
||||
2,
|
||||
ChannelInfo { id: 2, name: "[cspacer1]Chill Zone".into(), ..Default::default() },
|
||||
);
|
||||
for id in 1..=people {
|
||||
p.clients.insert(id, ClientInfo { id, channel: 2, ..Default::default() });
|
||||
}
|
||||
@@ -241,7 +244,7 @@ mod tests {
|
||||
let info = Event::ServerInfo {
|
||||
session: 1,
|
||||
name: "Home".into(),
|
||||
flavor: ServerFlavor::Unknown(String::new()),
|
||||
backend: voelin_core::BackendInfo::default(),
|
||||
capabilities: Capabilities::default(),
|
||||
};
|
||||
assert_eq!(fg.update_at(&info, 6).voice, notice("Connecting…", "Home", false, 0));
|
||||
@@ -313,7 +316,7 @@ mod tests {
|
||||
};
|
||||
assert_eq!(fg.screen(), screen("Live in Chill Zone", "a server").flatten());
|
||||
let viewer = |client, state| ViewerInfo {
|
||||
client: tsclientlib::ClientId(client),
|
||||
client,
|
||||
state,
|
||||
message: String::new(),
|
||||
layer: None,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "voelin-audio"
|
||||
version = "0.1.0"
|
||||
description = "Voice pipeline: Opus encoding, framing, resampling, jitter buffer/mixer and audio devices."
|
||||
description = "Voice pipeline: Opus encoding, framing, resampling, jitter buffer/mixer and audio devices, independent of the voice transport."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
@@ -25,8 +25,6 @@ sonora-agc2 = "0.2"
|
||||
sonora-simd = "0.2"
|
||||
thiserror = "2.0.21"
|
||||
tracing = "0.1.44"
|
||||
tsclientlib = { path = "../proto/tsclientlib" }
|
||||
tsproto-packets = { path = "../proto/tsproto-packets" }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = "1"
|
||||
|
||||
@@ -1,45 +1,15 @@
|
||||
//! Opus encoding into TeamSpeak voice packets.
|
||||
//! Opus encoding of 20 ms frames into [`EncodedVoice`].
|
||||
|
||||
use opus2::{Application, Bitrate, Channels, Encoder};
|
||||
use tsproto_packets::packets::{AudioData, CodecType, OutAudio, OutPacket};
|
||||
|
||||
use crate::pcm::{FRAME_SAMPLES, SAMPLE_RATE};
|
||||
use crate::packet::{EncodedVoice, VoiceCodec};
|
||||
use crate::pcm::SAMPLE_RATE;
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Largest possible Opus packet.
|
||||
const MAX_PACKET: usize = 1275;
|
||||
|
||||
/// The two Opus codecs TeamSpeak channels use.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum VoiceCodec {
|
||||
/// Mono, tuned for speech (`CodecType::OpusVoice`).
|
||||
Voice,
|
||||
/// Stereo, tuned for music (`CodecType::OpusMusic`).
|
||||
Music,
|
||||
}
|
||||
|
||||
impl VoiceCodec {
|
||||
pub fn channels(self) -> usize {
|
||||
match self {
|
||||
VoiceCodec::Voice => 1,
|
||||
VoiceCodec::Music => 2,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn codec_type(self) -> CodecType {
|
||||
match self {
|
||||
VoiceCodec::Voice => CodecType::OpusVoice,
|
||||
VoiceCodec::Music => CodecType::OpusMusic,
|
||||
}
|
||||
}
|
||||
|
||||
/// Samples (all channels) in one 20 ms frame.
|
||||
pub fn frame_len(self) -> usize {
|
||||
FRAME_SAMPLES * self.channels()
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes 20 ms frames of 48 kHz audio into voice packets.
|
||||
/// Encodes 20 ms frames of 48 kHz audio into Opus packets.
|
||||
pub struct VoiceEncoder {
|
||||
encoder: Encoder,
|
||||
codec: VoiceCodec,
|
||||
@@ -53,7 +23,7 @@ impl VoiceEncoder {
|
||||
VoiceCodec::Music => (Channels::Stereo, Application::Audio),
|
||||
};
|
||||
let mut encoder = Encoder::new(SAMPLE_RATE, channels, application)?;
|
||||
// Survive some packet loss: TeamSpeak voice is plain UDP.
|
||||
// Survive some packet loss: voice travels over unreliable datagrams.
|
||||
encoder.set_inband_fec(true)?;
|
||||
encoder.set_packet_loss_perc(5)?;
|
||||
Ok(Self { encoder, codec, out: vec![0; MAX_PACKET] })
|
||||
@@ -82,26 +52,25 @@ impl VoiceEncoder {
|
||||
Ok(&self.out[..len])
|
||||
}
|
||||
|
||||
/// Encode one frame into a packet ready for `Connection::send_audio`.
|
||||
/// The connection assigns the packet id.
|
||||
pub fn encode(&mut self, frame: &[f32]) -> Result<OutPacket> {
|
||||
let codec = self.codec.codec_type();
|
||||
let data = self.encode_to_bytes(frame)?;
|
||||
Ok(OutAudio::new(&AudioData::C2S { id: 0, codec, data }))
|
||||
/// Encode one frame for the transport to send. The transport assigns the
|
||||
/// packet number.
|
||||
pub fn encode(&mut self, frame: &[f32]) -> Result<EncodedVoice> {
|
||||
let codec = self.codec;
|
||||
let payload = self.encode_to_bytes(frame)?.to_vec();
|
||||
Ok(EncodedVoice { codec, payload })
|
||||
}
|
||||
|
||||
/// The empty packet that tells listeners the transmission ended.
|
||||
pub fn end_of_stream(&self) -> OutPacket {
|
||||
OutAudio::new(&AudioData::C2S { id: 0, codec: self.codec.codec_type(), data: &[] })
|
||||
pub fn end_of_stream(&self) -> EncodedVoice {
|
||||
EncodedVoice { codec: self.codec, payload: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tsproto_packets::packets::{Direction, InAudioBuf};
|
||||
|
||||
use super::*;
|
||||
use crate::pcm;
|
||||
use crate::packet::{TalkerId, VoicePacket};
|
||||
use crate::pcm::{self, FRAME_SAMPLES};
|
||||
|
||||
/// Encode a tone, feed the packets through the mixer (jitter buffer +
|
||||
/// decoder), and check the tone comes out.
|
||||
@@ -112,15 +81,16 @@ mod tests {
|
||||
let tone = pcm::sine(1000.0, 1.0, 0.5);
|
||||
let mut decoded = Vec::new();
|
||||
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
|
||||
let data = encoder.encode_to_bytes(frame).unwrap().to_vec();
|
||||
let packet = OutAudio::new(&AudioData::S2C {
|
||||
id: i as u16,
|
||||
codec: CodecType::OpusVoice,
|
||||
from: 7,
|
||||
data: &data,
|
||||
});
|
||||
let packet = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
|
||||
mixer.handle_packet(tsclientlib::ClientId(7), packet).unwrap();
|
||||
let sent = encoder.encode(frame).unwrap();
|
||||
assert_eq!(sent.codec, VoiceCodec::Voice);
|
||||
let packet = VoicePacket {
|
||||
talker: TalkerId(7),
|
||||
seq: i as u16,
|
||||
codec: sent.codec,
|
||||
whisper: false,
|
||||
payload: sent.payload,
|
||||
};
|
||||
mixer.handle_packet(packet).unwrap();
|
||||
let mut out = vec![0.0; FRAME_SAMPLES * 2];
|
||||
mixer.fill_buffer(&mut out);
|
||||
decoded.extend(pcm::to_mono(&out, 2));
|
||||
@@ -131,6 +101,24 @@ mod tests {
|
||||
assert!(ratio > 0.8, "tone ratio {ratio}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_of_stream_has_no_payload() {
|
||||
let encoder = VoiceEncoder::new(VoiceCodec::Music).unwrap();
|
||||
let end = encoder.end_of_stream();
|
||||
assert_eq!(end, EncodedVoice { codec: VoiceCodec::Music, payload: vec![] });
|
||||
assert!(end.is_end());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoded_frames_carry_codec_and_audio() {
|
||||
let mut voice = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut music = VoiceEncoder::new(VoiceCodec::Music).unwrap();
|
||||
let a = voice.encode(&[0.1; FRAME_SAMPLES]).unwrap();
|
||||
let b = music.encode(&[0.1; FRAME_SAMPLES * 2]).unwrap();
|
||||
assert_eq!((a.codec, b.codec), (VoiceCodec::Voice, VoiceCodec::Music));
|
||||
assert!(!a.is_end() && !b.is_end());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_wrong_frame_size() {
|
||||
let mut encoder = VoiceEncoder::new(VoiceCodec::Music).unwrap();
|
||||
|
||||
@@ -0,0 +1,879 @@
|
||||
//! Handle receiving audio.
|
||||
//!
|
||||
//! Moved here from the vendored `tsclientlib::audio` and made independent of the
|
||||
//! transport: it reads [`VoicePacket`]s, whatever carried them.
|
||||
//!
|
||||
//! The [`AudioHandler`] collects all incoming audio packets and queues them per
|
||||
//! talker. It decodes the audio, handles out-of-order packets and missing
|
||||
//! packets. It automatically adjusts the queue length based on the jitter of
|
||||
//! incoming packets.
|
||||
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::convert::TryInto;
|
||||
|
||||
use opus2::{Channels, Decoder, packet};
|
||||
use thiserror::Error;
|
||||
use tracing::{Span, debug, info_span, trace, warn};
|
||||
|
||||
use crate::packet::{TalkerId, VoicePacket};
|
||||
|
||||
const SAMPLE_RATE: u32 = 48_000;
|
||||
const CHANNELS: Channels = Channels::Stereo;
|
||||
const CHANNEL_NUM: usize = 2;
|
||||
/// If this amount of packets is lost consecutively, we assume the stream stopped.
|
||||
const MAX_PACKET_LOSSES: usize = 3;
|
||||
/// Store the buffer sizes for the last `LAST_BUFFER_SIZE_COUNT` packets.
|
||||
const LAST_BUFFER_SIZE_COUNT: u8 = 255;
|
||||
/// The amount of samples to maximally buffer. Equivalent to 0.5 s.
|
||||
const MAX_BUFFER_SIZE: usize = 48_000 / 2;
|
||||
/// Maximum number of packets in the queue.
|
||||
const MAX_BUFFER_PACKETS: usize = 50;
|
||||
/// Buffer for maximal 0.5 s without playing anything.
|
||||
const MAX_BUFFER_TIME: usize = 48_000 / 2;
|
||||
/// Duplicate or remove every `step` sample when speeding-up.
|
||||
const SPEED_CHANGE_STEPS: usize = 100;
|
||||
/// The usual amount of samples in a frame.
|
||||
///
|
||||
/// Use 48 kHz, 20 ms frames (50 per second) and mono data (1 channel).
|
||||
/// This means 1920 samples and 7.5 kiB.
|
||||
const USUAL_FRAME_SIZE: usize = 48000 / 50;
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum Error {
|
||||
#[error("Failed to create opus decoder: {0}")]
|
||||
CreateDecoder(#[source] opus2::Error),
|
||||
#[error("Opus decode failed: {error} (packet: {packet:?})")]
|
||||
Decode {
|
||||
#[source]
|
||||
error: opus2::Error,
|
||||
packet: Option<Vec<u8>>,
|
||||
},
|
||||
#[error("Get duplicate packet id {0}")]
|
||||
Duplicate(u16),
|
||||
#[error("Failed to get packet samples: {0}")]
|
||||
GetPacketSample(#[source] opus2::Error),
|
||||
#[error("Audio queue is full, dropping")]
|
||||
QueueFull,
|
||||
#[error("Audio packet is too late, dropping (wanted {wanted}, got {got})")]
|
||||
TooLate { wanted: u16, got: u16 },
|
||||
#[error("Packet has too many samples")]
|
||||
TooManySamples,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct SlidingWindowMinimum<T: Copy + Default + Ord> {
|
||||
/// How long a value stays in the sliding window.
|
||||
size: u8,
|
||||
/// This is a sliding window minimum, it contains
|
||||
/// `(insertion time, value)`.
|
||||
///
|
||||
/// When we insert a value, we can remove all bigger sample counts,
|
||||
/// thus the queue always stays sorted with the minimum at the front
|
||||
/// and the maximum at the back (latest entry).
|
||||
///
|
||||
/// Provides amortized O(1) minimum.
|
||||
/// Source: https://people.cs.uct.ac.za/~ksmith/articles/sliding_window_minimum.html#sliding-window-minimum-algorithm
|
||||
queue: VecDeque<(u8, T)>,
|
||||
/// The current insertion time.
|
||||
cur_time: u8,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct QueuePacket {
|
||||
packet: VoicePacket,
|
||||
samples: usize,
|
||||
id: u16,
|
||||
}
|
||||
|
||||
/// A queue for audio packets for one audio stream.
|
||||
pub struct AudioQueue {
|
||||
span: Span,
|
||||
decoder: Decoder,
|
||||
pub volume: f32,
|
||||
/// The id of the next packet that should be decoded.
|
||||
///
|
||||
/// Used to check for packet loss.
|
||||
next_id: u16,
|
||||
/// If the last packet was a whisper packet.
|
||||
whispering: bool,
|
||||
packet_buffer: VecDeque<QueuePacket>,
|
||||
/// Amount of samples in the `packet_buffer`.
|
||||
packet_buffer_samples: usize,
|
||||
/// Temporary buffer that contains the samples of one decoded packet.
|
||||
decoded_buffer: Vec<f32>,
|
||||
/// The number of samples in `decoded_buffer` that have been returned.
|
||||
decoded_pos: usize,
|
||||
/// The number of samples in the last packet.
|
||||
last_packet_samples: usize,
|
||||
/// The last `packet_loss_num` packet decodes were a loss.
|
||||
packet_loss_num: usize,
|
||||
/// The amount of samples to buffer until this queue is ready to play.
|
||||
buffering_samples: usize,
|
||||
/// The amount of packets in the buffer when a packet was decoded.
|
||||
///
|
||||
/// Uses the amount of samples in the `packet_buffer` / `USUAL_PACKET_SAMPLES`.
|
||||
/// Used to expand or reduce the buffer.
|
||||
last_buffer_size_min: SlidingWindowMinimum<u8>,
|
||||
last_buffer_size_max: SlidingWindowMinimum<Reverse<u8>>,
|
||||
/// Buffered for this duration.
|
||||
buffered_for_samples: usize,
|
||||
}
|
||||
|
||||
/// Handles incoming audio, has one [`AudioQueue`] per talker.
|
||||
#[derive(Default)]
|
||||
pub struct AudioHandler {
|
||||
queues: HashMap<TalkerId, AudioQueue>,
|
||||
/// Buffer this amount of samples for new queues before starting to play.
|
||||
///
|
||||
/// Updated when a new queue gets added.
|
||||
avg_buffer_samples: usize,
|
||||
}
|
||||
|
||||
impl<T: Copy + Default + Ord> SlidingWindowMinimum<T> {
|
||||
fn new(size: u8) -> Self {
|
||||
Self { size, queue: Default::default(), cur_time: 0 }
|
||||
}
|
||||
|
||||
fn push(&mut self, value: T) {
|
||||
while self.queue.back().map(|(_, s)| *s >= value).unwrap_or_default() {
|
||||
self.queue.pop_back();
|
||||
}
|
||||
let i = self.cur_time;
|
||||
self.queue.push_back((i, value));
|
||||
while self
|
||||
.queue
|
||||
.front()
|
||||
.map(|(i, _)| self.cur_time.wrapping_sub(*i) >= self.size)
|
||||
.unwrap_or_default()
|
||||
{
|
||||
self.queue.pop_front();
|
||||
}
|
||||
self.cur_time = self.cur_time.wrapping_add(1);
|
||||
}
|
||||
|
||||
fn get_min(&self) -> T {
|
||||
self.queue.front().map(|(_, s)| *s).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioQueue {
|
||||
fn new(packet: VoicePacket) -> Result<Self> {
|
||||
let last_packet_samples =
|
||||
packet::get_nb_samples(&packet.payload, SAMPLE_RATE).map_err(Error::GetPacketSample)?;
|
||||
if last_packet_samples > MAX_BUFFER_SIZE {
|
||||
return Err(Error::TooManySamples);
|
||||
}
|
||||
|
||||
let last_packet_samples = last_packet_samples * CHANNEL_NUM;
|
||||
let whispering = packet.whisper;
|
||||
let decoder = Decoder::new(SAMPLE_RATE, CHANNELS).map_err(Error::CreateDecoder)?;
|
||||
|
||||
let mut res = Self {
|
||||
span: Span::current(),
|
||||
decoder,
|
||||
volume: 1.0,
|
||||
next_id: packet.seq,
|
||||
whispering,
|
||||
packet_buffer: Default::default(),
|
||||
packet_buffer_samples: 0,
|
||||
decoded_buffer: Default::default(),
|
||||
decoded_pos: 0,
|
||||
last_packet_samples,
|
||||
packet_loss_num: 0,
|
||||
buffering_samples: 0,
|
||||
last_buffer_size_min: SlidingWindowMinimum::new(LAST_BUFFER_SIZE_COUNT),
|
||||
last_buffer_size_max: SlidingWindowMinimum::<Reverse<u8>>::new(LAST_BUFFER_SIZE_COUNT),
|
||||
buffered_for_samples: 0,
|
||||
};
|
||||
res.add_buffer_size(0);
|
||||
res.add_packet(packet)?;
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
pub fn get_decoder(&self) -> &Decoder {
|
||||
&self.decoder
|
||||
}
|
||||
pub fn is_whispering(&self) -> bool {
|
||||
self.whispering
|
||||
}
|
||||
|
||||
/// Size is in samples.
|
||||
fn add_buffer_size(&mut self, size: usize) {
|
||||
if let Ok(size) = (size / USUAL_FRAME_SIZE).try_into() {
|
||||
self.last_buffer_size_min.push(size);
|
||||
self.last_buffer_size_max.push(Reverse(size));
|
||||
} else {
|
||||
warn!(parent: &self.span, size, "Failed to put amount of packets into an u8");
|
||||
}
|
||||
}
|
||||
|
||||
/// The approximate deviation of the buffer size.
|
||||
fn get_deviation(&self) -> u8 {
|
||||
let min = self.last_buffer_size_min.get_min();
|
||||
let max = self.last_buffer_size_max.get_min();
|
||||
max.0 - min
|
||||
}
|
||||
|
||||
fn add_packet(&mut self, packet: VoicePacket) -> Result<()> {
|
||||
let _span = self.span.enter();
|
||||
if self.packet_buffer.len() >= MAX_BUFFER_PACKETS {
|
||||
return Err(Error::QueueFull);
|
||||
}
|
||||
let samples;
|
||||
if packet.is_end() {
|
||||
// End of stream
|
||||
samples = 0;
|
||||
} else {
|
||||
samples = packet::get_nb_samples(&packet.payload, SAMPLE_RATE)
|
||||
.map_err(Error::GetPacketSample)?;
|
||||
if samples > MAX_BUFFER_SIZE {
|
||||
return Err(Error::TooManySamples);
|
||||
}
|
||||
}
|
||||
|
||||
let id = packet.seq;
|
||||
let packet = QueuePacket { packet, samples, id };
|
||||
if id.wrapping_sub(self.next_id) > MAX_BUFFER_PACKETS as u16 {
|
||||
return Err(Error::TooLate { wanted: self.next_id, got: id });
|
||||
}
|
||||
|
||||
// Put into first spot where the id is smaller
|
||||
let i = self.packet_buffer.len()
|
||||
- self
|
||||
.packet_buffer
|
||||
.iter()
|
||||
.enumerate()
|
||||
.rev()
|
||||
.take_while(|(_, p)| p.id.wrapping_sub(id) <= MAX_BUFFER_PACKETS as u16)
|
||||
.count();
|
||||
// Check for duplicate packet
|
||||
if let Some(p) = self.packet_buffer.get(i)
|
||||
&& p.id == packet.id
|
||||
{
|
||||
return Err(Error::Duplicate(p.id));
|
||||
}
|
||||
|
||||
trace!("Insert packet {} at {}", id, i);
|
||||
let last_id = self.packet_buffer.back().map(|p| p.id.wrapping_add(1)).unwrap_or(id);
|
||||
if last_id <= id {
|
||||
self.buffering_samples = self.buffering_samples.saturating_sub(samples);
|
||||
// Reduce buffering counter by lost packets if there are some
|
||||
self.buffering_samples = self
|
||||
.buffering_samples
|
||||
.saturating_sub(usize::from(id - last_id) * self.last_packet_samples);
|
||||
}
|
||||
|
||||
self.packet_buffer_samples += packet.samples;
|
||||
self.packet_buffer.insert(i, packet);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn decode_packet(&mut self, packet: Option<&QueuePacket>, fec: bool) -> Result<()> {
|
||||
let _span = self.span.clone().entered();
|
||||
trace!(has_packet = packet.is_some(), fec, "Decoding packet");
|
||||
let packet_data;
|
||||
let len;
|
||||
if let Some(p) = packet {
|
||||
packet_data = &p.packet.payload[..];
|
||||
len = p.samples;
|
||||
self.whispering = p.packet.whisper;
|
||||
} else {
|
||||
// An empty slice signals packet loss to the decoder
|
||||
packet_data = &[];
|
||||
len = self.last_packet_samples;
|
||||
}
|
||||
self.packet_loss_num += 1;
|
||||
|
||||
let orig_buffer_len = self.decoded_buffer.len();
|
||||
self.decoded_buffer.resize(orig_buffer_len + len * CHANNEL_NUM, 0.0);
|
||||
let len = self
|
||||
.decoder
|
||||
.decode_float(packet_data, &mut self.decoded_buffer[orig_buffer_len..], fec)
|
||||
.map_err(|e| Error::Decode {
|
||||
error: e,
|
||||
packet: packet.map(|p| p.packet.payload.clone()),
|
||||
})?;
|
||||
self.last_packet_samples = len;
|
||||
self.decoded_buffer.truncate(orig_buffer_len + len * CHANNEL_NUM);
|
||||
|
||||
// Update packet_loss_num
|
||||
if packet.is_some() && !fec {
|
||||
self.packet_loss_num = 0;
|
||||
}
|
||||
|
||||
// Update last_buffer_size
|
||||
let mut count = self.packet_buffer_samples;
|
||||
if let Some(last) = self.packet_buffer.back() {
|
||||
// Lost packets
|
||||
trace!(
|
||||
last.id,
|
||||
next_id = self.next_id,
|
||||
first_id = self.packet_buffer.front().unwrap().id,
|
||||
buffer_len = self.packet_buffer.len(),
|
||||
"Ids"
|
||||
);
|
||||
count += (usize::from(last.id.wrapping_sub(self.next_id)) + 1
|
||||
- self.packet_buffer.len())
|
||||
* self.last_packet_samples;
|
||||
}
|
||||
self.add_buffer_size(count);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decode data and return the requested length of buffered data.
|
||||
///
|
||||
/// Returns `true` in the second return value when the stream ended,
|
||||
/// `false` when it continues normally.
|
||||
pub fn get_next_data(&mut self, len: usize) -> Result<(&[f32], bool)> {
|
||||
let _span = self.span.clone().entered();
|
||||
if self.buffering_samples > 0 {
|
||||
if self.buffered_for_samples >= MAX_BUFFER_TIME {
|
||||
self.buffering_samples = 0;
|
||||
self.buffered_for_samples = 0;
|
||||
trace!(
|
||||
buffered_for_samples = self.buffered_for_samples,
|
||||
buffering_samples = self.buffering_samples,
|
||||
"Buffered for too long"
|
||||
);
|
||||
} else {
|
||||
self.buffered_for_samples += len;
|
||||
trace!(
|
||||
buffered_for_samples = self.buffered_for_samples,
|
||||
buffering_samples = self.buffering_samples,
|
||||
"Buffering"
|
||||
);
|
||||
return Ok((&[], false));
|
||||
}
|
||||
}
|
||||
// Need to refill buffer
|
||||
self.decoded_buffer.drain(..self.decoded_pos);
|
||||
|
||||
while self.decoded_buffer.len() < len {
|
||||
trace!(decoded_buffer = self.decoded_buffer.len(), len, "get_next_data");
|
||||
|
||||
// Decode a packet
|
||||
if let Some(packet) = self.packet_buffer.pop_front() {
|
||||
if packet.packet.is_end() {
|
||||
// End of stream
|
||||
return Ok((&self.decoded_buffer, true));
|
||||
}
|
||||
|
||||
self.packet_buffer_samples -= packet.samples;
|
||||
let cur_id = self.next_id;
|
||||
self.next_id = self.next_id.wrapping_add(1);
|
||||
if packet.id != cur_id {
|
||||
debug_assert!(
|
||||
packet.id.wrapping_sub(cur_id) < MAX_BUFFER_PACKETS as u16,
|
||||
"Invalid packet queue state: {} < {}",
|
||||
packet.id,
|
||||
cur_id
|
||||
);
|
||||
// Packet loss
|
||||
debug!(need = cur_id, have = packet.id, "Audio packet loss");
|
||||
if packet.id == self.next_id {
|
||||
// Can use forward-error-correction
|
||||
self.decode_packet(Some(&packet), true)?;
|
||||
} else {
|
||||
self.decode_packet(None, false)?;
|
||||
}
|
||||
self.packet_buffer_samples += packet.samples;
|
||||
self.packet_buffer.push_front(packet);
|
||||
} else {
|
||||
self.decode_packet(Some(&packet), false)?;
|
||||
}
|
||||
} else {
|
||||
debug!("No packets in queue");
|
||||
// Packet loss or end of stream
|
||||
self.decode_packet(None, false)?;
|
||||
}
|
||||
|
||||
if self.last_packet_samples == 0 {
|
||||
break;
|
||||
}
|
||||
|
||||
// Check if we should speed-up playback
|
||||
let min = self.last_buffer_size_min.get_min();
|
||||
let dev = self.get_deviation();
|
||||
if min > (MAX_BUFFER_SIZE / USUAL_FRAME_SIZE) as u8 {
|
||||
debug!(min, "Truncating buffer");
|
||||
// Throw out all but min samples
|
||||
let mut keep_samples = 0;
|
||||
let keep = self
|
||||
.packet_buffer
|
||||
.iter()
|
||||
.rev()
|
||||
.take_while(|p| {
|
||||
keep_samples += p.samples;
|
||||
keep_samples < usize::from(min) + USUAL_FRAME_SIZE
|
||||
})
|
||||
.count();
|
||||
let len = self.packet_buffer.len() - keep;
|
||||
self.packet_buffer.drain(..len);
|
||||
self.packet_buffer_samples = self.packet_buffer.iter().map(|p| p.samples).sum();
|
||||
if let Some(p) = self.packet_buffer.front() {
|
||||
self.next_id = p.id;
|
||||
}
|
||||
} else if min > dev {
|
||||
// Speed-up
|
||||
debug!(
|
||||
min,
|
||||
cur_packet_count = self.packet_buffer.len(),
|
||||
last_packet_samples = self.last_packet_samples,
|
||||
dev,
|
||||
"Speed-up buffer"
|
||||
);
|
||||
let start = self.decoded_buffer.len() - self.last_packet_samples * CHANNEL_NUM;
|
||||
for i in 0..(self.last_packet_samples / SPEED_CHANGE_STEPS) {
|
||||
let i = start + i * (SPEED_CHANGE_STEPS - 1) * CHANNEL_NUM;
|
||||
self.decoded_buffer.drain(i..(i + CHANNEL_NUM));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.decoded_pos = len;
|
||||
Ok((&self.decoded_buffer[..len], false))
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioHandler {
|
||||
pub fn new() -> Self {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
/// Delete all queues
|
||||
pub fn reset(&mut self) {
|
||||
self.queues.clear();
|
||||
}
|
||||
|
||||
pub fn get_queues(&self) -> &HashMap<TalkerId, AudioQueue> {
|
||||
&self.queues
|
||||
}
|
||||
pub fn get_mut_queues(&mut self) -> &mut HashMap<TalkerId, AudioQueue> {
|
||||
&mut self.queues
|
||||
}
|
||||
|
||||
/// `buf` is not cleared before filling it.
|
||||
///
|
||||
/// Returns the clients that are not talking anymore.
|
||||
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<TalkerId> {
|
||||
self.fill_buffer_with_proc(buf, |_, _| {})
|
||||
}
|
||||
|
||||
/// `buf` is not cleared before filling it.
|
||||
///
|
||||
/// Same as [`Self::fill_buffer`] but before merging a queue into the output buffer, a preprocessor
|
||||
/// function is called. The queue volume is applied after calling the preprocessor.
|
||||
///
|
||||
/// Returns the clients that are not talking anymore.
|
||||
pub fn fill_buffer_with_proc<F: FnMut(&TalkerId, &[f32])>(
|
||||
&mut self,
|
||||
buf: &mut [f32],
|
||||
mut handle: F,
|
||||
) -> Vec<TalkerId> {
|
||||
trace!(len = buf.len(), "Filling audio buffer");
|
||||
let mut to_remove = Vec::new();
|
||||
for (id, queue) in self.queues.iter_mut() {
|
||||
if queue.packet_loss_num >= MAX_PACKET_LOSSES {
|
||||
debug!(packet_loss_num = queue.packet_loss_num, "Removing talker");
|
||||
to_remove.push(*id);
|
||||
continue;
|
||||
}
|
||||
|
||||
let vol = queue.volume;
|
||||
match queue.get_next_data(buf.len()) {
|
||||
Err(error) => {
|
||||
warn!(%error, "Failed to decode audio packet");
|
||||
}
|
||||
Ok((r, is_end)) => {
|
||||
handle(id, r);
|
||||
for i in 0..r.len() {
|
||||
buf[i] += r[i] * vol;
|
||||
}
|
||||
if is_end {
|
||||
to_remove.push(*id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for id in &to_remove {
|
||||
self.queues.remove(id);
|
||||
}
|
||||
to_remove
|
||||
}
|
||||
|
||||
/// Add a packet to the queue of its talker.
|
||||
///
|
||||
/// If a new talker started talking, returns its id.
|
||||
pub fn handle_packet(&mut self, packet: VoicePacket) -> Result<Option<TalkerId>> {
|
||||
let id = packet.talker;
|
||||
let empty = packet.is_end();
|
||||
|
||||
if let Some(queue) = self.queues.get_mut(&id) {
|
||||
queue.add_packet(packet)?;
|
||||
Ok(None)
|
||||
} else {
|
||||
if empty {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let _span = info_span!("audio queue", client = ?id);
|
||||
trace!("Adding talker");
|
||||
let mut queue = AudioQueue::new(packet)?;
|
||||
if !self.queues.is_empty() {
|
||||
// Update avg_buffer_samples
|
||||
let total: usize = self
|
||||
.queues
|
||||
.values()
|
||||
.map(|q| usize::from(q.last_buffer_size_min.get_min()))
|
||||
.sum();
|
||||
self.avg_buffer_samples = USUAL_FRAME_SIZE + total / self.queues.len();
|
||||
}
|
||||
queue.buffering_samples = self.avg_buffer_samples;
|
||||
self.queues.insert(id, queue);
|
||||
Ok(Some(id))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use opus2::Encoder;
|
||||
|
||||
use super::*;
|
||||
use crate::packet::VoiceCodec;
|
||||
|
||||
type TestResult = std::result::Result<(), Box<dyn std::error::Error>>;
|
||||
|
||||
const ID: TalkerId = TalkerId(0);
|
||||
|
||||
fn packet(seq: u16, payload: &[u8]) -> VoicePacket {
|
||||
VoicePacket {
|
||||
talker: ID,
|
||||
seq,
|
||||
codec: VoiceCodec::Music,
|
||||
whisper: false,
|
||||
payload: payload.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
enum SimulateAction {
|
||||
CreateEncoder,
|
||||
/// Create packet with id.
|
||||
///
|
||||
/// The `bool` is `false` if packet handling should fail.
|
||||
ReceivePacket(u16, bool),
|
||||
ReceiveRaw(u16, Vec<u8>),
|
||||
/// Fetch audio of this sample count and expect a certain packet id.
|
||||
FillBuffer(usize, Option<u16>),
|
||||
/// Custom check
|
||||
Check(Box<dyn FnOnce(&AudioHandler)>),
|
||||
}
|
||||
|
||||
fn simulate(actions: Vec<SimulateAction>) -> TestResult {
|
||||
let mut encoder = None;
|
||||
let mut opus_output = [0; 1275]; // Max size for an opus packet
|
||||
let mut handler = AudioHandler::new();
|
||||
|
||||
for a in actions {
|
||||
println!("\nCurrent state");
|
||||
for q in &handler.queues {
|
||||
print!("Queue {:?}:", q.0);
|
||||
for p in &q.1.packet_buffer {
|
||||
print!(" {:?},", p);
|
||||
}
|
||||
println!();
|
||||
}
|
||||
|
||||
match a {
|
||||
SimulateAction::CreateEncoder => {
|
||||
encoder = Some(Encoder::new(
|
||||
48_000,
|
||||
opus2::Channels::Mono,
|
||||
opus2::Application::Voip,
|
||||
)?);
|
||||
}
|
||||
SimulateAction::ReceivePacket(i, success) => {
|
||||
let e = encoder.as_mut().unwrap();
|
||||
let data = vec![i as f32; USUAL_FRAME_SIZE];
|
||||
let len = e.encode_float(&data, &mut opus_output[..])?;
|
||||
if handler.handle_packet(packet(i, &opus_output[..len])).is_ok() != success {
|
||||
return Err(format!(
|
||||
"handle_packet returned {:?} but expected {:?}",
|
||||
!success, success
|
||||
)
|
||||
.into());
|
||||
}
|
||||
}
|
||||
SimulateAction::ReceiveRaw(i, data) => {
|
||||
let _ = handler.handle_packet(packet(i, &data));
|
||||
}
|
||||
SimulateAction::FillBuffer(size, expect) => {
|
||||
let mut buf = vec![0.0; size * 2]; // Stereo
|
||||
let cur_packet_id =
|
||||
handler.queues.get(&ID).and_then(|q| q.packet_buffer.front()).map(|p| p.id);
|
||||
handler.fill_buffer(&mut buf);
|
||||
let next_packet_id =
|
||||
handler.queues.get(&ID).and_then(|q| q.packet_buffer.front()).map(|p| p.id);
|
||||
|
||||
if expect.is_some() {
|
||||
assert_eq!(expect, cur_packet_id);
|
||||
assert_ne!(cur_packet_id, next_packet_id);
|
||||
}
|
||||
}
|
||||
SimulateAction::Check(f) => {
|
||||
f(&handler);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sliding_window_minimum() {
|
||||
let data = &[
|
||||
(5, 5),
|
||||
(6, 5),
|
||||
(3, 3),
|
||||
(4, 3),
|
||||
(6, 3),
|
||||
(5, 3),
|
||||
(6, 3),
|
||||
(6, 4),
|
||||
(6, 5),
|
||||
(6, 5),
|
||||
(6, 6),
|
||||
(7, 6),
|
||||
(5, 5),
|
||||
];
|
||||
let mut window = SlidingWindowMinimum::new(5);
|
||||
assert_eq!(window.get_min(), 0);
|
||||
for (i, (val, min)) in data.iter().enumerate() {
|
||||
println!("{:?}", window);
|
||||
window.push(*val);
|
||||
assert_eq!(window.get_min(), *min, "Failed in iteration {} ({:?})", i, window);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sliding_window_minimum_full() {
|
||||
let mut window = SlidingWindowMinimum::new(255);
|
||||
window.push(1);
|
||||
assert_eq!(window.get_min(), 1);
|
||||
for _ in 0..254 {
|
||||
window.push(2);
|
||||
}
|
||||
assert_eq!(window.get_min(), 1);
|
||||
window.push(2);
|
||||
assert_eq!(window.get_min(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packets_wrapping() {
|
||||
let mut handler = AudioHandler::new();
|
||||
let mut buf = vec![0.0; 48_000 / 100 * 2];
|
||||
|
||||
for i in 0..100 {
|
||||
let seq = 65_500u16.wrapping_add(i);
|
||||
handler.handle_packet(packet(seq, &[0, 0, 0, 0, 0, 0, 0])).unwrap();
|
||||
|
||||
if i > 5 {
|
||||
handler.fill_buffer(&mut buf);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Short and malformed packets of any content are errors, never panics.
|
||||
#[test]
|
||||
fn short_packet_fuzz() {
|
||||
let mut handler = AudioHandler::new();
|
||||
let mut buf = vec![0.0; 48_000 / 100 * 2];
|
||||
let mut state = 0x2545_f491_4f6c_dd1du64;
|
||||
let mut next = move || {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
state
|
||||
};
|
||||
|
||||
for _ in 0..3_000 {
|
||||
// Payloads of 0..=100 bytes: empty, a lone TOC byte, and frames of any shape.
|
||||
let len = (next() % 101) as usize;
|
||||
let payload: Vec<u8> = (0..len).map(|_| next() as u8).collect();
|
||||
let _ = handler.handle_packet(packet(30, &payload));
|
||||
|
||||
handler.fill_buffer(&mut buf);
|
||||
handler.fill_buffer(&mut buf);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packets_wrapping2() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for i in 0..100 {
|
||||
let i = 65_500u16.wrapping_add(i);
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
|
||||
}
|
||||
for _ in 0..4 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn silence() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for _ in 0..100 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reversed() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for i in 0..5 {
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
|
||||
}
|
||||
a.push(SimulateAction::ReceivePacket(4, false));
|
||||
a.push(SimulateAction::ReceivePacket(3, false));
|
||||
for _ in 0..4 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
a.push(SimulateAction::ReceivePacket(0, true));
|
||||
a.push(SimulateAction::ReceivePacket(0, false));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(0)));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn big_whole() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for i in 27120..27124 {
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
|
||||
}
|
||||
a.push(SimulateAction::ReceiveRaw(27124, vec![2]));
|
||||
for _ in 0..10 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
for i in 27339..27349 {
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
for _ in 0..4 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_packet() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
for i in 0..10 {
|
||||
a.push(SimulateAction::ReceivePacket(i, true));
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
|
||||
}
|
||||
a.push(SimulateAction::ReceiveRaw(10, vec![]));
|
||||
for _ in 0..4 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packet_loss() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
a.push(SimulateAction::ReceivePacket(50, true));
|
||||
a.push(SimulateAction::ReceivePacket(53, true));
|
||||
for _ in 0..8 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packet_wrapping_loss() -> TestResult {
|
||||
let mut a = vec![SimulateAction::CreateEncoder];
|
||||
a.push(SimulateAction::ReceivePacket(65534, true));
|
||||
a.push(SimulateAction::ReceivePacket(0, true));
|
||||
for _ in 0..7 {
|
||||
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||
}
|
||||
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
|
||||
simulate(a)
|
||||
}
|
||||
|
||||
/// The talker is the key of the queues, and a new one is reported once.
|
||||
#[test]
|
||||
fn talkers_have_their_own_queues() -> TestResult {
|
||||
let mut encoder = Encoder::new(48_000, opus2::Channels::Mono, opus2::Application::Voip)?;
|
||||
let mut out = [0; 1275];
|
||||
let len = encoder.encode_float(&vec![0.1; USUAL_FRAME_SIZE], &mut out)?;
|
||||
let from = |talker: u16, seq: u16| VoicePacket {
|
||||
talker: TalkerId(talker),
|
||||
seq,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: out[..len].to_vec(),
|
||||
};
|
||||
let mut handler = AudioHandler::new();
|
||||
assert_eq!(handler.handle_packet(from(7, 100))?, Some(TalkerId(7)));
|
||||
assert_eq!(handler.handle_packet(from(7, 101))?, None);
|
||||
assert_eq!(handler.handle_packet(from(9, 5))?, Some(TalkerId(9)));
|
||||
let mut talkers: Vec<_> = handler.get_queues().keys().map(|t| t.0).collect();
|
||||
talkers.sort_unstable();
|
||||
assert_eq!(talkers, [7, 9]);
|
||||
// A talker that only says goodbye never gets a queue.
|
||||
let end = VoicePacket { payload: vec![], ..from(11, 0) };
|
||||
assert_eq!(handler.handle_packet(end)?, None);
|
||||
assert_eq!(handler.get_queues().len(), 2);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A queue knows whether the last packet it played was a whisper.
|
||||
#[test]
|
||||
fn whisper_flag_follows_the_packets() -> TestResult {
|
||||
let mut encoder = Encoder::new(48_000, opus2::Channels::Mono, opus2::Application::Voip)?;
|
||||
let mut out = [0; 1275];
|
||||
let len = encoder.encode_float(&vec![0.1; USUAL_FRAME_SIZE], &mut out)?;
|
||||
let packet = |seq: u16, whisper: bool| VoicePacket {
|
||||
talker: ID,
|
||||
seq,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper,
|
||||
payload: out[..len].to_vec(),
|
||||
};
|
||||
let mut handler = AudioHandler::new();
|
||||
handler.handle_packet(packet(0, true))?;
|
||||
assert!(handler.get_queues()[&ID].is_whispering());
|
||||
handler.handle_packet(packet(1, false))?;
|
||||
// One packet is played per call.
|
||||
let mut buf = [0.0; USUAL_FRAME_SIZE * 2];
|
||||
handler.fill_buffer(&mut buf);
|
||||
handler.fill_buffer(&mut buf);
|
||||
assert!(!handler.get_queues()[&ID].is_whispering());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,17 @@
|
||||
//! Voice pipeline building blocks.
|
||||
//!
|
||||
//! - [`pcm`]: sample-rate constants, tone generation and detection helpers
|
||||
//! - [`encode`]: Opus encoding of 20 ms frames into TeamSpeak voice packets
|
||||
//! - [`packet`]: the voice packet types the pipeline takes and produces
|
||||
//! ([`VoicePacket`], [`EncodedVoice`]), independent of the transport
|
||||
//! - [`encode`]: Opus encoding of 20 ms frames into [`EncodedVoice`]
|
||||
//! - [`framer`]: slice an arbitrary sample stream into codec frames
|
||||
//! - [`resample`]: sample-rate conversion to the 48 kHz the codec uses
|
||||
//! - [`wav`]: WAV file input/output
|
||||
//! - [`process`]: echo cancellation, noise suppression and gain control
|
||||
//! - [`vad`]: voice activity detection
|
||||
//! - [`mixer`]: per-client jitter buffer, decoder, volume and mixing (on the
|
||||
//! vendored `tsclientlib::audio::AudioHandler`)
|
||||
//! - [`jitter`]: the per-talker jitter buffer and Opus decoder
|
||||
//! - [`mixer`]: per-talker volume, mute and priority dimming over the jitter
|
||||
//! buffer, mixing to stereo
|
||||
//! - [`settings`]: all user audio settings in one serde struct
|
||||
//! - [`tap`]: the processed microphone for other consumers (the stream
|
||||
//! mixer), free while nobody listens
|
||||
@@ -17,7 +20,9 @@
|
||||
|
||||
pub mod encode;
|
||||
pub mod framer;
|
||||
pub mod jitter;
|
||||
pub mod mixer;
|
||||
pub mod packet;
|
||||
pub mod pcm;
|
||||
pub mod process;
|
||||
pub mod resample;
|
||||
@@ -29,12 +34,13 @@ pub mod wav;
|
||||
#[cfg(feature = "device")]
|
||||
pub mod device;
|
||||
|
||||
pub use encode::{VoiceCodec, VoiceEncoder};
|
||||
pub use encode::VoiceEncoder;
|
||||
pub use framer::Framer;
|
||||
pub use jitter::AudioHandler;
|
||||
pub use mixer::Mixer;
|
||||
pub use packet::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket};
|
||||
pub use process::{ProcessingSettings, Processor};
|
||||
pub use settings::AudioSettings;
|
||||
pub use tsclientlib::audio::AudioHandler;
|
||||
pub use vad::{Vad, VadSettings};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! Incoming voice: per-client jitter buffer, decoder and mixer, with a
|
||||
//! volume and mute per client.
|
||||
//! Incoming voice: per-talker jitter buffer, decoder and mixer, with a
|
||||
//! volume and mute per talker, and everyone else dimmed while a priority
|
||||
//! speaker talks.
|
||||
//!
|
||||
//! The jitter buffer is the vendored `tsclientlib::audio::AudioHandler`. Per
|
||||
//! sender it keeps a queue of Opus packets and adapts its length:
|
||||
//! The jitter buffer is [`AudioHandler`]. Per sender it keeps a queue of Opus
|
||||
//! packets and adapts its length:
|
||||
//!
|
||||
//! - a new talker starts after a pre-buffer derived from the queue lengths of
|
||||
//! the other talkers (none for the first one);
|
||||
@@ -20,20 +21,46 @@
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use tsclientlib::ClientId;
|
||||
use tsclientlib::audio::{AudioHandler, Error as QueueError};
|
||||
use tsproto_packets::packets::InAudioBuf;
|
||||
use crate::jitter::{AudioHandler, Error as QueueError};
|
||||
use crate::packet::{TalkerId, VoicePacket};
|
||||
use crate::pcm::FRAME_SAMPLES;
|
||||
|
||||
/// Loudest per-client volume: +12 dB.
|
||||
/// Loudest per-talker volume: +12 dB.
|
||||
pub const MAX_CLIENT_VOLUME: f32 = 4.0;
|
||||
/// Most a priority speaker dims the others (dB).
|
||||
const MAX_DIMM_DB: f32 = -60.0;
|
||||
/// The dimming for a priority speaker fades in and out over this many
|
||||
/// samples (5 frames, 100 ms) instead of jumping.
|
||||
const DIMM_RAMP_SAMPLES: usize = 5 * FRAME_SAMPLES;
|
||||
|
||||
/// Jitter buffer, decoder and mixer for incoming voice, keyed by sender.
|
||||
/// Jitter buffer, decoder and mixer for incoming voice, keyed by talker.
|
||||
/// Output is interleaved stereo at 48 kHz.
|
||||
#[derive(Default)]
|
||||
pub struct Mixer {
|
||||
handler: AudioHandler<ClientId>,
|
||||
volumes: HashMap<ClientId, f32>,
|
||||
muted: HashSet<ClientId>,
|
||||
handler: AudioHandler,
|
||||
volumes: HashMap<TalkerId, f32>,
|
||||
muted: HashSet<TalkerId>,
|
||||
/// While one of them talks, everyone else is dimmed.
|
||||
priority: HashSet<TalkerId>,
|
||||
/// Linear gain of the others while a priority speaker talks (1: none).
|
||||
dimm: f32,
|
||||
/// How far the dimming has faded in (0..=1).
|
||||
fade: f32,
|
||||
/// The others' mix while the dimming fades (reused).
|
||||
others: Vec<f32>,
|
||||
}
|
||||
|
||||
impl Default for Mixer {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
handler: AudioHandler::new(),
|
||||
volumes: HashMap::new(),
|
||||
muted: HashSet::new(),
|
||||
priority: HashSet::new(),
|
||||
dimm: 1.0,
|
||||
fade: 0.0,
|
||||
others: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Mixer {
|
||||
@@ -41,35 +68,76 @@ impl Mixer {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Queue a voice packet from `id`. Returns `Some(id)` when this client
|
||||
/// just started talking. Late, duplicate and malformed packets are
|
||||
/// errors; on UDP they are expected and can be ignored.
|
||||
pub fn handle_packet(
|
||||
&mut self,
|
||||
id: ClientId,
|
||||
packet: InAudioBuf,
|
||||
) -> Result<Option<ClientId>, QueueError> {
|
||||
self.handler.handle_packet(id, packet)
|
||||
/// Queue a voice packet for its talker. Returns `Some(talker)` when this
|
||||
/// talker just started talking. Late, duplicate and malformed packets are
|
||||
/// errors; on datagrams they are expected and can be ignored.
|
||||
pub fn handle_packet(&mut self, packet: VoicePacket) -> Result<Option<TalkerId>, QueueError> {
|
||||
self.handler.handle_packet(packet)
|
||||
}
|
||||
|
||||
/// Add the next `buf.len() / 2` stereo frames of all talkers to `buf`
|
||||
/// (not cleared first), each scaled by its volume. Returns the clients
|
||||
/// that stopped talking.
|
||||
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<ClientId> {
|
||||
for (id, queue) in self.handler.get_mut_queues() {
|
||||
queue.volume = if self.muted.contains(id) {
|
||||
/// (not cleared first), each scaled by its volume, and dimmed while a
|
||||
/// priority speaker talks. Returns the talkers that stopped talking.
|
||||
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<TalkerId> {
|
||||
let queues = self.handler.get_mut_queues();
|
||||
// A priority speaker with a queue (talking or buffering) dims all
|
||||
// other queues, streams too, unless we muted it.
|
||||
let dim = queues.keys().any(|id| self.priority.contains(id) && !self.muted.contains(id));
|
||||
let frames = buf.len() / 2;
|
||||
let step = frames as f32 / DIMM_RAMP_SAMPLES as f32;
|
||||
let from = self.fade;
|
||||
self.fade = if dim { (from + step).min(1.0) } else { (from - step).max(0.0) };
|
||||
let to = self.fade;
|
||||
let dimm = self.dimm;
|
||||
let gain = |fade: f32| 1.0 + (dimm - 1.0) * fade;
|
||||
let fading = from != to;
|
||||
// While fading, the others are mixed into a buffer of their own and
|
||||
// ramped sample by sample; the priority speakers go straight to `buf`.
|
||||
let mut priority = Vec::new();
|
||||
for (id, queue) in queues {
|
||||
// Muted talkers are still decoded so their queues stay in sync.
|
||||
let volume = if self.muted.contains(id) {
|
||||
0.0
|
||||
} else {
|
||||
self.volumes.get(id).copied().unwrap_or(1.0)
|
||||
};
|
||||
queue.volume = if self.priority.contains(id) {
|
||||
if fading {
|
||||
priority.push((*id, volume));
|
||||
0.0
|
||||
} else {
|
||||
volume
|
||||
}
|
||||
} else if fading {
|
||||
volume
|
||||
} else {
|
||||
volume * gain(to)
|
||||
};
|
||||
}
|
||||
// Muted talkers are still decoded so their queues stay in sync.
|
||||
self.handler.fill_buffer(buf)
|
||||
if !fading {
|
||||
return self.handler.fill_buffer(buf);
|
||||
}
|
||||
self.others.clear();
|
||||
self.others.resize(buf.len(), 0.0);
|
||||
let stopped = self.handler.fill_buffer_with_proc(&mut self.others, |id, samples| {
|
||||
if let Some(&(_, volume)) = priority.iter().find(|(p, _)| p == id) {
|
||||
for (out, s) in buf.iter_mut().zip(samples) {
|
||||
*out += s * volume;
|
||||
}
|
||||
}
|
||||
});
|
||||
// From the last frame's gain to this one's.
|
||||
for (i, (out, s)) in buf.chunks_exact_mut(2).zip(self.others.chunks_exact(2)).enumerate() {
|
||||
let g = gain(from + (to - from) * (i + 1) as f32 / frames as f32);
|
||||
out[0] += s[0] * g;
|
||||
out[1] += s[1] * g;
|
||||
}
|
||||
stopped
|
||||
}
|
||||
|
||||
/// Linear gain for one client, clamped to `0..=`[`MAX_CLIENT_VOLUME`].
|
||||
/// Kept when the client stops and starts talking again.
|
||||
pub fn set_volume(&mut self, id: ClientId, volume: f32) {
|
||||
/// Linear gain for one talker, clamped to `0..=`[`MAX_CLIENT_VOLUME`].
|
||||
/// Kept when the talker stops and starts talking again.
|
||||
pub fn set_volume(&mut self, id: TalkerId, volume: f32) {
|
||||
let volume = if volume.is_finite() { volume.clamp(0.0, MAX_CLIENT_VOLUME) } else { 1.0 };
|
||||
if volume == 1.0 {
|
||||
self.volumes.remove(&id);
|
||||
@@ -79,15 +147,15 @@ impl Mixer {
|
||||
}
|
||||
|
||||
/// Like [`set_volume`](Self::set_volume), in dB (0 dB = unchanged).
|
||||
pub fn set_volume_db(&mut self, id: ClientId, db: f32) {
|
||||
pub fn set_volume_db(&mut self, id: TalkerId, db: f32) {
|
||||
self.set_volume(id, 10f32.powf(db / 20.0));
|
||||
}
|
||||
|
||||
pub fn volume(&self, id: ClientId) -> f32 {
|
||||
pub fn volume(&self, id: TalkerId) -> f32 {
|
||||
self.volumes.get(&id).copied().unwrap_or(1.0)
|
||||
}
|
||||
|
||||
pub fn set_muted(&mut self, id: ClientId, muted: bool) {
|
||||
pub fn set_muted(&mut self, id: TalkerId, muted: bool) {
|
||||
if muted {
|
||||
self.muted.insert(id);
|
||||
} else {
|
||||
@@ -95,20 +163,30 @@ impl Mixer {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_muted(&self, id: ClientId) -> bool {
|
||||
pub fn is_muted(&self, id: TalkerId) -> bool {
|
||||
self.muted.contains(&id)
|
||||
}
|
||||
|
||||
/// Forget volume and mute of a client (e.g. it left the server; client
|
||||
/// ids are reused).
|
||||
pub fn forget(&mut self, id: ClientId) {
|
||||
/// The priority speakers, and how much everyone else is dimmed while
|
||||
/// one of them talks: dB, clamped to -60..=0 (NaN: not at all).
|
||||
/// Replaces the previous set; [`forget`](Self::forget) leaves it alone,
|
||||
/// the caller sends a new set when the talkers change.
|
||||
pub fn set_priority(&mut self, talkers: impl IntoIterator<Item = TalkerId>, dimm_db: f32) {
|
||||
self.priority = talkers.into_iter().collect();
|
||||
let db = if dimm_db.is_nan() { 0.0 } else { dimm_db.clamp(MAX_DIMM_DB, 0.0) };
|
||||
self.dimm = 10f32.powf(db / 20.0);
|
||||
}
|
||||
|
||||
/// Forget volume and mute of a talker (e.g. it left the server; ids may
|
||||
/// be reused).
|
||||
pub fn forget(&mut self, id: TalkerId) {
|
||||
self.volumes.remove(&id);
|
||||
self.muted.remove(&id);
|
||||
self.handler.get_mut_queues().remove(&id);
|
||||
}
|
||||
|
||||
/// Clients with a queue, i.e. currently talking or buffering.
|
||||
pub fn talkers(&self) -> impl Iterator<Item = ClientId> + '_ {
|
||||
/// Talkers with a queue, i.e. currently talking or buffering.
|
||||
pub fn talkers(&self) -> impl Iterator<Item = TalkerId> + '_ {
|
||||
self.handler.get_queues().keys().copied()
|
||||
}
|
||||
|
||||
@@ -118,7 +196,7 @@ impl Mixer {
|
||||
}
|
||||
|
||||
/// The underlying jitter buffer.
|
||||
pub fn handler(&self) -> &AudioHandler<ClientId> {
|
||||
pub fn handler(&self) -> &AudioHandler {
|
||||
&self.handler
|
||||
}
|
||||
}
|
||||
@@ -129,29 +207,34 @@ impl std::fmt::Debug for Mixer {
|
||||
.field("talkers", &self.handler.get_queues().len())
|
||||
.field("volumes", &self.volumes)
|
||||
.field("muted", &self.muted)
|
||||
.field("priority", &self.priority)
|
||||
.field("dimm", &self.dimm)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tsproto_packets::packets::{AudioData, CodecType, Direction, OutAudio};
|
||||
|
||||
use super::*;
|
||||
use crate::VoiceEncoder;
|
||||
use crate::encode::VoiceCodec;
|
||||
use crate::packet::VoiceCodec;
|
||||
use crate::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE};
|
||||
|
||||
fn packet(from: u16, id: u16, data: &[u8]) -> InAudioBuf {
|
||||
let packet = OutAudio::new(&AudioData::S2C { id, codec: CodecType::OpusVoice, from, data });
|
||||
InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap()
|
||||
fn packet(from: u16, seq: u16, data: &[u8]) -> VoicePacket {
|
||||
VoicePacket {
|
||||
talker: TalkerId(from),
|
||||
seq,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: data.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Two clients send tones at the same level; after setting volumes the
|
||||
/// mix carries each at its own gain, and a muted one not at all.
|
||||
#[test]
|
||||
fn volume_per_client() {
|
||||
let (a, b) = (ClientId(3), ClientId(4));
|
||||
let (a, b) = (TalkerId(3), TalkerId(4));
|
||||
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut enc_b = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let tone_a = pcm::sine(500.0, 2.0, 0.2);
|
||||
@@ -165,11 +248,11 @@ mod tests {
|
||||
let frames = tone_a.chunks_exact(FRAME_SAMPLES).zip(tone_b.chunks_exact(FRAME_SAMPLES));
|
||||
for (i, (fa, fb)) in frames.enumerate() {
|
||||
let id = i as u16;
|
||||
let started = mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
|
||||
let started = mixer.handle_packet(packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
|
||||
if i == 0 {
|
||||
assert_eq!(started.unwrap(), Some(a));
|
||||
}
|
||||
mixer.handle_packet(b, packet(4, id, enc_b.encode_to_bytes(fb).unwrap())).unwrap();
|
||||
mixer.handle_packet(packet(4, id, enc_b.encode_to_bytes(fb).unwrap())).unwrap();
|
||||
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
|
||||
mixer.fill_buffer(&mut buf);
|
||||
out.extend(pcm::to_mono(&buf, 2));
|
||||
@@ -188,8 +271,8 @@ mod tests {
|
||||
let id = 100 + i;
|
||||
let fa = &tone_a[..FRAME_SAMPLES];
|
||||
let fb = &tone_b[..FRAME_SAMPLES];
|
||||
let _ = mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
|
||||
let _ = mixer.handle_packet(b, packet(4, id, enc_b.encode_to_bytes(fb).unwrap()));
|
||||
let _ = mixer.handle_packet(packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
|
||||
let _ = mixer.handle_packet(packet(4, id, enc_b.encode_to_bytes(fb).unwrap()));
|
||||
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
|
||||
mixer.fill_buffer(&mut buf);
|
||||
out.extend(pcm::to_mono(&buf, 2));
|
||||
@@ -199,10 +282,138 @@ mod tests {
|
||||
assert!(pcm::goertzel_power(tail, 500.0, SAMPLE_RATE) > 1e-4);
|
||||
}
|
||||
|
||||
/// A priority speaker dims the other talker by the server's -18 dB, fading
|
||||
/// in and out, but not itself, and not while we muted it.
|
||||
#[test]
|
||||
fn priority_speaker_dims_others() {
|
||||
let (a, p) = (TalkerId(3), TalkerId(5));
|
||||
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut enc_p = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let tone_a = pcm::sine(500.0, 4.0, 0.2);
|
||||
let tone_p = pcm::sine(1300.0, 4.0, 0.2);
|
||||
let frame = |tone: &[f32], i: u16| {
|
||||
let at = i as usize * FRAME_SAMPLES;
|
||||
tone[at..at + FRAME_SAMPLES].to_vec()
|
||||
};
|
||||
|
||||
let mut mixer = Mixer::new();
|
||||
mixer.set_priority([p], -18.0);
|
||||
let (mut id_a, mut id_p) = (0u16, 0u16);
|
||||
// `frames` frames with a talking and p too if `with_p`; returns the
|
||||
// second half of the mix.
|
||||
let mut play = |mixer: &mut Mixer, frames: u16, with_p: bool| {
|
||||
let mut out = Vec::new();
|
||||
for _ in 0..frames {
|
||||
let fa = frame(&tone_a, id_a);
|
||||
mixer.handle_packet(packet(3, id_a, enc_a.encode_to_bytes(&fa).unwrap())).unwrap();
|
||||
id_a += 1;
|
||||
if with_p {
|
||||
let fp = frame(&tone_p, id_p);
|
||||
let data = enc_p.encode_to_bytes(&fp).unwrap();
|
||||
mixer.handle_packet(packet(5, id_p, data)).unwrap();
|
||||
id_p += 1;
|
||||
}
|
||||
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
|
||||
mixer.fill_buffer(&mut buf);
|
||||
out.extend(pcm::to_mono(&buf, 2));
|
||||
}
|
||||
out.split_off(out.len() / 2)
|
||||
};
|
||||
let power = |out: &[f32], f| pcm::goertzel_power(out, f, SAMPLE_RATE);
|
||||
let db = |level: f32, full: f32| 10.0 * (level / full).log10();
|
||||
|
||||
let alone = play(&mut mixer, 30, false);
|
||||
let full = power(&alone, 500.0);
|
||||
assert!(full > 1e-4);
|
||||
// The dimming fades in over 5 frames: 1/5 of the way after the first.
|
||||
play(&mut mixer, 1, true);
|
||||
assert!((mixer.fade - 0.2).abs() < 1e-6, "fade {}", mixer.fade);
|
||||
let both = play(&mut mixer, 50, true);
|
||||
let dimmed = db(power(&both, 500.0), full);
|
||||
assert!((dimmed + 18.0).abs() < 1.0, "dimmed by {dimmed} dB");
|
||||
let own = db(power(&both, 1300.0), full);
|
||||
assert!(own.abs() < 1.0, "priority speaker at {own} dB");
|
||||
|
||||
// p stops: its queue ends after three lost frames, and a is back.
|
||||
let after = play(&mut mixer, 40, false);
|
||||
assert_eq!(mixer.talkers().collect::<Vec<_>>(), vec![a]);
|
||||
assert_eq!(mixer.fade, 0.0);
|
||||
let back = db(power(&after, 500.0), full);
|
||||
assert!(back.abs() < 1.0, "after the priority speaker: {back} dB");
|
||||
|
||||
// A priority speaker we muted dims nobody.
|
||||
mixer.set_muted(p, true);
|
||||
let muted = play(&mut mixer, 40, true);
|
||||
assert_eq!(mixer.talkers().count(), 2);
|
||||
let level = db(power(&muted, 500.0), full);
|
||||
assert!(level.abs() < 1.0, "muted priority speaker: {level} dB");
|
||||
assert!(power(&muted, 1300.0) < 1e-6);
|
||||
}
|
||||
|
||||
/// The dimming fades in and out sample by sample, not in a step per
|
||||
/// frame: the other talker's level (per period of its tone) never jumps.
|
||||
#[test]
|
||||
fn priority_dimming_ramps_per_sample() {
|
||||
let p = TalkerId(5);
|
||||
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut enc_p = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let tone = pcm::sine(500.0, 2.0, 0.2);
|
||||
let mut mixer = Mixer::new();
|
||||
mixer.set_priority([p], -18.0);
|
||||
// p is not heard (volume 0) but dims, so the mix is a's tone alone.
|
||||
mixer.set_volume(p, 0.0);
|
||||
let mut out = Vec::new();
|
||||
// p talks from frame 30 to 59.
|
||||
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
|
||||
let id = i as u16;
|
||||
mixer.handle_packet(packet(3, id, enc_a.encode_to_bytes(frame).unwrap())).unwrap();
|
||||
if let Some(j) = i.checked_sub(30).filter(|j| *j < 30) {
|
||||
let data = enc_p.encode_to_bytes(frame).unwrap();
|
||||
mixer.handle_packet(packet(5, j as u16, data)).unwrap();
|
||||
}
|
||||
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
|
||||
mixer.fill_buffer(&mut buf);
|
||||
out.extend(pcm::to_mono(&buf, 2));
|
||||
}
|
||||
assert_eq!(mixer.fade, 0.0);
|
||||
// The level per period of the 500 Hz tone (96 samples, 10 a frame).
|
||||
let level: Vec<f32> = out.chunks_exact(96).map(|c| pcm::energy(c).sqrt()).collect();
|
||||
let full = level[200..300].iter().sum::<f32>() / 100.0;
|
||||
let mean = |range: std::ops::Range<usize>| {
|
||||
level[range.clone()].iter().sum::<f32>() / range.len() as f32 / full
|
||||
};
|
||||
let jump = level[200..].windows(2).map(|w| (w[1] - w[0]).abs() / full).fold(0.0, f32::max);
|
||||
assert!(jump < 0.05, "the level jumps by {jump} of full");
|
||||
// Fully dimmed after 5 frames, and back after p's queue ended.
|
||||
let dimmed = mean(350..600);
|
||||
assert!((dimmed - 0.126).abs() < 0.02, "dimmed to {dimmed}");
|
||||
let back = mean(800..1000);
|
||||
assert!((back - 1.0).abs() < 0.05, "back to {back}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn priority_dimm_bounds() {
|
||||
let mut mixer = Mixer::new();
|
||||
assert_eq!(mixer.dimm, 1.0);
|
||||
mixer.set_priority([TalkerId(1)], -18.0);
|
||||
assert!((mixer.dimm - 0.1259).abs() < 1e-3);
|
||||
mixer.set_priority([TalkerId(1)], 6.0);
|
||||
assert_eq!(mixer.dimm, 1.0);
|
||||
mixer.set_priority([TalkerId(1)], f32::NEG_INFINITY);
|
||||
assert!((mixer.dimm - 0.001).abs() < 1e-6);
|
||||
mixer.set_priority([TalkerId(1)], f32::NAN);
|
||||
assert_eq!(mixer.dimm, 1.0);
|
||||
// Forgetting a client keeps the set: the caller replaces it.
|
||||
mixer.forget(TalkerId(1));
|
||||
assert!(mixer.priority.contains(&TalkerId(1)));
|
||||
mixer.set_priority([], -18.0);
|
||||
assert!(mixer.priority.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volume_bounds_and_forget() {
|
||||
let mut mixer = Mixer::new();
|
||||
let id = ClientId(9);
|
||||
let id = TalkerId(9);
|
||||
mixer.set_volume(id, 100.0);
|
||||
assert_eq!(mixer.volume(id), MAX_CLIENT_VOLUME);
|
||||
mixer.set_volume(id, -1.0);
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
//! Voice packets as the audio pipeline sees them, whatever transport carries
|
||||
//! them (the TeamSpeak connection today, a Voelin server later).
|
||||
//!
|
||||
//! The transport adapter turns what it receives into a [`VoicePacket`] and
|
||||
//! what [`VoiceEncoder`](crate::VoiceEncoder) produces ([`EncodedVoice`])
|
||||
//! into its own wire format; nothing in this crate knows either format.
|
||||
|
||||
use crate::pcm::FRAME_SAMPLES;
|
||||
|
||||
/// Who is talking: a sender id, unique among the talkers of one voice
|
||||
/// connection. A transport maps its own client ids onto it (TeamSpeak's
|
||||
/// 16-bit client id is used as is).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct TalkerId(pub u16);
|
||||
|
||||
/// The two Opus flavours voice is sent in.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum VoiceCodec {
|
||||
/// Mono, tuned for speech.
|
||||
Voice,
|
||||
/// Stereo, tuned for music.
|
||||
Music,
|
||||
}
|
||||
|
||||
impl VoiceCodec {
|
||||
pub fn channels(self) -> usize {
|
||||
match self {
|
||||
VoiceCodec::Voice => 1,
|
||||
VoiceCodec::Music => 2,
|
||||
}
|
||||
}
|
||||
|
||||
/// Samples (all channels) in one 20 ms frame.
|
||||
pub fn frame_len(self) -> usize {
|
||||
FRAME_SAMPLES * self.channels()
|
||||
}
|
||||
}
|
||||
|
||||
/// A voice packet received from a talker.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct VoicePacket {
|
||||
pub talker: TalkerId,
|
||||
/// Packet number of this talker, counting up by one per 20 ms frame and
|
||||
/// wrapping at 65536; the jitter buffer orders by it and finds gaps.
|
||||
pub seq: u16,
|
||||
pub codec: VoiceCodec,
|
||||
/// Sent to us as a whisper instead of to the whole channel.
|
||||
pub whisper: bool,
|
||||
/// One Opus packet. An empty one ends the talk (a single byte counts as
|
||||
/// empty too: some servers send one).
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
|
||||
impl VoicePacket {
|
||||
/// Whether this packet only ends the talk and carries no audio.
|
||||
pub fn is_end(&self) -> bool {
|
||||
self.payload.len() <= 1
|
||||
}
|
||||
}
|
||||
|
||||
/// One encoded frame to send. The transport assigns the packet number.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct EncodedVoice {
|
||||
pub codec: VoiceCodec,
|
||||
/// One Opus packet; empty: the transmission ended.
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
|
||||
impl EncodedVoice {
|
||||
/// Whether this only tells listeners the transmission ended.
|
||||
pub fn is_end(&self) -> bool {
|
||||
self.payload.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn codec_frames() {
|
||||
assert_eq!(VoiceCodec::Voice.frame_len(), FRAME_SAMPLES);
|
||||
assert_eq!(VoiceCodec::Music.frame_len(), FRAME_SAMPLES * 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_of_talk() {
|
||||
let voice = |payload: &[u8]| VoicePacket {
|
||||
talker: TalkerId(1),
|
||||
seq: 0,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: payload.to_vec(),
|
||||
};
|
||||
assert!(voice(&[]).is_end());
|
||||
assert!(voice(&[2]).is_end());
|
||||
assert!(!voice(&[2, 3]).is_end());
|
||||
assert!(EncodedVoice { codec: VoiceCodec::Voice, payload: vec![] }.is_end());
|
||||
assert!(!EncodedVoice { codec: VoiceCodec::Voice, payload: vec![0] }.is_end());
|
||||
}
|
||||
}
|
||||
@@ -7,10 +7,8 @@
|
||||
//! loss. Every 30 s it sends a loud marker frame instead of the quiet one;
|
||||
//! the latency is the time from generating a marker to it leaving the mixer.
|
||||
|
||||
use tsclientlib::ClientId;
|
||||
use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio};
|
||||
use voelin_audio::pcm::{FRAME_SAMPLES, SAMPLE_RATE, energy, sine, white_noise};
|
||||
use voelin_audio::{Mixer, VoiceCodec, VoiceEncoder};
|
||||
use voelin_audio::{Mixer, TalkerId, VoiceCodec, VoiceEncoder, VoicePacket};
|
||||
|
||||
/// The receiver pulls 10 ms at a time, like a playback loop.
|
||||
const PULL: usize = SAMPLE_RATE as usize / 100;
|
||||
@@ -38,7 +36,7 @@ fn simulate(ppm: f64, hours: f64) -> Vec<f64> {
|
||||
|
||||
let mut rng = Rng(ppm.to_bits());
|
||||
let mut mixer = Mixer::new();
|
||||
let client = ClientId(5);
|
||||
let talker = TalkerId(5);
|
||||
let total = (hours * 3600.0 * SAMPLE_RATE as f64) as u64;
|
||||
// Sender frame n is made at n * 20 ms of the sender's clock.
|
||||
let frame_time = |n: u64| n as f64 * FRAME_SAMPLES as f64 / (1.0 + ppm * 1e-6);
|
||||
@@ -68,15 +66,15 @@ fn simulate(ppm: f64, hours: f64) -> Vec<f64> {
|
||||
let arrived = in_flight.partition_point(|&(t, _)| t <= now as f64);
|
||||
for (_, n) in in_flight.drain(..arrived) {
|
||||
let data = if n % MARKER_EVERY == MARKER_EVERY / 2 { &marker } else { &quiet };
|
||||
let packet = OutAudio::new(&AudioData::S2C {
|
||||
id: n as u16,
|
||||
codec: CodecType::OpusVoice,
|
||||
from: 5,
|
||||
data,
|
||||
});
|
||||
let packet = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
|
||||
let packet = VoicePacket {
|
||||
talker,
|
||||
seq: n as u16,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: data.clone(),
|
||||
};
|
||||
// Late packets are dropped by the jitter buffer, as on a real network.
|
||||
let _ = mixer.handle_packet(client, packet);
|
||||
let _ = mixer.handle_packet(packet);
|
||||
}
|
||||
|
||||
out.fill(0.0);
|
||||
|
||||
@@ -14,23 +14,33 @@ default = ["audio-device"]
|
||||
audio-device = ["voelin-audio/device"]
|
||||
# The `media` module: capture and video codecs for streams, with whatever
|
||||
# voelin-media backends are enabled (e.g. MediaCodec and a registered capture
|
||||
# source on Android).
|
||||
media = ["dep:voelin-media"]
|
||||
# `media` with voelin-media's desktop backends: libvpx, OpenH264 loaded at
|
||||
# runtime, X11 and PipeWire on Linux. Not for Android (libvpx does not
|
||||
# cross-compile there).
|
||||
# source on Android), and the studio's WHIP output. The crate itself is always
|
||||
# there: the stream types in the API (`EncodedFrame`, `LayerSpec`) are its.
|
||||
media = ["voelin-media/whip"]
|
||||
# `media` with voelin-media's desktop backends: libvpx, dav1d, OpenH264 and
|
||||
# FFmpeg loaded at runtime, X11 and PipeWire on Linux. Not for Android
|
||||
# (libvpx does not cross-compile there).
|
||||
media-desktop = ["media", "voelin-media/default"]
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
base64 = "0.22"
|
||||
# The RTP packets of the session seam (`voelin_proto::link::MediaPacket`).
|
||||
bytes = "1"
|
||||
dirs = "6"
|
||||
futures = "0.3"
|
||||
# Finding a server's gateway in DNS (the voice resolver's version).
|
||||
hickory-resolver = "0.26"
|
||||
md5 = "0.8"
|
||||
# A stalled HTTP/2 connection's error, told apart (the version reqwest's hyper
|
||||
# uses).
|
||||
h2 = "0.4"
|
||||
# Retry-After dates (already in the tree through hyper).
|
||||
httpdate = "1"
|
||||
# Banners on the web; the client the workspace has (voelin-query, voelin-media).
|
||||
reqwest = { version = "0.13.5", default-features = false, features = ["rustls"] }
|
||||
# `system-proxy`: the proxy settings of Windows and macOS; `socks`: SOCKS
|
||||
# proxies (from the desktop's settings or ALL_PROXY).
|
||||
reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "socks", "system-proxy"] }
|
||||
# Reading the official clients' settings.db when importing identities.
|
||||
rusqlite = { version = "0.40.2", features = ["bundled"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
@@ -42,11 +52,17 @@ toml = "1.1.6"
|
||||
tracing = "0.1"
|
||||
voelin-audio = { path = "../voelin-audio", default-features = false }
|
||||
voelin-gateway-proto = { path = "../voelin-gateway-proto", features = ["client"] }
|
||||
voelin-media = { path = "../voelin-media", default-features = false, features = ["str0m", "whip"], optional = true }
|
||||
voelin-model = { path = "../voelin-model" }
|
||||
# `IdentityBlob`, the identity of the API (a TeamSpeak identity as the key store
|
||||
# keeps it, or a Voelin key).
|
||||
voelin-identity = { workspace = true }
|
||||
voelin-media = { path = "../voelin-media", default-features = false }
|
||||
voelin-model = { workspace = true }
|
||||
voelin-observer = { path = "../voelin-observer" }
|
||||
# Paths only (the cache directory).
|
||||
voelin-platform = { path = "../voelin-platform", default-features = false }
|
||||
# The backend-neutral session seam the engine consumes (`voelin_proto::link`)
|
||||
# and the v1 messages it speaks.
|
||||
voelin-proto = { workspace = true }
|
||||
voelin-query = { path = "../voelin-query" }
|
||||
voelin-store = { path = "../voelin-store" }
|
||||
voelin-stream = { path = "../voelin-stream" }
|
||||
@@ -57,11 +73,15 @@ tsproto-packets = { path = "../proto/tsproto-packets" }
|
||||
tsproto-types = { path = "../proto/tsproto-types" }
|
||||
|
||||
[dev-dependencies]
|
||||
# An HTTP/2 connection in a test (already in the tree through h2).
|
||||
http = "1"
|
||||
# Already in the app's graph (reqwest); for one_rustls_crypto_provider.
|
||||
rustls = { version = "0.23", default-features = false }
|
||||
voelin-myts = { path = "../voelin-myts" }
|
||||
# `process`: the browser interop test drives Chromium through Node.js.
|
||||
tokio = { version = "1", features = ["macros", "net", "process", "rt-multi-thread", "test-util"] }
|
||||
# The fakes of the session seam (`FakeHost`, `FakeSession`, the conformance
|
||||
# suite).
|
||||
voelin-proto = { workspace = true, features = ["test-util"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -16,16 +16,18 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::{debug, warn};
|
||||
use tsclientlib::ClientId;
|
||||
use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio, OutPacket};
|
||||
use voelin_audio::pcm::{self, FRAME_SAMPLES};
|
||||
use voelin_audio::settings::TransmitMode;
|
||||
use voelin_audio::tap;
|
||||
use voelin_audio::vad::SILENCE_DB;
|
||||
use voelin_audio::{AudioSettings, Framer, Mixer, Processor, Vad, VoiceCodec, VoiceEncoder};
|
||||
use voelin_audio::{
|
||||
AudioSettings, EncodedVoice, Framer, Mixer, Processor, TalkerId, Vad, VoiceCodec, VoiceEncoder,
|
||||
VoicePacket,
|
||||
};
|
||||
|
||||
pub(crate) enum AudioIn {
|
||||
Packet(InAudioBuf),
|
||||
/// Voice of a talker, from the voice connection.
|
||||
Packet(VoicePacket),
|
||||
Transmit(bool),
|
||||
InputMuted(bool),
|
||||
OutputMuted(bool),
|
||||
@@ -33,15 +35,21 @@ pub(crate) enum AudioIn {
|
||||
Settings(Box<AudioSettings>),
|
||||
/// Playback volume of one client, linear (1 = unchanged, up to 4).
|
||||
ClientVolume {
|
||||
client: ClientId,
|
||||
client: TalkerId,
|
||||
volume: f32,
|
||||
},
|
||||
ClientMuted {
|
||||
client: ClientId,
|
||||
client: TalkerId,
|
||||
muted: bool,
|
||||
},
|
||||
/// The client left; client ids are reused, so forget its volume.
|
||||
ClientLeft(ClientId),
|
||||
ClientLeft(TalkerId),
|
||||
/// The priority speakers: while one talks, everyone else (streams too)
|
||||
/// is dimmed by `dimm_db` (the server's setting, e.g. -18).
|
||||
PrioritySpeakers {
|
||||
clients: Vec<TalkerId>,
|
||||
dimm_db: f32,
|
||||
},
|
||||
/// An Opus frame (48 kHz) of a watched stream; `time` is its RTP time
|
||||
/// on the 48 kHz clock.
|
||||
StreamAudio {
|
||||
@@ -105,10 +113,10 @@ pub(crate) const LEVEL_INTERVAL: Duration = Duration::from_millis(100);
|
||||
/// Samples of one 20 ms Opus frame at 48 kHz: the unit of stream packet ids.
|
||||
const OPUS_FRAME: u64 = 960;
|
||||
|
||||
/// Start the audio thread. Encoded packets go to `outgoing`; problems (e.g.
|
||||
/// Start the audio thread. Encoded voice goes to `outgoing`; problems (e.g.
|
||||
/// no device) and the microphone level are reported through `events`.
|
||||
pub(crate) fn spawn(
|
||||
outgoing: mpsc::UnboundedSender<OutPacket>,
|
||||
outgoing: mpsc::UnboundedSender<EncodedVoice>,
|
||||
events: mpsc::UnboundedSender<AudioEvent>,
|
||||
settings: AudioSettings,
|
||||
) -> AudioHandle {
|
||||
@@ -120,9 +128,9 @@ pub(crate) fn spawn(
|
||||
AudioHandle { tx }
|
||||
}
|
||||
|
||||
/// Audio of a watched stream in the mixer, under a made-up client id.
|
||||
/// Audio of a watched stream in the mixer, under a made-up talker id.
|
||||
struct StreamAudio {
|
||||
client: ClientId,
|
||||
client: TalkerId,
|
||||
/// RTP time and packet id of the last packet.
|
||||
last: Option<(u64, u64)>,
|
||||
}
|
||||
@@ -184,11 +192,7 @@ impl Pipeline {
|
||||
fn handle(&mut self, msg: AudioIn) {
|
||||
match msg {
|
||||
AudioIn::Packet(packet) => {
|
||||
let from = match packet.data().data() {
|
||||
AudioData::S2C { from, .. } | AudioData::S2CWhisper { from, .. } => *from,
|
||||
_ => return,
|
||||
};
|
||||
if let Err(error) = self.mixer.handle_packet(ClientId(from), packet) {
|
||||
if let Err(error) = self.mixer.handle_packet(packet) {
|
||||
debug!(%error, "dropped voice packet");
|
||||
}
|
||||
}
|
||||
@@ -208,6 +212,9 @@ impl Pipeline {
|
||||
AudioIn::ClientVolume { client, volume } => self.mixer.set_volume(client, volume),
|
||||
AudioIn::ClientMuted { client, muted } => self.mixer.set_muted(client, muted),
|
||||
AudioIn::ClientLeft(client) => self.mixer.forget(client),
|
||||
AudioIn::PrioritySpeakers { clients, dimm_db } => {
|
||||
self.mixer.set_priority(clients, dimm_db);
|
||||
}
|
||||
AudioIn::StreamAudio { stream, time, data } => self.stream_packet(stream, time, &data),
|
||||
AudioIn::StreamVolume { stream, volume } => {
|
||||
if let Some(s) = self.streams.get(&stream) {
|
||||
@@ -232,8 +239,8 @@ impl Pipeline {
|
||||
let client = match self.streams.get(&stream) {
|
||||
Some(s) => s.client,
|
||||
None => {
|
||||
let used: Vec<ClientId> = self.streams.values().map(|s| s.client).collect();
|
||||
let Some(client) = (0..=u16::MAX).rev().map(ClientId).find(|c| !used.contains(c))
|
||||
let used: Vec<TalkerId> = self.streams.values().map(|s| s.client).collect();
|
||||
let Some(client) = (0..=u16::MAX).rev().map(TalkerId).find(|c| !used.contains(c))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
@@ -254,19 +261,15 @@ impl Pipeline {
|
||||
}
|
||||
};
|
||||
entry.last = Some((time, id));
|
||||
let packet = OutAudio::new(&AudioData::S2C {
|
||||
id: id as u16,
|
||||
codec: CodecType::OpusMusic,
|
||||
from: client.0,
|
||||
data,
|
||||
});
|
||||
match InAudioBuf::try_new(Direction::S2C, packet.into_vec()) {
|
||||
Ok(packet) => {
|
||||
if let Err(error) = self.mixer.handle_packet(client, packet) {
|
||||
debug!(%error, "dropped stream audio packet");
|
||||
}
|
||||
}
|
||||
Err(error) => debug!(?error, "stream audio packet"),
|
||||
let packet = VoicePacket {
|
||||
talker: client,
|
||||
seq: id as u16,
|
||||
codec: VoiceCodec::Music,
|
||||
whisper: false,
|
||||
payload: data.to_vec(),
|
||||
};
|
||||
if let Err(error) = self.mixer.handle_packet(packet) {
|
||||
debug!(%error, "dropped stream audio packet");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -277,7 +280,7 @@ impl Pipeline {
|
||||
|
||||
/// Microphone audio in (mono, 48 kHz, any length); voice packets out.
|
||||
/// `delay_ms` is the playback-to-capture delay hint for the echo canceller.
|
||||
fn capture(&mut self, samples: &[f32], delay_ms: u32, send: &mut impl FnMut(OutPacket)) {
|
||||
fn capture(&mut self, samples: &[f32], delay_ms: u32, send: &mut impl FnMut(EncodedVoice)) {
|
||||
self.processor.set_delay_ms(delay_ms);
|
||||
self.processed.clear();
|
||||
self.processor.capture(samples, &mut self.processed);
|
||||
@@ -299,7 +302,7 @@ impl Pipeline {
|
||||
}
|
||||
}
|
||||
|
||||
fn transmit(&mut self, frame: Vec<f32>, send: &mut impl FnMut(OutPacket)) {
|
||||
fn transmit(&mut self, frame: Vec<f32>, send: &mut impl FnMut(EncodedVoice)) {
|
||||
// Always analysed, so the detector's state is current when needed.
|
||||
let voice = self.vad.process(&frame);
|
||||
let level = self.vad.level_db().max(SILENCE_DB);
|
||||
@@ -360,7 +363,7 @@ fn sanitize(mut settings: AudioSettings) -> AudioSettings {
|
||||
|
||||
fn run(
|
||||
rx: std_mpsc::Receiver<AudioIn>,
|
||||
outgoing: mpsc::UnboundedSender<OutPacket>,
|
||||
outgoing: mpsc::UnboundedSender<EncodedVoice>,
|
||||
events: mpsc::UnboundedSender<AudioEvent>,
|
||||
settings: AudioSettings,
|
||||
) {
|
||||
@@ -436,11 +439,10 @@ fn run(
|
||||
#[cfg(feature = "audio-device")]
|
||||
mod devices {
|
||||
use tracing::debug;
|
||||
use tsproto_packets::packets::OutPacket;
|
||||
use voelin_audio::AudioSettings;
|
||||
use voelin_audio::device::{Capture, DeviceEvent, Managed, Playback};
|
||||
use voelin_audio::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE};
|
||||
use voelin_audio::resample::Linear;
|
||||
use voelin_audio::{AudioSettings, EncodedVoice};
|
||||
|
||||
use super::{DEVICE_LATENCY_MS, PLAYBACK_CAPACITY_MS, Pipeline};
|
||||
|
||||
@@ -500,7 +502,7 @@ mod devices {
|
||||
pub fn step(
|
||||
&mut self,
|
||||
pipeline: &mut Pipeline,
|
||||
send: &mut impl FnMut(OutPacket),
|
||||
send: &mut impl FnMut(EncodedVoice),
|
||||
error: &impl Fn(String),
|
||||
) -> bool {
|
||||
if let Some(event) = self.playback.poll() {
|
||||
@@ -547,7 +549,7 @@ mod devices {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use voelin_audio::pcm::{SAMPLE_RATE, energy, sine, white_noise};
|
||||
use voelin_audio::pcm::{SAMPLE_RATE, energy, goertzel_power, sine, white_noise};
|
||||
use voelin_audio::{ProcessingSettings, VadSettings};
|
||||
|
||||
use super::*;
|
||||
@@ -566,16 +568,20 @@ mod tests {
|
||||
/// end-of-stream packets).
|
||||
fn capture(p: &mut Pipeline, samples: &[f32]) -> (usize, usize) {
|
||||
let (mut voice, mut end) = (0, 0);
|
||||
p.capture(samples, 0, &mut |packet: OutPacket| {
|
||||
// Header of 3 bytes (id + codec) for C2S audio.
|
||||
if packet.content().len() > 3 { voice += 1 } else { end += 1 }
|
||||
p.capture(samples, 0, &mut |packet: EncodedVoice| {
|
||||
if packet.is_end() { end += 1 } else { voice += 1 }
|
||||
});
|
||||
(voice, end)
|
||||
}
|
||||
|
||||
fn incoming(from: u16, id: u16, data: &[u8]) -> AudioIn {
|
||||
let packet = OutAudio::new(&AudioData::S2C { id, codec: CodecType::OpusVoice, from, data });
|
||||
AudioIn::Packet(InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap())
|
||||
fn incoming(from: u16, seq: u16, data: &[u8]) -> AudioIn {
|
||||
AudioIn::Packet(VoicePacket {
|
||||
talker: TalkerId(from),
|
||||
seq,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper: false,
|
||||
payload: data.to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -658,14 +664,52 @@ mod tests {
|
||||
energy(&out[out.len() / 2..])
|
||||
};
|
||||
let full = play(&mut p, 1);
|
||||
p.handle(AudioIn::ClientVolume { client: ClientId(2), volume: 0.5 });
|
||||
p.handle(AudioIn::ClientVolume { client: TalkerId(2), volume: 0.5 });
|
||||
let half = play(&mut p, 2);
|
||||
let ratio_db = 10.0 * (half / full).log10();
|
||||
assert!((ratio_db + 6.0).abs() < 1.0, "volume 0.5 gave {ratio_db} dB");
|
||||
p.handle(AudioIn::ClientMuted { client: ClientId(3), muted: true });
|
||||
p.handle(AudioIn::ClientMuted { client: TalkerId(3), muted: true });
|
||||
assert!(play(&mut p, 3) < 1e-8);
|
||||
p.handle(AudioIn::ClientLeft(ClientId(3)));
|
||||
assert!(!p.mixer.is_muted(ClientId(3)));
|
||||
p.handle(AudioIn::ClientLeft(TalkerId(3)));
|
||||
assert!(!p.mixer.is_muted(TalkerId(3)));
|
||||
}
|
||||
|
||||
/// While a priority speaker talks, another talker and a watched stream
|
||||
/// are dimmed by the server's setting.
|
||||
#[test]
|
||||
fn priority_speaker() {
|
||||
let mut p = pipeline(TransmitMode::PushToTalk);
|
||||
p.handle(AudioIn::PrioritySpeakers { clients: vec![TalkerId(2)], dimm_db: -12.0 });
|
||||
let mut voice = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut priority = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut music = VoiceEncoder::new(VoiceCodec::Music).unwrap();
|
||||
let tone = sine(700.0, 2.0, 0.3);
|
||||
let stream = pcm::from_mono(&sine(1100.0, 2.0, 0.3), 2);
|
||||
let other = sine(1700.0, 1.0, 0.3);
|
||||
let mut out = Vec::new();
|
||||
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
|
||||
p.handle(incoming(1, i as u16, voice.encode_to_bytes(frame).unwrap()));
|
||||
let frame = &stream[i * FRAME_SAMPLES * 2..(i + 1) * FRAME_SAMPLES * 2];
|
||||
let data: Arc<[u8]> = music.encode_to_bytes(frame).unwrap().into();
|
||||
let time = i as u64 * OPUS_FRAME;
|
||||
p.handle(AudioIn::StreamAudio { stream: "s".into(), time, data });
|
||||
// The priority speaker talks during the second second.
|
||||
if let Some(j) = i.checked_sub(50) {
|
||||
let frame = &other[j * FRAME_SAMPLES..(j + 1) * FRAME_SAMPLES];
|
||||
p.handle(incoming(2, j as u16, priority.encode_to_bytes(frame).unwrap()));
|
||||
}
|
||||
out.extend(p.playback_frame());
|
||||
}
|
||||
// The second half of each second.
|
||||
let half = SAMPLE_RATE as usize / 2;
|
||||
let level = |second: usize, freq: f32| {
|
||||
let from = second * 2 * half + half;
|
||||
goertzel_power(&out[from..from + half], freq, SAMPLE_RATE)
|
||||
};
|
||||
for freq in [700.0, 1100.0] {
|
||||
let ratio_db = 10.0 * (level(1, freq) / level(0, freq)).log10();
|
||||
assert!((ratio_db + 12.0).abs() < 1.0, "{freq} Hz dimmed by {ratio_db} dB");
|
||||
}
|
||||
}
|
||||
|
||||
/// End to end: a remote talker is played, the speakers leak into the
|
||||
|
||||
@@ -1,269 +0,0 @@
|
||||
//! The voice connection's book (tsclientlib) as model types.
|
||||
|
||||
use tsclientlib::{ClientType, MaxClients, data};
|
||||
use voelin_model::{
|
||||
BannerMode, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType, HostMessageMode,
|
||||
Presence, ServerDetails, parse_badges,
|
||||
};
|
||||
|
||||
fn group_info(
|
||||
id: u64,
|
||||
name: &str,
|
||||
icon: tsclientlib::IconId,
|
||||
sort_id: i32,
|
||||
naming_mode: tsclientlib::GroupNamingMode,
|
||||
group_type: tsclientlib::GroupType,
|
||||
) -> GroupInfo {
|
||||
GroupInfo {
|
||||
id,
|
||||
name: name.to_owned(),
|
||||
icon: icon.0,
|
||||
sort_id,
|
||||
naming_mode: match naming_mode {
|
||||
tsclientlib::GroupNamingMode::None => GroupNamingMode::None,
|
||||
tsclientlib::GroupNamingMode::Before => GroupNamingMode::Before,
|
||||
tsclientlib::GroupNamingMode::After => GroupNamingMode::After,
|
||||
},
|
||||
group_type: match group_type {
|
||||
tsclientlib::GroupType::Template => GroupType::Template,
|
||||
tsclientlib::GroupType::Regular => GroupType::Regular,
|
||||
tsclientlib::GroupType::Query => GroupType::Query,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// What the server tells about itself; `uid` as the voice source computed it.
|
||||
fn server_details(server: &data::Server, uid: Option<&str>) -> ServerDetails {
|
||||
ServerDetails {
|
||||
name: server.name.clone(),
|
||||
uid: uid.map(str::to_owned),
|
||||
welcome_message: server.welcome_message.clone(),
|
||||
host_message: server.hostmessage.clone(),
|
||||
host_message_mode: match server.hostmessage_mode {
|
||||
tsclientlib::HostMessageMode::None => HostMessageMode::None,
|
||||
tsclientlib::HostMessageMode::Log => HostMessageMode::Log,
|
||||
tsclientlib::HostMessageMode::Modal => HostMessageMode::Modal,
|
||||
tsclientlib::HostMessageMode::Modalquit => HostMessageMode::ModalQuit,
|
||||
},
|
||||
banner_url: server.hostbanner_url.clone(),
|
||||
banner_gfx_url: server.hostbanner_gfx_url.clone(),
|
||||
banner_gfx_interval_s: server.hostbanner_gfx_interval.whole_seconds().max(0) as u64,
|
||||
banner_mode: match server.hostbanner_mode {
|
||||
tsclientlib::HostBannerMode::NoAdjust => BannerMode::NoAdjust,
|
||||
tsclientlib::HostBannerMode::AdjustIgnoreAspect => BannerMode::IgnoreAspect,
|
||||
tsclientlib::HostBannerMode::AdjustKeepAspect => BannerMode::KeepAspect,
|
||||
},
|
||||
host_button_tooltip: server.hostbutton_tooltip.clone(),
|
||||
host_button_url: server.hostbutton_url.clone(),
|
||||
host_button_gfx_url: server.hostbutton_gfx_url.clone(),
|
||||
icon: server.icon.0,
|
||||
platform: server.platform.clone(),
|
||||
version: server.version.clone(),
|
||||
max_clients: server.max_clients,
|
||||
default_server_group: Some(server.default_server_group.0),
|
||||
default_channel_group: Some(server.default_channel_group.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// The presence visible through a voice connection; `server_uid` as
|
||||
/// the voice source computed it, `talking` the clients talking now.
|
||||
pub(crate) fn presence_from_book(
|
||||
book: &data::Connection,
|
||||
server_uid: Option<&str>,
|
||||
talking: impl Fn(u16) -> bool,
|
||||
) -> Presence {
|
||||
let limit = |m: &Option<MaxClients>| match m {
|
||||
Some(MaxClients::Limited(n)) => Some(*n as i32),
|
||||
_ => None,
|
||||
};
|
||||
Presence {
|
||||
server_name: book.server.name.clone(),
|
||||
server: server_details(&book.server, server_uid),
|
||||
server_groups: book
|
||||
.server_groups
|
||||
.values()
|
||||
.map(|g| {
|
||||
let info =
|
||||
group_info(g.id.0, &g.name, g.icon, g.sort_id, g.naming_mode, g.group_type);
|
||||
(g.id.0, info)
|
||||
})
|
||||
.collect(),
|
||||
channel_groups: book
|
||||
.channel_groups
|
||||
.values()
|
||||
.map(|g| {
|
||||
let info =
|
||||
group_info(g.id.0, &g.name, g.icon, g.sort_id, g.naming_mode, g.group_type);
|
||||
(g.id.0, info)
|
||||
})
|
||||
.collect(),
|
||||
channels: book
|
||||
.channels
|
||||
.values()
|
||||
.map(|c| {
|
||||
(
|
||||
c.id.0,
|
||||
ChannelInfo {
|
||||
id: c.id.0,
|
||||
parent: c.parent.0,
|
||||
order: c.order.0,
|
||||
name: c.name.clone(),
|
||||
topic: c.topic.clone().filter(|t| !t.is_empty()),
|
||||
has_password: c.has_password.unwrap_or(false),
|
||||
max_clients: limit(&c.max_clients),
|
||||
needed_subscribe_power: 0,
|
||||
needed_talk_power: c.needed_talk_power.unwrap_or(0),
|
||||
is_default: c.is_default.unwrap_or(false),
|
||||
icon: c.icon.map_or(0, |i| i.0),
|
||||
banner_gfx_url: c.banner_gfx_url.clone().filter(|u| !u.is_empty()),
|
||||
// A number the book keeps as text.
|
||||
banner_mode: c
|
||||
.banner_mode
|
||||
.as_deref()
|
||||
.map_or(BannerMode::NoAdjust, BannerMode::from_wire),
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
clients: book
|
||||
.clients
|
||||
.values()
|
||||
.map(|c| {
|
||||
let mut server_groups: Vec<u64> = c.server_groups.iter().map(|g| g.0).collect();
|
||||
server_groups.sort_unstable();
|
||||
(
|
||||
c.id.0,
|
||||
ClientInfo {
|
||||
id: c.id.0,
|
||||
uid: c.uid.as_ref().map(|u| u.as_ref().to_string()),
|
||||
nickname: c.name.clone(),
|
||||
channel: c.channel.0,
|
||||
is_query: matches!(c.client_type, ClientType::Query { .. }),
|
||||
away: c.away_message.clone(),
|
||||
input_muted: c.input_muted,
|
||||
output_muted: c.output_muted,
|
||||
talking: Some(talking(c.id.0)),
|
||||
streaming: c.is_streaming,
|
||||
server_groups,
|
||||
country: Some(c.country_code.clone()).filter(|c| !c.is_empty()),
|
||||
avatar: Some(c.avatar_hash.clone()).filter(|h| !h.is_empty()),
|
||||
description: Some(c.description.clone()).filter(|d| !d.is_empty()),
|
||||
talk_power: c.talk_power,
|
||||
talker: c.talk_power_granted,
|
||||
channel_group: Some(c.channel_group.0),
|
||||
badges: parse_badges(&c.badges),
|
||||
icon: c.icon.0,
|
||||
recording: c.is_recording,
|
||||
priority_speaker: c.is_priority_speaker,
|
||||
channel_commander: c.is_channel_commander,
|
||||
database_id: Some(c.database_id.0),
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tsclientlib::InMessage;
|
||||
use tsproto_packets::packets::{Direction, Flags, OutPacket, PacketType};
|
||||
use tsproto_types::crypto::EccKeyPrivP256;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn message(text: &str) -> InMessage {
|
||||
let packet = OutPacket::new_with_dir(Direction::S2C, Flags::empty(), PacketType::Command);
|
||||
InMessage::new(&packet.header(), text.as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
/// Channel banners as a TeamSpeak 6 server (6.0.0-beta13.1) sends them:
|
||||
/// in the channel list, when a channel is created and when it is edited.
|
||||
#[test]
|
||||
fn channel_banners() {
|
||||
let InMessage::InitServer(init) = message(concat!(
|
||||
"initserver virtualserver_name=Test virtualserver_welcomemessage ",
|
||||
"virtualserver_platform=Linux virtualserver_version=6.0.0-beta13.1 ",
|
||||
"virtualserver_maxclients=32 virtualserver_created=0 ",
|
||||
"virtualserver_codec_encryption_mode=0 virtualserver_hostmessage ",
|
||||
"virtualserver_hostmessage_mode=0 virtualserver_default_server_group=8 ",
|
||||
"virtualserver_default_channel_group=8 virtualserver_hostbanner_url ",
|
||||
r"virtualserver_hostbanner_gfx_url=https:\/\/example.com\/banner.png ",
|
||||
"virtualserver_hostbanner_gfx_interval=60 ",
|
||||
"virtualserver_priority_speaker_dimm_modificator=-18.0000 virtualserver_id=1 ",
|
||||
"virtualserver_ask_for_privilegekey=0 ",
|
||||
"virtualserver_hostbutton_tooltip virtualserver_hostbutton_url ",
|
||||
"virtualserver_hostbutton_gfx_url virtualserver_name_phonetic ",
|
||||
"virtualserver_icon_id=0 virtualserver_hostbanner_mode=2 ",
|
||||
"virtualserver_channel_temp_delete_delay_default=0 acn=t aclid=2 pv=7 ",
|
||||
"client_talk_power=75 client_needed_serverquery_view_power=75",
|
||||
)) else {
|
||||
panic!("not an initserver");
|
||||
};
|
||||
let mut book = data::Connection::new(EccKeyPrivP256::create().to_pub(), &init);
|
||||
let channel = |cid: u64, order: u64, name: &str, banner: &str| {
|
||||
format!(
|
||||
"cid={cid} cpid=0 channel_name={name} channel_topic channel_codec=4 \
|
||||
channel_codec_quality=6 channel_maxclients=-1 channel_maxfamilyclients=-1 \
|
||||
channel_order={order} channel_flag_permanent=1 channel_flag_semi_permanent=0 \
|
||||
channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 \
|
||||
channel_codec_is_unencrypted=1 channel_delete_delay=0 \
|
||||
channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=1 \
|
||||
channel_flag_maxfamilyclients_inherited=0 channel_needed_talk_power=0 \
|
||||
channel_forced_silence=0 channel_name_phonetic channel_icon_id=0 {banner} \
|
||||
channel_storage_quota=4294967295"
|
||||
)
|
||||
};
|
||||
let list = format!(
|
||||
"channellist {}|{}",
|
||||
channel(1, 0, "Lobby", "channel_banner_gfx_url channel_banner_mode=0"),
|
||||
channel(
|
||||
12,
|
||||
1,
|
||||
"Raid",
|
||||
r"channel_banner_gfx_url=http:\/\/127.0.0.1:1\/d.png channel_banner_mode=2"
|
||||
),
|
||||
);
|
||||
for text in [
|
||||
list.as_str(),
|
||||
concat!(
|
||||
"notifychannelcreated cid=13 cpid=0 invokerid=1 invokername=serveradmin ",
|
||||
"invokeruid=serveradmin channel_name=New channel_order=12 ",
|
||||
r"channel_flag_permanent=1 channel_banner_gfx_url=https:\/\/example.com\/new.jpg ",
|
||||
"channel_banner_mode=1",
|
||||
),
|
||||
concat!(
|
||||
"notifychanneledited cid=12 reasonid=10 invokerid=1 invokername=serveradmin ",
|
||||
"invokeruid=serveradmin channel_banner_mode=1",
|
||||
),
|
||||
] {
|
||||
book.handle_command(&message(text)).unwrap();
|
||||
}
|
||||
let p = presence_from_book(&book, None, |_| false);
|
||||
let banner = |p: &Presence, cid| {
|
||||
let c = &p.channels[&cid];
|
||||
(c.banner_gfx_url.clone(), c.banner_mode)
|
||||
};
|
||||
assert_eq!(banner(&p, 1), (None, BannerMode::NoAdjust));
|
||||
assert_eq!(
|
||||
banner(&p, 12),
|
||||
(Some("http://127.0.0.1:1/d.png".into()), BannerMode::IgnoreAspect)
|
||||
);
|
||||
assert_eq!(
|
||||
banner(&p, 13),
|
||||
(Some("https://example.com/new.jpg".into()), BannerMode::IgnoreAspect)
|
||||
);
|
||||
// Removing the banner sends an empty address.
|
||||
book.handle_command(&message(
|
||||
"notifychanneledited cid=12 reasonid=10 invokerid=1 invokername=x channel_banner_gfx_url",
|
||||
))
|
||||
.unwrap();
|
||||
let p = presence_from_book(&book, None, |_| false);
|
||||
assert_eq!(p.channels[&12].banner_gfx_url, None);
|
||||
// The host banner, for comparison.
|
||||
assert_eq!(p.server.banner_gfx_url, "https://example.com/banner.png");
|
||||
assert_eq!(p.server.banner_gfx_interval_s, 60);
|
||||
assert_eq!(p.server.banner_mode, BannerMode::KeepAspect);
|
||||
assert_eq!(BannerMode::from_wire("7"), BannerMode::NoAdjust);
|
||||
}
|
||||
}
|
||||
+293
-10
@@ -4,26 +4,123 @@
|
||||
//! id (the CRC32 of the image, as TeamSpeak assigns them), so a lookup is a
|
||||
//! map access, and the same image seen on several servers or under
|
||||
//! several clients is one file. Pictures from the web (banners,
|
||||
//! [`crate::web`]) are named by the MD5 hash of their address. Keys are
|
||||
//! `web`) are named by the MD5 hash of their address. Keys are
|
||||
//! relative paths (`avatars/<md5>`, `icons/<id>`, `pictures/<md5>`).
|
||||
//!
|
||||
//! The cache is bounded by `cache.max_mb` (read on every insert; 0: no
|
||||
//! limit): the least recently used files go first. Use times survive
|
||||
//! restarts as the files' modification times.
|
||||
//!
|
||||
//! Downloads are deduplicated: [`Cache::fetch`] tells the first asker to
|
||||
//! Downloads are deduplicated: `Cache::fetch` tells the first asker to
|
||||
//! download (into a temporary path), later askers wait for the same
|
||||
//! download ([`Cache::finish`] answers them all).
|
||||
//! download (`Cache::finish` answers them all).
|
||||
//!
|
||||
//! A picture from the web keeps its host's validators (`ETag`,
|
||||
//! `Last-Modified`) next to it, in `validators/pictures/<md5>`: asked for
|
||||
//! again, it is downloaded only if it changed (`Cache::validators`,
|
||||
//! `Arrived::Unchanged`).
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::fmt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, PoisonError, RwLock};
|
||||
use std::time::SystemTime;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use tracing::debug;
|
||||
|
||||
/// Called with the cached file's path, or why it could not be fetched.
|
||||
pub(crate) type Waiter = Box<dyn FnOnce(Result<PathBuf, String>) + Send>;
|
||||
pub(crate) type Waiter = Box<dyn FnOnce(Result<PathBuf, FetchError>) + Send>;
|
||||
|
||||
/// Why a fetch failed (for the log), and when it may be tried again.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct FetchError {
|
||||
pub text: String,
|
||||
pub retry: RetryHint,
|
||||
}
|
||||
|
||||
/// When a failed fetch may be tried again, as its host told.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) enum RetryHint {
|
||||
/// Whenever the asker's own schedule says.
|
||||
#[default]
|
||||
Default,
|
||||
/// Not before this long (the host's `Retry-After`).
|
||||
After(Duration),
|
||||
/// The address is wrong or gone (HTTP 400, 404, 410): not soon.
|
||||
Permanent,
|
||||
}
|
||||
|
||||
impl FetchError {
|
||||
pub fn new(text: impl Into<String>, retry: RetryHint) -> Self {
|
||||
Self { text: text.into(), retry }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for FetchError {
|
||||
fn from(text: String) -> Self {
|
||||
Self::new(text, RetryHint::Default)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for FetchError {
|
||||
fn from(text: &str) -> Self {
|
||||
Self::new(text, RetryHint::Default)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for FetchError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(&self.text)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a host said identifies the version of a picture it sent, to ask
|
||||
/// later whether it changed (`If-None-Match`, `If-Modified-Since`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct Validators {
|
||||
pub etag: Option<String>,
|
||||
pub last_modified: Option<String>,
|
||||
}
|
||||
|
||||
impl Validators {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.etag.is_none() && self.last_modified.is_none()
|
||||
}
|
||||
|
||||
/// As kept: a `name: value` line each.
|
||||
fn to_text(&self) -> String {
|
||||
let mut text = String::new();
|
||||
for (name, value) in [("etag", &self.etag), ("last-modified", &self.last_modified)] {
|
||||
if let Some(value) = value {
|
||||
text.push_str(&format!("{name}: {value}\n"));
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn from_text(text: &str) -> Self {
|
||||
let mut validators = Self::default();
|
||||
for line in text.lines() {
|
||||
match line.split_once(": ") {
|
||||
Some(("etag", value)) => validators.etag = Some(value.to_owned()),
|
||||
Some(("last-modified", value)) => validators.last_modified = Some(value.to_owned()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
validators
|
||||
}
|
||||
}
|
||||
|
||||
/// How a download ended well.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Arrived {
|
||||
/// In the temporary path, with what identifies its version (when the
|
||||
/// host said).
|
||||
File(Validators),
|
||||
/// The host said the cached copy is still what it has (HTTP 304): the
|
||||
/// copy stays, nothing was downloaded.
|
||||
Unchanged,
|
||||
}
|
||||
|
||||
/// What [`Cache::fetch`] decided.
|
||||
pub(crate) enum Fetch {
|
||||
@@ -80,16 +177,28 @@ pub(crate) fn icon_key(id: u32) -> String {
|
||||
/// The largest picture downloaded into the cache, from the web or from the
|
||||
/// server's files: animated banners of several megabytes are common. The
|
||||
/// download goes to disk as it arrives, so this bounds the disk, not memory.
|
||||
pub(crate) const MAX_PICTURE_BYTES: u64 = 64 << 20;
|
||||
pub(crate) const MAX_PICTURE_BYTES: u64 = 128 << 20;
|
||||
|
||||
/// The slowest a picture may arrive on average after its first seconds:
|
||||
/// a large banner on a slow link still arrives, one trickling in forever
|
||||
/// does not hold a download slot.
|
||||
pub(crate) const MIN_PICTURE_RATE: u64 = 32 << 10;
|
||||
pub(crate) const MIN_PICTURE_RATE: u64 = 8 << 10;
|
||||
|
||||
/// How long a picture of `size` bytes may take to arrive: a minute, plus
|
||||
/// its size at [`MIN_PICTURE_RATE`], so large banners arrive on slow
|
||||
/// links while a stalled transfer still ends.
|
||||
pub(crate) fn image_download_time(size: u64) -> std::time::Duration {
|
||||
std::time::Duration::from_secs(60 + size / MIN_PICTURE_RATE)
|
||||
}
|
||||
|
||||
/// How long the server may take to start an image transfer (a busy server
|
||||
/// answers the requests of a large channel tree in turn).
|
||||
pub(crate) const IMAGE_NEGOTIATION: std::time::Duration = std::time::Duration::from_secs(30);
|
||||
|
||||
/// The cache key of a picture on the web: only `http` and `https`
|
||||
/// addresses.
|
||||
/// addresses (blanks around one are not part of it).
|
||||
pub(crate) fn picture_key(url: &str) -> Option<String> {
|
||||
let url = url.trim();
|
||||
let (scheme, rest) = url.split_once("://")?;
|
||||
let web = scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https");
|
||||
(web && !rest.is_empty()).then(|| format!("pictures/{:x}", md5::compute(url)))
|
||||
@@ -198,10 +307,35 @@ impl Cache {
|
||||
&self,
|
||||
key: &str,
|
||||
temp: &Path,
|
||||
result: Result<(), String>,
|
||||
result: Result<(), FetchError>,
|
||||
max_bytes: u64,
|
||||
) {
|
||||
let result = result.and_then(|()| self.insert_file(key, temp, max_bytes));
|
||||
let arrived = result.map(|()| Arrived::File(Validators::default()));
|
||||
self.finish_with(key, temp, arrived, max_bytes);
|
||||
}
|
||||
|
||||
/// [`finish`](Self::finish) a download from the web: a new file with
|
||||
/// its validators, or the cached copy confirmed (kept, and marked as
|
||||
/// used).
|
||||
pub(crate) fn finish_with(
|
||||
&self,
|
||||
key: &str,
|
||||
temp: &Path,
|
||||
result: Result<Arrived, FetchError>,
|
||||
max_bytes: u64,
|
||||
) {
|
||||
let result = result.and_then(|arrived| match arrived {
|
||||
Arrived::File(validators) => {
|
||||
let path = self.insert_file(key, temp, max_bytes)?;
|
||||
self.keep_validators(key, &validators);
|
||||
Ok(path)
|
||||
}
|
||||
Arrived::Unchanged => {
|
||||
let mut index = self.lock();
|
||||
self.touch(&mut index, key)
|
||||
.ok_or_else(|| FetchError::from("cache: the copy was removed meanwhile"))
|
||||
}
|
||||
});
|
||||
let _ = std::fs::remove_file(temp);
|
||||
let waiters = self.lock().in_flight.remove(key).unwrap_or_default();
|
||||
for waiter in waiters {
|
||||
@@ -209,6 +343,32 @@ impl Cache {
|
||||
}
|
||||
}
|
||||
|
||||
/// What identifies the cached version of `key` (a picture from the
|
||||
/// web), if it is cached and its host said.
|
||||
pub(crate) fn validators(&self, key: &str) -> Option<Validators> {
|
||||
if !self.lock().entries.contains_key(key) || !self.dir.join(key).is_file() {
|
||||
return None;
|
||||
}
|
||||
let text = std::fs::read_to_string(validators_path(&self.dir, key)).ok()?;
|
||||
Some(Validators::from_text(&text)).filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
/// Keep `validators` with `key`'s new file (none: the old ones go).
|
||||
fn keep_validators(&self, key: &str, validators: &Validators) {
|
||||
let path = validators_path(&self.dir, key);
|
||||
if validators.is_empty() {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
return;
|
||||
}
|
||||
let written = path
|
||||
.parent()
|
||||
.map_or(Ok(()), std::fs::create_dir_all)
|
||||
.and_then(|()| std::fs::write(&path, validators.to_text()));
|
||||
if let Err(e) = written {
|
||||
debug!("cache: cannot keep the validators of {key}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Put a file we have (e.g. our own avatar) into the cache.
|
||||
pub(crate) fn insert_copy(
|
||||
&self,
|
||||
@@ -263,6 +423,7 @@ impl Cache {
|
||||
if let Err(e) = std::fs::remove_file(self.dir.join(&key)) {
|
||||
debug!("cache: cannot remove {key}: {e}");
|
||||
}
|
||||
let _ = std::fs::remove_file(validators_path(&self.dir, &key));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -296,6 +457,22 @@ fn scan(dir: &Path, index: &mut Index) {
|
||||
index.lru.insert(tick, key.clone());
|
||||
index.entries.insert(key, Entry { size, tick });
|
||||
}
|
||||
// Validators of pictures no longer here.
|
||||
let Ok(kept) = std::fs::read_dir(dir.join(VALIDATORS).join("pictures")) else { return };
|
||||
for entry in kept.flatten() {
|
||||
let key = format!("pictures/{}", entry.file_name().to_string_lossy());
|
||||
if !index.entries.contains_key(&key) {
|
||||
let _ = std::fs::remove_file(entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The directory of the pictures' validators.
|
||||
const VALIDATORS: &str = "validators";
|
||||
|
||||
/// Where the validators of `key` are kept.
|
||||
fn validators_path(dir: &Path, key: &str) -> PathBuf {
|
||||
dir.join(VALIDATORS).join(key)
|
||||
}
|
||||
|
||||
/// The engine's cache: one [`Cache`] that [`crate::Command::AttachCache`]
|
||||
@@ -323,6 +500,15 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn large_pictures_get_time_to_arrive() {
|
||||
let secs = std::time::Duration::from_secs;
|
||||
assert_eq!(image_download_time(0), secs(60));
|
||||
assert_eq!(image_download_time(100 << 10), secs(72));
|
||||
// The largest picture, at the slowest rate allowed.
|
||||
assert_eq!(image_download_time(MAX_PICTURE_BYTES), secs(60 + 16384));
|
||||
}
|
||||
|
||||
fn temp_dir(tag: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"voelin-cache-{tag}-{}-{:?}",
|
||||
@@ -464,6 +650,103 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A picture keeps its host's validators; confirmed unchanged, the copy
|
||||
/// stays and is used; replaced without validators or evicted, they go.
|
||||
#[test]
|
||||
fn validators_go_with_their_picture() {
|
||||
let dir = temp_dir("validators");
|
||||
let cache = Cache::new(&dir);
|
||||
let key = picture_key("https://example.com/v.png").unwrap();
|
||||
let validators = Validators {
|
||||
etag: Some("W/\"v1\"".into()),
|
||||
last_modified: Some("Tue, 06 Oct 2026 10:00:00 GMT".into()),
|
||||
};
|
||||
assert_eq!(cache.validators(&key), None);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let waiter = |tx: &mpsc::Sender<_>| -> Waiter {
|
||||
let tx = tx.clone();
|
||||
Box::new(move |r| tx.send(r).unwrap())
|
||||
};
|
||||
let Fetch::Download(temp) = cache.fetch(&key, false, waiter(&tx)) else { panic!() };
|
||||
std::fs::create_dir_all(temp.parent().unwrap()).unwrap();
|
||||
std::fs::write(&temp, b"v1").unwrap();
|
||||
cache.finish_with(&key, &temp, Ok(Arrived::File(validators.clone())), 0);
|
||||
let path = rx.recv().unwrap().unwrap();
|
||||
assert_eq!(cache.validators(&key), Some(validators.clone()));
|
||||
// Asked again: unchanged, the same file answers both askers.
|
||||
let Fetch::Download(temp) = cache.fetch(&key, true, waiter(&tx)) else { panic!() };
|
||||
assert!(matches!(cache.fetch(&key, true, waiter(&tx)), Fetch::Waiting));
|
||||
cache.finish_with(&key, &temp, Ok(Arrived::Unchanged), 0);
|
||||
assert_eq!(rx.recv().unwrap(), Ok(path.clone()));
|
||||
assert_eq!(rx.recv().unwrap(), Ok(path.clone()));
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"v1");
|
||||
// They survive a restart, with their picture.
|
||||
assert_eq!(Cache::new(&dir).validators(&key), Some(validators.clone()));
|
||||
// A new version without validators: the old ones are not sent again.
|
||||
let Fetch::Download(temp) = cache.fetch(&key, true, waiter(&tx)) else { panic!() };
|
||||
// (The restart above cleared the temporary files' directory.)
|
||||
std::fs::create_dir_all(temp.parent().unwrap()).unwrap();
|
||||
std::fs::write(&temp, b"new").unwrap();
|
||||
cache.finish(&key, &temp, Ok(()), 0);
|
||||
rx.recv().unwrap().unwrap();
|
||||
assert_eq!(cache.validators(&key), None);
|
||||
// Evicted with the picture.
|
||||
let Fetch::Download(temp) = cache.fetch(&key, true, waiter(&tx)) else { panic!() };
|
||||
std::fs::write(&temp, b"v2").unwrap();
|
||||
cache.finish_with(&key, &temp, Ok(Arrived::File(validators.clone())), 0);
|
||||
rx.recv().unwrap().unwrap();
|
||||
assert!(validators_path(&dir, &key).is_file());
|
||||
put(&cache, "icons/1", 10, 10);
|
||||
assert!(!path.exists());
|
||||
assert!(!validators_path(&dir, &key).exists());
|
||||
// Unchanged, but the copy went meanwhile: a failure, retried in full.
|
||||
let Fetch::Download(temp) = cache.fetch(&key, true, waiter(&tx)) else { panic!() };
|
||||
cache.finish_with(&key, &temp, Ok(Arrived::Unchanged), 0);
|
||||
assert!(rx.recv().unwrap().is_err());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// A picture confirmed unchanged counts as used: others go first.
|
||||
#[test]
|
||||
fn an_unchanged_picture_counts_as_used() {
|
||||
let dir = temp_dir("unchanged-used");
|
||||
let cache = Cache::new(&dir);
|
||||
let key = picture_key("https://example.com/u.png").unwrap();
|
||||
let picture = put(&cache, &key, 400, 1000);
|
||||
let icon = put(&cache, "icons/1", 400, 1000);
|
||||
let Fetch::Download(temp) = cache.fetch(&key, true, Box::new(|_| {})) else { panic!() };
|
||||
cache.finish_with(&key, &temp, Ok(Arrived::Unchanged), 1000);
|
||||
put(&cache, "icons/2", 400, 1000);
|
||||
assert!(picture.exists(), "the picture confirmed unchanged stays");
|
||||
assert!(!icon.exists(), "the least recently used file goes");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// Validators whose picture is gone go at the next start.
|
||||
#[test]
|
||||
fn orphaned_validators_are_removed() {
|
||||
let dir = temp_dir("orphans");
|
||||
let key = picture_key("https://example.com/o.png").unwrap();
|
||||
let orphan = validators_path(&dir, &key);
|
||||
std::fs::create_dir_all(orphan.parent().unwrap()).unwrap();
|
||||
std::fs::write(&orphan, "etag: \"x\"\n").unwrap();
|
||||
let cache = Cache::new(&dir);
|
||||
assert_eq!(cache.size(), 0);
|
||||
assert!(!orphan.exists());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_errors_carry_their_retry_hint() {
|
||||
let error = FetchError::from("HTTP 503 Service Unavailable");
|
||||
assert_eq!(error.retry, RetryHint::Default);
|
||||
assert_eq!(error.to_string(), "HTTP 503 Service Unavailable");
|
||||
let gone = FetchError::new("HTTP 404 Not Found", RetryHint::Permanent);
|
||||
assert_ne!(gone, FetchError::from("HTTP 404 Not Found"));
|
||||
let text = Validators { etag: Some("\"a: b\"".into()), last_modified: None }.to_text();
|
||||
assert_eq!(Validators::from_text(&text).etag.as_deref(), Some("\"a: b\""));
|
||||
}
|
||||
|
||||
/// Pictures are cached files like the others (counted after a restart).
|
||||
#[test]
|
||||
fn pictures_survive_restart() {
|
||||
|
||||
@@ -8,16 +8,31 @@
|
||||
//! - SRV `_tsgws._tcp.<name>`: `wss://<target>:<port><path>`,
|
||||
//! - SRV `_tsgw._tcp.<name>`: `ws://<target>:<port><path>`,
|
||||
//!
|
||||
//! TLS first at the same name; `<path>` is `path=…` from a TXT record at the
|
||||
//! SRV record's name, `/v1` without one. Without any such record, as TSDNS
|
||||
//! has its well-known port, the gateway itself is asked at tsgw's default
|
||||
//! port: `http://<name>:7788/.well-known/tsgw` answers `{"url": "…"}`. For an
|
||||
//! IP address (or `localhost`) only that is tried. What an admin publishes is
|
||||
//! in `docs/gateway-admin.md`.
|
||||
//! `<path>` is `path=…` from a TXT record at the SRV record's name, `/v1`
|
||||
//! without one. As TSDNS has its well-known port, the gateway itself is also
|
||||
//! asked at tsgw's default port: `http://<name>:7788/.well-known/tsgw`
|
||||
//! answers `{"url": "…"}`; for an IP address (or `localhost`) only that is
|
||||
//! tried. That answer is plain HTTP, so it is used only when nothing or a
|
||||
//! plain record is published: a TLS-only publication stays TLS-only.
|
||||
//!
|
||||
//! Everything is asked at once (SRV and TXT at every name, and the gateway
|
||||
//! at every name), so a discovery takes as long as its slowest needed
|
||||
//! answer, not their sum; DNS gives up after 2 s (twice).
|
||||
//!
|
||||
//! The most specific name with a record wins: a parent domain's records
|
||||
//! are another server's gateway when the host publishes its own. Every
|
||||
//! gateway of that name is kept, best first (TLS before plain, by
|
||||
//! priority, then the gateway's own answer at that name), and tried in turn
|
||||
//! ([`crate::Command::ObserveGateway`]): a TLS proxy that fails falls back
|
||||
//! to the plain gateway published next to it. Discovery trusts DNS and the
|
||||
//! network as TSDNS does; falling back from a published `_tsgws` to a
|
||||
//! published `_tsgw` is no weaker than publishing only `_tsgw`. What an
|
||||
//! admin publishes is in `docs/gateway-admin.md`. Each discovery is logged
|
||||
//! (target `voelin_core::discover`, the details at debug).
|
||||
|
||||
use std::net::IpAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use futures::future::{BoxFuture, FutureExt, join_all};
|
||||
use hickory_resolver::TokioResolver;
|
||||
@@ -26,7 +41,9 @@ use hickory_resolver::net::runtime::TokioRuntimeProvider;
|
||||
use hickory_resolver::proto::rr::RData;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::time::timeout;
|
||||
use tracing::{debug, info};
|
||||
|
||||
/// The port tsgw listens on by default, where it is asked for its URL.
|
||||
pub const DEFAULT_PORT: u16 = 7788;
|
||||
@@ -34,9 +51,14 @@ pub const DEFAULT_PORT: u16 = 7788;
|
||||
const DEFAULT_PATH: &str = "/v1";
|
||||
/// Give up on asking one name's gateway after this long.
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
/// Give up on one DNS query after this long (it is sent twice).
|
||||
const DNS_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
/// At most this many gateways are kept, best first.
|
||||
const MAX_CANDIDATES: usize = 8;
|
||||
|
||||
type SrvFn = dyn Fn(String) -> BoxFuture<'static, Vec<(u16, String, u16)>> + Send + Sync;
|
||||
type TxtFn = dyn Fn(String) -> BoxFuture<'static, Vec<String>> + Send + Sync;
|
||||
type ProbeFn = dyn Fn(String) -> BoxFuture<'static, Option<String>> + Send + Sync;
|
||||
|
||||
/// Where [`gateway`] gets its answers from; the tests put fakes in.
|
||||
#[derive(Clone)]
|
||||
@@ -45,28 +67,47 @@ struct Lookups {
|
||||
srv: Arc<SrvFn>,
|
||||
/// The strings of the TXT records at a name.
|
||||
txt: Arc<TxtFn>,
|
||||
/// Where a gateway is asked for its URL.
|
||||
probe_port: u16,
|
||||
/// The URL a gateway at a name gives for itself (`/.well-known/tsgw`).
|
||||
probe: Arc<ProbeFn>,
|
||||
}
|
||||
|
||||
impl Lookups {
|
||||
fn system() -> Self {
|
||||
// The system's resolver, else (Android) a public one, as the voice
|
||||
// connection's resolver does.
|
||||
let resolver = TokioResolver::builder_tokio().and_then(|b| b.build()).or_else(|_| {
|
||||
TokioResolver::builder_with_config(
|
||||
ResolverConfig::udp_and_tcp(&CLOUDFLARE),
|
||||
TokioRuntimeProvider::default(),
|
||||
)
|
||||
.build()
|
||||
});
|
||||
let resolver = resolver.ok();
|
||||
// connection's resolver does. A query that is not answered is sent
|
||||
// again soon: discovery runs once a run, and finding nothing is
|
||||
// final until the next.
|
||||
let resolver = TokioResolver::builder_tokio()
|
||||
.map(|mut b| {
|
||||
let options = b.options_mut();
|
||||
options.timeout = DNS_TIMEOUT;
|
||||
options.attempts = options.attempts.max(2);
|
||||
b
|
||||
})
|
||||
.and_then(|b| b.build())
|
||||
.or_else(|_| {
|
||||
let mut b = TokioResolver::builder_with_config(
|
||||
ResolverConfig::udp_and_tcp(&CLOUDFLARE),
|
||||
TokioRuntimeProvider::default(),
|
||||
);
|
||||
b.options_mut().timeout = DNS_TIMEOUT;
|
||||
b.build()
|
||||
});
|
||||
let resolver = match resolver {
|
||||
Ok(resolver) => Some(resolver),
|
||||
Err(e) => {
|
||||
debug!(error = %e, "no DNS resolver for gateway discovery");
|
||||
None
|
||||
}
|
||||
};
|
||||
let txt_resolver = resolver.clone();
|
||||
Self {
|
||||
srv: Arc::new(move |name| {
|
||||
let resolver = resolver.clone();
|
||||
async move {
|
||||
let lookup = resolver?.srv_lookup(name).await.ok()?;
|
||||
let started = Instant::now();
|
||||
let lookup = resolver?.srv_lookup(name.as_str()).await;
|
||||
let lookup = dns_answer(&name, "SRV", started, lookup)?;
|
||||
Some(
|
||||
lookup
|
||||
.answers()
|
||||
@@ -84,7 +125,9 @@ impl Lookups {
|
||||
txt: Arc::new(move |name| {
|
||||
let resolver = txt_resolver.clone();
|
||||
async move {
|
||||
let lookup = resolver?.txt_lookup(name).await.ok()?;
|
||||
let started = Instant::now();
|
||||
let lookup = resolver?.txt_lookup(name.as_str()).await;
|
||||
let lookup = dns_answer(&name, "TXT", started, lookup)?;
|
||||
Some(
|
||||
lookup
|
||||
.answers()
|
||||
@@ -101,30 +144,150 @@ impl Lookups {
|
||||
.map(Option::unwrap_or_default)
|
||||
.boxed()
|
||||
}),
|
||||
probe_port: DEFAULT_PORT,
|
||||
probe: Arc::new(|name| {
|
||||
async move {
|
||||
let started = Instant::now();
|
||||
let answer = match timeout(PROBE_TIMEOUT, well_known(&name, DEFAULT_PORT)).await
|
||||
{
|
||||
Ok(answer) => answer,
|
||||
Err(_) => Err(format!("no answer within {} s", PROBE_TIMEOUT.as_secs())),
|
||||
};
|
||||
let elapsed_ms = started.elapsed().as_millis() as u64;
|
||||
match &answer {
|
||||
Ok(url) => debug!(name, %url, elapsed_ms, "tsgw well-known probe answered"),
|
||||
Err(outcome) => debug!(name, %outcome, elapsed_ms, "tsgw well-known probe"),
|
||||
}
|
||||
answer.ok()
|
||||
}
|
||||
.boxed()
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The URL of the gateway of the server at `address` (as a bookmark has it:
|
||||
/// host, host:port, an IP), if one is published.
|
||||
pub async fn gateway(address: &str) -> Option<String> {
|
||||
gateway_with(address, Lookups::system()).await
|
||||
/// A DNS answer, the failure logged (no record at most names is normal).
|
||||
fn dns_answer<T>(
|
||||
name: &str,
|
||||
kind: &str,
|
||||
started: Instant,
|
||||
lookup: Result<T, hickory_resolver::net::NetError>,
|
||||
) -> Option<T> {
|
||||
let elapsed_ms = started.elapsed().as_millis() as u64;
|
||||
match lookup {
|
||||
Ok(lookup) => Some(lookup),
|
||||
Err(e) if e.is_no_records_found() => {
|
||||
debug!(name, kind, elapsed_ms, "no DNS record");
|
||||
None
|
||||
}
|
||||
Err(e) => {
|
||||
debug!(name, kind, elapsed_ms, error = %e, "DNS lookup failed");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn gateway_with(address: &str, lookups: Lookups) -> Option<String> {
|
||||
/// The URLs of the gateway of the server at `address` (as a bookmark has
|
||||
/// it: host, host:port, an IP), best first: everything published, to be
|
||||
/// tried in turn. Empty: none is published.
|
||||
pub async fn gateways(address: &str) -> Vec<String> {
|
||||
gateways_with(address, Lookups::system()).await
|
||||
}
|
||||
|
||||
async fn gateways_with(address: &str, lookups: Lookups) -> Vec<String> {
|
||||
let started = Instant::now();
|
||||
let host = host_of(address);
|
||||
let names = names(host);
|
||||
if names.is_empty() {
|
||||
return None;
|
||||
debug!(address, "no gateway discovery for a server nickname");
|
||||
return Vec::new();
|
||||
}
|
||||
if host.parse::<IpAddr>().is_err()
|
||||
&& host.contains('.')
|
||||
&& let Some(url) = from_srv(&names, &lookups).await
|
||||
{
|
||||
return Some(url);
|
||||
// The gateway's own answer is asked at every name while DNS is; only
|
||||
// the answer that counts is waited for.
|
||||
let mut probes = Probes::start(&names, &lookups);
|
||||
let srv = if host.parse::<IpAddr>().is_err() && host.contains('.') {
|
||||
from_srv(&names, &lookups).await
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// The gateway's own answer comes over plain HTTP: not for a server that
|
||||
// publishes only TLS; at the name that publishes, or without records the
|
||||
// most specific name that answers.
|
||||
let (mut urls, well_known) = match &srv {
|
||||
None => match probes.first().await {
|
||||
Some((name, url)) => (vec![url.clone()], format!("{name}: {url}")),
|
||||
None => (Vec::new(), "none".to_owned()),
|
||||
},
|
||||
Some(found) if found.urls.iter().any(|url| url.starts_with("ws://")) => {
|
||||
let mut urls = found.urls.clone();
|
||||
match probes.of(found.name).await {
|
||||
Some(url) => {
|
||||
let well_known = format!("{}: {url}", found.name);
|
||||
if !urls.contains(&url) {
|
||||
urls.push(url);
|
||||
}
|
||||
(urls, well_known)
|
||||
}
|
||||
None => (urls, "none".to_owned()),
|
||||
}
|
||||
}
|
||||
Some(found) => (found.urls.clone(), "not used (TLS only)".to_owned()),
|
||||
};
|
||||
urls.truncate(MAX_CANDIDATES);
|
||||
let (srv_name, srv_urls, txt) = match &srv {
|
||||
Some(found) => (found.name, found.urls.as_slice(), found.txt.as_slice()),
|
||||
None => ("", &[][..], &[][..]),
|
||||
};
|
||||
info!(
|
||||
address,
|
||||
names = ?names,
|
||||
srv_name,
|
||||
srv = ?srv_urls,
|
||||
txt = ?txt,
|
||||
%well_known,
|
||||
result = ?urls,
|
||||
elapsed_ms = started.elapsed().as_millis() as u64,
|
||||
"gateway discovery"
|
||||
);
|
||||
urls
|
||||
}
|
||||
|
||||
/// The gateway's own answers being asked, one per name, most specific
|
||||
/// first; those still asking when dropped are given up.
|
||||
struct Probes<'a>(Vec<(&'a str, JoinHandle<Option<String>>)>);
|
||||
|
||||
impl<'a> Probes<'a> {
|
||||
fn start(names: &[&'a str], lookups: &Lookups) -> Self {
|
||||
Self(
|
||||
names
|
||||
.iter()
|
||||
.map(|name| (*name, tokio::spawn((lookups.probe)(name.to_string()))))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The answer at `name`.
|
||||
async fn of(&mut self, name: &str) -> Option<String> {
|
||||
let (_, probe) = self.0.iter_mut().find(|(n, _)| *n == name)?;
|
||||
probe.await.ok().flatten()
|
||||
}
|
||||
|
||||
/// The answer of the most specific name that answers.
|
||||
async fn first(&mut self) -> Option<(&'a str, String)> {
|
||||
for (name, probe) in &mut self.0 {
|
||||
if let Some(url) = probe.await.ok().flatten() {
|
||||
return Some((*name, url));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Probes<'_> {
|
||||
fn drop(&mut self) {
|
||||
for (_, probe) in &self.0 {
|
||||
probe.abort();
|
||||
}
|
||||
}
|
||||
from_well_known(&names, lookups.probe_port).await
|
||||
}
|
||||
|
||||
/// The host of an address: without the port, the brackets of an IPv6
|
||||
@@ -155,59 +318,103 @@ fn names(host: &str) -> Vec<&str> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The URL from SRV records, every name and service asked at once.
|
||||
async fn from_srv(names: &[&str], lookups: &Lookups) -> Option<String> {
|
||||
let queries: Vec<(&str, String)> = names
|
||||
/// What SRV records publish: at `name`, the most specific name with a
|
||||
/// usable record.
|
||||
struct Published<'a> {
|
||||
name: &'a str,
|
||||
/// TLS first, by priority.
|
||||
urls: Vec<String>,
|
||||
/// The TXT strings at the records' names.
|
||||
txt: Vec<String>,
|
||||
}
|
||||
|
||||
/// The URLs from SRV records, every name and service asked at once, with
|
||||
/// the TXT records there (the path; most names have none): those of the
|
||||
/// most specific name with a usable record.
|
||||
async fn from_srv<'a>(names: &[&'a str], lookups: &Lookups) -> Option<Published<'a>> {
|
||||
let queries: Vec<(&str, &str, String)> = names
|
||||
.iter()
|
||||
.flat_map(|name| {
|
||||
[("wss", format!("_tsgws._tcp.{name}.")), ("ws", format!("_tsgw._tcp.{name}."))]
|
||||
[
|
||||
(*name, "wss", format!("_tsgws._tcp.{name}.")),
|
||||
(*name, "ws", format!("_tsgw._tcp.{name}.")),
|
||||
]
|
||||
})
|
||||
.collect();
|
||||
let answers = join_all(queries.iter().map(|(_, owner)| (lookups.srv)(owner.clone()))).await;
|
||||
// The first (most specific, TLS first) name with a usable record.
|
||||
let ((scheme, owner), (_, target, port)) =
|
||||
queries.iter().zip(answers).find_map(|(q, records)| {
|
||||
let (answers, texts) = futures::join!(
|
||||
join_all(queries.iter().map(|(.., owner)| (lookups.srv)(owner.clone()))),
|
||||
join_all(queries.iter().map(|(.., owner)| (lookups.txt)(owner.clone()))),
|
||||
);
|
||||
let mut found: Vec<_> = queries
|
||||
.iter()
|
||||
.zip(answers)
|
||||
.zip(texts)
|
||||
.filter_map(|((query, mut records), txt)| {
|
||||
// A target of "." says there is no such service there.
|
||||
let best = records.into_iter().filter(|r| r.1 != ".").min_by_key(|r| r.0)?;
|
||||
Some((q, best))
|
||||
})?;
|
||||
let mut path = (lookups.txt)(owner.clone())
|
||||
.await
|
||||
.into_iter()
|
||||
records.retain(|r| r.1 != ".");
|
||||
records.sort_by_key(|r| r.0);
|
||||
(!records.is_empty()).then_some((query, records, txt))
|
||||
})
|
||||
.collect();
|
||||
let name = found.first()?.0.0;
|
||||
found.retain(|((n, ..), ..)| *n == name);
|
||||
let mut published = Published { name, urls: Vec::new(), txt: Vec::new() };
|
||||
for ((_, scheme, _), records, txt) in found {
|
||||
let path = path_in(&txt);
|
||||
published.txt.extend(txt);
|
||||
for (_, target, port) in records {
|
||||
let url = format!("{scheme}://{}:{port}{path}", target.trim_end_matches('.'));
|
||||
if !published.urls.contains(&url) {
|
||||
published.urls.push(url);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(published)
|
||||
}
|
||||
|
||||
/// The path in a SRV record's name's TXT strings: `path=…`, `/v1` without
|
||||
/// one.
|
||||
fn path_in(txt: &[String]) -> String {
|
||||
let mut path = txt
|
||||
.iter()
|
||||
.find_map(|s| s.strip_prefix("path=").map(str::to_owned))
|
||||
.unwrap_or_else(|| DEFAULT_PATH.to_owned());
|
||||
if !path.starts_with('/') {
|
||||
path.insert(0, '/');
|
||||
}
|
||||
Some(format!("{scheme}://{}:{port}{path}", target.trim_end_matches('.')))
|
||||
path
|
||||
}
|
||||
|
||||
/// The URL a gateway gives for itself at one of `names`, all asked at once;
|
||||
/// the most specific that answers wins.
|
||||
async fn from_well_known(names: &[&str], port: u16) -> Option<String> {
|
||||
let answers =
|
||||
join_all(names.iter().map(|name| timeout(PROBE_TIMEOUT, well_known(name, port)))).await;
|
||||
answers.into_iter().find_map(|answer| answer.ok().flatten())
|
||||
}
|
||||
|
||||
/// tsgw's answer at `http://<host>:<port>/.well-known/tsgw`.
|
||||
async fn well_known(host: &str, port: u16) -> Option<String> {
|
||||
let mut stream = TcpStream::connect((host, port)).await.ok()?;
|
||||
/// tsgw's answer at `http://<host>:<port>/.well-known/tsgw`; else what
|
||||
/// happened instead.
|
||||
async fn well_known(host: &str, port: u16) -> Result<String, String> {
|
||||
let mut stream =
|
||||
TcpStream::connect((host, port)).await.map_err(|e| format!("cannot connect: {e}"))?;
|
||||
let authority =
|
||||
if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
|
||||
let request =
|
||||
format!("GET /.well-known/tsgw HTTP/1.1\r\nHost: {authority}\r\nConnection: close\r\n\r\n");
|
||||
stream.write_all(request.as_bytes()).await.ok()?;
|
||||
stream.write_all(request.as_bytes()).await.map_err(|e| format!("cannot ask: {e}"))?;
|
||||
let mut response = Vec::new();
|
||||
stream.take(16 * 1024).read_to_end(&mut response).await.ok()?;
|
||||
let response = String::from_utf8(response).ok()?;
|
||||
let (head, body) = response.split_once("\r\n\r\n")?;
|
||||
if head.split_whitespace().nth(1) != Some("200") {
|
||||
return None;
|
||||
stream
|
||||
.take(16 * 1024)
|
||||
.read_to_end(&mut response)
|
||||
.await
|
||||
.map_err(|e| format!("no answer: {e}"))?;
|
||||
let response = String::from_utf8(response).map_err(|_| "not text".to_owned())?;
|
||||
let (head, body) = response.split_once("\r\n\r\n").ok_or("not HTTP")?;
|
||||
let status = head.split_whitespace().nth(1).unwrap_or_default();
|
||||
if status != "200" {
|
||||
return Err(format!("http {status}"));
|
||||
}
|
||||
let answer: serde_json::Value =
|
||||
serde_json::from_str(body).map_err(|_| "not a tsgw answer".to_owned())?;
|
||||
let url = answer.get("url").and_then(|url| url.as_str()).ok_or("no url in the answer")?;
|
||||
if url.starts_with("ws://") || url.starts_with("wss://") {
|
||||
Ok(url.to_owned())
|
||||
} else {
|
||||
Err(format!("not a gateway URL: {url}"))
|
||||
}
|
||||
let answer: serde_json::Value = serde_json::from_str(body).ok()?;
|
||||
let url = answer.get("url")?.as_str()?;
|
||||
(url.starts_with("ws://") || url.starts_with("wss://")).then(|| url.to_owned())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -215,8 +422,8 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
/// DNS answers from these lists only: SRV `(name, priority, target,
|
||||
/// port)`, TXT `(name, string)`.
|
||||
fn fake(srv: &[(&str, u16, &str, u16)], txt: &[(&str, &str)], probe_port: u16) -> Lookups {
|
||||
/// port)`, TXT `(name, string)`; no gateway answers for itself.
|
||||
fn fake(srv: &[(&str, u16, &str, u16)], txt: &[(&str, &str)]) -> Lookups {
|
||||
let srv: Vec<(String, u16, String, u16)> =
|
||||
srv.iter().map(|(n, p, t, port)| (n.to_string(), *p, t.to_string(), *port)).collect();
|
||||
let txt: Vec<(String, String)> =
|
||||
@@ -231,10 +438,29 @@ mod tests {
|
||||
let found = txt.iter().filter(|r| r.0 == name).map(|r| r.1.clone()).collect();
|
||||
futures::future::ready(found).boxed()
|
||||
}),
|
||||
probe_port,
|
||||
probe: Arc::new(|_| futures::future::ready(None).boxed()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `lookups` where the gateway at a name answers `(name, url)`.
|
||||
fn answering(mut lookups: Lookups, answers: &[(&str, &str)]) -> Lookups {
|
||||
let answers: Vec<(String, String)> =
|
||||
answers.iter().map(|(n, u)| (n.to_string(), u.to_string())).collect();
|
||||
lookups.probe = Arc::new(move |name| {
|
||||
let url = answers.iter().find(|a| a.0 == name).map(|a| a.1.clone());
|
||||
futures::future::ready(url).boxed()
|
||||
});
|
||||
lookups
|
||||
}
|
||||
|
||||
/// `lookups` asking the real `/.well-known/tsgw` at `port`.
|
||||
fn probing(mut lookups: Lookups, port: u16) -> Lookups {
|
||||
lookups.probe = Arc::new(move |name| {
|
||||
async move { timeout(PROBE_TIMEOUT, well_known(&name, port)).await.ok()?.ok() }.boxed()
|
||||
});
|
||||
lookups
|
||||
}
|
||||
|
||||
/// A port nothing listens on.
|
||||
fn closed_port() -> u16 {
|
||||
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
|
||||
@@ -242,20 +468,22 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn finds_the_gateway_at_the_host_or_its_domain() {
|
||||
let lookups = fake(&[("_tsgw._tcp.example.test.", 0, "gw.example.test.", 7788)], &[], 0);
|
||||
let lookups = fake(&[("_tsgw._tcp.example.test.", 0, "gw.example.test.", 7788)], &[]);
|
||||
for address in ["ts.example.test", "ts.example.test:9987", "example.test"] {
|
||||
assert_eq!(
|
||||
gateway_with(address, lookups.clone()).await.as_deref(),
|
||||
Some("ws://gw.example.test:7788/v1"),
|
||||
gateways_with(address, lookups.clone()).await,
|
||||
["ws://gw.example.test:7788/v1"],
|
||||
"{address}"
|
||||
);
|
||||
}
|
||||
// The parent's parent is not the domain any more.
|
||||
assert_eq!(gateway_with("example", lookups).await, None);
|
||||
assert!(gateways_with("example", lookups).await.is_empty());
|
||||
}
|
||||
|
||||
/// All of the most specific name's gateways, TLS first, by priority; a
|
||||
/// parent domain's only for a host without its own.
|
||||
#[tokio::test]
|
||||
async fn the_most_specific_name_wins_then_tls() {
|
||||
async fn the_most_specific_name_wins_with_all_its_gateways() {
|
||||
let lookups = fake(
|
||||
&[
|
||||
("_tsgws._tcp.example.test.", 0, "domain.example.test.", 443),
|
||||
@@ -264,18 +492,181 @@ mod tests {
|
||||
("_tsgws._tcp.ts.example.test.", 1, "tls.example.test.", 8443),
|
||||
],
|
||||
&[("_tsgws._tcp.ts.example.test.", "path=/tsgw/v1")],
|
||||
0,
|
||||
);
|
||||
assert_eq!(
|
||||
gateway_with("ts.example.test", lookups.clone()).await.as_deref(),
|
||||
Some("wss://tls.example.test:8443/tsgw/v1")
|
||||
gateways_with("ts.example.test", lookups.clone()).await,
|
||||
[
|
||||
"wss://tls.example.test:8443/tsgw/v1",
|
||||
"wss://backup.example.test:443/tsgw/v1",
|
||||
"ws://plain.example.test:7788/v1",
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
gateway_with("voice.example.test", lookups).await.as_deref(),
|
||||
Some("wss://domain.example.test:443/v1")
|
||||
gateways_with("voice.example.test", lookups).await,
|
||||
["wss://domain.example.test:443/v1"]
|
||||
);
|
||||
}
|
||||
|
||||
/// A TLS proxy in front of tsgw and tsgw itself published next to the
|
||||
/// server (and again at the domain): TLS first, the plain one after it,
|
||||
/// once; the gateway's own answer is the plain one again.
|
||||
#[tokio::test]
|
||||
async fn a_tls_proxy_falls_back_to_the_published_plain_gateway() {
|
||||
let lookups = answering(
|
||||
fake(
|
||||
&[
|
||||
("_tsgws._tcp.ts.example.test.", 0, "gw.example.test.", 443),
|
||||
("_tsgw._tcp.ts.example.test.", 0, "ts.example.test.", 7788),
|
||||
("_tsgw._tcp.example.test.", 0, "ts.example.test.", 7788),
|
||||
],
|
||||
&[],
|
||||
),
|
||||
&[("ts.example.test", "ws://ts.example.test:7788/v1")],
|
||||
);
|
||||
assert_eq!(
|
||||
gateways_with("ts.example.test", lookups).await,
|
||||
["wss://gw.example.test:443/v1", "ws://ts.example.test:7788/v1"]
|
||||
);
|
||||
}
|
||||
|
||||
/// A gateway at the domain fronts another server than one of its hosts
|
||||
/// that publishes its own: never a fallback for it, nor the domain's own
|
||||
/// answer.
|
||||
#[tokio::test]
|
||||
async fn another_servers_gateway_is_no_fallback() {
|
||||
let lookups = answering(
|
||||
fake(
|
||||
&[
|
||||
("_tsgws._tcp.ts1.example.test.", 0, "gw1.example.test.", 443),
|
||||
("_tsgw._tcp.ts1.example.test.", 0, "ts1.example.test.", 7788),
|
||||
("_tsgws._tcp.example.test.", 0, "gw-main.example.test.", 443),
|
||||
],
|
||||
&[],
|
||||
),
|
||||
&[("example.test", "ws://main.example.test:7788/v1")],
|
||||
);
|
||||
assert_eq!(
|
||||
gateways_with("ts1.example.test", lookups).await,
|
||||
["wss://gw1.example.test:443/v1", "ws://ts1.example.test:7788/v1"]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_gateways_own_answer_comes_last() {
|
||||
let lookups = answering(
|
||||
fake(&[("_tsgw._tcp.ts.example.test.", 0, "plain.example.test.", 7788)], &[]),
|
||||
&[("ts.example.test", "wss://gw.example.test/v1")],
|
||||
);
|
||||
assert_eq!(
|
||||
gateways_with("ts.example.test", lookups).await,
|
||||
["ws://plain.example.test:7788/v1", "wss://gw.example.test/v1"]
|
||||
);
|
||||
}
|
||||
|
||||
/// The gateway's plain answer is asked with DNS, but not used.
|
||||
#[tokio::test]
|
||||
async fn a_tls_only_publication_is_not_widened() {
|
||||
let lookups = answering(
|
||||
fake(&[("_tsgws._tcp.ts.example.test.", 0, "gw.example.test.", 443)], &[]),
|
||||
&[("ts.example.test", "ws://ts.example.test:7788/v1")],
|
||||
);
|
||||
assert_eq!(
|
||||
gateways_with("ts.example.test", lookups).await,
|
||||
["wss://gw.example.test:443/v1"]
|
||||
);
|
||||
}
|
||||
|
||||
/// `lookups` whose DNS answers take `dns` and the gateway's own `probe`.
|
||||
fn slow(lookups: Lookups, dns: Duration, probe: Duration) -> Lookups {
|
||||
let Lookups { srv, txt, probe: answer } = lookups;
|
||||
Lookups {
|
||||
srv: Arc::new(move |name| {
|
||||
let found = srv(name);
|
||||
async move {
|
||||
tokio::time::sleep(dns).await;
|
||||
found.await
|
||||
}
|
||||
.boxed()
|
||||
}),
|
||||
txt: Arc::new(move |name| {
|
||||
let found = txt(name);
|
||||
async move {
|
||||
tokio::time::sleep(dns).await;
|
||||
found.await
|
||||
}
|
||||
.boxed()
|
||||
}),
|
||||
probe: Arc::new(move |name| {
|
||||
let found = answer(name);
|
||||
async move {
|
||||
tokio::time::sleep(probe).await;
|
||||
found.await
|
||||
}
|
||||
.boxed()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// SRV, TXT and the gateway's own answer are asked at once: a slow
|
||||
/// gateway and slow DNS cost the slower of them, not the sum; an answer
|
||||
/// that is not used is not waited for.
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn everything_is_asked_at_once() {
|
||||
let published = |srv: &[(&str, u16, &str, u16)]| {
|
||||
answering(
|
||||
fake(srv, &[("_tsgw._tcp.ts.example.test.", "path=/gw")]),
|
||||
&[("ts.example.test", "wss://proxy.example.test/v1")],
|
||||
)
|
||||
};
|
||||
let plain = [("_tsgw._tcp.ts.example.test.", 0, "ts.example.test.", 7788)];
|
||||
let (dns, probe) = (Duration::from_millis(400), Duration::from_millis(2500));
|
||||
let started = tokio::time::Instant::now();
|
||||
assert_eq!(
|
||||
gateways_with("ts.example.test", slow(published(&plain), dns, probe)).await,
|
||||
["ws://ts.example.test:7788/gw", "wss://proxy.example.test/v1"]
|
||||
);
|
||||
assert_eq!(started.elapsed().as_millis(), 2500);
|
||||
let started = tokio::time::Instant::now();
|
||||
assert_eq!(
|
||||
gateways_with("ts.example.test", slow(published(&plain), probe, dns)).await,
|
||||
["ws://ts.example.test:7788/gw", "wss://proxy.example.test/v1"]
|
||||
);
|
||||
assert_eq!(started.elapsed().as_millis(), 2500);
|
||||
// TLS only: the gateway's plain answer is not waited for.
|
||||
let tls = [("_tsgws._tcp.ts.example.test.", 0, "gw.example.test.", 443)];
|
||||
let started = tokio::time::Instant::now();
|
||||
assert_eq!(
|
||||
gateways_with("ts.example.test", slow(published(&tls), dns, probe)).await,
|
||||
["wss://gw.example.test:443/v1"]
|
||||
);
|
||||
assert_eq!(started.elapsed().as_millis(), 400);
|
||||
}
|
||||
|
||||
/// Without records, the most specific name's gateway is waited for
|
||||
/// before a parent domain's answer is taken.
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn without_records_the_most_specific_answer_wins() {
|
||||
let mut lookups = fake(&[], &[]);
|
||||
lookups.probe = Arc::new(|name| {
|
||||
async move {
|
||||
match name.as_str() {
|
||||
"ts.example.test" => {
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
Some("ws://ts.example.test:7788/v1".to_owned())
|
||||
}
|
||||
_ => Some("ws://example.test:7788/v1".to_owned()),
|
||||
}
|
||||
}
|
||||
.boxed()
|
||||
});
|
||||
let started = tokio::time::Instant::now();
|
||||
assert_eq!(
|
||||
gateways_with("ts.example.test", lookups).await,
|
||||
["ws://ts.example.test:7788/v1"]
|
||||
);
|
||||
assert_eq!(started.elapsed().as_millis(), 2000);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_record_that_says_no_service_is_skipped() {
|
||||
let lookups = fake(
|
||||
@@ -284,12 +675,8 @@ mod tests {
|
||||
("_tsgw._tcp.example.test.", 0, "gw.example.test.", 80),
|
||||
],
|
||||
&[("_tsgw._tcp.example.test.", "path=ws")],
|
||||
closed_port(),
|
||||
);
|
||||
assert_eq!(
|
||||
gateway_with("ts.example.test", lookups).await.as_deref(),
|
||||
Some("ws://gw.example.test:80/ws")
|
||||
);
|
||||
assert_eq!(gateways_with("ts.example.test", lookups).await, ["ws://gw.example.test:80/ws"]);
|
||||
}
|
||||
|
||||
/// Without records the gateway next to the server answers at its port,
|
||||
@@ -313,16 +700,17 @@ mod tests {
|
||||
socket.write_all(response.as_bytes()).await.unwrap();
|
||||
}
|
||||
});
|
||||
let lookups = fake(&[], &[], port);
|
||||
let lookups = probing(fake(&[], &[]), port);
|
||||
for address in ["127.0.0.1", "127.0.0.1:9987", "localhost"] {
|
||||
assert_eq!(
|
||||
gateway_with(address, lookups.clone()).await.as_deref(),
|
||||
Some("wss://gw.example.test/v1"),
|
||||
gateways_with(address, lookups.clone()).await,
|
||||
["wss://gw.example.test/v1"],
|
||||
"{address}"
|
||||
);
|
||||
}
|
||||
// Nothing there.
|
||||
assert_eq!(gateway_with("127.0.0.1", fake(&[], &[], closed_port())).await, None);
|
||||
let nothing = probing(fake(&[], &[]), closed_port());
|
||||
assert!(gateways_with("127.0.0.1", nothing).await.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -32,13 +32,13 @@
|
||||
//! never downloaded). [`crate::Command::SetAvatar`] uploads our own.
|
||||
|
||||
use std::fmt;
|
||||
use std::future::Future;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde::Serialize;
|
||||
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeekExt, AsyncWrite, AsyncWriteExt};
|
||||
|
||||
/// Picked by the caller; the answer carries it back.
|
||||
pub type RequestId = u64;
|
||||
@@ -106,11 +106,11 @@ impl TransferState {
|
||||
}
|
||||
|
||||
/// Reports a transfer's states.
|
||||
pub(crate) type Report = Arc<dyn Fn(TransferState) + Send + Sync>;
|
||||
pub type Report = Arc<dyn Fn(TransferState) + Send + Sync>;
|
||||
|
||||
/// Where a running download writes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) enum Sink {
|
||||
pub enum Sink {
|
||||
/// Write `part` (appending with `append`), then rename it to `dest`.
|
||||
File {
|
||||
part: PathBuf,
|
||||
@@ -168,9 +168,10 @@ impl Progress<'_> {
|
||||
const CHUNK: usize = 64 * 1024;
|
||||
|
||||
/// Receive a file: `size` bytes in total, `offset` of them already in the
|
||||
/// sink. Reports `Started`, `Progress` and the final state.
|
||||
pub(crate) async fn download(
|
||||
mut stream: TcpStream,
|
||||
/// sink; `stream` carries the rest. Reports `Started`, `Progress` and the
|
||||
/// final state.
|
||||
pub(crate) async fn download<R: AsyncRead + Unpin>(
|
||||
mut stream: R,
|
||||
size: u64,
|
||||
offset: u64,
|
||||
sink: Sink,
|
||||
@@ -185,8 +186,8 @@ pub(crate) async fn download(
|
||||
});
|
||||
}
|
||||
|
||||
async fn receive(
|
||||
stream: &mut TcpStream,
|
||||
async fn receive<R: AsyncRead + Unpin>(
|
||||
stream: &mut R,
|
||||
size: u64,
|
||||
offset: u64,
|
||||
sink: &Sink,
|
||||
@@ -253,26 +254,34 @@ async fn receive(
|
||||
}
|
||||
}
|
||||
|
||||
/// Send `file` from `offset` (`size` bytes in total). Reports `Started`,
|
||||
/// `Progress` and the final state.
|
||||
pub(crate) async fn upload(
|
||||
mut stream: TcpStream,
|
||||
/// Send `file` from `offset` (`size` bytes in total) into `writer`, then end
|
||||
/// it and wait for `stored`, which resolves once the server has the file.
|
||||
/// Reports `Started`, `Progress` and the final state.
|
||||
pub(crate) async fn upload_to<W, F>(
|
||||
mut writer: W,
|
||||
stored: F,
|
||||
file: PathBuf,
|
||||
size: u64,
|
||||
offset: u64,
|
||||
progress_every: Duration,
|
||||
report: Report,
|
||||
) {
|
||||
) where
|
||||
W: AsyncWrite + Unpin,
|
||||
F: Future<Output = Result<(), String>>,
|
||||
{
|
||||
report(TransferState::Started { size, offset });
|
||||
let result = send(&mut stream, &file, size, offset, progress_every, &report).await;
|
||||
let result = match send(&mut writer, &file, size, offset, progress_every, &report).await {
|
||||
Ok(()) => stored.await,
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
report(match result {
|
||||
Ok(()) => TransferState::Done { size, path: Some(file), data: None },
|
||||
Err(e) => TransferState::Failed(e),
|
||||
});
|
||||
}
|
||||
|
||||
async fn send(
|
||||
stream: &mut TcpStream,
|
||||
async fn send<W: AsyncWrite + Unpin>(
|
||||
stream: &mut W,
|
||||
path: &Path,
|
||||
size: u64,
|
||||
offset: u64,
|
||||
@@ -300,8 +309,6 @@ async fn send(
|
||||
}
|
||||
stream.flush().await.map_err(|e| e.to_string())?;
|
||||
stream.shutdown().await.map_err(|e| e.to_string())?;
|
||||
// The server closes the connection once it has everything.
|
||||
let _ = tokio::time::timeout(Duration::from_secs(30), stream.read(&mut buf[..1])).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -421,7 +428,7 @@ fn percent_decode(text: &str) -> Option<String> {
|
||||
mod tests {
|
||||
use std::sync::Mutex;
|
||||
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -562,7 +569,8 @@ mod tests {
|
||||
});
|
||||
let (report, states) = recorder();
|
||||
let stream = TcpStream::connect(addr).await.unwrap();
|
||||
upload(stream, file.clone(), 10, 4, Duration::ZERO, report).await;
|
||||
let (_, write) = tokio::io::split(stream);
|
||||
upload_to(write, async { Ok(()) }, file.clone(), 10, 4, Duration::ZERO, report).await;
|
||||
assert_eq!(server.await.unwrap(), b"456789");
|
||||
assert!(matches!(states.lock().unwrap().last(), Some(TransferState::Done { .. })));
|
||||
assert_eq!(md5_file(&file).unwrap(), "781e5e245d69b566979b86e28d23f2c7");
|
||||
|
||||
@@ -38,17 +38,30 @@
|
||||
//! and is removed when it ends. The directory is also where the session's
|
||||
//! streams look for streams that started before we joined, next to the
|
||||
//! server's `requeststreaminfo`.
|
||||
//!
|
||||
//! A gateway that cannot be reached, or cannot log us in yet (the server
|
||||
//! does not know the identity before voice connected once; its server is
|
||||
//! restarting), is tried again by itself: after 1, 2, 5, 10, 20, then every
|
||||
//! 30 s, give or take 30 %, and at once when voice connects. Only a refused
|
||||
//! login (signature, security level, ban, not allowed) ends it. A connection
|
||||
//! is pinged every 30 s and left after 60 s without an answer. All of it is
|
||||
//! logged (target `voelin_core::gateway`), never shown.
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use futures::future::{Fuse, FusedFuture, FutureExt};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::info;
|
||||
use voelin_gateway_proto::client::Login;
|
||||
use tracing::{debug, info, warn};
|
||||
pub use voelin_gateway_proto::client::{ClientError, GatewayClient, Push};
|
||||
use voelin_gateway_proto::client::{Login, Progress};
|
||||
use voelin_gateway_proto::{
|
||||
Action, ActivityEntry, ClientMsg, ConfigEntry, ErrorCode, EventInfo, EventQuery, EventSpec,
|
||||
HistoryEntry, HistoryQuery, PermRule, PermRuleInfo, PinInfo, RsvpStatus, StreamEntry,
|
||||
StreamSpec, TopicInfo, UserRef,
|
||||
};
|
||||
use voelin_identity::IdentityBlob;
|
||||
use voelin_model::{ChannelId, ChatTarget, Presence};
|
||||
use voelin_store::WriteOutcome;
|
||||
|
||||
@@ -59,39 +72,349 @@ pub(crate) enum GatewayCmd {
|
||||
OpenChat(ChatTarget),
|
||||
CloseChat(ChatTarget),
|
||||
SendChat(ChatTarget, String),
|
||||
/// Waiting for the next attempt: make it now (voice connected, which
|
||||
/// makes the identity known to the server; the server was selected
|
||||
/// again). Nothing while connected.
|
||||
RetryNow,
|
||||
Stop,
|
||||
}
|
||||
|
||||
pub(crate) enum GatewayEvent {
|
||||
/// Logged in; requests go through `client`.
|
||||
Connected(GatewayClient),
|
||||
/// Logged in at the URL; requests go through the client.
|
||||
Connected(GatewayClient, String),
|
||||
Presence(Box<Presence>),
|
||||
/// A push other than presence.
|
||||
Push(Box<Push>),
|
||||
/// The gateway could not be reached, or the connection was lost; the
|
||||
/// next attempt follows by itself.
|
||||
Retrying(String),
|
||||
/// Stopped, or the gateway refused the login (the reason).
|
||||
Disconnected(Option<String>),
|
||||
}
|
||||
|
||||
/// Connect to a gateway (`ws://…/v1` or `wss://…/v1`) and log in with a
|
||||
/// TeamSpeak identity.
|
||||
pub async fn connect(
|
||||
url: &str,
|
||||
identity: &tsclientlib::Identity,
|
||||
) -> Result<(GatewayClient, mpsc::UnboundedReceiver<Push>), ClientError> {
|
||||
let login = Login::Identity { key: identity.key().clone(), key_offset: identity.counter() };
|
||||
voelin_gateway_proto::client::connect(url, login).await
|
||||
/// The TeamSpeak identity of a blob, or why a gateway cannot be logged in to
|
||||
/// with it.
|
||||
fn login_identity(blob: &IdentityBlob) -> Result<tsclientlib::Identity, String> {
|
||||
crate::ts::identity::from_blob(blob).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Connect to a gateway (`ws://…/v1` or `wss://…/v1`) and log in with a
|
||||
/// TeamSpeak identity (a blob of kind `teamspeak`, see
|
||||
/// [`crate::ts::identity::to_blob`]; one that is none is refused as
|
||||
/// [`ErrorCode::AuthFailed`], the way the gateway would).
|
||||
pub async fn connect(
|
||||
url: &str,
|
||||
identity: &IdentityBlob,
|
||||
) -> Result<(GatewayClient, mpsc::UnboundedReceiver<Push>), ClientError> {
|
||||
let identity = login_identity(identity)
|
||||
.map_err(|message| ClientError::Gateway { code: ErrorCode::AuthFailed, message })?;
|
||||
connect_watched(url, &identity, &Progress::default()).await
|
||||
}
|
||||
|
||||
/// [`connect`], telling `progress` each step (for the log).
|
||||
async fn connect_watched(
|
||||
url: &str,
|
||||
identity: &tsclientlib::Identity,
|
||||
progress: &Progress,
|
||||
) -> Result<(GatewayClient, mpsc::UnboundedReceiver<Push>), ClientError> {
|
||||
let login = Login::Identity { key: identity.key().clone(), key_offset: identity.counter() };
|
||||
voelin_gateway_proto::client::connect_watched(url, login, progress).await
|
||||
}
|
||||
|
||||
/// Observe through the first of `urls` (best first, as published) that
|
||||
/// logs in.
|
||||
pub(crate) async fn run(
|
||||
url: String,
|
||||
identity: tsclientlib::Identity,
|
||||
mut urls: Vec<String>,
|
||||
identity: IdentityBlob,
|
||||
mut commands: mpsc::UnboundedReceiver<GatewayCmd>,
|
||||
events: mpsc::UnboundedSender<GatewayEvent>,
|
||||
) {
|
||||
let reason =
|
||||
run_inner(&url, &identity, &mut commands, &events).await.err().map(|e| e.to_string());
|
||||
// An identity that cannot be read will not be tomorrow: like a refused login.
|
||||
let identity = match login_identity(&identity) {
|
||||
Ok(identity) => identity,
|
||||
Err(reason) => {
|
||||
debug!(%reason, "gateway: the identity cannot be read");
|
||||
let _ = events.send(GatewayEvent::Disconnected(Some(reason)));
|
||||
return;
|
||||
}
|
||||
};
|
||||
// A gateway that is away (down, restarting, a network change, a proxy
|
||||
// in front of it that fails) or cannot log us in yet (it does not know
|
||||
// the identity before voice connected once, its server is restarting)
|
||||
// is tried again until the session stops observing; only a refused
|
||||
// login ends it. A round tries every URL in turn without waiting; only
|
||||
// a round that fails waits.
|
||||
debug!(?urls, "gateway: starting");
|
||||
let mut chats = Chats::default();
|
||||
let mut failures = 0;
|
||||
let mut told = Told::default();
|
||||
// Why the last failed round failed.
|
||||
let mut last_round: Option<String> = None;
|
||||
// Attempts since observing started or the connection was lost.
|
||||
let (mut attempts, mut since) = (0, Instant::now());
|
||||
let reason = 'observe: loop {
|
||||
let mut lost = None;
|
||||
let mut index = 0;
|
||||
while index < urls.len() {
|
||||
attempts += 1;
|
||||
let url = urls[index].clone();
|
||||
let next = urls.get(index + 1).map(String::as_str);
|
||||
debug!(%url, attempt = attempts, "gateway: trying");
|
||||
let at = Try { url: &url, number: attempts, since, next };
|
||||
match attempt(&at, &identity, &mut commands, &events, &mut chats, &mut told).await {
|
||||
Ended::Stopped => break 'observe None,
|
||||
Ended::Refused(reason) => break 'observe Some(reason),
|
||||
Ended::Lost { reason, logged_in } => {
|
||||
lost = Some(reason);
|
||||
if logged_in {
|
||||
// It worked: it is tried first again, after a wait.
|
||||
urls[..=index].rotate_right(1);
|
||||
failures = 0;
|
||||
(attempts, since) = (0, Instant::now());
|
||||
break;
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(reason) = lost else { break None };
|
||||
failures += 1;
|
||||
let delay = retry_delay(failures, jitter());
|
||||
// Past the longest wait, the same cause again is not news (a server
|
||||
// only observed, never joined, cannot log us in at all).
|
||||
let wait = delay.as_secs_f64();
|
||||
if failures as usize > RETRY_SECONDS.len() && last_round.as_ref() == Some(&reason) {
|
||||
debug!(failures, error = %reason, "gateway: trying again in {wait:.1} s");
|
||||
} else {
|
||||
info!(failures, error = %reason, "gateway: trying again in {wait:.1} s");
|
||||
}
|
||||
last_round = Some(reason.clone());
|
||||
let _ = events.send(GatewayEvent::Retrying(reason));
|
||||
if !chats.wait(delay, &mut commands).await {
|
||||
break None;
|
||||
}
|
||||
};
|
||||
debug!(?reason, "gateway: stopped");
|
||||
let _ = events.send(GatewayEvent::Disconnected(reason));
|
||||
}
|
||||
|
||||
/// How one connection to the gateway ended.
|
||||
enum Ended {
|
||||
/// The session stopped observing.
|
||||
Stopped,
|
||||
/// The gateway refused the login: trying again would not help.
|
||||
Refused(String),
|
||||
/// Not reached, not logged in yet, or lost (after logging in): try
|
||||
/// again.
|
||||
Lost { reason: String, logged_in: bool },
|
||||
}
|
||||
|
||||
/// Login errors that trying again does not change: the identity or the
|
||||
/// user is not allowed. Anything else (the gateway's server away, an
|
||||
/// identity voice has not made known yet, too many logins) passes.
|
||||
fn refused(code: ErrorCode) -> bool {
|
||||
matches!(
|
||||
code,
|
||||
ErrorCode::AuthFailed | ErrorCode::LevelTooLow | ErrorCode::Banned | ErrorCode::Forbidden
|
||||
)
|
||||
}
|
||||
|
||||
/// One attempt of [`run`], for the log.
|
||||
struct Try<'a> {
|
||||
url: &'a str,
|
||||
/// Since observing started, or the connection was lost; 1 first.
|
||||
number: u32,
|
||||
/// When observing started, or the connection was lost.
|
||||
since: Instant,
|
||||
/// The URL tried next in this round if this one fails.
|
||||
next: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// What was logged per URL: each cause once while it lasts (until a login
|
||||
/// works), not at every attempt of a long absence.
|
||||
#[derive(Default)]
|
||||
struct Told(Vec<(String, String)>);
|
||||
|
||||
impl Told {
|
||||
/// Whether `url` failing with `cause` is news.
|
||||
fn news(&mut self, url: &str, cause: &str) -> bool {
|
||||
if self.0.iter().any(|(u, c)| u == url && c == cause) {
|
||||
return false;
|
||||
}
|
||||
self.0.retain(|(u, _)| u != url);
|
||||
self.0.push((url.to_owned(), cause.to_owned()));
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// One attempt to reach a gateway and log in (TCP, TLS, the WebSocket
|
||||
/// upgrade, the login's own queries at the gateway) gives up after this
|
||||
/// long, so a gateway that never answers does not hold up the next one.
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
|
||||
|
||||
/// The waits after failed rounds in a row, the last one repeated.
|
||||
const RETRY_SECONDS: [u64; 6] = [1, 2, 5, 10, 20, 30];
|
||||
|
||||
/// The wait before the next attempt after `failures` failed rounds in a
|
||||
/// row, give or take 30 % (`jitter`, -1 to 1): clients that lost the same
|
||||
/// gateway do not all come back at the same moment.
|
||||
fn retry_delay(failures: u32, jitter: f64) -> Duration {
|
||||
let index = (failures.max(1) as usize - 1).min(RETRY_SECONDS.len() - 1);
|
||||
Duration::from_secs(RETRY_SECONDS[index]).mul_f64(1.0 + 0.3 * jitter.clamp(-1.0, 1.0))
|
||||
}
|
||||
|
||||
/// A number from -1 to 1, another each time: the standard library's
|
||||
/// randomly keyed hasher over a counter and the clock.
|
||||
fn jitter() -> f64 {
|
||||
use std::hash::{BuildHasher, Hasher};
|
||||
static COUNT: AtomicU64 = AtomicU64::new(0);
|
||||
let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
|
||||
hasher.write_u64(COUNT.fetch_add(1, Ordering::Relaxed));
|
||||
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH);
|
||||
hasher.write_u128(now.unwrap_or_default().as_nanos());
|
||||
(hasher.finish() >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0
|
||||
}
|
||||
|
||||
/// Asking a gateway that is still connecting to try again at once, at most
|
||||
/// this often ([`Observed::nudge`]): selecting servers does not hammer a
|
||||
/// struggling gateway.
|
||||
const NUDGE_EVERY: Duration = Duration::from_secs(5);
|
||||
|
||||
/// What a session's gateway observes with, so that asking again for the
|
||||
/// same ([`crate::Command::ObserveGateway`], e.g. the server selected again)
|
||||
/// does not start it over, at most makes it try again sooner.
|
||||
pub(crate) struct Observed {
|
||||
urls: Vec<String>,
|
||||
/// The identity's public key.
|
||||
key: String,
|
||||
/// The identity's counter, which the login sends: a raised security
|
||||
/// level keeps the key and changes only this.
|
||||
counter: u64,
|
||||
nudged: Option<Instant>,
|
||||
}
|
||||
|
||||
impl Observed {
|
||||
pub(crate) fn new(urls: &[String], identity: &IdentityBlob) -> Self {
|
||||
let (key, counter) = Self::of(identity);
|
||||
Self { urls: urls.to_vec(), key, counter, nudged: None }
|
||||
}
|
||||
|
||||
/// The public key and the counter of an identity: an identity that cannot be
|
||||
/// read has neither (and so is the same as any other that cannot).
|
||||
fn of(identity: &IdentityBlob) -> (String, u64) {
|
||||
match login_identity(identity) {
|
||||
Ok(identity) => (identity.key().to_pub().to_ts(), identity.counter()),
|
||||
Err(_) => (String::new(), 0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this is what is observed with.
|
||||
pub(crate) fn same(&self, urls: &[String], identity: &IdentityBlob) -> bool {
|
||||
let (key, counter) = Self::of(identity);
|
||||
self.urls == urls && self.counter == counter && self.key == key
|
||||
}
|
||||
|
||||
/// Whether to try again now ([`GatewayCmd::RetryNow`]): not twice
|
||||
/// within [`NUDGE_EVERY`].
|
||||
pub(crate) fn nudge(&mut self) -> bool {
|
||||
self.nudge_at(Instant::now())
|
||||
}
|
||||
|
||||
fn nudge_at(&mut self, now: Instant) -> bool {
|
||||
if self.nudged.is_some_and(|at| now.saturating_duration_since(at) < NUDGE_EVERY) {
|
||||
return false;
|
||||
}
|
||||
self.nudged = Some(now);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Messages written while the gateway is away, at most this many, go out
|
||||
/// when it is back.
|
||||
const MAX_UNSENT: usize = 64;
|
||||
|
||||
/// What a new connection restores: the chats open at the gateway, and
|
||||
/// messages written while it was away.
|
||||
#[derive(Default)]
|
||||
struct Chats {
|
||||
open: Vec<ChatTarget>,
|
||||
unsent: Vec<(ChatTarget, String)>,
|
||||
}
|
||||
|
||||
impl Chats {
|
||||
/// Note a chat command; it goes out when connected.
|
||||
fn note(&mut self, cmd: GatewayCmd) {
|
||||
match cmd {
|
||||
GatewayCmd::OpenChat(target) => {
|
||||
if !self.open.contains(&target) {
|
||||
self.open.push(target);
|
||||
}
|
||||
}
|
||||
GatewayCmd::CloseChat(target) => self.open.retain(|open| *open != target),
|
||||
GatewayCmd::SendChat(target, text) => {
|
||||
if self.unsent.len() < MAX_UNSENT {
|
||||
self.unsent.push((target, text));
|
||||
}
|
||||
}
|
||||
GatewayCmd::RetryNow | GatewayCmd::Stop => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Carry out a chat command on a connected gateway.
|
||||
fn apply(&mut self, client: &GatewayClient, cmd: GatewayCmd) -> Result<(), ClientError> {
|
||||
match cmd {
|
||||
GatewayCmd::OpenChat(target) => {
|
||||
if !self.open.contains(&target) {
|
||||
self.open.push(target.clone());
|
||||
}
|
||||
client.send(ClientMsg::OpenChat { target })
|
||||
}
|
||||
GatewayCmd::CloseChat(target) => {
|
||||
self.open.retain(|open| *open != target);
|
||||
client.send(ClientMsg::CloseChat { target })
|
||||
}
|
||||
GatewayCmd::SendChat(target, text) => client.send(ClientMsg::SendChat { target, text }),
|
||||
GatewayCmd::RetryNow | GatewayCmd::Stop => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the chats again on a new connection and send what waited.
|
||||
fn restore(&mut self, client: &GatewayClient) -> Result<(), ClientError> {
|
||||
for target in &self.open {
|
||||
client.send(ClientMsg::OpenChat { target: target.clone() })?;
|
||||
}
|
||||
for (target, text) in std::mem::take(&mut self.unsent) {
|
||||
client.send(ClientMsg::SendChat { target, text })?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Wait `delay` before the next attempt, noting the commands that come
|
||||
/// meanwhile, or until told to try now; false when the session stops
|
||||
/// observing.
|
||||
async fn wait(
|
||||
&mut self,
|
||||
delay: Duration,
|
||||
commands: &mut mpsc::UnboundedReceiver<GatewayCmd>,
|
||||
) -> bool {
|
||||
let sleep = tokio::time::sleep(delay);
|
||||
tokio::pin!(sleep);
|
||||
loop {
|
||||
tokio::select! {
|
||||
() = &mut sleep => return true,
|
||||
cmd = commands.recv() => match cmd {
|
||||
None | Some(GatewayCmd::Stop) => return false,
|
||||
Some(GatewayCmd::RetryNow) => {
|
||||
debug!("gateway: trying again now");
|
||||
return true;
|
||||
}
|
||||
Some(cmd) => self.note(cmd),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Features whose pushes for open chats need [`ClientMsg::Enable`].
|
||||
const CHAT_EXTENSIONS: [&str; 4] = [
|
||||
voelin_gateway_proto::feature::HISTORY,
|
||||
@@ -100,38 +423,155 @@ const CHAT_EXTENSIONS: [&str; 4] = [
|
||||
voelin_gateway_proto::feature::TOPICS,
|
||||
];
|
||||
|
||||
async fn run_inner(
|
||||
url: &str,
|
||||
/// One connection: log in, then relay until it ends.
|
||||
async fn attempt(
|
||||
at: &Try<'_>,
|
||||
identity: &tsclientlib::Identity,
|
||||
commands: &mut mpsc::UnboundedReceiver<GatewayCmd>,
|
||||
events: &mpsc::UnboundedSender<GatewayEvent>,
|
||||
) -> anyhow::Result<()> {
|
||||
let (client, mut pushes) = match connect(url, identity).await {
|
||||
Ok(connected) => connected,
|
||||
Err(ClientError::Gateway { code, message }) => {
|
||||
let _ = events
|
||||
.send(GatewayEvent::Push(Box::new(Push::Error { code, message: message.clone() })));
|
||||
anyhow::bail!("gateway refused login: {message}");
|
||||
chats: &mut Chats,
|
||||
told: &mut Told,
|
||||
) -> Ended {
|
||||
let url = at.url;
|
||||
let lost = |reason: String| Ended::Lost { reason, logged_in: false };
|
||||
let progress = Progress::default();
|
||||
let started = Instant::now();
|
||||
let result =
|
||||
tokio::time::timeout(CONNECT_TIMEOUT, connect_watched(url, identity, &progress)).await;
|
||||
let elapsed_ms = started.elapsed().as_millis() as u64;
|
||||
let (stage, peer) = (progress.stage(), progress.peer_addr());
|
||||
let (client, mut pushes) = match result {
|
||||
Ok(Ok(connected)) => connected,
|
||||
Ok(Err(ClientError::Gateway { code, message })) if refused(code) => {
|
||||
warn!(%url, ?code, %message, "gateway refused the login");
|
||||
return Ended::Refused(format!("gateway refused login: {code:?}: {message}"));
|
||||
}
|
||||
// Observing starts before voice: on a server we never joined, the
|
||||
// first login cannot work. Voice connecting makes it try again.
|
||||
Ok(Err(ClientError::Gateway { code: ErrorCode::UnknownIdentity, message })) => {
|
||||
if told.news(url, "unknown identity") {
|
||||
info!(%url, elapsed_ms, "the server does not know this identity yet (voice connects it); trying again");
|
||||
} else {
|
||||
debug!(%url, elapsed_ms, "the server does not know this identity yet");
|
||||
}
|
||||
return lost(format!("UnknownIdentity: {message}"));
|
||||
}
|
||||
Ok(Err(ClientError::Gateway { code, message })) => {
|
||||
if told.news(url, &format!("{code:?}")) {
|
||||
warn!(%url, ?code, %message, elapsed_ms, next = ?at.next, "gateway did not log us in; trying again");
|
||||
} else {
|
||||
debug!(%url, ?code, %message, elapsed_ms, "gateway still does not log us in");
|
||||
}
|
||||
return lost(format!("{code:?}: {message}"));
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
let reason = e.to_string();
|
||||
if told.news(url, &reason) {
|
||||
warn!(%url, %stage, ?peer, steps = %progress, elapsed_ms, error = %reason, next = ?at.next, "gateway unreachable");
|
||||
} else {
|
||||
debug!(%url, %stage, steps = %progress, elapsed_ms, error = %reason, "gateway still unreachable");
|
||||
}
|
||||
return lost(reason);
|
||||
}
|
||||
Err(_) => {
|
||||
let reason = format!("no answer within {} s ({stage})", CONNECT_TIMEOUT.as_secs());
|
||||
if told.news(url, &reason) {
|
||||
warn!(%url, %stage, ?peer, steps = %progress, elapsed_ms, next = ?at.next, "gateway unreachable: {reason}");
|
||||
} else {
|
||||
debug!(%url, %stage, steps = %progress, elapsed_ms, "gateway still unreachable: {reason}");
|
||||
}
|
||||
return lost(reason);
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
info!(server_name = %client.info().server_name, capabilities = ?client.capabilities(), "gateway connected");
|
||||
*told = Told::default();
|
||||
info!(
|
||||
%url,
|
||||
attempt = at.number,
|
||||
connect_ms = elapsed_ms,
|
||||
since_start_ms = at.since.elapsed().as_millis() as u64,
|
||||
server = %client.info().server_name,
|
||||
?peer,
|
||||
steps = %progress,
|
||||
capabilities = ?client.capabilities(),
|
||||
"gateway connected"
|
||||
);
|
||||
let connected = Instant::now();
|
||||
let reason = match relay(url, &client, &mut pushes, commands, events, chats, connected).await {
|
||||
Ok(Ended::Lost { reason, .. }) => reason,
|
||||
Ok(ended) => {
|
||||
debug!(%url, connected_for_s = connected.elapsed().as_secs(), "gateway: left");
|
||||
return ended;
|
||||
}
|
||||
Err(e) => e.to_string(),
|
||||
};
|
||||
warn!(%url, connected_for_s = connected.elapsed().as_secs(), error = %reason, "gateway connection lost");
|
||||
Ended::Lost { reason, logged_in: true }
|
||||
}
|
||||
|
||||
/// A connection is checked this often while nothing else asks the gateway
|
||||
/// anything ([`ClientMsg::Ping`])…
|
||||
const PING_EVERY: Duration = Duration::from_secs(30);
|
||||
/// …and taken as lost without an answer within this long (the gateway
|
||||
/// answers in turn, after requests that can take a while).
|
||||
const PING_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Whether the gateway still answers: a ping, answered in time.
|
||||
async fn alive(client: &GatewayClient) -> Result<(), String> {
|
||||
match tokio::time::timeout(PING_TIMEOUT, client.request(ClientMsg::Ping)).await {
|
||||
// Any answer will do, also an error from an older gateway.
|
||||
Ok(Ok(_) | Err(ClientError::Gateway { .. })) => Ok(()),
|
||||
Ok(Err(e)) => Err(e.to_string()),
|
||||
Err(_) => Err(format!("no answer to a ping within {} s", PING_TIMEOUT.as_secs())),
|
||||
}
|
||||
}
|
||||
|
||||
async fn relay(
|
||||
url: &str,
|
||||
client: &GatewayClient,
|
||||
pushes: &mut mpsc::UnboundedReceiver<Push>,
|
||||
commands: &mut mpsc::UnboundedReceiver<GatewayCmd>,
|
||||
events: &mpsc::UnboundedSender<GatewayEvent>,
|
||||
chats: &mut Chats,
|
||||
connected: Instant,
|
||||
) -> Result<Ended, ClientError> {
|
||||
let lost = |reason: String| Ended::Lost { reason, logged_in: true };
|
||||
// Messages with their gateway ids, pins, reactions and topics of open
|
||||
// chats (older gateways answer `unknown_type` as a push; ignored).
|
||||
if CHAT_EXTENSIONS.iter().any(|f| client.has(f)) {
|
||||
client.send(ClientMsg::Enable { features: Vec::new() })?;
|
||||
}
|
||||
let _ = events.send(GatewayEvent::Connected(client.clone()));
|
||||
let _ = events.send(GatewayEvent::Connected(client.clone(), url.to_owned()));
|
||||
client.subscribe_presence()?;
|
||||
chats.restore(client)?;
|
||||
let mut presence = Presence::default();
|
||||
let mut synced = false;
|
||||
// A connection that died without closing (a network change, sleep, a
|
||||
// NAT that forgot it) shows only when the gateway stops answering.
|
||||
let start = tokio::time::Instant::now() + PING_EVERY;
|
||||
let mut keepalive = tokio::time::interval_at(start, PING_EVERY);
|
||||
keepalive.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
||||
let ping = Fuse::terminated();
|
||||
tokio::pin!(ping);
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
push = pushes.recv() => match push {
|
||||
None | Some(Push::Disconnected(None)) => return Ok(()),
|
||||
Some(Push::Disconnected(Some(reason))) => anyhow::bail!(reason),
|
||||
None | Some(Push::Disconnected(None)) => {
|
||||
return Ok(lost("the gateway closed the connection".into()));
|
||||
}
|
||||
Some(Push::Disconnected(Some(reason))) => return Ok(lost(reason)),
|
||||
Some(Push::PresenceSnapshot(snapshot)) => {
|
||||
presence = Presence::from_snapshot(snapshot);
|
||||
if !synced {
|
||||
synced = true;
|
||||
info!(
|
||||
%url,
|
||||
channels = presence.channels.len(),
|
||||
clients = presence.clients.len(),
|
||||
since_connect_ms = connected.elapsed().as_millis() as u64,
|
||||
"gateway presence"
|
||||
);
|
||||
}
|
||||
let _ = events.send(GatewayEvent::Presence(Box::new(presence.clone())));
|
||||
}
|
||||
Some(Push::PresenceDelta(delta)) => {
|
||||
@@ -140,25 +580,24 @@ async fn run_inner(
|
||||
}
|
||||
// Answers to requests sent without waiting.
|
||||
Some(Push::Other(_) | Push::Error { code: ErrorCode::UnknownType, .. }) => {}
|
||||
// The gateway forgot the login (restarted): log in again.
|
||||
Some(Push::Error { code: ErrorCode::NotAuthenticated, message }) => {
|
||||
let _ = events.send(GatewayEvent::Push(Box::new(Push::Error {
|
||||
code: ErrorCode::NotAuthenticated,
|
||||
message: message.clone(),
|
||||
})));
|
||||
anyhow::bail!("gateway session lost: {message}");
|
||||
return Ok(lost(format!("gateway session lost: {message}")));
|
||||
}
|
||||
Some(push) => {
|
||||
let _ = events.send(GatewayEvent::Push(Box::new(push)));
|
||||
}
|
||||
},
|
||||
cmd = commands.recv() => match cmd {
|
||||
None | Some(GatewayCmd::Stop) => return Ok(()),
|
||||
Some(GatewayCmd::OpenChat(target)) => client.send(ClientMsg::OpenChat { target })?,
|
||||
Some(GatewayCmd::CloseChat(target)) => client.send(ClientMsg::CloseChat { target })?,
|
||||
Some(GatewayCmd::SendChat(target, text)) => {
|
||||
client.send(ClientMsg::SendChat { target, text })?;
|
||||
}
|
||||
None | Some(GatewayCmd::Stop) => return Ok(Ended::Stopped),
|
||||
Some(cmd) => chats.apply(client, cmd)?,
|
||||
},
|
||||
_ = keepalive.tick(), if ping.is_terminated() => ping.set(alive(client).fuse()),
|
||||
answer = &mut ping => {
|
||||
if let Err(reason) = answer {
|
||||
return Ok(lost(reason));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -388,6 +827,8 @@ pub struct Pin {
|
||||
pub enum GatewayUpdate {
|
||||
/// Logged in.
|
||||
Connected {
|
||||
/// Where: the first of the published URLs that logged in.
|
||||
url: String,
|
||||
gateway_id: String,
|
||||
server_uid: String,
|
||||
server_name: String,
|
||||
@@ -733,3 +1174,195 @@ pub(crate) struct ReactionPush {
|
||||
pub added: bool,
|
||||
pub count: u32,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
|
||||
use futures::{SinkExt, StreamExt};
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use voelin_gateway_proto::{Envelope, ServerMsg};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn millis(d: Duration) -> u64 {
|
||||
(d.as_secs_f64() * 1000.0).round() as u64
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retries_come_soon_then_every_30_s_spread() {
|
||||
let seconds: Vec<u64> = (0..=8).map(|n| retry_delay(n, 0.0).as_secs()).collect();
|
||||
assert_eq!(seconds, [1, 1, 2, 5, 10, 20, 30, 30, 30]);
|
||||
// Give or take 30 %.
|
||||
assert_eq!(millis(retry_delay(1, -1.0)), 700);
|
||||
assert_eq!(millis(retry_delay(1, 1.0)), 1300);
|
||||
assert_eq!(millis(retry_delay(6, 1.0)), 39_000);
|
||||
assert_eq!(millis(retry_delay(3, 7.0)), millis(retry_delay(3, 1.0)));
|
||||
let samples: Vec<f64> = (0..1000).map(|_| jitter()).collect();
|
||||
assert!(samples.iter().all(|j| (-1.0..1.0).contains(j)), "{samples:?}");
|
||||
assert!(samples.iter().any(|j| *j < -0.5) && samples.iter().any(|j| *j > 0.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_observation_is_nudged_at_most_every_5_s() {
|
||||
let blob = crate::ts::identity::to_blob;
|
||||
let identity = tsclientlib::Identity::create();
|
||||
let urls = vec!["ws://gw.example.test:7788/v1".to_owned()];
|
||||
let mut observed = Observed::new(&urls, &blob(&identity));
|
||||
assert!(observed.same(&urls, &blob(&identity)));
|
||||
assert!(!observed.same(&["wss://gw.example.test/v1".to_owned()], &blob(&identity)));
|
||||
assert!(!observed.same(&urls, &blob(&tsclientlib::Identity::create())));
|
||||
// Its security level raised: logged in with the new counter.
|
||||
let raised = tsclientlib::Identity::new(identity.key().clone(), identity.counter() + 1);
|
||||
assert!(!observed.same(&urls, &blob(&raised)));
|
||||
let now = Instant::now();
|
||||
assert!(observed.nudge_at(now));
|
||||
assert!(!observed.nudge_at(now + Duration::from_secs(4)));
|
||||
assert!(observed.nudge_at(now + NUDGE_EVERY));
|
||||
assert!(!observed.nudge_at(now + NUDGE_EVERY + Duration::from_secs(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_some_login_errors_are_final() {
|
||||
use ErrorCode as E;
|
||||
for code in [E::AuthFailed, E::LevelTooLow, E::Banned, E::Forbidden] {
|
||||
assert!(refused(code), "{code:?}");
|
||||
}
|
||||
for code in [
|
||||
E::Unavailable,
|
||||
E::Internal,
|
||||
E::RateLimited,
|
||||
E::UnknownIdentity,
|
||||
E::NotAuthenticated,
|
||||
E::BadRequest,
|
||||
E::Unknown,
|
||||
] {
|
||||
assert!(!refused(code), "{code:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn retry_now_ends_the_wait() {
|
||||
let (tx, mut rx) = mpsc::unbounded_channel();
|
||||
let mut chats = Chats::default();
|
||||
let start = tokio::time::Instant::now();
|
||||
// What comes meanwhile is noted; RetryNow ends the wait at once.
|
||||
tx.send(GatewayCmd::OpenChat(ChatTarget::Channel(1))).unwrap();
|
||||
tx.send(GatewayCmd::RetryNow).unwrap();
|
||||
assert!(chats.wait(Duration::from_secs(30), &mut rx).await);
|
||||
assert_eq!(start.elapsed(), Duration::ZERO);
|
||||
assert_eq!(chats.open, [ChatTarget::Channel(1)]);
|
||||
// Told 3 s into a wait of 30.
|
||||
let told = tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_secs(3)).await;
|
||||
tx.send(GatewayCmd::RetryNow).unwrap();
|
||||
tx
|
||||
});
|
||||
assert!(chats.wait(Duration::from_secs(30), &mut rx).await);
|
||||
assert_eq!(millis(start.elapsed()), 3000);
|
||||
let tx = told.await.unwrap();
|
||||
// Not told: the whole wait.
|
||||
assert!(chats.wait(Duration::from_secs(30), &mut rx).await);
|
||||
assert_eq!(millis(start.elapsed()), 33_000);
|
||||
tx.send(GatewayCmd::Stop).unwrap();
|
||||
assert!(!chats.wait(Duration::from_secs(30), &mut rx).await);
|
||||
}
|
||||
|
||||
/// A logged-in client of a gateway on an in-memory connection that
|
||||
/// answers pings when `pings`; counts the pings.
|
||||
async fn gateway(
|
||||
pings: bool,
|
||||
) -> (GatewayClient, mpsc::UnboundedReceiver<Push>, Arc<AtomicUsize>) {
|
||||
let (near, far) = tokio::io::duplex(64 * 1024);
|
||||
let count = Arc::new(AtomicUsize::new(0));
|
||||
let counted = count.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut ws = tokio_tungstenite::accept_async(far).await.unwrap();
|
||||
let hello = ServerMsg::Hello {
|
||||
gateway_id: "gw".into(),
|
||||
server_uid: "server".into(),
|
||||
server_name: "Server".into(),
|
||||
nonce: "n".into(),
|
||||
capabilities: Vec::new(),
|
||||
};
|
||||
let text = serde_json::to_string(&Envelope::new(hello)).unwrap();
|
||||
ws.send(Message::Text(text.into())).await.unwrap();
|
||||
while let Some(Ok(frame)) = ws.next().await {
|
||||
let Message::Text(text) = frame else { continue };
|
||||
let env: Envelope<ClientMsg> = serde_json::from_str(text.as_str()).unwrap();
|
||||
let reply = match env.msg {
|
||||
ClientMsg::Resume { .. } => ServerMsg::AuthOk {
|
||||
uid: "me".into(),
|
||||
token: "t".into(),
|
||||
token_expires: 0,
|
||||
capabilities: Vec::new(),
|
||||
},
|
||||
ClientMsg::Ping => {
|
||||
counted.fetch_add(1, Ordering::SeqCst);
|
||||
if !pings {
|
||||
continue;
|
||||
}
|
||||
ServerMsg::Pong
|
||||
}
|
||||
_ => ServerMsg::Ok,
|
||||
};
|
||||
let text = serde_json::to_string(&Envelope::with_id(env.id.unwrap_or(0), reply));
|
||||
if ws.send(Message::Text(text.unwrap().into())).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let (ws, _) = tokio_tungstenite::client_async("ws://gw.test/v1", near).await.unwrap();
|
||||
let (client, pushes) = GatewayClient::start(ws, Login::Token("t".into())).await.unwrap();
|
||||
(client, pushes, count)
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_gateway_that_stops_answering_is_left() {
|
||||
let (client, mut pushes, pings) = gateway(false).await;
|
||||
let (_tx, mut commands) = mpsc::unbounded_channel();
|
||||
let (events, _events) = mpsc::unbounded_channel();
|
||||
let start = tokio::time::Instant::now();
|
||||
let mut chats = Chats::default();
|
||||
let ended = relay(
|
||||
"ws://gw.test/v1",
|
||||
&client,
|
||||
&mut pushes,
|
||||
&mut commands,
|
||||
&events,
|
||||
&mut chats,
|
||||
Instant::now(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let Ended::Lost { reason, logged_in: true } = ended else { panic!("not lost") };
|
||||
assert!(reason.contains("ping"), "{reason}");
|
||||
assert_eq!(millis(start.elapsed()), millis(PING_EVERY + PING_TIMEOUT));
|
||||
assert_eq!(pings.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_gateway_that_answers_pings_is_kept() {
|
||||
let (client, mut pushes, pings) = gateway(true).await;
|
||||
let (_tx, mut commands) = mpsc::unbounded_channel();
|
||||
let (events, _events) = mpsc::unbounded_channel();
|
||||
let mut chats = Chats::default();
|
||||
let relayed = tokio::time::timeout(
|
||||
// The 20th ping at 600 s, answered.
|
||||
Duration::from_secs(615),
|
||||
relay(
|
||||
"ws://gw.test/v1",
|
||||
&client,
|
||||
&mut pushes,
|
||||
&mut commands,
|
||||
&events,
|
||||
&mut chats,
|
||||
Instant::now(),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert!(relayed.is_err(), "the connection was left");
|
||||
assert_eq!(pings.load(Ordering::SeqCst), 20);
|
||||
}
|
||||
}
|
||||
+144
-58
@@ -3,7 +3,10 @@
|
||||
//! The UI talks to an [`Engine`] with [`Command`]s and receives [`Event`]s.
|
||||
//! Each server the user works with is a session with up to three sources:
|
||||
//!
|
||||
//! - **voice**: a normal client connection (visible, can talk)
|
||||
//! - **voice**: a normal client connection (visible, can talk): a
|
||||
//! `voelin_proto::link::Session` that the connector of the server's address
|
||||
//! makes ([`Backends`], and [`ts::TsConnector`] for TeamSpeak servers; see
|
||||
//! [`link`])
|
||||
//! - **gateway**: a `tsgw` gateway (invisible presence, relayed chat)
|
||||
//! - **query**: the user's own ServerQuery credentials (same, without a gateway)
|
||||
//!
|
||||
@@ -16,9 +19,9 @@
|
||||
//! [`Engine::subscribe_frames`] for the frames of watched streams. The audio
|
||||
//! of watched streams plays through the session's speakers by itself
|
||||
//! ([`Command::SetStreamVolume`]); capture, encoding and decoding of video
|
||||
//! are in [`media`] (feature `media`), and the Stream Studio (scenes of
|
||||
//! are in `media` (feature `media`), and the Stream Studio (scenes of
|
||||
//! sources composited into one stream, recording, a replay buffer, WHIP) in
|
||||
//! [`studio`].
|
||||
//! `studio`.
|
||||
//!
|
||||
//! Settings are a [`settings::Settings`] service: typed keys, runtime
|
||||
//! values stored in the client database ahead of command line, config file
|
||||
@@ -39,20 +42,19 @@
|
||||
//! [`Event::Poke`]), private messages to any client (a
|
||||
//! [`ChatTarget::Private`] chat, stored under the peer's unique id), the
|
||||
//! channels' file browsers, avatars and icons ([`files`], cached in
|
||||
//! [`cache`]) and offline messages ([`offline`]). The host banner and
|
||||
//! channel banners are pictures on the web, fetched into the same cache
|
||||
//! ([`Event::PictureReady`]). Contacts (friends, blocked people, per-person
|
||||
//! [`cache`]) and offline messages ([`offline`]). The host banner, channel
|
||||
//! banners and the clients' badges are pictures on the web, fetched into the
|
||||
//! same cache ([`Event::PictureReady`]). Contacts (friends, blocked people, per-person
|
||||
//! volume) are engine-wide ([`contacts`]).
|
||||
|
||||
mod audio;
|
||||
mod book;
|
||||
pub mod cache;
|
||||
pub mod contacts;
|
||||
pub mod discover;
|
||||
pub mod files;
|
||||
pub mod gateway;
|
||||
pub mod history;
|
||||
pub mod identity;
|
||||
pub mod link;
|
||||
#[cfg(feature = "media")]
|
||||
pub mod media;
|
||||
pub mod offline;
|
||||
@@ -61,22 +63,21 @@ mod route;
|
||||
mod session;
|
||||
pub mod settings;
|
||||
pub mod stream;
|
||||
mod stream_types;
|
||||
#[cfg(feature = "media")]
|
||||
pub mod studio;
|
||||
pub mod versions;
|
||||
mod voice;
|
||||
pub mod ts;
|
||||
mod web;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::{broadcast, mpsc, watch};
|
||||
use tokio::sync::{broadcast, mpsc};
|
||||
pub use voelin_audio::settings::TransmitMode;
|
||||
pub use voelin_audio::{AudioSettings, ProcessingSettings, VadSettings};
|
||||
use voelin_model::{
|
||||
Capabilities, ChannelId, ChatMessage, ChatTarget, FileRef, GroupInfo, Presence, ServerDetails,
|
||||
ServerFlavor,
|
||||
};
|
||||
|
||||
use crate::audio::{AudioEvent, AudioHandle, AudioIn};
|
||||
@@ -88,22 +89,28 @@ pub use files::{Bytes, DownloadTo, FileEntry, RequestId, TransferId, TransferSta
|
||||
pub use gateway::{GatewayRequest, GatewayUpdate};
|
||||
use history::SharedHistory;
|
||||
pub use history::{History, HistoryMessage, HistorySource};
|
||||
pub use link::{Backends, VoiceOptions};
|
||||
pub use offline::{OfflineMessage, OfflineMessageInfo};
|
||||
pub use query::{QueryLogin, QueryTransport};
|
||||
pub use route::{ChatRoute, Dedup, route_chat};
|
||||
use settings::{SettingChange, Settings, SharedSettings};
|
||||
use stream::{EncodedFrame, LayerId, LayerSpec, StreamInfo, StreamSetup, ViewerInfo};
|
||||
pub use stream::{StreamFrame, StreamSink, StreamState, WatchState};
|
||||
use voelin_stream::{
|
||||
EncodedFrame, LayerId, LayerSpec, SrtpProfile, StreamInfo, StreamSetup, ViewerInfo,
|
||||
};
|
||||
pub use voice::VoiceOptions;
|
||||
pub use voelin_identity::IdentityBlob;
|
||||
/// Banners are downloaded and shown by the same rule.
|
||||
pub use web::is_svg;
|
||||
/// Pictures from the web go through the desktop's proxy (set at startup).
|
||||
pub use web::set_proxy_resolver;
|
||||
|
||||
pub type SessionId = u64;
|
||||
|
||||
/// The longest poke message servers take, in characters; a longer one is
|
||||
/// cut ([`Command::Poke`]).
|
||||
pub const POKE_MESSAGE_MAX: usize = 100;
|
||||
|
||||
/// What the UI asks for.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Command {
|
||||
/// Main account proof for every current and future voice connection.
|
||||
SetMytsIdentity(Option<Arc<tsproto::myts::Identity>>),
|
||||
ConnectVoice {
|
||||
session: SessionId,
|
||||
options: Box<VoiceOptions>,
|
||||
@@ -111,16 +118,23 @@ pub enum Command {
|
||||
DisconnectVoice {
|
||||
session: SessionId,
|
||||
},
|
||||
/// Invisible presence and relay chat through a `tsgw` gateway.
|
||||
/// Invisible presence and relay chat through a `tsgw` gateway: the first
|
||||
/// of `urls` (best first, [`discover::gateways`]) that logs in, tried in
|
||||
/// turn again whenever it is lost. Sent again with the same `urls` and
|
||||
/// identity while it runs, it is not started over; while still
|
||||
/// connecting, it tries again at once (at most every 5 s).
|
||||
ObserveGateway {
|
||||
session: SessionId,
|
||||
url: String,
|
||||
identity: Box<tsclientlib::Identity>,
|
||||
urls: Vec<String>,
|
||||
/// The TeamSpeak identity to log in with ([`ts::identity::to_blob`]).
|
||||
/// One that is none, or cannot be read, ends the observation with
|
||||
/// its reason.
|
||||
identity: Box<IdentityBlob>,
|
||||
},
|
||||
/// Invisible presence and relay chat with own ServerQuery credentials.
|
||||
ObserveQuery {
|
||||
session: SessionId,
|
||||
connect: Box<voelin_query::Connect>,
|
||||
connect: Box<QueryLogin>,
|
||||
},
|
||||
StopObserving {
|
||||
session: SessionId,
|
||||
@@ -153,6 +167,7 @@ pub enum Command {
|
||||
session: SessionId,
|
||||
request: GatewayRequest,
|
||||
},
|
||||
/// Refusals come as [`Event::JoinFailed`].
|
||||
MoveToChannel {
|
||||
session: SessionId,
|
||||
channel: ChannelId,
|
||||
@@ -230,11 +245,13 @@ pub enum Command {
|
||||
session: SessionId,
|
||||
layers: Vec<LayerSpec>,
|
||||
},
|
||||
/// SRTP protection profiles for stream connections, in order of
|
||||
/// preference (a user setting; empty: the default,
|
||||
/// `SrtpProfile::DEFAULT_ORDER`). Applies to connections made from now
|
||||
/// on, in all sessions and those started later.
|
||||
SetSrtpProfiles(Vec<SrtpProfile>),
|
||||
/// SRTP protection profiles for stream connections by name (RFC 5764 and
|
||||
/// RFC 7714: `AEAD_AES_128_GCM`, `AES128_CM_SHA1_80`, ...; names the stream
|
||||
/// transport does not know are left out), in order of preference (the
|
||||
/// `stream.srtp_profiles` setting). Empty: the transport's default order.
|
||||
/// Applies to connections made from now on, in all sessions and those
|
||||
/// started later.
|
||||
SetSrtpProfiles(Vec<String>),
|
||||
/// Watch a stream from [`Event::StreamsChanged`]. Frames arrive through
|
||||
/// [`Engine::subscribe_frames`].
|
||||
WatchStream {
|
||||
@@ -252,7 +269,7 @@ pub enum Command {
|
||||
},
|
||||
/// The video of a watched stream arrives, but none of it decodes: watch
|
||||
/// it in another codec the streamer offered, if there is one (a new
|
||||
/// connection without this one). [`media::Viewer`] sends it.
|
||||
/// connection without this one). `media::Viewer` sends it.
|
||||
StreamUndecodable {
|
||||
session: SessionId,
|
||||
stream_id: String,
|
||||
@@ -273,7 +290,8 @@ pub enum Command {
|
||||
volume: f32,
|
||||
},
|
||||
/// Poke a client (voice): the server shows it a notification with
|
||||
/// `message`. Failures come as [`Event::Error`].
|
||||
/// `message`, cut to [`POKE_MESSAGE_MAX`] characters. Failures come as
|
||||
/// [`Event::Error`].
|
||||
Poke {
|
||||
session: SessionId,
|
||||
client: u16,
|
||||
@@ -365,6 +383,14 @@ pub enum Command {
|
||||
session: SessionId,
|
||||
client_uid: String,
|
||||
},
|
||||
/// Get a picture on the web that a chat message shows (`[img]`) into
|
||||
/// the cache ([`Event::PictureReady`]) while `cache.fetch_images` is on;
|
||||
/// one larger than `max_bytes` is not reported.
|
||||
FetchPicture {
|
||||
session: SessionId,
|
||||
url: String,
|
||||
max_bytes: u64,
|
||||
},
|
||||
/// Our offline messages ([`Event::OfflineMessages`]); see [`offline`].
|
||||
ListOfflineMessages {
|
||||
session: SessionId,
|
||||
@@ -469,6 +495,41 @@ pub struct SessionState {
|
||||
pub server_uid: Option<String>,
|
||||
}
|
||||
|
||||
/// Why the server did not let us into a channel ([`Event::JoinFailed`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum JoinFailure {
|
||||
/// The channel's password is missing or wrong.
|
||||
Password,
|
||||
/// The channel, or the channel with its subchannels, is full.
|
||||
Full,
|
||||
/// Anything else, as a sentence for the user.
|
||||
Other(String),
|
||||
}
|
||||
|
||||
/// The software on the other end of a session, as its link names it. It is
|
||||
/// for people to read; nothing branches on it (what the server can do is
|
||||
/// [`Capabilities`]).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct BackendInfo {
|
||||
/// What it is called ("TeamSpeak 6"); empty when it was not recognised.
|
||||
pub product: String,
|
||||
/// Its version as the product shows it ("6.0.0-beta13.1"); what the
|
||||
/// server said, as it is, when `product` is empty.
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
impl BackendInfo {
|
||||
/// For a sentence: the product and the version, whichever there are
|
||||
/// ("TeamSpeak 6 6.0.0-beta13.1", "TeamSpeak 3", "custom 9").
|
||||
pub fn label(&self) -> String {
|
||||
match (self.product.is_empty(), self.version.is_empty()) {
|
||||
(false, false) => format!("{} {}", self.product, self.version),
|
||||
(false, true) => self.product.clone(),
|
||||
(true, _) => self.version.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the engine reports.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Event {
|
||||
@@ -476,10 +537,12 @@ pub enum Event {
|
||||
session: SessionId,
|
||||
state: SessionState,
|
||||
},
|
||||
/// The server answered: its name, the software it runs and what that
|
||||
/// software can do (the UI hides what it cannot).
|
||||
ServerInfo {
|
||||
session: SessionId,
|
||||
name: String,
|
||||
flavor: ServerFlavor,
|
||||
backend: BackendInfo,
|
||||
capabilities: Capabilities,
|
||||
},
|
||||
/// Full presence of the session (the UI rebuilds its view from it).
|
||||
@@ -534,6 +597,12 @@ pub enum Event {
|
||||
session: SessionId,
|
||||
message: String,
|
||||
},
|
||||
/// The server refused [`Command::MoveToChannel`] into `channel`.
|
||||
JoinFailed {
|
||||
session: SessionId,
|
||||
channel: ChannelId,
|
||||
reason: JoinFailure,
|
||||
},
|
||||
/// The streams in our channel (TeamSpeak 6), full list.
|
||||
StreamsChanged {
|
||||
session: SessionId,
|
||||
@@ -640,9 +709,10 @@ pub enum Event {
|
||||
request: RequestId,
|
||||
result: Result<(), String>,
|
||||
},
|
||||
/// A client's avatar is in the cache: `path`, its MD5 `hash`
|
||||
/// ([`voelin_model::ClientInfo::avatar`]). Comes when the client appears
|
||||
/// with an avatar and when it changes.
|
||||
/// A client's avatar is in the cache: `path`, and `hash`: the MD5 of a
|
||||
/// server avatar ([`voelin_model::ClientInfo::avatar`]), or the address
|
||||
/// of a myTeamSpeak avatar ([`voelin_model::ClientInfo::myts_avatar`]).
|
||||
/// Comes when the client appears with an avatar and when it changes.
|
||||
AvatarReady {
|
||||
session: SessionId,
|
||||
client_uid: String,
|
||||
@@ -656,9 +726,11 @@ pub enum Event {
|
||||
path: PathBuf,
|
||||
},
|
||||
/// A picture on the web is in the cache: the host banner
|
||||
/// ([`ServerDetails::banner_gfx_url`]) or a channel's
|
||||
/// ([`voelin_model::ChannelInfo::banner_gfx_url`]) at `url` (setting
|
||||
/// `cache.fetch_images`). Comes again when the host banner was reloaded
|
||||
/// ([`ServerDetails::banner_gfx_url`]), a channel's
|
||||
/// ([`voelin_model::ChannelInfo::banner_gfx_url`]), a badge's
|
||||
/// ([`voelin_model::badges::icon_url`]) or one a chat message shows
|
||||
/// ([`Command::FetchPicture`]) at `url` (setting `cache.fetch_images`).
|
||||
/// Comes again when the host banner was reloaded
|
||||
/// (`banner_gfx_interval_s`, at least a minute): the file at `path`
|
||||
/// changed.
|
||||
PictureReady {
|
||||
@@ -713,8 +785,18 @@ impl Engine {
|
||||
}
|
||||
|
||||
/// Start the engine on the current tokio runtime with `settings` and
|
||||
/// chat `history`.
|
||||
/// chat `history`, connecting voice with the engine's own connectors
|
||||
/// ([`Backends::default`]: TeamSpeak 3 and 6).
|
||||
pub fn start_with(settings: Settings, history: History) -> Self {
|
||||
Self::start_with_backends(settings, history, Backends::default())
|
||||
}
|
||||
|
||||
/// Start the engine on the current tokio runtime with `settings` and
|
||||
/// chat `history`, connecting voice with the connectors in `backends`:
|
||||
/// the one for the scheme of a session's address makes its
|
||||
/// `voelin_proto::link::Session`.
|
||||
pub fn start_with_backends(settings: Settings, history: History, backends: Backends) -> Self {
|
||||
let link = Arc::new(link::SessionLink::new(backends));
|
||||
let (commands, rx) = mpsc::unbounded_channel();
|
||||
let (events, _) = broadcast::channel(4096);
|
||||
// About a minute of one watched stream.
|
||||
@@ -726,7 +808,7 @@ impl Engine {
|
||||
history,
|
||||
cache: SharedCache::new(Cache::new(Cache::default_dir())),
|
||||
};
|
||||
tokio::spawn(run(rx, events.clone(), frames.clone(), shared.clone()));
|
||||
tokio::spawn(run(rx, events.clone(), frames.clone(), shared.clone(), link));
|
||||
Self { commands, events, frames, runtime: tokio::runtime::Handle::current(), shared }
|
||||
}
|
||||
|
||||
@@ -810,18 +892,18 @@ async fn run(
|
||||
events: broadcast::Sender<Event>,
|
||||
frames: broadcast::Sender<StreamFrame>,
|
||||
engine: Shared,
|
||||
link: Arc<link::SessionLink>,
|
||||
) {
|
||||
let Shared { settings: shared, history, cache, contacts } = engine.clone();
|
||||
// Before any command: a contact set meanwhile would be lost.
|
||||
contacts.load().await;
|
||||
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
|
||||
let (myts_identity, _) = watch::channel(None);
|
||||
let mut current = shared.current();
|
||||
// Pruning: at start, then hourly (and when the setting changes).
|
||||
let mut prune = tokio::time::interval(std::time::Duration::from_secs(3600));
|
||||
let mut changes = current.subscribe();
|
||||
let mut settings = AudioSettings::default();
|
||||
let mut srtp_profiles: Option<Vec<SrtpProfile>> = None;
|
||||
let mut srtp_profiles: Option<Vec<String>> = None;
|
||||
let mut mic_test: Option<AudioHandle> = None;
|
||||
loop {
|
||||
let input = tokio::select! {
|
||||
@@ -860,19 +942,6 @@ async fn run(
|
||||
},
|
||||
};
|
||||
let id = match command {
|
||||
Command::SetMytsIdentity(identity) => {
|
||||
// Still no account is no change: every notification restarts
|
||||
// handshakes and sends `updatemytsid` on every connection. Any
|
||||
// account is (each connection's proof is signed anew).
|
||||
myts_identity.send_if_modified(|current| {
|
||||
if current.is_none() && identity.is_none() {
|
||||
return false;
|
||||
}
|
||||
*current = identity;
|
||||
true
|
||||
});
|
||||
continue;
|
||||
}
|
||||
Command::SetAudioSettings(new) => {
|
||||
settings = (*new).clone();
|
||||
for s in sessions.values() {
|
||||
@@ -948,7 +1017,7 @@ async fn run(
|
||||
frames.clone(),
|
||||
settings.clone(),
|
||||
engine.clone(),
|
||||
myts_identity.subscribe(),
|
||||
link.clone(),
|
||||
);
|
||||
if let Some(profiles) = &srtp_profiles {
|
||||
s.send(Command::SetSrtpProfiles(profiles.clone()));
|
||||
@@ -1020,14 +1089,14 @@ fn command_session(command: &Command) -> SessionId {
|
||||
| Command::CreateDirectory { session, .. }
|
||||
| Command::SetAvatar { session, .. }
|
||||
| Command::FetchAvatar { session, .. }
|
||||
| Command::FetchPicture { session, .. }
|
||||
| Command::ListOfflineMessages { session, .. }
|
||||
| Command::GetOfflineMessage { session, .. }
|
||||
| Command::SendOfflineMessage { session, .. }
|
||||
| Command::DeleteOfflineMessage { session, .. }
|
||||
| Command::SetOfflineMessageRead { session, .. }
|
||||
| Command::CloseSession { session } => *session,
|
||||
Command::SetMytsIdentity(_)
|
||||
| Command::SetAudioSettings(_)
|
||||
Command::SetAudioSettings(_)
|
||||
| Command::SetSrtpProfiles(_)
|
||||
| Command::TestMicrophone { .. }
|
||||
| Command::SetSetting { .. }
|
||||
@@ -1044,10 +1113,27 @@ fn command_session(command: &Command) -> SessionId {
|
||||
|
||||
/// The app has one rustls crypto provider. With two (aws-lc-rs and ring), a
|
||||
/// TLS client built without an explicit provider panics: `wss://` gateways
|
||||
/// did. This test's build has the app's TLS dependencies (reqwest here,
|
||||
/// tonic through the voelin-myts dev-dependency).
|
||||
/// did. This test's build has the app's TLS dependencies (reqwest).
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn one_rustls_crypto_provider() {
|
||||
let _ = rustls::ClientConfig::builder();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::BackendInfo;
|
||||
|
||||
#[test]
|
||||
fn a_backend_reads_as_its_product_and_version() {
|
||||
let backend = |product: &str, version: &str| BackendInfo {
|
||||
product: product.into(),
|
||||
version: version.into(),
|
||||
};
|
||||
assert_eq!(backend("TeamSpeak 6", "6.0.0-beta13.1").label(), "TeamSpeak 6 6.0.0-beta13.1");
|
||||
assert_eq!(backend("TeamSpeak 3", "").label(), "TeamSpeak 3");
|
||||
// Not recognised: the version string alone, or nothing.
|
||||
assert_eq!(backend("", "custom 9").label(), "custom 9");
|
||||
assert_eq!(BackendInfo::default().label(), "");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
//! The registry of the engine's connectors, by address scheme.
|
||||
//!
|
||||
//! A session's voice source is a `voelin_proto::link::Session`
|
||||
//! (`docs/session-seam.md` section 4.1). Which backend makes it is the
|
||||
//! scheme of the address: [`Backends`] holds the plain connectors of
|
||||
//! `voelin_proto::link::Connectors` (the Voelin protocol's QUIC connector
|
||||
//! later, `FakeConnector` in tests) and the in-process connectors, which
|
||||
//! also hand the engine what a `Session` has no room for yet (the TeamSpeak 6
|
||||
//! stream task, [`StreamPort`]).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use voelin_proto::link::{
|
||||
AccountAgent, BoxFuture, ConnectParams, Connected, Connector, Connectors, HostIdentity,
|
||||
HostTrust, SessionError,
|
||||
};
|
||||
use voelin_stream::PeerConfig;
|
||||
|
||||
use super::LinkCtx;
|
||||
use crate::stream::{OwnStreamEvent, StreamCmd};
|
||||
use crate::ts::TsConnector;
|
||||
|
||||
/// The scheme of the TeamSpeak servers a bookmark names without one.
|
||||
pub(crate) const TEAMSPEAK_SCHEME: &str = "ts3server";
|
||||
|
||||
/// What comes back from the stream task of a connection that has one.
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum StreamEvent {
|
||||
/// Our own stream's life, for the gateway directory.
|
||||
OwnStream(OwnStreamEvent),
|
||||
/// An Opus frame of a watched stream, for the audio thread.
|
||||
Audio { stream: String, time: u64, data: Arc<[u8]> },
|
||||
/// A watched stream ended.
|
||||
AudioEnded(String),
|
||||
}
|
||||
|
||||
/// The in-process channel of TeamSpeak 6 streams past the `Session` trait
|
||||
/// (`docs/session-seam.md` section 6.4): TeamSpeak 6 streams are peer to peer
|
||||
/// and not v1 entities yet, so the commands go to the connection's stream
|
||||
/// task and its events come back here.
|
||||
pub(crate) struct StreamPort {
|
||||
send: Box<dyn Fn(StreamCmd) + Send + Sync>,
|
||||
/// What the stream task reports.
|
||||
pub(crate) events: mpsc::UnboundedReceiver<StreamEvent>,
|
||||
}
|
||||
|
||||
impl StreamPort {
|
||||
/// A port whose commands go to `send`.
|
||||
pub(crate) fn new(
|
||||
send: impl Fn(StreamCmd) + Send + Sync + 'static,
|
||||
events: mpsc::UnboundedReceiver<StreamEvent>,
|
||||
) -> Self {
|
||||
Self { send: Box::new(send), events }
|
||||
}
|
||||
|
||||
/// Give the stream task a command.
|
||||
pub(crate) fn send(&self, cmd: StreamCmd) {
|
||||
(self.send)(cmd);
|
||||
}
|
||||
}
|
||||
|
||||
/// What an in-process backend needs besides the connect parameters.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct LocalCtx {
|
||||
/// The session's side of the engine: its id, event bus, frames and
|
||||
/// settings.
|
||||
pub(crate) link: LinkCtx,
|
||||
/// Open the audio devices (the stream task plays what streams carry).
|
||||
pub(crate) audio: bool,
|
||||
/// Network settings for stream peer connections.
|
||||
pub(crate) stream_peer: PeerConfig,
|
||||
}
|
||||
|
||||
impl LocalCtx {
|
||||
pub(crate) fn new(link: LinkCtx, audio: bool, stream_peer: PeerConfig) -> Self {
|
||||
Self { link, audio, stream_peer }
|
||||
}
|
||||
|
||||
/// A context for a connection made outside an engine (a test or a tool
|
||||
/// that calls a connector itself): a session of its own that nobody
|
||||
/// listens to.
|
||||
pub(crate) fn standalone() -> Self {
|
||||
let (events, _) = tokio::sync::broadcast::channel(16);
|
||||
let (frames, _) = tokio::sync::broadcast::channel(16);
|
||||
let link = LinkCtx {
|
||||
session: 0,
|
||||
events,
|
||||
frames,
|
||||
settings: crate::settings::SharedSettings::new(crate::settings::Settings::in_memory()),
|
||||
};
|
||||
Self { link, audio: false, stream_peer: PeerConfig::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// A connection an in-process connector made.
|
||||
pub(crate) struct LocalConnected {
|
||||
pub(crate) connected: Connected,
|
||||
/// The stream task's port, for a backend that runs one.
|
||||
pub(crate) streams: Option<StreamPort>,
|
||||
}
|
||||
|
||||
/// A connector that runs in this process and can use the engine's context
|
||||
/// ([`LocalCtx`]); its sessions may come with a [`StreamPort`].
|
||||
pub(crate) trait LocalConnector: Connector {
|
||||
/// Whether this connector serves addresses of `scheme`. By default, the
|
||||
/// schemes it names.
|
||||
fn accepts(&self, scheme: &str) -> bool {
|
||||
self.schemes().contains(&scheme)
|
||||
}
|
||||
|
||||
/// Connect with the engine's context.
|
||||
fn connect_local(
|
||||
&self,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> BoxFuture<Result<LocalConnected, SessionError>>;
|
||||
}
|
||||
|
||||
/// The connectors of an engine, found by the scheme of an address.
|
||||
///
|
||||
/// A scheme served by an in-process connector goes to it, one served by a
|
||||
/// plain connector ([`Backends::register`]) to that. An address without a
|
||||
/// scheme is a TeamSpeak bookmark and is taken for a `ts3server` one.
|
||||
#[derive(Clone)]
|
||||
pub struct Backends {
|
||||
connectors: Connectors,
|
||||
locals: Vec<Arc<dyn LocalConnector>>,
|
||||
account: Option<Arc<dyn AccountAgent>>,
|
||||
/// The connections' trust in hosts that are neither valid nor pinned.
|
||||
trust: Option<Arc<dyn HostTrust>>,
|
||||
}
|
||||
|
||||
impl Default for Backends {
|
||||
/// The engine's connectors: TeamSpeak 3 and 6 (`ts3server://` and
|
||||
/// `teamspeak://`, and an address without a scheme).
|
||||
fn default() -> Self {
|
||||
let mut backends = Self::empty();
|
||||
backends.register_teamspeak(TsConnector::new());
|
||||
backends
|
||||
}
|
||||
}
|
||||
|
||||
impl Backends {
|
||||
/// No connector at all. ([`Backends::default`] has the TeamSpeak one.)
|
||||
pub fn empty() -> Self {
|
||||
Self { connectors: Connectors::default(), locals: Vec::new(), account: None, trust: None }
|
||||
}
|
||||
|
||||
/// Register a connector for the schemes it names.
|
||||
pub fn register(&mut self, connector: Arc<dyn Connector>) {
|
||||
self.connectors.register(connector);
|
||||
}
|
||||
|
||||
pub(crate) fn register_local(&mut self, connector: Arc<dyn LocalConnector>) {
|
||||
self.locals.push(connector);
|
||||
}
|
||||
|
||||
/// Register the TeamSpeak connector for the schemes it names
|
||||
/// (`ts3server`, `teamspeak`, and addresses without a scheme).
|
||||
/// [`Backends::default`] registers one of its own; register yours to keep a
|
||||
/// clone of it, whose [`TsConnector::set_myts_identity`] and
|
||||
/// [`TsConnector::set_myts_data`] set the main myTeamSpeak account for every
|
||||
/// connection it makes.
|
||||
pub fn register_teamspeak(&mut self, connector: TsConnector) {
|
||||
self.register_local(Arc::new(connector));
|
||||
}
|
||||
|
||||
/// The device's Voelin account, for the connectors that use it (the QUIC
|
||||
/// connector's certificate, the TeamSpeak connector's myTS ID proof).
|
||||
/// None is the default: nothing uses an account yet.
|
||||
pub fn set_account(&mut self, agent: Option<Arc<dyn AccountAgent>>) {
|
||||
self.account = agent;
|
||||
}
|
||||
|
||||
/// The account agent, if one was set ([`Backends::set_account`]).
|
||||
pub fn account(&self) -> Option<Arc<dyn AccountAgent>> {
|
||||
self.account.clone()
|
||||
}
|
||||
|
||||
/// Decide about hosts that are neither valid nor pinned. The default
|
||||
/// refuses them: there is no trust dialog yet, and TeamSpeak has no host
|
||||
/// key.
|
||||
pub fn set_trust(&mut self, trust: Option<Arc<dyn HostTrust>>) {
|
||||
self.trust = trust;
|
||||
}
|
||||
|
||||
pub(crate) fn trust(&self) -> Arc<dyn HostTrust> {
|
||||
self.trust.clone().unwrap_or_else(|| Arc::new(RefuseUnknownHosts))
|
||||
}
|
||||
|
||||
/// The scheme of an address, lowercase; a TeamSpeak bookmark's when there
|
||||
/// is none.
|
||||
pub(crate) fn scheme(address: &str) -> String {
|
||||
match address.split_once("://") {
|
||||
Some((scheme, _)) => scheme.to_ascii_lowercase(),
|
||||
None => TEAMSPEAK_SCHEME.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a session to `params.address` with the connector of its scheme.
|
||||
pub(crate) fn connect(
|
||||
&self,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> BoxFuture<Result<LocalConnected, SessionError>> {
|
||||
let scheme = Self::scheme(¶ms.address);
|
||||
if let Some(local) = self.locals.iter().find(|c| c.accepts(&scheme)) {
|
||||
return local.connect_local(params, ctx);
|
||||
}
|
||||
// Not `Connectors::connect`, which names the whole address when none serves it:
|
||||
// the text is shown, and a TeamSpeak link carries a channel password.
|
||||
let Some(connector) = self.connectors.for_address(¶ms.address) else {
|
||||
let shown = without_query(¶ms.address).to_owned();
|
||||
return Box::pin(async move {
|
||||
Err(SessionError::Protocol(format!("no connector for {shown}")))
|
||||
});
|
||||
};
|
||||
let connect = connector.connect(params);
|
||||
Box::pin(async move {
|
||||
let connected = connect.await?;
|
||||
Ok(LocalConnected { connected, streams: None })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// An address as it may be shown or logged: without its query and fragment,
|
||||
/// where a link keeps a channel password or a host pin.
|
||||
pub(crate) fn without_query(address: &str) -> &str {
|
||||
address.split(['?', '#']).next().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Refuses every host that asks to be trusted.
|
||||
struct RefuseUnknownHosts;
|
||||
|
||||
impl HostTrust for RefuseUnknownHosts {
|
||||
fn confirm(&self, _host: HostIdentity) -> BoxFuture<bool> {
|
||||
Box::pin(async { false })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_bookmark_without_a_scheme_is_a_teamspeak_server() {
|
||||
assert_eq!(Backends::scheme("ts.example.com:9987"), "ts3server");
|
||||
assert_eq!(Backends::scheme("[::1]:9987"), "ts3server");
|
||||
assert_eq!(Backends::scheme("TS3Server://ts.example.com"), "ts3server");
|
||||
assert_eq!(Backends::scheme("teamspeak://x"), "teamspeak");
|
||||
assert_eq!(Backends::scheme("voelin://host/i/code"), "voelin");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_address_is_shown_without_its_secrets() {
|
||||
assert_eq!(without_query("ts3server://h?port=1&channelpassword=hunter2"), "ts3server://h");
|
||||
assert_eq!(without_query("voelin://h/i/code#h=abcd"), "voelin://h/i/code");
|
||||
assert_eq!(without_query("host:9987"), "host:9987");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
//! What a session hands the connector of an address: the `ConnectParams` of
|
||||
//! a [`VoiceOptions`] (`docs/session-seam.md` section 4.2).
|
||||
//!
|
||||
//! The options are the engine's own, and a connector reads them back: the
|
||||
//! address is the link of the bookmark (a `ts3server://` link for a
|
||||
//! bookmark that names a TeamSpeak server by `host[:port]`), the nickname,
|
||||
//! the server password and the privilege key are in the hello, the identity
|
||||
//! is the credential. What v1 has no field for yet (the channel to join and
|
||||
//! its password, the client version a TeamSpeak server is shown) rides in
|
||||
//! the address, as parameters of the link.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use bytes::Bytes;
|
||||
use voelin_identity::{IdentityBlob, KIND_TEAMSPEAK};
|
||||
use voelin_model::Link;
|
||||
use voelin_proto::link::{ConnectParams, Credential, IssuerTrust, MediaSink, SessionError};
|
||||
use voelin_proto::v1;
|
||||
|
||||
use super::{Backends, VoiceOptions, without_query};
|
||||
|
||||
/// The link parameter that carries the client version to impersonate: the
|
||||
/// user's spec (`VoiceOptions::client_version`), in unpadded URL-safe base64.
|
||||
/// The connector for TeamSpeak resolves it; other connectors never read it.
|
||||
pub(crate) const VERSION_PARAM: &str = "client_version";
|
||||
|
||||
/// The connect parameters of a connection, from the options the session was
|
||||
/// asked to connect with.
|
||||
///
|
||||
/// The address is the link of the bookmark (the channel and its password
|
||||
/// ride in it, and so does the client version to claim, until v1 has fields
|
||||
/// for them), the server password is `Hello.password` and the privilege key
|
||||
/// `Hello.invite_code`. The identity goes as the credential of its kind; no
|
||||
/// account is used yet.
|
||||
///
|
||||
/// An address a link cannot carry is refused here ([`bookmark`]), and so is
|
||||
/// an identity that is of no kind a connector can use.
|
||||
pub(crate) fn connect_params(
|
||||
options: &VoiceOptions,
|
||||
media: Arc<dyn MediaSink>,
|
||||
backends: &Backends,
|
||||
) -> Result<ConnectParams, SessionError> {
|
||||
let hello = v1::Hello {
|
||||
version: 1,
|
||||
client: Some(v1::ClientInfo {
|
||||
name: "Voelin".into(),
|
||||
version: voelin_platform::crash::app_version().to_owned(),
|
||||
platform: std::env::consts::OS.into(),
|
||||
kind: v1::ClientKind::User as i32,
|
||||
}),
|
||||
nickname: options.nickname.clone(),
|
||||
password: options.server_password.clone().unwrap_or_default(),
|
||||
invite_code: options.token.clone().unwrap_or_default(),
|
||||
..Default::default()
|
||||
};
|
||||
Ok(ConnectParams {
|
||||
address: address_link(options)?,
|
||||
credential: credential(options.identity.as_ref())?,
|
||||
linked: Vec::new(),
|
||||
account: backends.account(),
|
||||
issuer_trust: IssuerTrust::Unknown,
|
||||
hello,
|
||||
host_pin: None,
|
||||
trust: backends.trust(),
|
||||
media,
|
||||
push_capacity: 1024,
|
||||
timeout: Duration::from_secs(35),
|
||||
})
|
||||
}
|
||||
|
||||
/// The credential of an identity (`docs/session-seam.md` section 7). A
|
||||
/// TeamSpeak identity goes as the JSON the key store keeps, and none at all as
|
||||
/// an empty one, for which the TeamSpeak connector makes an identity up (the
|
||||
/// protocol's convention for "generate one", follow-up P11); a Voelin key
|
||||
/// signs. A TeamSpeak identity that holds no JSON is refused: sent as it is,
|
||||
/// it would be that same empty blob and be taken for the request to make one
|
||||
/// up, which only the absence of an identity may be.
|
||||
fn credential(identity: Option<&IdentityBlob>) -> Result<Credential, SessionError> {
|
||||
let Some(blob) = identity else {
|
||||
return Ok(Credential::Foreign { kind: KIND_TEAMSPEAK, blob: Bytes::new() });
|
||||
};
|
||||
if blob.is_teamspeak() {
|
||||
if blob.json.trim().is_empty() {
|
||||
return Err(SessionError::Protocol(
|
||||
"the TeamSpeak identity cannot be read: it is empty".into(),
|
||||
));
|
||||
}
|
||||
let json = Bytes::copy_from_slice(blob.json.as_bytes());
|
||||
Ok(Credential::Foreign { kind: KIND_TEAMSPEAK, blob: json })
|
||||
} else if blob.is_voelin() {
|
||||
let key = blob.voelin_key().map_err(|e| {
|
||||
SessionError::Protocol(format!("the Voelin identity cannot be read: {e}"))
|
||||
})?;
|
||||
Ok(Credential::Voelin(Arc::new(key)))
|
||||
} else {
|
||||
Err(SessionError::Protocol(format!(
|
||||
"an identity of kind {:?} cannot be used to connect",
|
||||
blob.kind
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The `ts3server://` link of the options' address, with the channel to join
|
||||
/// and the client version to claim.
|
||||
fn address_link(options: &VoiceOptions) -> Result<String, SessionError> {
|
||||
let mut link = match Link::parse(&options.address) {
|
||||
Some(Link::Server(link)) => link,
|
||||
// Not a TeamSpeak link, or none: a bookmark's `host[:port]`.
|
||||
_ if !options.address.contains("://") => bookmark(&options.address)?,
|
||||
// Some other scheme: as given, for the connector of that scheme.
|
||||
_ => return Ok(options.address.clone()),
|
||||
};
|
||||
link.channel = options.channel.clone().filter(|c| !c.is_empty()).or(link.channel);
|
||||
link.channel_password =
|
||||
options.channel_password.clone().filter(|p| !p.is_empty()).or(link.channel_password);
|
||||
let mut url = link.to_url();
|
||||
if let Some(spec) = &options.client_version {
|
||||
url.push(if url.contains('?') { '&' } else { '?' });
|
||||
url.push_str(VERSION_PARAM);
|
||||
url.push('=');
|
||||
url.push_str(&URL_SAFE_NO_PAD.encode(spec));
|
||||
}
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
/// The link to a bookmark's `host[:port]`.
|
||||
///
|
||||
/// A link cannot say everything an address can: it drops a port that is no
|
||||
/// port (`ServerLink::new` takes `host:99999` for the host `host` and joins
|
||||
/// the default port), and it ends the host at a `?`, `#` or `/` and decodes a
|
||||
/// `%` (so that a `?` in the host would hide the channel behind the next
|
||||
/// one). The TeamSpeak library refuses such an address when it resolves it;
|
||||
/// so does this, in words, instead of connecting to something else.
|
||||
fn bookmark(address: &str) -> Result<voelin_model::ServerLink, SessionError> {
|
||||
let address = address.trim();
|
||||
// Without the query: a link keeps secrets in it.
|
||||
let shown = without_query(address);
|
||||
let not_an_address = || SessionError::Protocol(format!("not a server address: {shown}"));
|
||||
if address.is_empty()
|
||||
|| address
|
||||
.chars()
|
||||
.any(|c| matches!(c, '?' | '#' | '/' | '%') || c.is_whitespace() || c.is_control())
|
||||
{
|
||||
return Err(not_an_address());
|
||||
}
|
||||
// The text after the port's colon: `[v6]:port`, or `host:port` with the one
|
||||
// colon (more colons are an IPv6 address without a port).
|
||||
let port = if let Some(rest) = address.strip_prefix('[') {
|
||||
let (_, after) = rest.split_once(']').ok_or_else(not_an_address)?;
|
||||
(!after.is_empty()).then(|| after.strip_prefix(':').unwrap_or(after))
|
||||
} else {
|
||||
address.rsplit_once(':').filter(|(host, _)| !host.contains(':')).map(|(_, port)| port)
|
||||
};
|
||||
if let Some(port) = port
|
||||
&& !port.parse::<u16>().is_ok_and(|port| port != 0)
|
||||
{
|
||||
return Err(SessionError::Protocol(format!(
|
||||
"the port in {shown} is not a number from 1 to 65535"
|
||||
)));
|
||||
}
|
||||
Ok(voelin_model::ServerLink::new(address))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use voelin_identity::IdentityKey;
|
||||
|
||||
fn params(options: &VoiceOptions) -> Result<ConnectParams, SessionError> {
|
||||
let (media, _rx) = voelin_proto::test_util::media_channel();
|
||||
connect_params(options, media, &Backends::empty())
|
||||
}
|
||||
|
||||
/// The identity of the options is the credential of its kind: a TeamSpeak
|
||||
/// identity as the JSON the key store keeps, none as the empty blob a
|
||||
/// connector makes an identity up for, a Voelin key as its signer.
|
||||
#[test]
|
||||
fn an_identity_is_the_credential_of_its_kind() {
|
||||
let mut options = VoiceOptions::new("ts.example.com", "nick");
|
||||
let none = params(&options).unwrap();
|
||||
assert!(matches!(
|
||||
&none.credential,
|
||||
Credential::Foreign { kind: "teamspeak", blob } if blob.is_empty()
|
||||
));
|
||||
|
||||
options.identity = Some(IdentityBlob::teamspeak("uid=", 8, r#"{"key":"k"}"#));
|
||||
let sent = params(&options).unwrap();
|
||||
assert!(matches!(
|
||||
&sent.credential,
|
||||
Credential::Foreign { kind: "teamspeak", blob } if &blob[..] == br#"{"key":"k"}"#
|
||||
));
|
||||
|
||||
let key = IdentityKey::generate().unwrap();
|
||||
options.identity = Some(IdentityBlob::voelin(&key).unwrap());
|
||||
let Credential::Voelin(signer) = params(&options).unwrap().credential else {
|
||||
panic!("a Voelin credential")
|
||||
};
|
||||
assert_eq!(signer.public_key(), key.public_key());
|
||||
assert_eq!(signer.sign(b"hello"), key.sign(b"hello"));
|
||||
|
||||
// A Voelin blob whose key cannot be read, and a kind that connects to
|
||||
// nothing: refused in words, without the JSON.
|
||||
options.identity = Some(IdentityBlob::new("voelin", "x", 0, "hunter2"));
|
||||
let Err(SessionError::Protocol(text)) = params(&options) else { panic!("a refusal") };
|
||||
assert!(
|
||||
text.starts_with("the Voelin identity cannot be read") && !text.contains("hunter2")
|
||||
);
|
||||
options.identity = Some(IdentityBlob::new("account", "x", 0, "hunter2"));
|
||||
let Err(SessionError::Protocol(text)) = params(&options) else { panic!("a refusal") };
|
||||
assert_eq!(text, "an identity of kind \"account\" cannot be used to connect");
|
||||
}
|
||||
|
||||
/// A TeamSpeak identity with no JSON is no identity. The empty blob is
|
||||
/// what asks the TeamSpeak connector to make one up (`identity: None`), so
|
||||
/// it is refused here instead of being sent as that request.
|
||||
#[test]
|
||||
fn a_teamspeak_identity_without_json_is_refused() {
|
||||
let mut options = VoiceOptions::new("ts.example.com", "nick");
|
||||
for json in ["", " \n\t"] {
|
||||
options.identity = Some(IdentityBlob::teamspeak("uid=", 8, json));
|
||||
let Err(SessionError::Protocol(text)) = params(&options) else {
|
||||
panic!("a refusal for {json:?}")
|
||||
};
|
||||
assert_eq!(text, "the TeamSpeak identity cannot be read: it is empty");
|
||||
}
|
||||
// No identity at all is the request to make one up, as before.
|
||||
options.identity = None;
|
||||
assert!(matches!(
|
||||
params(&options).unwrap().credential,
|
||||
Credential::Foreign { kind: "teamspeak", blob } if blob.is_empty()
|
||||
));
|
||||
}
|
||||
|
||||
/// The client version spec rides the link as it was typed, whatever it
|
||||
/// holds, and only for an address that is a TeamSpeak bookmark or link.
|
||||
#[test]
|
||||
fn the_client_version_spec_rides_the_link_unchanged() {
|
||||
let spec = |address: &str, spec: &str| {
|
||||
let mut options = VoiceOptions::new(address, "nick");
|
||||
options.client_version = Some(spec.into());
|
||||
params(&options).unwrap().address
|
||||
};
|
||||
let address = spec("ts.example.com:9988", "windows@3.6.2 [Build: 1]&x=#");
|
||||
let (_, query) = address.split_once('?').unwrap();
|
||||
let text = query
|
||||
.split('&')
|
||||
.find_map(|pair| pair.strip_prefix("client_version="))
|
||||
.expect("the parameter");
|
||||
let decoded = URL_SAFE_NO_PAD.decode(text).unwrap();
|
||||
assert_eq!(decoded, b"windows@3.6.2 [Build: 1]&x=#");
|
||||
// Another scheme is left as it is: its connector has no use for a TeamSpeak
|
||||
// client's version.
|
||||
assert_eq!(spec("voelin://host/i/code", "generic"), "voelin://host/i/code");
|
||||
// No spec, no parameter.
|
||||
let options = VoiceOptions::new("ts.example.com", "nick");
|
||||
assert!(!params(&options).unwrap().address.contains(VERSION_PARAM));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
//! The session through an in-memory [`ServerLink`]: a `FakeLink` hands each
|
||||
//! connection the test asks for to the test, which plays the server by
|
||||
//! sending scripted [`LinkEvent`]s and reads the [`LinkCmd`]s the session
|
||||
//! gives. These are the tests that need the inner link itself:
|
||||
//!
|
||||
//! - the stream commands, which travel on the in-process port of the link
|
||||
//! and which a `voelin_proto::link::Session` has no part in until the
|
||||
//! stream task moves (`docs/session-seam.md` sections 6.4 and 9.2);
|
||||
//! - the order in which a reconnect shuts the streams and the old connection
|
||||
//! down, which is the order of the one queue `LinkSession` keeps;
|
||||
//! - a link that keeps talking after the engine replaced its connection,
|
||||
//! which a closed `FakeSession` cannot do on purpose.
|
||||
//!
|
||||
//! (They were integration tests while the inner link was public; it is the
|
||||
//! TeamSpeak module's now, and so are these.)
|
||||
//!
|
||||
//! Presence, chat, the dedup of a message that comes twice, history, transfers
|
||||
//! and the rest of what the engine does with a session are tested on the
|
||||
//! protocol repository's fake host in `tests/session_fake.rs`. Nothing here
|
||||
//! needs a TeamSpeak server or a TeamSpeak type.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use tokio::sync::{broadcast, mpsc};
|
||||
|
||||
use super::{Backends, LinkCmd, LinkCtx, LinkEvent};
|
||||
use crate::settings::Settings;
|
||||
use crate::stream::{StreamCmd, StreamSetup};
|
||||
use crate::ts::ts_session::LinkConnector;
|
||||
use crate::ts::{ConnectOptions, ServerLink};
|
||||
use crate::{
|
||||
BackendInfo, Command, Engine, Event, History, SessionId, SessionState, VoiceOptions, VoiceState,
|
||||
};
|
||||
use voelin_model::{
|
||||
Capabilities, ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence,
|
||||
ServerDetails,
|
||||
};
|
||||
|
||||
/// A connection the session asked the link for.
|
||||
struct Conn {
|
||||
cmds: mpsc::UnboundedReceiver<LinkCmd>,
|
||||
events: mpsc::UnboundedSender<LinkEvent>,
|
||||
}
|
||||
|
||||
impl Conn {
|
||||
/// Play `script`, the server's side, in order.
|
||||
fn play(&self, script: impl IntoIterator<Item = LinkEvent>) {
|
||||
for event in script {
|
||||
self.events.send(event).expect("the session listens");
|
||||
}
|
||||
}
|
||||
|
||||
/// The next command the session gave.
|
||||
async fn cmd(&mut self) -> LinkCmd {
|
||||
tokio::time::timeout(Duration::from_secs(10), self.cmds.recv())
|
||||
.await
|
||||
.expect("a command in time")
|
||||
.expect("the session keeps the connection")
|
||||
}
|
||||
}
|
||||
|
||||
/// Hands every connection to the test.
|
||||
struct FakeLink {
|
||||
conns: mpsc::UnboundedSender<Conn>,
|
||||
}
|
||||
|
||||
impl FakeLink {
|
||||
fn new() -> (Self, mpsc::UnboundedReceiver<Conn>) {
|
||||
let (conns, rx) = mpsc::unbounded_channel();
|
||||
(Self { conns }, rx)
|
||||
}
|
||||
}
|
||||
|
||||
impl ServerLink for FakeLink {
|
||||
fn spawn(
|
||||
&self,
|
||||
_options: ConnectOptions,
|
||||
_ctx: LinkCtx,
|
||||
cmds: mpsc::UnboundedReceiver<LinkCmd>,
|
||||
events: mpsc::UnboundedSender<LinkEvent>,
|
||||
) {
|
||||
let _ = self.conns.send(Conn { cmds, events });
|
||||
}
|
||||
}
|
||||
|
||||
const SESSION: SessionId = 1;
|
||||
const SERVER_UID: &str = "fake-server=";
|
||||
const ME: u16 = 7;
|
||||
const ME_UID: &str = "me=";
|
||||
const LOBBY: ChannelId = 1;
|
||||
const GAMES: ChannelId = 2;
|
||||
|
||||
struct Harness {
|
||||
engine: Engine,
|
||||
events: broadcast::Receiver<Event>,
|
||||
conns: mpsc::UnboundedReceiver<Conn>,
|
||||
}
|
||||
|
||||
impl Harness {
|
||||
fn start() -> Self {
|
||||
let (link, conns) = FakeLink::new();
|
||||
let mut backends = Backends::empty();
|
||||
backends.register_local(Arc::new(LinkConnector::any(Arc::new(link))));
|
||||
let engine =
|
||||
Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends);
|
||||
let events = engine.subscribe();
|
||||
Self { engine, events, conns }
|
||||
}
|
||||
|
||||
/// Ask for a voice connection and take it from the link.
|
||||
async fn connect(&mut self) -> Conn {
|
||||
let options = VoiceOptions::new("fake.test:9987", "tester");
|
||||
self.engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) });
|
||||
tokio::time::timeout(Duration::from_secs(10), self.conns.recv())
|
||||
.await
|
||||
.expect("the session spawns the link")
|
||||
.expect("the link lives")
|
||||
}
|
||||
|
||||
/// The next event `f` picks, skipping the others.
|
||||
async fn next<T>(&mut self, mut f: impl FnMut(Event) -> Option<T>) -> T {
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
if let Some(t) = f(self.events.recv().await.expect("engine events")) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("event in time")
|
||||
}
|
||||
|
||||
/// The next state of the session that `ok` accepts.
|
||||
async fn state(&mut self, mut ok: impl FnMut(&SessionState) -> bool) -> SessionState {
|
||||
self.next(|e| match e {
|
||||
Event::State { state, .. } if ok(&state) => Some(state),
|
||||
_ => None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The next live chat message.
|
||||
async fn chat(&mut self) -> ChatMessage {
|
||||
self.next(|e| match e {
|
||||
Event::Chat { message, .. } => Some(message),
|
||||
_ => None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
fn now_ms() -> i64 {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as i64
|
||||
}
|
||||
|
||||
fn capabilities(streams: bool) -> Capabilities {
|
||||
Capabilities { streams, file_transfer: true, ..Default::default() }
|
||||
}
|
||||
|
||||
fn backend() -> BackendInfo {
|
||||
BackendInfo { product: "Fake".into(), version: "1.2".into() }
|
||||
}
|
||||
|
||||
fn connected(streams: bool) -> LinkEvent {
|
||||
LinkEvent::Connected {
|
||||
name: "Fake Server".into(),
|
||||
backend: backend(),
|
||||
capabilities: capabilities(streams),
|
||||
own_client: ME,
|
||||
server_uid: SERVER_UID.into(),
|
||||
own_uid: Some(ME_UID.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A client as a TeamSpeak link reports one: with its database id, and not
|
||||
/// talking (who talks comes from the media, which the session derives).
|
||||
fn client(id: u16, nickname: &str, channel: ChannelId) -> ClientInfo {
|
||||
ClientInfo {
|
||||
id,
|
||||
uid: Some(format!("{nickname}=")),
|
||||
nickname: nickname.into(),
|
||||
channel,
|
||||
talking: Some(false),
|
||||
database_id: Some(1_000 + u64::from(id)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Two channels, three clients; we are in the second channel. The shape is
|
||||
/// what a TeamSpeak link reports: sibling channels form an order chain, the
|
||||
/// server is named and has its unique id.
|
||||
fn presence() -> Presence {
|
||||
let channel =
|
||||
|id, name: &str, order| ChannelInfo { id, name: name.into(), order, ..Default::default() };
|
||||
let mut presence = Presence { server_name: "Fake Server".into(), ..Default::default() };
|
||||
presence.server = ServerDetails {
|
||||
name: "Fake Server".into(),
|
||||
uid: Some(SERVER_UID.into()),
|
||||
version: backend().version,
|
||||
..Default::default()
|
||||
};
|
||||
presence.channels.insert(LOBBY, channel(LOBBY, "Lobby", 0));
|
||||
presence.channels.insert(GAMES, channel(GAMES, "Games", LOBBY));
|
||||
let me = ClientInfo { uid: Some(ME_UID.into()), ..client(ME, "tester", GAMES) };
|
||||
for c in [me, client(8, "alice", GAMES), client(9, "bob", LOBBY)] {
|
||||
presence.clients.insert(c.id, c);
|
||||
}
|
||||
presence
|
||||
}
|
||||
|
||||
fn message(author: &str, text: &str, ts_ms: i64) -> ChatMessage {
|
||||
ChatMessage {
|
||||
target: ChatTarget::Channel(GAMES),
|
||||
author_name: author.into(),
|
||||
author_uid: Some(format!("{author}=")),
|
||||
author_id: None,
|
||||
text: text.into(),
|
||||
ts_ms,
|
||||
via_relay: false,
|
||||
blocked: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Stream commands reach a link that has streams in its capabilities, and
|
||||
/// end with the connection; a link without them is spared. (The rest of what
|
||||
/// the user asks for is checked on the fake host in `session_fake.rs`.)
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn stream_commands_reach_a_link_with_streams() {
|
||||
let mut h = Harness::start();
|
||||
let mut conn = h.connect().await;
|
||||
conn.play([
|
||||
connected(false),
|
||||
LinkEvent::Presence(Box::new(presence())),
|
||||
LinkEvent::OwnChannel(GAMES),
|
||||
]);
|
||||
h.state(|s| s.own_channel == Some(GAMES)).await;
|
||||
|
||||
// No streams in the capabilities: the session refuses them itself.
|
||||
let engine = h.engine.clone();
|
||||
let setup = || StreamSetup { name: "screen".into(), ..Default::default() };
|
||||
engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true });
|
||||
let error = h
|
||||
.next(|e| match e {
|
||||
Event::Error { message, .. } => Some(message),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert!(error.contains("streams"), "{error}");
|
||||
assert!(conn.cmds.try_recv().is_err(), "nothing reached the link");
|
||||
|
||||
// A link with streams: stream commands go to it, and end with the connection.
|
||||
let mut with_streams = {
|
||||
let link_engine = h.engine.clone();
|
||||
link_engine.send(Command::ConnectVoice {
|
||||
session: SESSION,
|
||||
options: Box::new(VoiceOptions::new("fake.test:9987", "tester")),
|
||||
});
|
||||
h.conns.recv().await.expect("the second connection")
|
||||
};
|
||||
// The replaced connection is told to go.
|
||||
assert!(matches!(conn.cmd().await, LinkCmd::Disconnect));
|
||||
with_streams.play([connected(true)]);
|
||||
h.next(|e| match e {
|
||||
Event::ServerInfo { capabilities, .. } if capabilities.streams => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
// A connection with streams is given the (empty) stream directory first.
|
||||
let LinkCmd::Stream(StreamCmd::Directory(directory)) = with_streams.cmd().await else {
|
||||
panic!("the stream directory")
|
||||
};
|
||||
assert!(directory.is_empty());
|
||||
engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true });
|
||||
let LinkCmd::Stream(StreamCmd::Start { setup, auto_accept }) = with_streams.cmd().await else {
|
||||
panic!("a stream start")
|
||||
};
|
||||
assert_eq!((setup.name.as_str(), auto_accept), ("screen", true));
|
||||
engine.send(Command::StopStream { session: SESSION });
|
||||
assert!(matches!(with_streams.cmd().await, LinkCmd::Stream(StreamCmd::Stop)));
|
||||
engine.send(Command::DisconnectVoice { session: SESSION });
|
||||
assert!(matches!(with_streams.cmd().await, LinkCmd::Disconnect));
|
||||
}
|
||||
|
||||
/// A reconnect ends the streams of the connection it replaces through that
|
||||
/// connection, before the connection itself: the old link is given
|
||||
/// `StreamCmd::Shutdown` and only then `Disconnect`. A link that ends its
|
||||
/// connection on `Disconnect` (the TeamSpeak one stops reading commands
|
||||
/// there) relies on this order for the streams to hear of their end.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_reconnect_shuts_the_streams_down_before_the_old_connection() {
|
||||
let mut h = Harness::start();
|
||||
let mut old = h.connect().await;
|
||||
old.play([
|
||||
connected(true),
|
||||
LinkEvent::Presence(Box::new(presence())),
|
||||
LinkEvent::OwnChannel(GAMES),
|
||||
]);
|
||||
h.state(|s| s.own_channel == Some(GAMES)).await;
|
||||
let LinkCmd::Stream(StreamCmd::Directory(directory)) = old.cmd().await else {
|
||||
panic!("the stream directory")
|
||||
};
|
||||
assert!(directory.is_empty());
|
||||
|
||||
// Connecting again replaces the connection.
|
||||
let _new = h.connect().await;
|
||||
let LinkCmd::Stream(StreamCmd::Shutdown(reason)) = old.cmd().await else {
|
||||
panic!("the streams end first")
|
||||
};
|
||||
assert_eq!(reason, "voice reconnecting");
|
||||
assert!(matches!(old.cmd().await, LinkCmd::Disconnect));
|
||||
}
|
||||
|
||||
/// Events of a connection the session replaced do not reach it.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_replaced_connection_is_ignored() {
|
||||
let mut h = Harness::start();
|
||||
let mut old = h.connect().await;
|
||||
old.play([
|
||||
connected(false),
|
||||
LinkEvent::Presence(Box::new(presence())),
|
||||
LinkEvent::OwnChannel(GAMES),
|
||||
]);
|
||||
h.state(|s| s.own_channel == Some(GAMES)).await;
|
||||
|
||||
let new = h.connect().await;
|
||||
assert!(matches!(old.cmd().await, LinkCmd::Disconnect));
|
||||
// The old connection winds down, and says more than it should.
|
||||
let mut stale = presence();
|
||||
stale.clients.insert(10, client(10, "ghost", LOBBY));
|
||||
old.play([
|
||||
LinkEvent::Presence(Box::new(stale)),
|
||||
LinkEvent::Chat(message("ghost", "boo", now_ms())),
|
||||
LinkEvent::Disconnected(None),
|
||||
]);
|
||||
let mut fresh = presence();
|
||||
fresh.clients.remove(&9);
|
||||
// A link that says we are in the lobby shows us in the lobby.
|
||||
fresh.clients.get_mut(&ME).expect("we are on the server").channel = LOBBY;
|
||||
new.play([
|
||||
connected(false),
|
||||
LinkEvent::Presence(Box::new(fresh.clone())),
|
||||
LinkEvent::OwnChannel(LOBBY),
|
||||
]);
|
||||
// Only the new connection's presence is shown (nobody else has 2 clients).
|
||||
let shown = h
|
||||
.next(|e| match e {
|
||||
Event::Presence { presence, .. } if presence.clients.len() == fresh.clients.len() => {
|
||||
Some(presence)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(*shown, fresh);
|
||||
let state = h.state(|s| s.own_channel == Some(LOBBY)).await;
|
||||
assert_eq!(state.voice, VoiceState::Connected, "the old disconnect did not count");
|
||||
// Channel chat reaches the channel we are in (the lobby, now).
|
||||
new.play([LinkEvent::Chat(ChatMessage {
|
||||
target: ChatTarget::Channel(LOBBY),
|
||||
..message("alice", "hello", now_ms())
|
||||
})]);
|
||||
assert_eq!(h.chat().await.text, "hello", "the old connection's chat never showed");
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
//! The engine's side of the seam against the protocol repository's fake host
|
||||
//! (`docs/session-seam.md` sections 9.2 and 16): the voice path through a
|
||||
//! `SessionLink` that talks to a `FakeSession`, and the link conformance
|
||||
//! suite run against the session the engine's registry hands over.
|
||||
//!
|
||||
//! The tests that need only the engine's public API are in
|
||||
//! `tests/session_fake.rs`; these need what is private to the crate: the
|
||||
//! `LinkCmd`/`LinkEvent` vocabulary between `session.rs` and `SessionLink`,
|
||||
//! the registry's `connect` and the context of a connector called outside an
|
||||
//! engine.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use voelin_audio::{EncodedVoice, VoiceCodec, VoicePacket};
|
||||
use voelin_proto::link::{FlowId, MediaClass, MediaPacket, voice_sub};
|
||||
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, PT_OPUS};
|
||||
use voelin_proto::media::{RtpHeader, RtpView};
|
||||
use voelin_proto::test_util::conformance::{self, Fixture, Verdict};
|
||||
use voelin_proto::test_util::{
|
||||
FAKE_HOST_UID, FakeConnector, FakeHandle, connect_params, eventually,
|
||||
};
|
||||
use voelin_proto::v1::{self, entity::Kind};
|
||||
|
||||
use super::*;
|
||||
|
||||
const WAIT: Duration = Duration::from_secs(10);
|
||||
/// An Opus frame of 20 ms, mono (TOC `0xf8`), and the same as stereo (`0xfc`).
|
||||
const MONO: [u8; 3] = [0xf8, 0xff, 0xfe];
|
||||
const STEREO: [u8; 3] = [0xfc, 0xff, 0xfe];
|
||||
const ALICE: u32 = 50;
|
||||
const ALICE_SLOT: u32 = 90;
|
||||
const BOB: u32 = 51;
|
||||
const BOB_SLOT: u32 = 91;
|
||||
|
||||
fn put(connector: &FakeConnector, kind: Kind) {
|
||||
connector.host().put(v1::Entity { kind: Some(kind) }).expect("the fake host stores it");
|
||||
}
|
||||
|
||||
/// A host with one server, a lobby, and alice and bob talking in it.
|
||||
fn host() -> FakeConnector {
|
||||
let connector = FakeConnector::new();
|
||||
put(
|
||||
&connector,
|
||||
Kind::Server(v1::Server {
|
||||
id: 1,
|
||||
name: "Fake Host".into(),
|
||||
uid: "fake-host".into(),
|
||||
default_channel_id: 10,
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
put(
|
||||
&connector,
|
||||
Kind::Channel(v1::Channel {
|
||||
id: 10,
|
||||
server_id: 1,
|
||||
kind: v1::ChannelKind::Voice as i32,
|
||||
name: "Lobby".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
for (user, participant, slot, name) in
|
||||
[(2, ALICE, ALICE_SLOT, "alice"), (3, BOB, BOB_SLOT, "bob")]
|
||||
{
|
||||
put(
|
||||
&connector,
|
||||
Kind::User(v1::User {
|
||||
id: user,
|
||||
uid: vec![user as u8; 32].into(),
|
||||
uid_kind: v1::IdKind::Voelin as i32,
|
||||
name: name.into(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
put(
|
||||
&connector,
|
||||
Kind::Voice(v1::VoiceState {
|
||||
server_id: 1,
|
||||
participant_id: participant,
|
||||
user_id: user,
|
||||
channel_id: 10,
|
||||
slot,
|
||||
nick: name.into(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
}
|
||||
connector
|
||||
}
|
||||
|
||||
/// A `SessionLink` over a fake host, driven the way `session.rs` drives it.
|
||||
struct HostRig {
|
||||
handle: FakeHandle,
|
||||
cmds: mpsc::UnboundedSender<LinkCmd>,
|
||||
events: mpsc::UnboundedReceiver<LinkEvent>,
|
||||
/// Our participant and voice slot, as the host gave them.
|
||||
own_client: u16,
|
||||
own_slot: u32,
|
||||
/// The clients the link told started talking, in order.
|
||||
talking: Vec<u16>,
|
||||
}
|
||||
|
||||
/// The next event `f` picks from `events`, skipping the others.
|
||||
async fn event_of<T>(
|
||||
events: &mut mpsc::UnboundedReceiver<LinkEvent>,
|
||||
mut f: impl FnMut(LinkEvent) -> Option<T>,
|
||||
) -> T {
|
||||
tokio::time::timeout(WAIT, async {
|
||||
loop {
|
||||
if let Some(t) = f(events.recv().await.expect("the link lives")) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("an event in time")
|
||||
}
|
||||
|
||||
impl HostRig {
|
||||
async fn connect() -> Self {
|
||||
let connector = host();
|
||||
let mut backends = Backends::empty();
|
||||
backends.register(Arc::new(connector.clone()));
|
||||
let link = SessionLink::new(backends);
|
||||
let (cmds, cmd_rx) = mpsc::unbounded_channel();
|
||||
let (event_tx, mut events) = mpsc::unbounded_channel();
|
||||
let ctx = LocalCtx::standalone().link;
|
||||
link.spawn(VoiceOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx);
|
||||
let own_client = event_of(&mut events, |e| match e {
|
||||
LinkEvent::Connected { own_client, .. } => Some(own_client),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
event_of(&mut events, |e| matches!(e, LinkEvent::OwnChannel(10)).then_some(())).await;
|
||||
let own_slot = connector
|
||||
.host()
|
||||
.entities(&v1::Scope { kind: v1::ScopeKind::Live as i32, id: 1 })
|
||||
.into_iter()
|
||||
.find_map(|e| match e.kind? {
|
||||
Kind::Voice(v) if v.participant_id == u32::from(own_client) => Some(v.slot),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the host seated us in voice");
|
||||
let handle = connector.last_session().expect("the connector made a session");
|
||||
Self { handle, cmds, events, own_client, own_slot, talking: Vec::new() }
|
||||
}
|
||||
|
||||
/// The next voice packet the audio thread would get; who started to talk on
|
||||
/// the way is kept in `talking`.
|
||||
async fn audio(&mut self) -> VoicePacket {
|
||||
let talking = &mut self.talking;
|
||||
event_of(&mut self.events, |e| match e {
|
||||
LinkEvent::Talking { client, talking: true } => {
|
||||
talking.push(client);
|
||||
None
|
||||
}
|
||||
LinkEvent::Audio(packet) => Some(packet),
|
||||
_ => None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
fn give(&self, cmd: LinkCmd) {
|
||||
self.cmds.send(cmd).expect("the link listens");
|
||||
}
|
||||
}
|
||||
|
||||
/// A voice packet of `slot` on sub-flow `sub`, as a host delivers it.
|
||||
fn voice_packet(slot: u32, sub: u8, sequence: u16, payload: &[u8]) -> MediaPacket {
|
||||
let flow = FlowId::new(slot, sub);
|
||||
let mut out = bytes::BytesMut::new();
|
||||
RtpHeader::new(PT_OPUS, sequence, u32::from(sequence) * 960)
|
||||
.write(flow, &mut out)
|
||||
.expect("a header");
|
||||
out.extend_from_slice(payload);
|
||||
MediaPacket { flow, rtp: out.freeze() }
|
||||
}
|
||||
|
||||
fn voice(payload: &[u8]) -> EncodedVoice {
|
||||
EncodedVoice { codec: VoiceCodec::Voice, payload: payload.to_vec() }
|
||||
}
|
||||
|
||||
/// Our voice leaves as RTP on the slot the host gave us: the sequence counts
|
||||
/// every packet, the timestamp advances by the duration of the previous one,
|
||||
/// the marker is on the first packet of a spurt, the end of a spurt is an
|
||||
/// empty payload sent once, and the SSRC is the flow (protocol section 6).
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn our_voice_is_rtp_on_the_slot_the_host_gave_us() {
|
||||
let rig = HostRig::connect().await;
|
||||
// The fake host loops accepted media back; this test looks at what left.
|
||||
rig.handle.set_loopback(false);
|
||||
for n in 1..=3 {
|
||||
rig.give(LinkCmd::Audio(voice(&[0xf8, 0xff, 0xfe, n])));
|
||||
}
|
||||
rig.give(LinkCmd::Audio(voice(&[])));
|
||||
rig.give(LinkCmd::Audio(voice(&[0xf8, 0xff, 0xfe, 9])));
|
||||
let handle = rig.handle.clone();
|
||||
eventually(WAIT, "the five packets", || handle.sent_media().len() == 5).await;
|
||||
|
||||
let flow = FlowId::new(rig.own_slot, voice_sub::CHANNEL);
|
||||
let sent = rig.handle.sent_media();
|
||||
let seen: Vec<_> = sent
|
||||
.iter()
|
||||
.map(|(class, packet)| {
|
||||
let view = RtpView::parse(&packet.rtp).expect("RTP");
|
||||
assert_eq!(*class, MediaClass::Voice);
|
||||
assert_eq!(packet.flow, flow);
|
||||
assert_eq!((view.payload_type(), view.ssrc()), (PT_OPUS, flow.0));
|
||||
(view.sequence(), view.marker(), view.timestamp(), view.payload().to_vec())
|
||||
})
|
||||
.collect();
|
||||
let ticks = OPUS_20_MS_TICKS;
|
||||
assert_eq!(
|
||||
seen,
|
||||
[
|
||||
(0, true, 0, vec![0xf8, 0xff, 0xfe, 1]),
|
||||
(1, false, ticks, vec![0xf8, 0xff, 0xfe, 2]),
|
||||
(2, false, 2 * ticks, vec![0xf8, 0xff, 0xfe, 3]),
|
||||
// The end of the spurt: no payload, no marker, once.
|
||||
(3, false, 3 * ticks, vec![]),
|
||||
// The next spurt marks its first packet again.
|
||||
(4, true, 3 * ticks, vec![0xf8, 0xff, 0xfe, 9]),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// The RTP of other slots becomes the packets of the audio thread: the talker
|
||||
/// is the participant of the slot, a whisper sub-flow is a whisper, a stereo
|
||||
/// Opus frame is music, an empty payload ends the spurt; what is no voice of a
|
||||
/// slot the host told about is dropped.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_voice_of_other_slots_reaches_the_audio_thread() {
|
||||
let mut rig = HostRig::connect().await;
|
||||
let handle = rig.handle.clone();
|
||||
|
||||
// A slot nobody has, a probe and feedback: nothing. Then alice, mono.
|
||||
handle.inject_media(voice_packet(777, voice_sub::CHANNEL, 1, &MONO));
|
||||
handle.inject_media(MediaPacket { flow: FlowId::PROBE, rtp: bytes::Bytes::from_static(&[1]) });
|
||||
handle.inject_media(MediaPacket {
|
||||
flow: FlowId::FEEDBACK,
|
||||
rtp: bytes::Bytes::from_static(&[1, 2]),
|
||||
});
|
||||
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 5, &MONO));
|
||||
let packet = rig.audio().await;
|
||||
assert_eq!(
|
||||
(packet.talker.0, packet.seq, packet.codec, packet.whisper, packet.payload.as_slice()),
|
||||
(ALICE as u16, 5, VoiceCodec::Voice, false, MONO.as_slice())
|
||||
);
|
||||
|
||||
// Bob whispers (sub-flow 1) in stereo: music, a whisper.
|
||||
handle.inject_media(voice_packet(BOB_SLOT, 1, 6, &STEREO));
|
||||
let packet = rig.audio().await;
|
||||
assert_eq!(
|
||||
(packet.talker.0, packet.seq, packet.codec, packet.whisper),
|
||||
(BOB as u16, 6, VoiceCodec::Music, true)
|
||||
);
|
||||
|
||||
// Alice stops: an empty payload.
|
||||
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 7, &[]));
|
||||
let packet = rig.audio().await;
|
||||
assert_eq!((packet.talker.0, packet.seq, packet.payload.len()), (ALICE as u16, 7, 0));
|
||||
|
||||
// Who talks comes from the same packets: alice started, then bob, once each
|
||||
// (the slot nobody has started nobody).
|
||||
assert_eq!(rig.talking, [ALICE as u16, BOB as u16]);
|
||||
}
|
||||
|
||||
/// A host whose session loops our own voice back (the fake one does, so that
|
||||
/// the conformance suite can see media move) does not make the engine play us
|
||||
/// our own voice or show us as talking: the engine never plays itself.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn our_own_voice_coming_back_is_not_played_back() {
|
||||
let mut rig = HostRig::connect().await;
|
||||
// The fake host loops accepted media back into the sink (the default).
|
||||
rig.give(LinkCmd::Audio(voice(&MONO)));
|
||||
let handle = rig.handle.clone();
|
||||
eventually(WAIT, "the packet to leave", || handle.sent_media().len() == 1).await;
|
||||
// A packet of alice behind it: when this one is out, ours has been through.
|
||||
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 1, &MONO));
|
||||
let own = rig.own_client;
|
||||
let mut heard = Vec::new();
|
||||
while heard.last().is_none_or(|talker| *talker != ALICE as u16) {
|
||||
heard.push(rig.audio().await.talker.0);
|
||||
}
|
||||
assert!(!heard.contains(&own), "the engine played our own voice back: {heard:?}");
|
||||
}
|
||||
|
||||
/// The link conformance suite of the protocol repository against the session
|
||||
/// the engine's registry hands over: the registry adds nothing to a plain
|
||||
/// connector's session (`Backends::connect` returns it untouched), so the 17
|
||||
/// cases pass as they do in the protocol repository, none skipped.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_conformance_suite_passes_on_a_session_of_the_registry() {
|
||||
async fn through_the_registry() -> Fixture {
|
||||
let connector = FakeConnector::new();
|
||||
let mut backends = Backends::empty();
|
||||
backends.register(Arc::new(connector.clone()));
|
||||
let (params, media) = connect_params("fake://conformance");
|
||||
let local = backends
|
||||
.connect(params, LocalCtx::standalone())
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("the registry connects: {e}"));
|
||||
assert_eq!(local.connected.host_uid, FAKE_HOST_UID, "the connector's own answer");
|
||||
assert!(local.streams.is_none(), "a plain connector has no stream port");
|
||||
let backend = connector.last_session().expect("the connector made a session");
|
||||
// The session is the connector's own, so a request id means the same to both.
|
||||
Fixture {
|
||||
shared_request_ids: true,
|
||||
..Fixture::new(local.connected.session, local.connected.pushes, media, backend)
|
||||
}
|
||||
}
|
||||
let report = conformance::run(&through_the_registry).await;
|
||||
assert_eq!(report.cases.len(), conformance::CASES.len());
|
||||
assert_eq!(report.cases.len(), 17, "the suite of c8e0e5a has 17 cases");
|
||||
assert!(
|
||||
report.cases.iter().all(|(_, verdict)| *verdict == Verdict::Passed),
|
||||
"{:?}",
|
||||
report.cases
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
//! Voice across the seam, engine side (`docs/session-seam.md` section 6.1):
|
||||
//! our encoded frames as RTP on our voice slot, the RTP of other slots as
|
||||
//! the audio thread's packets, and who is talking from the media.
|
||||
//!
|
||||
//! `voelin-audio`'s [`EncodedVoice`] and [`VoicePacket`] stay what the audio
|
||||
//! thread speaks; this is the framing in the v1 media codec
|
||||
//! (`voelin_proto::media`, protocol section 6).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::BytesMut;
|
||||
use voelin_audio::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket};
|
||||
use voelin_proto::link::{FlowId, MediaPacket, voice_sub};
|
||||
use voelin_proto::media::opus::{self, Toc};
|
||||
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, PT_OPUS};
|
||||
use voelin_proto::media::{RtpHeader, RtpView};
|
||||
|
||||
/// A talker is silent after this long without a packet.
|
||||
pub(crate) const TALK_SILENCE: Duration = Duration::from_millis(400);
|
||||
|
||||
/// Our voice as RTP: the sequence number counts every packet from 0, the
|
||||
/// timestamp starts at 0 and advances by the duration of the previous
|
||||
/// packet, the marker is set on the first packet of a spurt, and the end of a
|
||||
/// spurt is a packet with an empty payload, sent once.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Uplink {
|
||||
sequence: u16,
|
||||
timestamp: u32,
|
||||
/// The ticks the last voice packet spans.
|
||||
ticks: u32,
|
||||
in_spurt: bool,
|
||||
}
|
||||
|
||||
impl Uplink {
|
||||
/// `voice` as the RTP packet of our voice slot.
|
||||
pub(crate) fn frame(&mut self, slot: u32, voice: &EncodedVoice) -> Option<MediaPacket> {
|
||||
let flow = FlowId::new(slot, voice_sub::CHANNEL);
|
||||
// The previous packet's duration has passed.
|
||||
self.timestamp = self.timestamp.wrapping_add(self.ticks);
|
||||
let end = voice.is_end();
|
||||
let mut header = RtpHeader::new(PT_OPUS, self.sequence, self.timestamp);
|
||||
header.marker = !end && !self.in_spurt;
|
||||
self.ticks =
|
||||
if end { 0 } else { opus::packet_ticks(&voice.payload).unwrap_or(OPUS_20_MS_TICKS) };
|
||||
self.in_spurt = !end;
|
||||
self.sequence = self.sequence.wrapping_add(1);
|
||||
let mut out = BytesMut::with_capacity(header.encoded_len() + voice.payload.len());
|
||||
header.write(flow, &mut out).ok()?;
|
||||
out.extend_from_slice(&voice.payload);
|
||||
Some(MediaPacket { flow, rtp: out.freeze() })
|
||||
}
|
||||
}
|
||||
|
||||
/// A voice packet of some slot, taken from its RTP.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Incoming {
|
||||
pub(crate) slot: u32,
|
||||
/// Sent on a whisper sub-flow (1 to 6).
|
||||
pub(crate) whisper: bool,
|
||||
pub(crate) sequence: u16,
|
||||
pub(crate) codec: VoiceCodec,
|
||||
/// Empty: the spurt ends.
|
||||
pub(crate) payload: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Incoming {
|
||||
/// Parse a media packet. `None` for what is not the voice of a slot:
|
||||
/// feedback, probes, a flow that is no media, a packet that is no RTP.
|
||||
pub(crate) fn parse(packet: &MediaPacket) -> Option<Incoming> {
|
||||
if !packet.flow.is_media() {
|
||||
return None;
|
||||
}
|
||||
let view = RtpView::parse(&packet.rtp).ok()?;
|
||||
let payload = view.payload();
|
||||
// Stereo Opus is music; the jitter buffer decodes both the same way.
|
||||
let codec = match Toc::parse(payload) {
|
||||
Ok(toc) if toc.stereo() => VoiceCodec::Music,
|
||||
_ => VoiceCodec::Voice,
|
||||
};
|
||||
Some(Incoming {
|
||||
slot: packet.flow.slot(),
|
||||
whisper: (voice_sub::FIRST_TALK_TARGET..=voice_sub::LAST_TALK_TARGET)
|
||||
.contains(&packet.flow.sub()),
|
||||
sequence: view.sequence(),
|
||||
codec,
|
||||
payload: payload.to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The packet for the audio thread, from `talker`.
|
||||
pub(crate) fn voice(self, talker: u16) -> VoicePacket {
|
||||
VoicePacket {
|
||||
talker: TalkerId(talker),
|
||||
seq: self.sequence,
|
||||
codec: self.codec,
|
||||
whisper: self.whisper,
|
||||
payload: self.payload,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Who is talking: derived from the media (protocol section 6.4). A talker
|
||||
/// starts with its first packet and stops after [`TALK_SILENCE`] without one.
|
||||
///
|
||||
/// A host can also say that someone talks whose voice it does not carry as
|
||||
/// media (a `Speaking` signal; TeamSpeak's Speex and CELT talkers are such):
|
||||
/// that is a hint, which holds until the host says it is over.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct TalkTracker {
|
||||
last: HashMap<u16, Instant>,
|
||||
hinted: HashSet<u16>,
|
||||
}
|
||||
|
||||
impl TalkTracker {
|
||||
/// A packet of `client` arrived; whether this starts its talking.
|
||||
pub(crate) fn heard(&mut self, client: u16, now: Instant) -> bool {
|
||||
let was = self.is_talking(client);
|
||||
self.last.insert(client, now);
|
||||
!was
|
||||
}
|
||||
|
||||
/// The host says `client` talks or has stopped; whether this changes
|
||||
/// whether it is talking.
|
||||
pub(crate) fn hint(&mut self, client: u16, talking: bool) -> bool {
|
||||
let was = self.is_talking(client);
|
||||
if talking {
|
||||
self.hinted.insert(client);
|
||||
} else {
|
||||
self.hinted.remove(&client);
|
||||
}
|
||||
was != self.is_talking(client)
|
||||
}
|
||||
|
||||
/// Forget the hints about clients `present` does not hold any more: a
|
||||
/// client that left cannot say it stopped.
|
||||
pub(crate) fn retain_hints(&mut self, present: impl Fn(u16) -> bool) {
|
||||
self.hinted.retain(|client| present(*client));
|
||||
}
|
||||
|
||||
/// The talkers that have been silent long enough, no longer talking.
|
||||
pub(crate) fn expire(&mut self, now: Instant) -> Vec<u16> {
|
||||
let mut silent: Vec<u16> = self
|
||||
.last
|
||||
.iter()
|
||||
.filter(|(_, last)| now.saturating_duration_since(**last) >= TALK_SILENCE)
|
||||
.map(|(client, _)| *client)
|
||||
.collect();
|
||||
silent.sort_unstable();
|
||||
for client in &silent {
|
||||
self.last.remove(client);
|
||||
}
|
||||
silent.retain(|client| !self.hinted.contains(client));
|
||||
silent
|
||||
}
|
||||
|
||||
pub(crate) fn is_talking(&self, client: u16) -> bool {
|
||||
self.last.contains_key(&client) || self.hinted.contains(&client)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// 20 ms of CELT, mono, one frame.
|
||||
const OPUS_20_MS: [u8; 3] = [0x98, 0x01, 0x02];
|
||||
|
||||
fn voice(payload: &[u8]) -> EncodedVoice {
|
||||
EncodedVoice { codec: VoiceCodec::Voice, payload: payload.to_vec() }
|
||||
}
|
||||
|
||||
fn view(packet: &MediaPacket) -> RtpView<'_> {
|
||||
RtpView::parse(&packet.rtp).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn our_voice_is_sequenced_stamped_and_marked() {
|
||||
let mut up = Uplink::default();
|
||||
let first = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
let second = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
assert_eq!((first.flow.slot(), first.flow.sub()), (8, 0));
|
||||
let (a, b) = (view(&first), view(&second));
|
||||
assert_eq!((a.sequence(), a.timestamp(), a.marker()), (0, 0, true));
|
||||
assert_eq!((b.sequence(), b.timestamp(), b.marker()), (1, OPUS_20_MS_TICKS, false));
|
||||
assert_eq!((a.ssrc(), a.payload_type()), (first.flow.0, PT_OPUS));
|
||||
assert_eq!(a.payload(), OPUS_20_MS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_is_one_empty_packet_and_the_next_spurt_has_a_marker() {
|
||||
let mut up = Uplink::default();
|
||||
up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
let end = up.frame(8, &voice(&[])).unwrap();
|
||||
assert!(view(&end).payload().is_empty() && !view(&end).marker());
|
||||
assert_eq!(view(&end).sequence(), 1);
|
||||
let next = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
assert!(view(&next).marker());
|
||||
assert_eq!(view(&next).sequence(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sequence_wraps() {
|
||||
let mut up = Uplink { sequence: u16::MAX, ..Default::default() };
|
||||
up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
let wrapped = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
||||
assert_eq!(view(&wrapped).sequence(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn received_voice_is_split_into_slot_sub_flow_sequence_and_codec() {
|
||||
let flow = FlowId::new(9, 0);
|
||||
let mut header = RtpHeader::new(PT_OPUS, 513, 0);
|
||||
header.marker = true;
|
||||
let mut rtp = BytesMut::new();
|
||||
header.write(flow, &mut rtp).unwrap();
|
||||
rtp.extend_from_slice(&OPUS_20_MS);
|
||||
let packet = MediaPacket { flow, rtp: rtp.freeze() };
|
||||
let got = Incoming::parse(&packet).unwrap();
|
||||
assert_eq!(
|
||||
got,
|
||||
Incoming {
|
||||
slot: 9,
|
||||
whisper: false,
|
||||
sequence: 513,
|
||||
codec: VoiceCodec::Voice,
|
||||
payload: OPUS_20_MS.to_vec()
|
||||
}
|
||||
);
|
||||
let voice = got.voice(8);
|
||||
assert_eq!((voice.talker, voice.seq, voice.whisper), (TalkerId(8), 513, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whispers_stereo_ends_and_what_is_no_voice() {
|
||||
let packet = |flow: FlowId, payload: &[u8]| {
|
||||
let mut rtp = BytesMut::new();
|
||||
RtpHeader::new(PT_OPUS, 1, 0).write(flow, &mut rtp).unwrap();
|
||||
rtp.extend_from_slice(payload);
|
||||
MediaPacket { flow, rtp: rtp.freeze() }
|
||||
};
|
||||
assert!(Incoming::parse(&packet(FlowId::new(9, 3), &OPUS_20_MS)).unwrap().whisper);
|
||||
assert!(!Incoming::parse(&packet(FlowId::new(9, 7), &OPUS_20_MS)).unwrap().whisper);
|
||||
let stereo = [OPUS_20_MS[0] | 0x04, 1, 2];
|
||||
assert_eq!(
|
||||
Incoming::parse(&packet(FlowId::new(9, 0), &stereo)).unwrap().codec,
|
||||
VoiceCodec::Music
|
||||
);
|
||||
let end = Incoming::parse(&packet(FlowId::new(9, 0), &[])).unwrap();
|
||||
assert!(end.payload.is_empty() && end.voice(8).is_end());
|
||||
// Feedback and probes are no voice.
|
||||
assert!(
|
||||
Incoming::parse(&MediaPacket { flow: FlowId::FEEDBACK, rtp: Default::default() })
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
Incoming::parse(&MediaPacket { flow: FlowId::PROBE, rtp: Default::default() })
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
Incoming::parse(&MediaPacket { flow: FlowId::new(9, 0), rtp: vec![1, 2].into() })
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_talker_starts_with_a_packet_and_stops_400_ms_after_its_last() {
|
||||
let mut talk = TalkTracker::default();
|
||||
let t0 = Instant::now();
|
||||
assert!(talk.heard(8, t0));
|
||||
assert!(!talk.heard(8, t0 + Duration::from_millis(100)), "already talking");
|
||||
assert!(talk.heard(9, t0 + Duration::from_millis(150)));
|
||||
assert!(talk.is_talking(8));
|
||||
// 399 ms after 8's last packet: still talking.
|
||||
assert!(talk.expire(t0 + Duration::from_millis(499)).is_empty());
|
||||
assert_eq!(talk.expire(t0 + Duration::from_millis(500)), [8]);
|
||||
assert!(!talk.is_talking(8) && talk.is_talking(9));
|
||||
assert_eq!(talk.expire(t0 + Duration::from_millis(551)), [9]);
|
||||
// A packet after the silence starts it again.
|
||||
assert!(talk.heard(8, t0 + Duration::from_secs(2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_that_says_someone_talks_is_believed_until_it_says_otherwise() {
|
||||
let mut talk = TalkTracker::default();
|
||||
let t0 = Instant::now();
|
||||
// A talker whose voice is no media: on, and no silence ends it.
|
||||
assert!(talk.hint(8, true));
|
||||
assert!(!talk.hint(8, true), "already talking");
|
||||
assert!(talk.is_talking(8));
|
||||
assert!(talk.expire(t0 + Duration::from_secs(60)).is_empty());
|
||||
assert!(talk.hint(8, false));
|
||||
assert!(!talk.is_talking(8));
|
||||
// A talker with media that the host also names: the media ends it, when
|
||||
// the host has said it is over (in either order).
|
||||
assert!(talk.heard(9, t0));
|
||||
assert!(!talk.hint(9, true), "heard already");
|
||||
assert!(talk.expire(t0 + Duration::from_millis(500)).is_empty(), "the host still says so");
|
||||
assert!(talk.is_talking(9));
|
||||
assert!(talk.hint(9, false));
|
||||
assert!(!talk.is_talking(9));
|
||||
assert!(talk.heard(10, t0));
|
||||
assert!(!talk.hint(10, false), "the media goes on");
|
||||
assert_eq!(talk.expire(t0 + Duration::from_millis(500)), [10]);
|
||||
// A hint about somebody who is gone is forgotten.
|
||||
assert!(talk.hint(11, true));
|
||||
talk.retain_hints(|client| client != 11);
|
||||
assert!(!talk.is_talking(11));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
//! The engine's seam to the server its voice source talks to.
|
||||
//!
|
||||
//! A session merges up to three sources (voice, gateway, query). The *voice*
|
||||
//! source is the connection that is visible on the server, can talk and
|
||||
//! carries chat, files, pokes, offline messages and streams. The engine holds
|
||||
//! it as a `voelin_proto::link::Session`, the backend-neutral interface of the
|
||||
//! protocol repository, and knows nothing else of the server software behind
|
||||
//! it: which backend makes the `Session` is the scheme of the address, and
|
||||
//! [`Backends`] is the registry of connectors by scheme
|
||||
//! ([`Backends::default`] has the TeamSpeak one,
|
||||
//! [`crate::ts::TsConnector`]; a Voelin host's QUIC connector will be
|
||||
//! another). [`VoiceOptions`] says what to connect to and as whom.
|
||||
//!
|
||||
//! Inside the crate `session.rs` merges and routes, and an adapter below it
|
||||
//! turns what it asks into `Session` calls and what the `Session` pushes into
|
||||
//! what it hears (`link/session_link.rs`, with `project.rs` and `media.rs`);
|
||||
//! `docs/session-seam.md` describes the mapping row by row.
|
||||
|
||||
mod backends;
|
||||
mod connect;
|
||||
#[cfg(test)]
|
||||
mod fake_link_tests;
|
||||
#[cfg(test)]
|
||||
mod fake_tests;
|
||||
pub(crate) mod media;
|
||||
pub(crate) mod project;
|
||||
mod session_link;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub use backends::Backends;
|
||||
pub(crate) use backends::{
|
||||
LocalConnected, LocalConnector, LocalCtx, StreamEvent, StreamPort, without_query,
|
||||
};
|
||||
pub(crate) use connect::{VERSION_PARAM, connect_params};
|
||||
pub(crate) use session_link::SessionLink;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tokio::sync::{broadcast, oneshot};
|
||||
use voelin_audio::{EncodedVoice, VoicePacket};
|
||||
use voelin_identity::IdentityBlob;
|
||||
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence};
|
||||
use voelin_stream::PeerConfig;
|
||||
|
||||
use crate::files::{Report, RequestId, Sink, TransferId};
|
||||
use crate::settings::SharedSettings;
|
||||
use crate::stream::{OwnStreamEvent, StreamCmd, StreamFrame};
|
||||
use crate::{BackendInfo, Event, SessionId};
|
||||
|
||||
/// What a voice connection needs to know: the server, who to be, where to
|
||||
/// join ([`Command::ConnectVoice`](crate::Command::ConnectVoice)).
|
||||
///
|
||||
/// Nothing in it belongs to one kind of server: what a connector needs of it
|
||||
/// that is its own (a TeamSpeak identity, the client version to claim) is in
|
||||
/// the `identity` blob and the `client_version` spec, which the connector of
|
||||
/// the address reads.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct VoiceOptions {
|
||||
/// The server: `host[:port]` of a TeamSpeak bookmark, or an address with a
|
||||
/// scheme (`ts3server://`, `teamspeak://`, a Voelin host's `voelin://`)
|
||||
/// that picks the connector ([`Backends`]).
|
||||
pub address: String,
|
||||
pub nickname: String,
|
||||
/// The identity to connect with: a TeamSpeak identity
|
||||
/// ([`crate::ts::identity::to_blob`]) for a TeamSpeak server, a Voelin key
|
||||
/// for a Voelin host. None lets the connector make one up (a TeamSpeak
|
||||
/// connection generates an identity, which a server then knows as a new
|
||||
/// client).
|
||||
pub identity: Option<IdentityBlob>,
|
||||
/// The client version a TeamSpeak server is shown, as a spec for
|
||||
/// [`crate::ts::versions::resolve`] (`default`, `generic`, an index, or
|
||||
/// `<platform>@<version>`); `None` is the native platform's. A spec that is
|
||||
/// none ends the connect with the reason. Other backends ignore it.
|
||||
pub client_version: Option<String>,
|
||||
pub server_password: Option<String>,
|
||||
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
|
||||
pub channel: Option<String>,
|
||||
/// The password of `channel`.
|
||||
pub channel_password: Option<String>,
|
||||
/// A privilege key to use when connecting.
|
||||
pub token: Option<String>,
|
||||
/// Open the audio devices (capture and playback).
|
||||
pub audio: bool,
|
||||
/// Network settings for stream peer connections (TeamSpeak 6).
|
||||
pub stream_peer: PeerConfig,
|
||||
}
|
||||
|
||||
impl VoiceOptions {
|
||||
/// Options for `address` and `nickname`; everything else is left to the
|
||||
/// connector.
|
||||
pub fn new(address: impl Into<String>, nickname: impl Into<String>) -> Self {
|
||||
Self {
|
||||
address: address.into(),
|
||||
nickname: nickname.into(),
|
||||
identity: None,
|
||||
client_version: None,
|
||||
server_password: None,
|
||||
channel: None,
|
||||
channel_password: None,
|
||||
token: None,
|
||||
audio: false,
|
||||
stream_peer: PeerConfig::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the engine gives a link besides the options: where the connection
|
||||
/// answers the requests the session need not see, and what it shares with
|
||||
/// the session's other parts.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct LinkCtx {
|
||||
pub(crate) session: SessionId,
|
||||
pub(crate) events: broadcast::Sender<Event>,
|
||||
/// The frames of watched streams (kept off the event bus).
|
||||
pub(crate) frames: broadcast::Sender<StreamFrame>,
|
||||
pub(crate) settings: SharedSettings,
|
||||
}
|
||||
|
||||
impl LinkCtx {
|
||||
/// The session this connection belongs to.
|
||||
pub(crate) fn session(&self) -> SessionId {
|
||||
self.session
|
||||
}
|
||||
|
||||
/// Tell the engine's event bus something (a request's answer, a
|
||||
/// transfer's progress).
|
||||
pub(crate) fn emit(&self, event: Event) {
|
||||
let _ = self.events.send(event);
|
||||
}
|
||||
|
||||
pub(crate) fn done(&self, request: RequestId, result: Result<(), String>) {
|
||||
self.emit(Event::RequestDone { session: self.session, request, result });
|
||||
}
|
||||
}
|
||||
|
||||
/// A file on the server: channel, its password, path.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Remote {
|
||||
pub channel: ChannelId,
|
||||
pub password: Option<String>,
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
/// A boxed stream of bytes to read: the body of a file the server sends.
|
||||
pub(crate) type BoxRead = Pin<Box<dyn AsyncRead + Send>>;
|
||||
|
||||
/// A connection that can be read and written: a file transfer connection.
|
||||
pub(crate) trait Duplex: AsyncRead + AsyncWrite + Send {}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite + Send> Duplex for T {}
|
||||
|
||||
/// A boxed [`Duplex`].
|
||||
pub(crate) type BoxDuplex = Pin<Box<dyn Duplex>>;
|
||||
|
||||
/// What the session asks of a connection.
|
||||
pub(crate) enum LinkCmd {
|
||||
SendChat(ChatTarget, String),
|
||||
Move(ChannelId, Option<String>),
|
||||
SetInputMuted(bool),
|
||||
SetOutputMuted(bool),
|
||||
/// An encoded voice frame from the audio thread.
|
||||
Audio(EncodedVoice),
|
||||
/// A stream command; the link answers on the event bus. Only sent while
|
||||
/// the connection's capabilities include streams.
|
||||
Stream(StreamCmd),
|
||||
Poke {
|
||||
client: u16,
|
||||
message: String,
|
||||
},
|
||||
ListFiles {
|
||||
request: RequestId,
|
||||
dir: Remote,
|
||||
},
|
||||
/// Download `file`; `transfer` if the user can cancel it.
|
||||
Download {
|
||||
transfer: Option<TransferId>,
|
||||
file: Remote,
|
||||
sink: Sink,
|
||||
report: Report,
|
||||
},
|
||||
Upload {
|
||||
transfer: Option<TransferId>,
|
||||
file: Remote,
|
||||
from: PathBuf,
|
||||
overwrite: bool,
|
||||
resume: bool,
|
||||
report: Report,
|
||||
},
|
||||
CancelTransfer(TransferId),
|
||||
/// Open a file of the server for reading, from `offset`: the transfer
|
||||
/// connection itself, and the file's size in all, once the server has
|
||||
/// agreed (the text of the failure otherwise). The engine copies the
|
||||
/// bytes, reports the progress and cancels by dropping the connection, so
|
||||
/// this does not use [`LinkCmd::Download`]'s sink and report.
|
||||
OpenRead {
|
||||
file: Remote,
|
||||
offset: u64,
|
||||
reply: oneshot::Sender<Result<(u64, BoxRead), String>>,
|
||||
},
|
||||
/// Open a file of the server for writing: the transfer connection and the
|
||||
/// position the server wants the bytes from (the size it already has, if
|
||||
/// `resume`). The engine writes the bytes and ends the connection.
|
||||
OpenWrite {
|
||||
file: Remote,
|
||||
/// The file's size in all.
|
||||
size: u64,
|
||||
overwrite: bool,
|
||||
resume: bool,
|
||||
reply: oneshot::Sender<Result<(u64, BoxDuplex), String>>,
|
||||
},
|
||||
DeleteFiles {
|
||||
/// `None`: best effort, nobody waits for the answer.
|
||||
request: Option<RequestId>,
|
||||
channel: ChannelId,
|
||||
password: Option<String>,
|
||||
paths: Vec<String>,
|
||||
},
|
||||
RenameFile {
|
||||
request: RequestId,
|
||||
from: Remote,
|
||||
to: Remote,
|
||||
},
|
||||
CreateDirectory {
|
||||
request: RequestId,
|
||||
dir: Remote,
|
||||
},
|
||||
/// Announce our avatar's hash (empty: no avatar).
|
||||
SetAvatarHash {
|
||||
request: Option<RequestId>,
|
||||
hash: String,
|
||||
},
|
||||
OfflineList {
|
||||
request: RequestId,
|
||||
},
|
||||
OfflineGet {
|
||||
request: RequestId,
|
||||
id: u32,
|
||||
},
|
||||
OfflineAdd {
|
||||
request: RequestId,
|
||||
to_uid: String,
|
||||
subject: String,
|
||||
text: String,
|
||||
},
|
||||
OfflineDelete {
|
||||
request: RequestId,
|
||||
id: u32,
|
||||
},
|
||||
OfflineFlag {
|
||||
request: RequestId,
|
||||
id: u32,
|
||||
read: bool,
|
||||
},
|
||||
Disconnect,
|
||||
}
|
||||
|
||||
/// What a connection tells the session.
|
||||
pub(crate) enum LinkEvent {
|
||||
Connected {
|
||||
name: String,
|
||||
/// The server software, and what it can do (the connection knows
|
||||
/// both from the server's version).
|
||||
backend: BackendInfo,
|
||||
capabilities: Capabilities,
|
||||
/// Our client id when the link connected. TeamSpeak's own reconnect gives
|
||||
/// a new one, which is not announced; the engine follows it in the
|
||||
/// snapshots by our unique id.
|
||||
own_client: u16,
|
||||
/// The server's unique id.
|
||||
server_uid: String,
|
||||
/// Our unique id as the server knows it.
|
||||
own_uid: Option<String>,
|
||||
},
|
||||
/// The server's channels and clients as they are now.
|
||||
Presence(Box<Presence>),
|
||||
/// The channel we are in, after every [`LinkEvent::Presence`]. The engine
|
||||
/// derives it itself, from our own voice state in the snapshots of the
|
||||
/// `Session` it talks to, and so follows us when TeamSpeak's reconnect makes
|
||||
/// us another client. What an in-process link such as `TsLink` says here only
|
||||
/// tells the TeamSpeak `Session` made of it that a move has arrived.
|
||||
OwnChannel(ChannelId),
|
||||
Chat(ChatMessage),
|
||||
Poke {
|
||||
from: u16,
|
||||
from_uid: Option<String>,
|
||||
from_name: String,
|
||||
message: String,
|
||||
},
|
||||
/// Incoming voice for the audio thread.
|
||||
Audio(VoicePacket),
|
||||
/// Who is talking (on, and off again when it stopped). The engine derives
|
||||
/// it from the media of its `Session` (protocol section 6.4). What an
|
||||
/// in-process link such as `TsLink` says here reaches the engine as a
|
||||
/// speaking hint next to the media: that is what shows the talkers whose
|
||||
/// packets the link does not forward as Opus (Speex, CELT).
|
||||
Talking {
|
||||
client: u16,
|
||||
talking: bool,
|
||||
},
|
||||
/// Our own stream's life, for the gateway directory.
|
||||
OwnStream(OwnStreamEvent),
|
||||
/// An Opus frame (48 kHz) of a watched stream, for the audio thread
|
||||
/// ([`VoiceOptions::audio`]); `time` is its RTP time on the 48 kHz
|
||||
/// clock.
|
||||
StreamAudio {
|
||||
stream: String,
|
||||
time: u64,
|
||||
data: Arc<[u8]>,
|
||||
},
|
||||
/// A watched stream ended: its audio leaves the mixer.
|
||||
StreamAudioEnded(String),
|
||||
/// A command failed (the connection stays).
|
||||
Error(String),
|
||||
/// The connection ended; the reason if it was not asked for. Sent once;
|
||||
/// the stream task's closing reports may still follow (see the module
|
||||
/// documentation).
|
||||
Disconnected(Option<String>),
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
//! The engine's view of a session's replica, in the client's older model
|
||||
//! (`docs/session-seam.md` section 5.3).
|
||||
//!
|
||||
//! The UI and `session.rs` still speak `Presence`, `ChannelInfo`,
|
||||
//! `ClientInfo`, `ServerDetails` and `ChatMessage`. [`presence`] and
|
||||
//! [`chat_message`] project the replica into them with
|
||||
//! `voelin_model::replica::convert`, and fix up where that says less than the
|
||||
//! older model does (F1 to F10 of the design). The fix-ups apply the
|
||||
//! TeamSpeak gateway's id rules of protocol section 11.1, so the UI keeps the
|
||||
//! ids it has; they go when the UI reads the replica.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use voelin_model::replica::{Replica, convert};
|
||||
use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails};
|
||||
use voelin_proto::link::Features;
|
||||
use voelin_proto::v1::{self, ChannelKind, MessageFlag, RoleScope};
|
||||
|
||||
use super::media::TalkTracker;
|
||||
use crate::ts::ts_session::entities::user_uid;
|
||||
use crate::ts::ts_session::ids::{self, FOREIGN_SYSTEM};
|
||||
|
||||
/// What the projection needs to know besides the replica.
|
||||
pub(crate) struct View<'a> {
|
||||
pub(crate) replica: &'a Replica,
|
||||
/// The server of the session.
|
||||
pub(crate) server: u64,
|
||||
/// The backend is TeamSpeak (`Welcome.host.backend.product`): its id rules
|
||||
/// (channel groups) are undone.
|
||||
pub(crate) teamspeak: bool,
|
||||
/// The version the host said (`Welcome.host.backend.version`).
|
||||
pub(crate) version: &'a str,
|
||||
pub(crate) features: &'a Features,
|
||||
/// Whether the connection has streams (a port, not just the feature).
|
||||
pub(crate) streams: bool,
|
||||
pub(crate) talking: &'a TalkTracker,
|
||||
}
|
||||
|
||||
/// What a `Foreign` of TeamSpeak holds under `key`.
|
||||
fn foreign_value(
|
||||
foreign: Option<&v1::Foreign>,
|
||||
kind: &str,
|
||||
key: &str,
|
||||
) -> Option<serde_json::Value> {
|
||||
let foreign = foreign.filter(|f| f.system == FOREIGN_SYSTEM && f.kind == kind)?;
|
||||
serde_json::from_slice::<serde_json::Value>(&foreign.json).ok()?.get(key).cloned()
|
||||
}
|
||||
|
||||
/// The server's unique id as the client keys its history and aliases by it:
|
||||
/// the host's without the `ts:` of protocol section 11.2 (F3).
|
||||
pub(crate) fn server_key(uid: &str) -> String {
|
||||
uid.strip_prefix("ts:").unwrap_or(uid).to_owned()
|
||||
}
|
||||
|
||||
/// The client's older model of the server (what `LinkEvent::Presence` holds).
|
||||
pub(crate) fn presence(view: &View<'_>) -> Presence {
|
||||
let replica = view.replica;
|
||||
let server = view.server;
|
||||
// F1: only what the older model calls channels.
|
||||
let channels: Vec<&v1::Channel> = replica
|
||||
.channels(server)
|
||||
.filter(|channel| {
|
||||
!matches!(
|
||||
ChannelKind::try_from(channel.kind),
|
||||
Ok(ChannelKind::ServerChat
|
||||
| ChannelKind::Dm
|
||||
| ChannelKind::GroupDm
|
||||
| ChannelKind::Thread)
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let by_id: BTreeMap<u64, &v1::Channel> = channels.iter().map(|c| (c.id, *c)).collect();
|
||||
let channel_infos = convert::channel_infos(&channels)
|
||||
.into_iter()
|
||||
.map(|mut info| {
|
||||
// F7: a limit of 0 is a limit, not "unlimited".
|
||||
let zero = by_id
|
||||
.get(&info.id)
|
||||
.and_then(|c| foreign_value(c.foreign.as_ref(), "channel", "max_clients"));
|
||||
if zero.and_then(|v| v.as_i64()) == Some(0) {
|
||||
info.max_clients = Some(0);
|
||||
}
|
||||
(info.id, info)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let clients = replica
|
||||
.voice_states(server)
|
||||
.filter_map(|voice| {
|
||||
let user = replica.user(voice.user_id);
|
||||
let member = replica.member(server, voice.user_id);
|
||||
let mut client =
|
||||
convert::client_info(voice, user, member, replica.presence_of(voice.user_id))?;
|
||||
// F10: a unique id that is no base64 rides in `Foreign`.
|
||||
client.uid = user.and_then(user_uid);
|
||||
// F2: the client's channel group is TeamSpeak's own number.
|
||||
if view.teamspeak {
|
||||
client.channel_group = client.channel_group.map(ids::channel_group);
|
||||
}
|
||||
// F6: the client's icon.
|
||||
client.icon = foreign_value(member.and_then(|m| m.foreign.as_ref()), "client", "icon")
|
||||
.and_then(|v| v.as_u64())
|
||||
.and_then(|v| u32::try_from(v).ok())
|
||||
.unwrap_or(0);
|
||||
// F8: who is talking comes from the media.
|
||||
client.talking = view.features.has("voice").then(|| view.talking.is_talking(client.id));
|
||||
// F9: the stream flag only where there are streams.
|
||||
if !view.streams {
|
||||
client.streaming = None;
|
||||
}
|
||||
Some((client.id, client))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut server_groups: BTreeMap<u64, GroupInfo> = BTreeMap::new();
|
||||
let mut channel_groups: BTreeMap<u64, GroupInfo> = BTreeMap::new();
|
||||
for role in replica.roles(server) {
|
||||
let mut info = convert::group_info(role);
|
||||
if role.scope == RoleScope::Channel as i32 {
|
||||
if view.teamspeak {
|
||||
info.id = ids::channel_group(info.id);
|
||||
}
|
||||
channel_groups.insert(info.id, info);
|
||||
} else {
|
||||
server_groups.insert(info.id, info);
|
||||
}
|
||||
}
|
||||
|
||||
let details = replica.server(server).map(|stub| server_details(view, stub)).unwrap_or_default();
|
||||
Presence {
|
||||
server_name: details.name.clone(),
|
||||
channels: channel_infos,
|
||||
clients,
|
||||
server: details,
|
||||
server_groups,
|
||||
channel_groups,
|
||||
}
|
||||
}
|
||||
|
||||
/// `convert::server_details` with F2 to F5.
|
||||
fn server_details(view: &View<'_>, server: &v1::Server) -> ServerDetails {
|
||||
let mut details = convert::server_details(server);
|
||||
// F3: the unique id as the client keys it.
|
||||
details.uid = details.uid.as_deref().map(server_key);
|
||||
let foreign = server.foreign.as_ref();
|
||||
// F4: the version the server sent, else the one the host reports.
|
||||
details.version = foreign_value(foreign, "server", "version")
|
||||
.and_then(|v| v.as_str().map(str::to_owned))
|
||||
.filter(|v| !v.is_empty())
|
||||
.unwrap_or_else(|| view.version.to_owned());
|
||||
// F5: the server's platform.
|
||||
details.platform = foreign_value(foreign, "server", "platform")
|
||||
.and_then(|v| v.as_str().map(str::to_owned))
|
||||
.unwrap_or_default();
|
||||
// F2: the default channel group is TeamSpeak's own number.
|
||||
if view.teamspeak {
|
||||
details.default_channel_group = details.default_channel_group.map(ids::channel_group);
|
||||
}
|
||||
details
|
||||
}
|
||||
|
||||
/// Where the older model files the messages of a channel (the replica's
|
||||
/// `chat_target`, with the unique id of F10).
|
||||
fn chat_target(replica: &Replica, channel: u64) -> ChatTarget {
|
||||
let Some(info) = replica.channel(channel) else { return ChatTarget::Channel(channel) };
|
||||
match ChannelKind::try_from(info.kind) {
|
||||
Ok(ChannelKind::ServerChat) => ChatTarget::Server,
|
||||
Ok(ChannelKind::Dm | ChannelKind::GroupDm) => {
|
||||
let own = replica.own_user();
|
||||
info.recipients
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|id| *id != own)
|
||||
.and_then(|id| replica.user(id))
|
||||
.and_then(user_uid)
|
||||
.map_or(ChatTarget::Channel(channel), ChatTarget::Private)
|
||||
}
|
||||
_ => ChatTarget::Channel(channel),
|
||||
}
|
||||
}
|
||||
|
||||
/// A message of the replica as the older model has it.
|
||||
pub(crate) fn chat_message(replica: &Replica, channel: u64, id: u64) -> Option<ChatMessage> {
|
||||
let message = replica.message(channel, id)?;
|
||||
let author = replica.user(message.author_id);
|
||||
let name = Some(message.author_name.as_str())
|
||||
.filter(|name| !name.is_empty())
|
||||
.or_else(|| author.map(|u| u.name.as_str()).filter(|name| !name.is_empty()))
|
||||
.unwrap_or_default();
|
||||
Some(ChatMessage {
|
||||
target: chat_target(replica, channel),
|
||||
author_name: name.to_owned(),
|
||||
author_uid: author.and_then(user_uid),
|
||||
author_id: (message.author_participant != 0)
|
||||
.then(|| u16::try_from(message.author_participant).ok())
|
||||
.flatten(),
|
||||
text: message.text.clone(),
|
||||
ts_ms: message.ts_ms,
|
||||
via_relay: message.flags & MessageFlag::Relayed as u32 != 0,
|
||||
blocked: false,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_ts_prefix_of_a_server_uid_goes() {
|
||||
assert_eq!(server_key("ts:abc="), "abc=");
|
||||
assert_eq!(server_key("abc="), "abc=");
|
||||
assert_eq!(server_key(""), "");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -56,16 +56,16 @@ use voelin_media::mix::{
|
||||
};
|
||||
pub use voelin_media::mix::{Level, SourceState};
|
||||
use voelin_media::scale::Pyramid;
|
||||
use voelin_media::stream::EncodedFrame;
|
||||
use voelin_media::studio::Studio;
|
||||
use voelin_media::studio::output::{Packet, Track};
|
||||
use voelin_media::{
|
||||
Codec, Codecs, ContentHint, EncodedChunk, EncoderConfig, FrameRef, GpuFrame, H264Profile,
|
||||
VideoEncoder, VideoFrame,
|
||||
LayerId, LayerSet, LayerSpec, VideoEncoder, VideoFrame,
|
||||
};
|
||||
pub use voelin_media::{DecoderBackend, DecoderPreference, EncoderBackend, EncoderPreference};
|
||||
use voelin_stream::{
|
||||
EncodedFrame, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, MediaFrame, MediaKind,
|
||||
MediaTime, PeerConfig, VideoCodec, VideoFormat,
|
||||
FrameSource, Frequency, MediaFrame, MediaKind, MediaTime, PeerConfig, VideoCodec, VideoFormat,
|
||||
};
|
||||
|
||||
use crate::settings::{AudioSourceKindSetting, AudioSourceSetting};
|
||||
@@ -127,13 +127,7 @@ fn spawn(name: &str, f: impl FnOnce() + Send + 'static) -> Result<JoinHandle<()>
|
||||
|
||||
/// The `voelin_media` codec of a negotiated video codec.
|
||||
pub fn media_codec(codec: VideoCodec) -> Codec {
|
||||
match codec {
|
||||
VideoCodec::Vp8 => Codec::Vp8,
|
||||
VideoCodec::Vp9 => Codec::Vp9,
|
||||
VideoCodec::H264 => Codec::H264,
|
||||
VideoCodec::Av1 => Codec::Av1,
|
||||
VideoCodec::H265 => Codec::H265,
|
||||
}
|
||||
crate::stream::media_codec(codec)
|
||||
}
|
||||
|
||||
/// The H.264 profile an encoder of `format` makes (Constrained High for
|
||||
@@ -2686,7 +2680,7 @@ pub struct DecodeStats {
|
||||
pub bytes: u64,
|
||||
/// Pictures decoded per second and video received in bit/s, over the
|
||||
/// time since the previous [`VideoPipeline::stats`] (at least
|
||||
/// [`RATE_WINDOW`]; the watch screen asks once a second).
|
||||
/// `RATE_WINDOW`; the watch screen asks once a second).
|
||||
pub fps: u32,
|
||||
pub bitrate: u64,
|
||||
}
|
||||
@@ -3416,7 +3410,14 @@ mod tests {
|
||||
assert!(all.is_hardware(backend), "{codec} offered in software");
|
||||
}
|
||||
if all.encoder_codecs().contains(&Codec::H264) && !offer.contains(&Codec::H264) {
|
||||
assert_eq!(offer_codecs(&all, Codec::H264)[..2], [Codec::H264, Codec::Vp8]);
|
||||
// H.264 in software only (so not in `offer`): it leads the same
|
||||
// codecs as with VP8 as the stream codec, whichever hardware
|
||||
// encoders this machine has (a hardware AV1 or VP9 encoder ranks
|
||||
// before VP8, so VP8 is not always second).
|
||||
let h264 = offer_codecs(&all, Codec::H264);
|
||||
assert_eq!(h264[0], Codec::H264, "{h264:?}");
|
||||
assert_eq!(h264.len(), offer.len() + 1, "{h264:?} against {offer:?}");
|
||||
assert!(offer.iter().all(|c| h264.contains(c)), "{h264:?} against {offer:?}");
|
||||
}
|
||||
// Whatever this machine has: codecs every TeamSpeak client decodes
|
||||
// come before H.264, HEVC last, and the automatic stream codec is
|
||||
@@ -3429,10 +3430,23 @@ mod tests {
|
||||
let ranks: Vec<_> = offer[1..].iter().map(rank).collect();
|
||||
assert!(ranks.is_sorted(), "{offer:?}");
|
||||
assert!(preferred_codec(&all, None).is_some_and(decoded_everywhere), "{all:?}");
|
||||
assert_eq!(
|
||||
preferred_codec(&all, Some(Codec::H264)).is_some(),
|
||||
all.encoder_codecs().contains(&Codec::H264)
|
||||
);
|
||||
// A configured codec is the stream codec when this machine can encode
|
||||
// it; otherwise the result is the automatic choice,
|
||||
// `preferred_codec(&all, None)` (some codec on any machine that
|
||||
// encodes anything). Whether H.264 is encodable depends on the
|
||||
// machine (a desktop with FFmpeg or a GPU has an encoder, a CI
|
||||
// runner has none), so the expectation follows `all.encoder_codecs()`.
|
||||
let h264 = preferred_codec(&all, Some(Codec::H264));
|
||||
if all.encoder_codecs().contains(&Codec::H264) {
|
||||
assert_eq!(h264, Some(Codec::H264), "{all:?}");
|
||||
} else {
|
||||
assert_eq!(h264, preferred_codec(&all, None), "{all:?}");
|
||||
}
|
||||
// The built-in codecs are the same everywhere (no OpenH264 loaded):
|
||||
// VP9 is encodable and wins, H.264 is not and falls back to VP8.
|
||||
assert_eq!(preferred_codec(&codecs, Some(Codec::Vp9)), Some(Codec::Vp9));
|
||||
assert_eq!(preferred_codec(&codecs, Some(Codec::H264)), preferred_codec(&codecs, None));
|
||||
assert_eq!(preferred_codec(&codecs, None), Some(Codec::Vp8));
|
||||
}
|
||||
|
||||
/// A sink whose viewers chose `codecs`; keeps every video frame with its
|
||||
|
||||
@@ -1,11 +1,94 @@
|
||||
//! The query source: own ServerQuery credentials, in-process observer and relays.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use tokio::sync::{broadcast, mpsc};
|
||||
use voelin_model::{ChatMessage, ChatTarget, Presence};
|
||||
use voelin_observer::{
|
||||
Observer, ObserverConfig, ObserverEvent, RelayConfig, RelayEvent, RelayPool,
|
||||
};
|
||||
|
||||
/// How a ServerQuery connection talks to the server.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum QueryTransport {
|
||||
/// The raw text protocol (TeamSpeak 3; port 10011).
|
||||
Raw,
|
||||
/// SSH.
|
||||
Ssh,
|
||||
/// The HTTP query (TeamSpeak 6; a WebQuery API key is the secret).
|
||||
Http,
|
||||
}
|
||||
|
||||
/// The user's own ServerQuery credentials for a server
|
||||
/// ([`Command::ObserveQuery`](crate::Command::ObserveQuery)): what the
|
||||
/// engine logs in with to observe a server invisibly and to relay its
|
||||
/// channels' chat. The connection's own tuning (flood protection, timeouts)
|
||||
/// is the engine's.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct QueryLogin {
|
||||
/// The protocol of the query interface at `address`.
|
||||
pub transport: QueryTransport,
|
||||
/// `host:port` of the query interface.
|
||||
pub address: String,
|
||||
/// The login name (raw and SSH; ignored for HTTP).
|
||||
pub user: String,
|
||||
/// The password (raw and SSH) or API key (HTTP, optional for guest access).
|
||||
pub secret: Option<String>,
|
||||
/// Select the virtual server by its voice port...
|
||||
pub server_port: Option<u16>,
|
||||
/// ...or by id (the first server when neither is given).
|
||||
pub server_id: Option<u32>,
|
||||
/// This machine's address is on the server's query allowlist, which the
|
||||
/// server's flood protection skips: the engine then sends its commands
|
||||
/// without the limit it keeps for a server that has not said so (a command
|
||||
/// the server refuses as a flood slows the connection down all the same).
|
||||
/// The application usually cannot know, and says `false`; the development
|
||||
/// servers of the tests allowlist their clients.
|
||||
pub allowlisted: bool,
|
||||
}
|
||||
|
||||
impl fmt::Debug for QueryLogin {
|
||||
// The secret is kept out of logs.
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("QueryLogin")
|
||||
.field("transport", &self.transport)
|
||||
.field("address", &self.address)
|
||||
.field("user", &self.user)
|
||||
.field("secret", &self.secret.as_ref().map(|_| "[secret]"))
|
||||
.field("server_port", &self.server_port)
|
||||
.field("server_id", &self.server_id)
|
||||
.field("allowlisted", &self.allowlisted)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl QueryLogin {
|
||||
/// The connection the observer and the relays open.
|
||||
fn connect(&self) -> voelin_query::Connect {
|
||||
voelin_query::Connect {
|
||||
transport: match self.transport {
|
||||
QueryTransport::Raw => voelin_query::Transport::Raw,
|
||||
QueryTransport::Ssh => voelin_query::Transport::Ssh,
|
||||
QueryTransport::Http => voelin_query::Transport::Http,
|
||||
},
|
||||
addr: self.address.clone(),
|
||||
user: self.user.clone(),
|
||||
secret: self.secret.clone(),
|
||||
server_port: self.server_port,
|
||||
server_id: self.server_id,
|
||||
line: voelin_query::LineOptions {
|
||||
// Off the client-side limit only where the server skips it.
|
||||
rate_limit: if self.allowlisted {
|
||||
None
|
||||
} else {
|
||||
voelin_query::LineOptions::default().rate_limit
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum QueryCmd {
|
||||
OpenChat(ChatTarget),
|
||||
CloseChat(ChatTarget),
|
||||
@@ -21,10 +104,11 @@ pub(crate) enum QueryEvent {
|
||||
}
|
||||
|
||||
pub(crate) async fn run(
|
||||
connect: voelin_query::Connect,
|
||||
login: QueryLogin,
|
||||
mut commands: mpsc::UnboundedReceiver<QueryCmd>,
|
||||
events: mpsc::UnboundedSender<QueryEvent>,
|
||||
) {
|
||||
let connect = login.connect();
|
||||
let observer = Observer::spawn(ObserverConfig::new(connect.clone()));
|
||||
let relays = RelayPool::new(RelayConfig::new(connect));
|
||||
let mut observed = observer.subscribe();
|
||||
@@ -88,3 +172,59 @@ pub(crate) async fn run(
|
||||
relays.close_all().await;
|
||||
let _ = events.send(QueryEvent::Disconnected);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_login_is_the_connection_the_query_crate_opens() {
|
||||
let login = QueryLogin {
|
||||
transport: QueryTransport::Ssh,
|
||||
address: "ts.example.com:10022".into(),
|
||||
user: "serveradmin".into(),
|
||||
secret: Some("hunter2".into()),
|
||||
server_port: Some(9987),
|
||||
server_id: Some(3),
|
||||
allowlisted: false,
|
||||
};
|
||||
let connect = login.connect();
|
||||
assert_eq!(connect.transport, voelin_query::Transport::Ssh);
|
||||
assert_eq!(
|
||||
(connect.addr.as_str(), connect.user.as_str(), connect.secret.as_deref()),
|
||||
("ts.example.com:10022", "serveradmin", Some("hunter2"))
|
||||
);
|
||||
assert_eq!((connect.server_port, connect.server_id), (Some(9987), Some(3)));
|
||||
for (ours, theirs) in [
|
||||
(QueryTransport::Raw, voelin_query::Transport::Raw),
|
||||
(QueryTransport::Http, voelin_query::Transport::Http),
|
||||
] {
|
||||
let connect = QueryLogin { transport: ours, ..login.clone() }.connect();
|
||||
assert_eq!(connect.transport, theirs);
|
||||
}
|
||||
// The line options are the query crate's defaults, as the UI always
|
||||
// gave them, unless the server allowlists the client.
|
||||
let line = voelin_query::LineOptions::default();
|
||||
assert!(line.rate_limit.is_some());
|
||||
assert_eq!(connect.line.rate_limit, line.rate_limit);
|
||||
assert_eq!(connect.line.timeout, line.timeout);
|
||||
let allowlisted = QueryLogin { allowlisted: true, ..login.clone() }.connect();
|
||||
assert_eq!(allowlisted.line.rate_limit, None);
|
||||
assert_eq!(allowlisted.line.timeout, line.timeout);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_secret_stays_out_of_the_debug_text() {
|
||||
let login = QueryLogin {
|
||||
transport: QueryTransport::Raw,
|
||||
address: "h:1".into(),
|
||||
user: "u".into(),
|
||||
secret: Some("hunter2".into()),
|
||||
server_port: None,
|
||||
server_id: None,
|
||||
allowlisted: false,
|
||||
};
|
||||
let text = format!("{login:?}");
|
||||
assert!(!text.contains("hunter2") && text.contains("[secret]"), "{text}");
|
||||
}
|
||||
}
|
||||
+913
-213
File diff suppressed because it is too large.
Load diff
@@ -50,8 +50,8 @@ use serde_json::{Value, json};
|
||||
use tokio::sync::{broadcast, watch};
|
||||
use tracing::{debug, warn};
|
||||
use voelin_audio::AudioSettings;
|
||||
use voelin_media::{LayerId, LayerSpec};
|
||||
use voelin_store::Store;
|
||||
use voelin_stream::{LayerId, LayerSpec};
|
||||
|
||||
/// A value of any key, typed (`Arc<T>` of the key's `T`).
|
||||
type Stored = Arc<dyn Any + Send + Sync>;
|
||||
@@ -1121,20 +1121,21 @@ pub static CHAT_RETENTION_DAYS: Key<u32> = Key::new(
|
||||
pub static CACHE_MAX_MB: Key<u64> = Key::new(
|
||||
"cache.max_mb",
|
||||
Kind::UInt { min: 0 },
|
||||
"Size of the avatar and icon cache in MiB (0: no limit).",
|
||||
|| 256,
|
||||
"Size of the picture cache (avatars, icons, banners) in MiB (0: no limit).",
|
||||
|| 1024,
|
||||
);
|
||||
|
||||
/// Download the avatars, icons and banners of servers we are on.
|
||||
/// Download the avatars, icons, banners and badges of servers we are on,
|
||||
/// and the pictures their chats show (`[img]`).
|
||||
pub static CACHE_FETCH_IMAGES: Key<bool> = Key::new(
|
||||
"cache.fetch_images",
|
||||
Kind::Bool,
|
||||
"Download avatars, icons and banners of the servers we are on.",
|
||||
"Download avatars, icons, banners and badges of the servers we are on, and pictures in chat.",
|
||||
|| true,
|
||||
);
|
||||
|
||||
/// Import identities from the official TeamSpeak clients when the app
|
||||
/// starts ([`crate::identity::import_new`]; their files are only read).
|
||||
/// starts ([`crate::ts::identity::import_new`]; their files are only read).
|
||||
pub static IDENTITY_IMPORT: Key<bool> = Key::new(
|
||||
"identity.import_from_teamspeak",
|
||||
Kind::Bool,
|
||||
|
||||
+500
-155
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,155 @@
|
||||
//! The stream types of the engine's API, owned by the core: what the UI is
|
||||
//! told about streams ([`StreamInfo`], [`ViewerInfo`], why a stream
|
||||
//! [ended](EndReason)) and what it asks for ([`StreamSetup`]).
|
||||
//!
|
||||
//! They carry plain fields only: client ids are `u16`, an SRTP profile is its
|
||||
//! name, a video codec is `voelin_media`'s. What a server link speaks (the
|
||||
//! TeamSpeak 6 stream crate today) is converted to and from them at the
|
||||
//! boundary in [`crate::stream`], so the UI does not depend on the link's
|
||||
//! types. The frame and simulcast layer types (`EncodedFrame`, `LayerSpec`,
|
||||
//! `LayerId`) are `voelin-media`'s.
|
||||
|
||||
use voelin_media::{Codec, LayerId};
|
||||
|
||||
/// What a stream shows.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum StreamKind {
|
||||
Camera,
|
||||
Screen,
|
||||
Window,
|
||||
/// A kind this client does not know, by its number on the server.
|
||||
Other(u8),
|
||||
}
|
||||
|
||||
impl StreamKind {
|
||||
/// From the number servers use: 2 camera, 3 screen, 4 window.
|
||||
pub fn from_u8(v: u8) -> Self {
|
||||
match v {
|
||||
2 => Self::Camera,
|
||||
3 => Self::Screen,
|
||||
4 => Self::Window,
|
||||
v => Self::Other(v),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`from_u8`](Self::from_u8) back.
|
||||
pub fn to_u8(self) -> u8 {
|
||||
match self {
|
||||
Self::Camera => 2,
|
||||
Self::Screen => 3,
|
||||
Self::Window => 4,
|
||||
Self::Other(v) => v,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What we announce when we start a stream ([`crate::Command::StartStream`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StreamSetup {
|
||||
pub name: String,
|
||||
pub kind: StreamKind,
|
||||
/// The stream's video bitrate in kbit/s (the single layer's without
|
||||
/// simulcast). TeamSpeak 6 servers keep it in 16 bits, so it is
|
||||
/// announced as at most 65535; the stream sends its real rate whatever
|
||||
/// the announcement says.
|
||||
pub bitrate: u32,
|
||||
/// `accessibility`: the official client sends 1.
|
||||
pub accessibility: u8,
|
||||
/// `mode`: 1 (none) is what clients send today; 2 is P2P, 3 SFU.
|
||||
pub mode: u8,
|
||||
/// 0 = unlimited.
|
||||
pub viewer_limit: u32,
|
||||
pub audio: bool,
|
||||
}
|
||||
|
||||
impl Default for StreamSetup {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
name: String::new(),
|
||||
kind: StreamKind::Screen,
|
||||
bitrate: 4608,
|
||||
accessibility: 1,
|
||||
mode: 1,
|
||||
viewer_limit: 0,
|
||||
audio: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A stream on the server ([`crate::Event::StreamsChanged`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StreamInfo {
|
||||
pub id: String,
|
||||
/// The client id of the streamer.
|
||||
pub streamer: u16,
|
||||
pub name: String,
|
||||
pub kind: StreamKind,
|
||||
pub bitrate: u32,
|
||||
pub viewer_limit: u32,
|
||||
pub audio: bool,
|
||||
/// How many watch it; `None` where nothing told (e.g. a gateway's
|
||||
/// directory entry).
|
||||
pub viewers: Option<u32>,
|
||||
}
|
||||
|
||||
/// A viewer of our stream, as we see it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ViewerState {
|
||||
/// Asked to watch, waiting for our decision.
|
||||
Requested,
|
||||
/// Offer sent; waiting for the answer and the connection.
|
||||
Connecting,
|
||||
Connected,
|
||||
}
|
||||
|
||||
/// A viewer of our stream ([`crate::Event::StreamViewers`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ViewerInfo {
|
||||
/// The client id of the viewer.
|
||||
pub client: u16,
|
||||
pub state: ViewerState,
|
||||
/// The message of the join request.
|
||||
pub message: String,
|
||||
/// The simulcast layer the viewer receives (it moves at a keyframe of the
|
||||
/// new layer); `None` before we offered, and with RID simulcast (all
|
||||
/// layers).
|
||||
pub layer: Option<LayerId>,
|
||||
/// The latest bandwidth estimate of the connection (bit/s).
|
||||
pub estimate: Option<u64>,
|
||||
/// The SRTP profile of the connection by its name (as in RFC 5764 and
|
||||
/// WebRTC statistics, e.g. `AEAD_AES_128_GCM`), once the key exchange is
|
||||
/// done.
|
||||
pub srtp_profile: Option<String>,
|
||||
/// The video codec the viewer's answer chose (it gets video in that
|
||||
/// codec).
|
||||
pub codec: Option<Codec>,
|
||||
}
|
||||
|
||||
/// Why a viewer left a stream.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LeaveReason {
|
||||
None,
|
||||
Left,
|
||||
Denied,
|
||||
Failed,
|
||||
Kicked,
|
||||
Banned,
|
||||
/// A reason this client does not know, by its number on the server.
|
||||
Other(u8),
|
||||
}
|
||||
|
||||
/// Why a stream ended for us ([`crate::StreamState::Ended`],
|
||||
/// [`crate::WatchState::Ended`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum EndReason {
|
||||
/// We stopped streaming or watching.
|
||||
Local,
|
||||
/// The streamer denied our join request.
|
||||
Denied,
|
||||
/// The stream was stopped (or its streamer disconnected).
|
||||
Stopped,
|
||||
/// The streamer or the server ended our viewing session.
|
||||
Removed(Option<LeaveReason>),
|
||||
/// A command failed or no connection could be established.
|
||||
Failed(String),
|
||||
}
|
||||
@@ -0,0 +1,631 @@
|
||||
//! The voice connection's book (tsclientlib) as model types.
|
||||
|
||||
use tsclientlib::{ClientType, MaxClients, data};
|
||||
use voelin_model::{
|
||||
BannerMode, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType, HostMessageMode,
|
||||
Presence, ServerDetails, myts_avatar_url, shown_badges,
|
||||
};
|
||||
|
||||
fn group_info(
|
||||
id: u64,
|
||||
name: &str,
|
||||
icon: tsclientlib::IconId,
|
||||
sort_id: i32,
|
||||
naming_mode: tsclientlib::GroupNamingMode,
|
||||
group_type: tsclientlib::GroupType,
|
||||
) -> GroupInfo {
|
||||
GroupInfo {
|
||||
id,
|
||||
name: name.to_owned(),
|
||||
icon: icon.0,
|
||||
sort_id,
|
||||
naming_mode: match naming_mode {
|
||||
tsclientlib::GroupNamingMode::None => GroupNamingMode::None,
|
||||
tsclientlib::GroupNamingMode::Before => GroupNamingMode::Before,
|
||||
tsclientlib::GroupNamingMode::After => GroupNamingMode::After,
|
||||
},
|
||||
group_type: match group_type {
|
||||
tsclientlib::GroupType::Template => GroupType::Template,
|
||||
tsclientlib::GroupType::Regular => GroupType::Regular,
|
||||
tsclientlib::GroupType::Query => GroupType::Query,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// What the server tells about itself; `uid` as the voice source computed it.
|
||||
fn server_details(server: &data::Server, uid: Option<&str>) -> ServerDetails {
|
||||
ServerDetails {
|
||||
name: server.name.clone(),
|
||||
uid: uid.map(str::to_owned),
|
||||
welcome_message: server.welcome_message.clone(),
|
||||
host_message: server.hostmessage.clone(),
|
||||
host_message_mode: match server.hostmessage_mode {
|
||||
tsclientlib::HostMessageMode::None => HostMessageMode::None,
|
||||
tsclientlib::HostMessageMode::Log => HostMessageMode::Log,
|
||||
tsclientlib::HostMessageMode::Modal => HostMessageMode::Modal,
|
||||
tsclientlib::HostMessageMode::Modalquit => HostMessageMode::ModalQuit,
|
||||
},
|
||||
banner_url: server.hostbanner_url.clone(),
|
||||
banner_gfx_url: server.hostbanner_gfx_url.trim().to_owned(),
|
||||
banner_gfx_interval_s: server.hostbanner_gfx_interval.whole_seconds().max(0) as u64,
|
||||
banner_mode: match server.hostbanner_mode {
|
||||
tsclientlib::HostBannerMode::NoAdjust => BannerMode::NoAdjust,
|
||||
tsclientlib::HostBannerMode::AdjustIgnoreAspect => BannerMode::IgnoreAspect,
|
||||
tsclientlib::HostBannerMode::AdjustKeepAspect => BannerMode::KeepAspect,
|
||||
},
|
||||
host_button_tooltip: server.hostbutton_tooltip.clone(),
|
||||
host_button_url: server.hostbutton_url.clone(),
|
||||
host_button_gfx_url: server.hostbutton_gfx_url.clone(),
|
||||
icon: server.icon.0,
|
||||
platform: server.platform.clone(),
|
||||
version: server.version.clone(),
|
||||
max_clients: server.max_clients,
|
||||
// `as` saturates (and turns NaN into 0); the mixer clamps it.
|
||||
priority_speaker_dimm_db: server.priority_speaker_dimm_modificator.round() as i32,
|
||||
default_server_group: Some(server.default_server_group.0),
|
||||
default_channel_group: Some(server.default_channel_group.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// The presence visible through a voice connection; `server_uid` as
|
||||
/// the voice source computed it, `talking` the clients talking now.
|
||||
pub(crate) fn presence_from_book(
|
||||
book: &data::Connection,
|
||||
server_uid: Option<&str>,
|
||||
talking: impl Fn(u16) -> bool,
|
||||
) -> Presence {
|
||||
let limit = |m: &Option<MaxClients>| match m {
|
||||
Some(MaxClients::Limited(n)) => Some(*n as i32),
|
||||
_ => None,
|
||||
};
|
||||
Presence {
|
||||
server_name: book.server.name.clone(),
|
||||
server: server_details(&book.server, server_uid),
|
||||
server_groups: book
|
||||
.server_groups
|
||||
.values()
|
||||
.map(|g| {
|
||||
let info =
|
||||
group_info(g.id.0, &g.name, g.icon, g.sort_id, g.naming_mode, g.group_type);
|
||||
(g.id.0, info)
|
||||
})
|
||||
.collect(),
|
||||
channel_groups: book
|
||||
.channel_groups
|
||||
.values()
|
||||
.map(|g| {
|
||||
let info =
|
||||
group_info(g.id.0, &g.name, g.icon, g.sort_id, g.naming_mode, g.group_type);
|
||||
(g.id.0, info)
|
||||
})
|
||||
.collect(),
|
||||
channels: book
|
||||
.channels
|
||||
.values()
|
||||
.map(|c| {
|
||||
(
|
||||
c.id.0,
|
||||
ChannelInfo {
|
||||
id: c.id.0,
|
||||
parent: c.parent.0,
|
||||
order: c.order.0,
|
||||
name: c.name.clone(),
|
||||
topic: c.topic.clone().filter(|t| !t.is_empty()),
|
||||
has_password: c.has_password.unwrap_or(false),
|
||||
max_clients: limit(&c.max_clients),
|
||||
needed_subscribe_power: 0,
|
||||
needed_talk_power: c.needed_talk_power.unwrap_or(0),
|
||||
is_default: c.is_default.unwrap_or(false),
|
||||
icon: c.icon.map_or(0, |i| i.0),
|
||||
banner_gfx_url: c
|
||||
.banner_gfx_url
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|u| !u.is_empty())
|
||||
.map(str::to_owned),
|
||||
// A number the book keeps as text.
|
||||
banner_mode: c
|
||||
.banner_mode
|
||||
.as_deref()
|
||||
.map_or(BannerMode::NoAdjust, BannerMode::from_wire),
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
clients: book
|
||||
.clients
|
||||
.values()
|
||||
.map(|c| {
|
||||
let mut server_groups: Vec<u64> = c.server_groups.iter().map(|g| g.0).collect();
|
||||
server_groups.sort_unstable();
|
||||
(
|
||||
c.id.0,
|
||||
ClientInfo {
|
||||
id: c.id.0,
|
||||
uid: c.uid.as_ref().map(|u| u.as_ref().to_string()),
|
||||
nickname: c.name.clone(),
|
||||
channel: c.channel.0,
|
||||
is_query: matches!(c.client_type, ClientType::Query { .. }),
|
||||
away: c.away_message.clone(),
|
||||
input_muted: c.input_muted,
|
||||
output_muted: c.output_muted,
|
||||
talking: Some(talking(c.id.0)),
|
||||
streaming: c.is_streaming,
|
||||
server_groups,
|
||||
country: Some(c.country_code.clone()).filter(|c| !c.is_empty()),
|
||||
avatar: Some(c.avatar_hash.clone()).filter(|h| !h.is_empty()),
|
||||
myts_avatar: c.my_team_speak_avatar.as_deref().and_then(myts_avatar_url),
|
||||
description: Some(c.description.clone()).filter(|d| !d.is_empty()),
|
||||
talk_power: c.talk_power,
|
||||
talker: c.talk_power_granted,
|
||||
channel_group: Some(c.channel_group.0),
|
||||
badges: shown_badges(
|
||||
&c.badges,
|
||||
c.signed_badges.as_deref().unwrap_or_default(),
|
||||
),
|
||||
icon: c.icon.0,
|
||||
recording: c.is_recording,
|
||||
priority_speaker: c.is_priority_speaker,
|
||||
channel_commander: c.is_channel_commander,
|
||||
database_id: Some(c.database_id.0),
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tsclientlib::InMessage;
|
||||
use tsproto_packets::packets::{Direction, Flags, OutPacket, PacketType};
|
||||
use tsproto_types::crypto::EccKeyPrivP256;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn message(text: &str) -> InMessage {
|
||||
let packet = OutPacket::new_with_dir(Direction::S2C, Flags::empty(), PacketType::Command);
|
||||
InMessage::new(&packet.header(), text.as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
/// The book of a TeamSpeak 6 server (6.0.0-beta13.1) after `initserver`.
|
||||
fn ts6_book() -> data::Connection {
|
||||
let InMessage::InitServer(init) = message(concat!(
|
||||
"initserver virtualserver_name=Test virtualserver_welcomemessage ",
|
||||
"virtualserver_platform=Linux virtualserver_version=6.0.0-beta13.1 ",
|
||||
"virtualserver_maxclients=32 virtualserver_created=0 ",
|
||||
"virtualserver_codec_encryption_mode=0 virtualserver_hostmessage ",
|
||||
"virtualserver_hostmessage_mode=0 virtualserver_default_server_group=8 ",
|
||||
"virtualserver_default_channel_group=8 virtualserver_hostbanner_url ",
|
||||
r"virtualserver_hostbanner_gfx_url=https:\/\/example.com\/banner.png ",
|
||||
"virtualserver_hostbanner_gfx_interval=60 ",
|
||||
"virtualserver_priority_speaker_dimm_modificator=-18.0000 virtualserver_id=1 ",
|
||||
"virtualserver_ask_for_privilegekey=0 ",
|
||||
"virtualserver_hostbutton_tooltip virtualserver_hostbutton_url ",
|
||||
"virtualserver_hostbutton_gfx_url virtualserver_name_phonetic ",
|
||||
"virtualserver_icon_id=0 virtualserver_hostbanner_mode=2 ",
|
||||
"virtualserver_channel_temp_delete_delay_default=0 acn=t aclid=2 pv=7 ",
|
||||
"client_talk_power=75 client_needed_serverquery_view_power=75",
|
||||
)) else {
|
||||
panic!("not an initserver");
|
||||
};
|
||||
data::Connection::new(EccKeyPrivP256::create().to_pub(), &init)
|
||||
}
|
||||
|
||||
/// A `channellist` entry as TeamSpeak 6 sends it.
|
||||
fn channel(cid: u64, order: u64, name: &str, banner: &str) -> String {
|
||||
format!(
|
||||
"cid={cid} cpid=0 channel_name={name} channel_topic channel_codec=4 \
|
||||
channel_codec_quality=6 channel_maxclients=-1 channel_maxfamilyclients=-1 \
|
||||
channel_order={order} channel_flag_permanent=1 channel_flag_semi_permanent=0 \
|
||||
channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 \
|
||||
channel_codec_is_unencrypted=1 channel_delete_delay=0 \
|
||||
channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=1 \
|
||||
channel_flag_maxfamilyclients_inherited=0 channel_needed_talk_power=0 \
|
||||
channel_forced_silence=0 channel_name_phonetic channel_icon_id=0 {banner} \
|
||||
channel_storage_quota=4294967295"
|
||||
)
|
||||
}
|
||||
|
||||
/// Channel banners as a TeamSpeak 6 server (6.0.0-beta13.1) sends them:
|
||||
/// in the channel list, when a channel is created and when it is edited.
|
||||
#[test]
|
||||
fn channel_banners() {
|
||||
let mut book = ts6_book();
|
||||
let list = format!(
|
||||
"channellist {}|{}",
|
||||
channel(1, 0, "Lobby", "channel_banner_gfx_url channel_banner_mode=0"),
|
||||
channel(
|
||||
12,
|
||||
1,
|
||||
"Raid",
|
||||
r"channel_banner_gfx_url=http:\/\/127.0.0.1:1\/d.png channel_banner_mode=2"
|
||||
),
|
||||
);
|
||||
for text in [
|
||||
list.as_str(),
|
||||
concat!(
|
||||
"notifychannelcreated cid=13 cpid=0 invokerid=1 invokername=serveradmin ",
|
||||
"invokeruid=serveradmin channel_name=New channel_order=12 ",
|
||||
r"channel_flag_permanent=1 channel_banner_gfx_url=https:\/\/example.com\/new.jpg ",
|
||||
"channel_banner_mode=1",
|
||||
),
|
||||
concat!(
|
||||
"notifychanneledited cid=12 reasonid=10 invokerid=1 invokername=serveradmin ",
|
||||
"invokeruid=serveradmin channel_banner_mode=1",
|
||||
),
|
||||
] {
|
||||
book.handle_command(&message(text)).unwrap();
|
||||
}
|
||||
let p = presence_from_book(&book, None, |_| false);
|
||||
let banner = |p: &Presence, cid| {
|
||||
let c = &p.channels[&cid];
|
||||
(c.banner_gfx_url.clone(), c.banner_mode)
|
||||
};
|
||||
assert_eq!(banner(&p, 1), (None, BannerMode::NoAdjust));
|
||||
assert_eq!(
|
||||
banner(&p, 12),
|
||||
(Some("http://127.0.0.1:1/d.png".into()), BannerMode::IgnoreAspect)
|
||||
);
|
||||
assert_eq!(
|
||||
banner(&p, 13),
|
||||
(Some("https://example.com/new.jpg".into()), BannerMode::IgnoreAspect)
|
||||
);
|
||||
// Removing the banner sends an empty address.
|
||||
book.handle_command(&message(
|
||||
"notifychanneledited cid=12 reasonid=10 invokerid=1 invokername=x channel_banner_gfx_url",
|
||||
))
|
||||
.unwrap();
|
||||
let p = presence_from_book(&book, None, |_| false);
|
||||
assert_eq!(p.channels[&12].banner_gfx_url, None);
|
||||
// The host banner, for comparison.
|
||||
assert_eq!(p.server.banner_gfx_url, "https://example.com/banner.png");
|
||||
assert_eq!(p.server.banner_gfx_interval_s, 60);
|
||||
assert_eq!(p.server.banner_mode, BannerMode::KeepAspect);
|
||||
assert_eq!(BannerMode::from_wire("7"), BannerMode::NoAdjust);
|
||||
assert_eq!(p.server.priority_speaker_dimm_db, -18);
|
||||
}
|
||||
|
||||
/// The myTeamSpeak avatar of a client as a TeamSpeak 6 server sends it:
|
||||
/// when the client enters and when it changes.
|
||||
#[test]
|
||||
fn myts_avatars() {
|
||||
let mut book = ts6_book();
|
||||
book.handle_command(&message(&format!("channellist {}", channel(1, 0, "Lobby", ""))))
|
||||
.unwrap();
|
||||
let enter = |clid: u16, avatar: &str| {
|
||||
format!(
|
||||
"notifycliententerview reasonid=0 ctid=1 clid={clid} client_database_id={clid} \
|
||||
client_nickname=c{clid} client_type=0 cfid=0 client_unique_identifier=u{clid}= \
|
||||
client_flag_avatar client_description client_icon_id=0 client_input_muted=0 \
|
||||
client_output_muted=0 client_outputonly_muted=0 client_input_hardware=1 \
|
||||
client_output_hardware=1 client_meta_data client_is_recording=0 \
|
||||
client_channel_group_id=8 client_channel_group_inherited_channel_id=1 \
|
||||
client_servergroups=8 client_away=0 client_away_message client_talk_power=75 \
|
||||
client_talk_request=0 client_talk_request_msg client_is_talker=0 \
|
||||
client_is_priority_speaker=0 client_unread_messages=0 client_nickname_phonetic \
|
||||
client_needed_serverquery_view_power=75 client_is_channel_commander=0 \
|
||||
client_country=RU client_badges client_myteamspeak_id=m{clid} \
|
||||
client_integrations{avatar}"
|
||||
)
|
||||
};
|
||||
for text in [
|
||||
enter(
|
||||
5,
|
||||
r" client_myteamspeak_avatar=3,https:\/\/a.example\/away.png;2,https:\/\/a.example\/on.png",
|
||||
),
|
||||
// A TeamSpeak 3 server, or a client without one.
|
||||
enter(6, ""),
|
||||
enter(7, " client_myteamspeak_avatar"),
|
||||
] {
|
||||
book.handle_command(&message(&text)).unwrap();
|
||||
}
|
||||
let p = presence_from_book(&book, None, |_| false);
|
||||
let avatar = |p: &Presence, clid: u16| p.clients[&clid].myts_avatar.clone();
|
||||
assert_eq!(avatar(&p, 5).as_deref(), Some("https://a.example/on.png"));
|
||||
assert_eq!((avatar(&p, 6), avatar(&p, 7)), (None, None));
|
||||
book.handle_command(&message(
|
||||
r"notifyclientupdated clid=6 client_myteamspeak_avatar=4,https:\/\/a.example\/off.png",
|
||||
))
|
||||
.unwrap();
|
||||
let p = presence_from_book(&book, None, |_| false);
|
||||
assert_eq!(avatar(&p, 6).as_deref(), Some("https://a.example/off.png"));
|
||||
}
|
||||
|
||||
// ---- across the session seam ---------------------------------------------
|
||||
|
||||
/// A presence made into the entities the TeamSpeak session writes
|
||||
/// (`ts_session::entities`), pushed the way a host syncs them, and
|
||||
/// projected back by the engine (`link::project`): what the UI is shown
|
||||
/// of what a TeamSpeak link reported (`docs/session-seam.md` section 5.1).
|
||||
fn through_the_seam(presence: &Presence, ts6: bool, own: Option<u16>) -> Presence {
|
||||
use voelin_model::replica::{Replica, SCHEMA_GENERATION, ScopeId};
|
||||
use voelin_proto::link::Features;
|
||||
use voelin_proto::v1::{self, push::Body};
|
||||
|
||||
use crate::link::media::TalkTracker;
|
||||
use crate::link::project::{View, presence as project};
|
||||
use crate::ts::ts_session::entities::build;
|
||||
|
||||
let built = build(presence, ts6, own);
|
||||
let mut replica = Replica::new(SCHEMA_GENERATION);
|
||||
for (scope, layer) in [(ScopeId::Server(1), &built.server), (ScopeId::Live(1), &built.live)]
|
||||
{
|
||||
replica.subscribe(scope);
|
||||
let pushes = [
|
||||
Body::SyncBegin(v1::SyncBegin {
|
||||
scope: Some(scope.to_proto()),
|
||||
mode: v1::SyncMode::Full as i32,
|
||||
epoch: 1,
|
||||
}),
|
||||
Body::Change(v1::Change {
|
||||
scope: Some(scope.to_proto()),
|
||||
rev: 1,
|
||||
put: layer.values().cloned().collect(),
|
||||
del: Vec::new(),
|
||||
}),
|
||||
Body::SyncEnd(v1::SyncEnd {
|
||||
scope: Some(scope.to_proto()),
|
||||
cursor: Some(v1::Cursor { epoch: 1, rev: 1 }),
|
||||
gap: false,
|
||||
}),
|
||||
];
|
||||
for body in pushes {
|
||||
replica.apply_push(&v1::Push { body: Some(body) });
|
||||
}
|
||||
}
|
||||
let features = Features::new(["voice"]);
|
||||
let talking = TalkTracker::default();
|
||||
project(&View {
|
||||
replica: &replica,
|
||||
server: 1,
|
||||
teamspeak: true,
|
||||
version: "",
|
||||
features: &features,
|
||||
streams: ts6,
|
||||
talking: &talking,
|
||||
})
|
||||
}
|
||||
|
||||
/// A TeamSpeak 6 server and some clients with what the book holds of them.
|
||||
fn ts6_presence() -> Presence {
|
||||
let mut book = ts6_book();
|
||||
let list = format!(
|
||||
"channellist {}|{}|{}",
|
||||
channel(1, 0, "Lobby", "channel_banner_gfx_url channel_banner_mode=0"),
|
||||
channel(
|
||||
12,
|
||||
1,
|
||||
"Raid",
|
||||
r"channel_banner_gfx_url=http:\/\/127.0.0.1:1\/d.png channel_banner_mode=2"
|
||||
),
|
||||
channel(20, 12, "Last", "channel_banner_gfx_url channel_banner_mode=0"),
|
||||
);
|
||||
book.handle_command(&message(&list)).unwrap();
|
||||
let enter = |clid: u16, channel: u64, groups: &str, away: &str, avatar: &str| {
|
||||
format!(
|
||||
"notifycliententerview reasonid=0 ctid={channel} clid={clid} \
|
||||
client_database_id={} client_nickname=c{clid} client_type=0 cfid=0 \
|
||||
client_unique_identifier=u{clid}= client_flag_avatar=abcdef \
|
||||
client_description=about\\sme client_icon_id=777 client_input_muted=1 \
|
||||
client_output_muted=0 client_outputonly_muted=0 client_input_hardware=1 \
|
||||
client_output_hardware=1 client_meta_data client_is_recording=1 \
|
||||
client_channel_group_id=8 client_channel_group_inherited_channel_id=1 \
|
||||
client_servergroups={groups} client_away={} client_away_message={away} \
|
||||
client_talk_power=75 client_talk_request=0 client_talk_request_msg \
|
||||
client_is_talker=1 client_is_priority_speaker=1 client_unread_messages=0 \
|
||||
client_nickname_phonetic client_needed_serverquery_view_power=75 \
|
||||
client_is_channel_commander=1 client_country=RU client_badges \
|
||||
client_myteamspeak_id=m{clid} client_integrations{avatar}",
|
||||
100 + u64::from(clid),
|
||||
u8::from(!away.is_empty()),
|
||||
)
|
||||
};
|
||||
for text in [
|
||||
enter(5, 1, "8", "", r" client_myteamspeak_avatar=2,https:\/\/a.example\/on.png"),
|
||||
enter(6, 12, "8,9", "gone\\sfishing", ""),
|
||||
enter(7, 12, "", "", " client_myteamspeak_avatar"),
|
||||
] {
|
||||
book.handle_command(&message(&text)).unwrap();
|
||||
}
|
||||
presence_from_book(&book, Some("ibhejBRSRRI7v+fSsUzpQ33JGK6rf5xKOLelpWUr0sE="), |_| false)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_book_is_what_the_ui_is_shown_across_the_seam() {
|
||||
let p = ts6_presence();
|
||||
assert_eq!(p.clients.len(), 3, "the fixture has clients");
|
||||
assert!(p.clients.values().any(|c| c.away.is_some()), "one is away");
|
||||
// A TeamSpeak 6 client the book has no streaming flag of (it was not
|
||||
// sent) is not streaming: v1 has no "unknown" for it.
|
||||
let mut expected = p.clone();
|
||||
for client in expected.clients.values_mut() {
|
||||
client.streaming = Some(client.streaming.unwrap_or(false));
|
||||
}
|
||||
assert_eq!(through_the_seam(&p, true, Some(5)), expected);
|
||||
// The same server as a TeamSpeak 3 one has no streams to tell of.
|
||||
let mut ts3 = p.clone();
|
||||
for client in ts3.clients.values_mut() {
|
||||
client.streaming = None;
|
||||
}
|
||||
assert_eq!(through_the_seam(&ts3, false, Some(5)), ts3);
|
||||
}
|
||||
|
||||
/// A deterministic stream of numbers for the generated presences.
|
||||
struct Numbers(u64);
|
||||
|
||||
impl Numbers {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n
|
||||
}
|
||||
|
||||
fn flag(&mut self) -> bool {
|
||||
self.below(2) == 0
|
||||
}
|
||||
|
||||
fn text(&mut self, prefix: &str) -> String {
|
||||
format!("{prefix}{}", self.below(1000))
|
||||
}
|
||||
}
|
||||
|
||||
/// A presence of the shape a TeamSpeak link reports: sibling channels in an
|
||||
/// order chain, every client with a database id, unique ids that are base64
|
||||
/// (TeamSpeak 3 and 6) or login names, groups of both kinds.
|
||||
fn generated(seed: u64, ts6: bool) -> Presence {
|
||||
use base64::Engine as _;
|
||||
use voelin_model::{
|
||||
BannerMode, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType,
|
||||
HostMessageMode,
|
||||
};
|
||||
let mut n = Numbers(seed | 1);
|
||||
let mut p = Presence::default();
|
||||
let name = n.text("Server ");
|
||||
p.server_name = name.clone();
|
||||
p.server = voelin_model::ServerDetails {
|
||||
name,
|
||||
uid: Some(n.text("uid")),
|
||||
welcome_message: n.text("welcome "),
|
||||
host_message: n.text("host "),
|
||||
host_message_mode: [
|
||||
HostMessageMode::None,
|
||||
HostMessageMode::Log,
|
||||
HostMessageMode::Modal,
|
||||
][n.below(3) as usize],
|
||||
banner_url: if n.flag() { n.text("https://b/") } else { String::new() },
|
||||
banner_gfx_url: if n.flag() { n.text("https://g/") } else { String::new() },
|
||||
banner_gfx_interval_s: n.below(100),
|
||||
banner_mode: [BannerMode::NoAdjust, BannerMode::IgnoreAspect, BannerMode::KeepAspect]
|
||||
[n.below(3) as usize],
|
||||
host_button_tooltip: if n.flag() { n.text("tip ") } else { String::new() },
|
||||
host_button_url: String::new(),
|
||||
host_button_gfx_url: String::new(),
|
||||
icon: n.below(5) as u32 * 1000,
|
||||
platform: "Linux".into(),
|
||||
version: n.text("6.0."),
|
||||
max_clients: n.below(500) as u16,
|
||||
priority_speaker_dimm_db: -(n.below(30) as i32),
|
||||
default_server_group: Some(1 + n.below(9)),
|
||||
default_channel_group: Some(1 + n.below(9)),
|
||||
};
|
||||
// Groups.
|
||||
for id in 1..=(2 + n.below(4)) {
|
||||
let group = |id: u64, n: &mut Numbers| GroupInfo {
|
||||
id,
|
||||
name: n.text("group "),
|
||||
icon: n.below(3) as u32 * 100,
|
||||
sort_id: n.below(1000) as i32 - 500,
|
||||
naming_mode: [
|
||||
GroupNamingMode::None,
|
||||
GroupNamingMode::Before,
|
||||
GroupNamingMode::After,
|
||||
][n.below(3) as usize],
|
||||
group_type: [GroupType::Regular, GroupType::Template, GroupType::Query]
|
||||
[n.below(3) as usize],
|
||||
};
|
||||
p.server_groups.insert(id, group(id, &mut n));
|
||||
p.channel_groups.insert(id, group(id, &mut n));
|
||||
}
|
||||
// Channels: a tree whose siblings follow each other.
|
||||
let mut parents = vec![0u64];
|
||||
for id in 1..=(3 + n.below(8)) {
|
||||
let parent = parents[n.below(parents.len() as u64) as usize];
|
||||
let order = p
|
||||
.channels
|
||||
.values()
|
||||
.filter(|c| c.parent == parent)
|
||||
.map(|c| c.id)
|
||||
.next_back()
|
||||
.unwrap_or(0);
|
||||
parents.push(id);
|
||||
p.channels.insert(
|
||||
id,
|
||||
ChannelInfo {
|
||||
id,
|
||||
parent,
|
||||
order,
|
||||
name: n.text("channel "),
|
||||
topic: n.flag().then(|| n.text("topic ")),
|
||||
has_password: n.flag(),
|
||||
max_clients: match n.below(3) {
|
||||
0 => None,
|
||||
1 => Some(0),
|
||||
_ => Some(1 + n.below(50) as i32),
|
||||
},
|
||||
needed_subscribe_power: n.below(3) as i32 * 10,
|
||||
needed_talk_power: n.below(3) as i32 * 25,
|
||||
is_default: id == 1,
|
||||
icon: n.below(3) as u32 * 500,
|
||||
banner_gfx_url: n.flag().then(|| n.text("https://c/")),
|
||||
banner_mode: [
|
||||
BannerMode::NoAdjust,
|
||||
BannerMode::IgnoreAspect,
|
||||
BannerMode::KeepAspect,
|
||||
][n.below(3) as usize],
|
||||
},
|
||||
);
|
||||
}
|
||||
// Clients.
|
||||
let channels: Vec<u64> = p.channels.keys().copied().collect();
|
||||
for id in 1..=(1 + n.below(12)) {
|
||||
let id = id as u16;
|
||||
let uid = match n.below(4) {
|
||||
0 => None,
|
||||
1 => Some(n.text("login")),
|
||||
_ => {
|
||||
let bytes: Vec<u8> =
|
||||
(0..if ts6 { 32 } else { 20 }).map(|_| n.below(256) as u8).collect();
|
||||
Some(base64::engine::general_purpose::STANDARD.encode(bytes))
|
||||
}
|
||||
};
|
||||
let channel = channels[n.below(channels.len() as u64) as usize];
|
||||
p.clients.insert(
|
||||
id,
|
||||
ClientInfo {
|
||||
id,
|
||||
uid,
|
||||
nickname: n.text("nick "),
|
||||
channel,
|
||||
is_query: n.below(5) == 0,
|
||||
away: n.flag().then(|| if n.flag() { n.text("away ") } else { String::new() }),
|
||||
input_muted: n.flag(),
|
||||
output_muted: n.flag(),
|
||||
talking: Some(false),
|
||||
streaming: ts6.then(|| n.flag()),
|
||||
server_groups: (0..n.below(3)).map(|_| 1 + n.below(9)).collect(),
|
||||
country: n.flag().then(|| "DE".into()),
|
||||
avatar: n.flag().then(|| n.text("hash")),
|
||||
myts_avatar: n.flag().then(|| n.text("https://a/")),
|
||||
description: n.flag().then(|| n.text("about ")),
|
||||
talk_power: n.below(100) as i32,
|
||||
talker: n.flag(),
|
||||
channel_group: n.flag().then(|| 1 + n.below(9)),
|
||||
badges: (0..n.below(3)).map(|_| n.text("badge")).collect(),
|
||||
icon: n.below(3) as u32 * 111,
|
||||
recording: n.flag(),
|
||||
priority_speaker: n.flag(),
|
||||
channel_commander: n.flag(),
|
||||
database_id: Some(1_000 + u64::from(id)),
|
||||
},
|
||||
);
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_presences_survive_the_seam() {
|
||||
for seed in 1..=200u64 {
|
||||
for ts6 in [false, true] {
|
||||
let p = generated(seed.wrapping_mul(0x9e37_79b9_7f4a_7c15), ts6);
|
||||
let own = p.clients.keys().next().copied();
|
||||
assert_eq!(through_the_seam(&p, ts6, own), p, "seed {seed}, ts6 {ts6}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,7 @@ use std::{fs, str};
|
||||
use rusqlite::{Connection, OpenFlags, OptionalExtension};
|
||||
use tsclientlib::Identity;
|
||||
use voelin_gateway_proto::UniqueIds;
|
||||
use voelin_identity::IdentityBlob;
|
||||
use voelin_store::{IdentityOrigin, Store};
|
||||
|
||||
/// Name given to an identity whose source kept none.
|
||||
@@ -55,6 +56,9 @@ pub enum IdentityError {
|
||||
NoIdentity { path: String },
|
||||
#[error("client database: {0}")]
|
||||
Store(String),
|
||||
/// An [`IdentityBlob`] that is no TeamSpeak identity ([`from_blob`]).
|
||||
#[error("{0}")]
|
||||
Blob(String),
|
||||
}
|
||||
|
||||
impl IdentityError {
|
||||
@@ -230,6 +234,43 @@ pub fn import_new(store: &Store, paths: &[PathBuf]) -> Result<LaunchImport, Iden
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// A TeamSpeak identity as the API takes it
|
||||
/// ([`VoiceOptions::identity`](crate::VoiceOptions::identity),
|
||||
/// [`Command::ObserveGateway`](crate::Command::ObserveGateway)) and the key
|
||||
/// store keeps it: kind `teamspeak`, the unique id TeamSpeak 3 servers know it
|
||||
/// by (also how [`voelin_store`] keys it), its security level, and the JSON
|
||||
/// the store writes.
|
||||
pub fn to_blob(identity: &Identity) -> IdentityBlob {
|
||||
// An identity is a key and two counters: writing it cannot fail. (A blob with
|
||||
// no JSON is refused when it is used, in words.)
|
||||
let json = serde_json::to_string(identity).unwrap_or_default();
|
||||
IdentityBlob::teamspeak(identity.key().to_pub().get_uid(), identity.level(), json)
|
||||
}
|
||||
|
||||
/// The TeamSpeak identity of a blob (the reverse of [`to_blob`]).
|
||||
pub fn from_blob(blob: &IdentityBlob) -> Result<Identity, IdentityError> {
|
||||
if !blob.is_teamspeak() {
|
||||
return Err(IdentityError::Blob(format!(
|
||||
"the identity is of kind {:?}, not a TeamSpeak one",
|
||||
blob.kind
|
||||
)));
|
||||
}
|
||||
serde_json::from_str(&blob.json).map_err(|e| {
|
||||
// Where the JSON is wrong, not what it says: it holds a private key.
|
||||
let what = match e.classify() {
|
||||
serde_json::error::Category::Syntax => "malformed",
|
||||
serde_json::error::Category::Eof => "cut short",
|
||||
serde_json::error::Category::Data => "not an identity",
|
||||
serde_json::error::Category::Io => "unreadable",
|
||||
};
|
||||
IdentityError::Blob(format!(
|
||||
"the TeamSpeak identity cannot be read: {what} at line {}, column {}",
|
||||
e.line(),
|
||||
e.column()
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// The TeamSpeak 3 `.ini` export of an identity, which the official client
|
||||
/// and every other tool reads.
|
||||
pub fn export(nickname: &str, identity: &Identity) -> String {
|
||||
@@ -548,6 +589,32 @@ mod tests {
|
||||
Identity::create()
|
||||
}
|
||||
|
||||
/// The blob of an identity is how the key store keeps it, and reads back as
|
||||
/// the same identity; what is no TeamSpeak identity is refused without
|
||||
/// quoting its JSON.
|
||||
#[test]
|
||||
fn an_identity_goes_through_its_blob() {
|
||||
let identity = synthetic();
|
||||
let blob = to_blob(&identity);
|
||||
assert!(blob.is_teamspeak());
|
||||
assert_eq!(blob.uid, identity.key().to_pub().get_uid());
|
||||
assert_eq!(blob.level, identity.level());
|
||||
assert_eq!(blob.json, serde_json::to_string(&identity).unwrap());
|
||||
let back = from_blob(&blob).unwrap();
|
||||
assert_eq!(serde_json::to_value(&back).unwrap(), serde_json::to_value(&identity).unwrap());
|
||||
|
||||
// Another kind.
|
||||
let other = IdentityBlob::new("voelin", "x", 0, blob.json.clone());
|
||||
let error = from_blob(&other).unwrap_err().to_string();
|
||||
assert!(error.contains("\"voelin\""), "{error}");
|
||||
// Not an identity: the text says where, and nothing of what it holds.
|
||||
for json in ["", "{", r#"{"key":"hunter2-key","counter":"hunter2"}"#, "[1]"] {
|
||||
let error = from_blob(&IdentityBlob::teamspeak("x", 0, json)).unwrap_err().to_string();
|
||||
assert!(error.starts_with("the TeamSpeak identity cannot be read"), "{error}");
|
||||
assert!(!error.contains("hunter2"), "{error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn improve_level_keeps_the_key() {
|
||||
let identity = synthetic();
|
||||
@@ -0,0 +1,30 @@
|
||||
//! The TeamSpeak implementation of the session seam.
|
||||
//!
|
||||
//! Everything of the engine that is TeamSpeak's lives here, so that it can
|
||||
//! leave this crate for the TeamSpeak gateway (`voelin-gateway-ts` of
|
||||
//! VoelinGateWay) as one piece (`docs/session-seam.md`, H9):
|
||||
//!
|
||||
//! - `ts_link.rs` and `voice.rs` are the connection of `tsclientlib`
|
||||
//! (chat, voice, files, pokes, offline messages, the stream task's
|
||||
//! requests) with `book.rs`, its presence from the library's book;
|
||||
//! - `ts_session/` makes a `voelin_proto::link::Session` of such a connection
|
||||
//! ([`TsConnector`] is the `Connector` the engine registers for
|
||||
//! `ts3server://` and `teamspeak://`);
|
||||
//! - [`versions`] and [`identity`] are what a TeamSpeak client has to know
|
||||
//! about itself: the signed compatibility versions it can claim, and the
|
||||
//! identities (reading, importing from the official clients, the security
|
||||
//! level).
|
||||
//!
|
||||
//! The TeamSpeak crates' types (`tsclientlib::Identity`, `Version`, ...) are
|
||||
//! named in the public items of this module and nowhere else of the crate's
|
||||
//! API.
|
||||
|
||||
mod book;
|
||||
pub mod identity;
|
||||
mod ts_link;
|
||||
pub(crate) mod ts_session;
|
||||
pub mod versions;
|
||||
mod voice;
|
||||
|
||||
pub(crate) use ts_link::{ConnectOptions, ServerLink, TsLink};
|
||||
pub use ts_session::TsConnector;
|
||||
@@ -0,0 +1,256 @@
|
||||
//! The inner link of the TeamSpeak side: [`ServerLink`], the trait that
|
||||
//! [`TsLink`] implements, and the [`ConnectOptions`] it connects with.
|
||||
//!
|
||||
//! The engine does not know this vocabulary: it talks to a
|
||||
//! `voelin_proto::link::Session`. The `ts_session` module makes a `Session`
|
||||
//! of a [`ServerLink`] (`LinkSession`), and the engine's tests give it a link
|
||||
//! of their own, an in-memory one. [`TsLink`] connects as a normal TeamSpeak 3
|
||||
//! or 6 client with `tsclientlib` and
|
||||
//! runs the connection ([`super::voice`]) with everything that rides on it:
|
||||
//! chat, voice, files, pokes, offline messages and, on TeamSpeak 6, the
|
||||
//! stream task. Which product the server is (and what it can do) is decided
|
||||
//! there, from the version it sends, and reported in
|
||||
//! [`LinkEvent::Connected`](crate::link::LinkEvent::Connected).
|
||||
//!
|
||||
//! Everything it uses (`voice.rs`, `book.rs`, `stream.rs`, `versions.rs`,
|
||||
//! `identity.rs`) is TeamSpeak's and leaves this crate together with it:
|
||||
//! the plan moves `TsLink` into the TeamSpeak gateway, `voelin-gateway-ts`
|
||||
//! of VoelinGateWay.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use voelin_stream::PeerConfig;
|
||||
|
||||
use super::voice;
|
||||
use crate::link::{LinkCmd, LinkCtx, LinkEvent};
|
||||
|
||||
/// Starts the connection of a link: the contract of `crate::link` for the
|
||||
/// vocabulary ([`LinkCmd`] in, [`LinkEvent`] out) holds for what a link does
|
||||
/// with them, and the module documentation of `link/session_link.rs` states
|
||||
/// it.
|
||||
///
|
||||
/// One link serves every session of an engine; [`spawn`](Self::spawn) starts
|
||||
/// one connection.
|
||||
pub(crate) trait ServerLink: Send + Sync + 'static {
|
||||
/// Connect to the server `options` names and run the connection on its
|
||||
/// own task: take commands from `cmds`, report through `events`, and end
|
||||
/// the connection with [`LinkEvent::Disconnected`]. Does not block.
|
||||
fn spawn(
|
||||
&self,
|
||||
options: ConnectOptions,
|
||||
ctx: LinkCtx,
|
||||
cmds: mpsc::UnboundedReceiver<LinkCmd>,
|
||||
events: mpsc::UnboundedSender<LinkEvent>,
|
||||
);
|
||||
}
|
||||
|
||||
/// What a TeamSpeak connection needs to know: the server, who to be, where
|
||||
/// to join. The reverse of what the engine's `ConnectParams` carry
|
||||
/// (`ts_session::inner_options`).
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ConnectOptions {
|
||||
pub address: String,
|
||||
pub nickname: String,
|
||||
/// The identity to connect with; none generates one.
|
||||
pub identity: Option<tsclientlib::Identity>,
|
||||
/// Signed compatibility version; `None` selects the native platform's tuple.
|
||||
pub client_version: Option<tsclientlib::Version>,
|
||||
pub server_password: Option<String>,
|
||||
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
|
||||
pub channel: Option<String>,
|
||||
/// The password of `channel`.
|
||||
pub channel_password: Option<String>,
|
||||
/// A privilege key to use when connecting.
|
||||
pub token: Option<String>,
|
||||
/// Open the audio devices (capture and playback).
|
||||
pub audio: bool,
|
||||
/// Network settings for stream peer connections.
|
||||
pub stream_peer: PeerConfig,
|
||||
}
|
||||
|
||||
impl ConnectOptions {
|
||||
/// Options for `address` and `nickname`, the rest as a test leaves it.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn new(address: impl Into<String>, nickname: impl Into<String>) -> Self {
|
||||
Self {
|
||||
address: address.into(),
|
||||
nickname: nickname.into(),
|
||||
identity: None,
|
||||
client_version: None,
|
||||
server_password: None,
|
||||
channel: None,
|
||||
channel_password: None,
|
||||
token: None,
|
||||
audio: false,
|
||||
stream_peer: PeerConfig::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The main myTeamSpeak account of an application, as its connections show
|
||||
/// it to the servers: the proof of the myTS ID, and what servers are shown
|
||||
/// of it (its avatar and badges with their certificates, its User Tag).
|
||||
///
|
||||
/// The senders live here, one pair for every connection of a [`TsLink`]; each
|
||||
/// connection watches the pair through [`Watches`], presents the account it
|
||||
/// finds when it connects, and follows the changes.
|
||||
pub(crate) struct Account {
|
||||
identity: watch::Sender<Option<Arc<tsproto::myts::Identity>>>,
|
||||
data: watch::Sender<Option<Arc<tsclientlib::MytsData>>>,
|
||||
}
|
||||
|
||||
impl Default for Account {
|
||||
/// No account is signed in.
|
||||
fn default() -> Self {
|
||||
Self { identity: watch::Sender::new(None), data: watch::Sender::new(None) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Account {
|
||||
/// The account proof for every current and future connection. Still no
|
||||
/// account is no change: every notification restarts the handshakes and
|
||||
/// sends `updatemytsid` on every connection. Any account is (each
|
||||
/// connection's proof is signed anew).
|
||||
pub(crate) fn set_identity(&self, identity: Option<Arc<tsproto::myts::Identity>>) {
|
||||
self.identity.send_if_modified(|current| {
|
||||
if current.is_none() && identity.is_none() {
|
||||
return false;
|
||||
}
|
||||
*current = identity;
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
/// What the servers are shown of the account: sent to every connection
|
||||
/// that presents the account's myTS ID, once connected and when it
|
||||
/// changes; cleared on a sign-out. The same data is no change.
|
||||
pub(crate) fn set_data(&self, data: Option<Arc<tsclientlib::MytsData>>) {
|
||||
self.data.send_if_modified(|current| {
|
||||
if *current == data {
|
||||
return false;
|
||||
}
|
||||
*current = data;
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
/// What one connection watches. It keeps the senders alive for as long as
|
||||
/// it runs: a connection ends with "account source closed" when its
|
||||
/// watches have lost them, so the account outlives the connector that
|
||||
/// made the connection.
|
||||
pub(crate) fn watches(self: &Arc<Self>) -> Watches {
|
||||
Watches {
|
||||
identity: self.identity.subscribe(),
|
||||
data: self.data.subscribe(),
|
||||
_keep: Some(self.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The account a connection presents and follows ([`Account::watches`]).
|
||||
pub(crate) struct Watches {
|
||||
pub(super) identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
pub(super) data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
_keep: Option<Arc<Account>>,
|
||||
}
|
||||
|
||||
impl Watches {
|
||||
/// Watches of senders that someone else keeps (a test's).
|
||||
#[cfg(test)]
|
||||
pub(super) fn of(
|
||||
identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
|
||||
data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
|
||||
) -> Self {
|
||||
Self { identity, data, _keep: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// Connects to TeamSpeak 3 and 6 servers. The link of [`TsConnector`](super::TsConnector).
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct TsLink {
|
||||
account: Arc<Account>,
|
||||
}
|
||||
|
||||
impl TsLink {
|
||||
/// A link that presents no account until it is given one.
|
||||
pub(crate) fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// The account the link's connections present.
|
||||
pub(crate) fn account(&self) -> &Arc<Account> {
|
||||
&self.account
|
||||
}
|
||||
}
|
||||
|
||||
impl ServerLink for TsLink {
|
||||
fn spawn(
|
||||
&self,
|
||||
options: ConnectOptions,
|
||||
ctx: LinkCtx,
|
||||
cmds: mpsc::UnboundedReceiver<LinkCmd>,
|
||||
events: mpsc::UnboundedSender<LinkEvent>,
|
||||
) {
|
||||
tokio::spawn(voice::run(options, ctx, self.account.watches(), cmds, events));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A myTS ID's proof (the standard Ed25519 base point as the public key).
|
||||
fn identity() -> Arc<tsproto::myts::Identity> {
|
||||
let mut private = [0; 32];
|
||||
private[0] = 1;
|
||||
let mut public = [0x66; 32];
|
||||
public[0] = 0x58;
|
||||
Arc::new(
|
||||
tsproto::myts::Identity::new(vec![1; 33], 42, public, private, vec![2; 65]).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
/// An account sets what it holds only when it changes: every notification
|
||||
/// of a watch restarts the handshake of a connection.
|
||||
#[test]
|
||||
fn a_watch_hears_of_a_change_and_not_of_the_same_account_again() {
|
||||
let account = Arc::new(Account::default());
|
||||
let mut watches = account.watches();
|
||||
// No account, still none: nothing.
|
||||
account.set_identity(None);
|
||||
account.set_data(None);
|
||||
assert!(!watches.identity.has_changed().unwrap());
|
||||
assert!(!watches.data.has_changed().unwrap());
|
||||
|
||||
let proof = identity();
|
||||
account.set_identity(Some(proof.clone()));
|
||||
assert!(watches.identity.borrow_and_update().is_some());
|
||||
// An account again is a change (each connection signs its proof anew), the
|
||||
// same data is none.
|
||||
account.set_identity(Some(proof));
|
||||
assert!(watches.identity.has_changed().unwrap());
|
||||
watches.identity.borrow_and_update();
|
||||
let data = Arc::new(tsclientlib::MytsData::default());
|
||||
account.set_data(Some(data.clone()));
|
||||
assert!(watches.data.has_changed().unwrap());
|
||||
watches.data.borrow_and_update();
|
||||
account.set_data(Some(Arc::new(tsclientlib::MytsData::default())));
|
||||
assert!(!watches.data.has_changed().unwrap(), "equal data is no change");
|
||||
// A sign-out is a change.
|
||||
account.set_identity(None);
|
||||
assert!(watches.identity.has_changed().unwrap());
|
||||
assert!(watches.identity.borrow_and_update().is_none());
|
||||
}
|
||||
|
||||
/// A connection outlives the connector that made it (a session handed out
|
||||
/// by a connector that was dropped): its watches keep their senders.
|
||||
#[test]
|
||||
fn a_connection_keeps_the_account_open_when_its_link_is_gone() {
|
||||
let link = TsLink::new();
|
||||
let watches = link.account().watches();
|
||||
drop(link);
|
||||
assert!(watches.identity.has_changed().is_ok(), "the identity watch lost its sender");
|
||||
assert!(watches.data.has_changed().is_ok(), "the data watch lost its sender");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,537 @@
|
||||
//! The TeamSpeak connection's presence as v1 entities (protocol section
|
||||
//! 11.1, "Ids and entities"): the client's older model on one side, the
|
||||
//! protocol's `Server`, `Channel`, `Role`, `User`, `Member`, `Presence` and
|
||||
//! `VoiceState` on the other.
|
||||
//!
|
||||
//! [`build`] is the translation the TeamSpeak `Session` makes of every
|
||||
//! snapshot its link reports; the engine's projection (`link/project.rs`)
|
||||
//! is its reverse, and `docs/session-seam.md` section 5.1 states the rule
|
||||
//! both keep: projecting what was built gives back the snapshot (up to the
|
||||
//! normalisations of section 5.4). What v1 has no field for rides in
|
||||
//! [`Foreign`](v1::Foreign) under [`FOREIGN_SYSTEM`].
|
||||
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
|
||||
use serde_json::json;
|
||||
use voelin_model::replica::Key;
|
||||
use voelin_model::{
|
||||
BannerMode, ChannelId, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType,
|
||||
HostMessageMode, Presence, ServerDetails,
|
||||
};
|
||||
use voelin_proto::v1::{self, Entity, entity::Kind};
|
||||
|
||||
use super::ids::{self, FOREIGN_SYSTEM, SERVER_CHAT, SERVER_ID};
|
||||
|
||||
/// Entities by key, as a scope holds them.
|
||||
pub(crate) type Layer = BTreeMap<Key, Entity>;
|
||||
|
||||
/// The entities one snapshot stands for, by scope.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Built {
|
||||
/// SERVER (1): the server, its channels and its roles.
|
||||
pub server: Layer,
|
||||
/// LIVE (1): who is online and where.
|
||||
pub live: Layer,
|
||||
/// The own user, for HOME, when the snapshot holds our client.
|
||||
pub own_user: Option<v1::User>,
|
||||
/// Clients by unique id: their user id and participant id.
|
||||
pub by_uid: HashMap<String, (u64, u32)>,
|
||||
}
|
||||
|
||||
/// The `Foreign` of something v1 has no field for.
|
||||
pub(crate) fn foreign(kind: &str, json: &serde_json::Value) -> v1::Foreign {
|
||||
v1::Foreign {
|
||||
system: FOREIGN_SYSTEM.into(),
|
||||
kind: kind.into(),
|
||||
json: serde_json::to_vec(json).unwrap_or_default().into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn entity(kind: Kind) -> Entity {
|
||||
Entity { kind: Some(kind) }
|
||||
}
|
||||
|
||||
/// A picture known by its id (an icon CRC).
|
||||
fn icon(id: u32) -> Option<v1::Image> {
|
||||
(id != 0).then(|| v1::Image { hash: id.to_string(), ..Default::default() })
|
||||
}
|
||||
|
||||
fn banner_mode(mode: BannerMode) -> v1::BannerMode {
|
||||
match mode {
|
||||
BannerMode::NoAdjust => v1::BannerMode::NoAdjust,
|
||||
BannerMode::IgnoreAspect => v1::BannerMode::IgnoreAspect,
|
||||
BannerMode::KeepAspect => v1::BannerMode::KeepAspect,
|
||||
}
|
||||
}
|
||||
|
||||
fn host_message_mode(mode: HostMessageMode) -> v1::HostMessageMode {
|
||||
match mode {
|
||||
HostMessageMode::None => v1::HostMessageMode::None,
|
||||
HostMessageMode::Log => v1::HostMessageMode::Log,
|
||||
HostMessageMode::Modal => v1::HostMessageMode::Modal,
|
||||
HostMessageMode::ModalQuit => v1::HostMessageMode::ModalQuit,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `Server` entity of a connection.
|
||||
pub(crate) fn server(details: &ServerDetails, name: &str, default_channel: u64) -> v1::Server {
|
||||
let gfx =
|
||||
|url: &str| (!url.is_empty()).then(|| v1::Image { url: url.into(), ..Default::default() });
|
||||
let banner = (!details.banner_url.is_empty()
|
||||
|| !details.banner_gfx_url.is_empty()
|
||||
|| details.banner_gfx_interval_s != 0
|
||||
|| details.banner_mode != BannerMode::NoAdjust)
|
||||
.then(|| v1::Banner {
|
||||
image: gfx(&details.banner_gfx_url),
|
||||
link: details.banner_url.clone(),
|
||||
reload_s: u32::try_from(details.banner_gfx_interval_s).unwrap_or(u32::MAX),
|
||||
mode: banner_mode(details.banner_mode) as i32,
|
||||
});
|
||||
let host_button = (!details.host_button_tooltip.is_empty()
|
||||
|| !details.host_button_url.is_empty()
|
||||
|| !details.host_button_gfx_url.is_empty())
|
||||
.then(|| v1::HostButton {
|
||||
tooltip: details.host_button_tooltip.clone(),
|
||||
url: details.host_button_url.clone(),
|
||||
icon: gfx(&details.host_button_gfx_url),
|
||||
});
|
||||
v1::Server {
|
||||
id: SERVER_ID,
|
||||
name: name.to_owned(),
|
||||
icon: icon(details.icon),
|
||||
banner,
|
||||
host_button,
|
||||
welcome: details.welcome_message.clone(),
|
||||
host_message: details.host_message.clone(),
|
||||
host_message_mode: host_message_mode(details.host_message_mode) as i32,
|
||||
default_channel_id: default_channel,
|
||||
default_role_id: details.default_server_group.unwrap_or(0),
|
||||
default_channel_role_id: details.default_channel_group.map_or(0, ids::channel_role),
|
||||
priority_dim_db: details.priority_speaker_dimm_db,
|
||||
max_members: u32::from(details.max_clients),
|
||||
uid: details.uid.as_deref().map(|uid| format!("ts:{uid}")).unwrap_or_default(),
|
||||
foreign: Some(foreign(
|
||||
"server",
|
||||
&json!({ "platform": details.platform, "version": details.version }),
|
||||
)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The server group or channel group `info` as a role.
|
||||
fn role(info: &GroupInfo, channel: bool) -> v1::Role {
|
||||
v1::Role {
|
||||
id: if channel { ids::channel_role(info.id) } else { info.id },
|
||||
server_id: SERVER_ID,
|
||||
name: info.name.clone(),
|
||||
icon: icon(info.icon),
|
||||
position: info.sort_id.saturating_neg(),
|
||||
scope: if channel { v1::RoleScope::Channel } else { v1::RoleScope::Server } as i32,
|
||||
name_mode: match info.naming_mode {
|
||||
GroupNamingMode::None => v1::NameMode::None,
|
||||
GroupNamingMode::Before => v1::NameMode::Before,
|
||||
GroupNamingMode::After => v1::NameMode::After,
|
||||
} as i32,
|
||||
kind: match info.group_type {
|
||||
GroupType::Template => v1::RoleKind::Template,
|
||||
GroupType::Regular => v1::RoleKind::Regular,
|
||||
GroupType::Query => v1::RoleKind::Query,
|
||||
} as i32,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The sibling chain of each parent as positions: `order` names the sibling
|
||||
/// above, so the chain is followed from 0; siblings that no chain reaches
|
||||
/// (a snapshot with broken orders) follow by id.
|
||||
fn positions(channels: &BTreeMap<ChannelId, ChannelInfo>) -> HashMap<ChannelId, i64> {
|
||||
let mut by_parent: BTreeMap<ChannelId, Vec<&ChannelInfo>> = BTreeMap::new();
|
||||
for channel in channels.values() {
|
||||
by_parent.entry(channel.parent).or_default().push(channel);
|
||||
}
|
||||
let mut positions = HashMap::new();
|
||||
for siblings in by_parent.values() {
|
||||
let mut placed: HashSet<ChannelId> = HashSet::new();
|
||||
let mut next = 0;
|
||||
let mut above = 0;
|
||||
// The sibling whose `order` is the one placed last (lowest id first, so
|
||||
// that two claiming the same place do not depend on map order).
|
||||
while let Some(channel) = siblings
|
||||
.iter()
|
||||
.filter(|c| c.order == above && !placed.contains(&c.id))
|
||||
.min_by_key(|c| c.id)
|
||||
{
|
||||
positions.insert(channel.id, next * 1024);
|
||||
placed.insert(channel.id);
|
||||
above = channel.id;
|
||||
next += 1;
|
||||
}
|
||||
for channel in siblings.iter().filter(|c| !placed.contains(&c.id)) {
|
||||
positions.insert(channel.id, next * 1024);
|
||||
next += 1;
|
||||
}
|
||||
}
|
||||
positions
|
||||
}
|
||||
|
||||
fn channel(info: &ChannelInfo, position: i64) -> v1::Channel {
|
||||
let mut needed = HashMap::new();
|
||||
if info.needed_talk_power != 0 {
|
||||
needed.insert(v1::Power::Talk as u32, info.needed_talk_power);
|
||||
}
|
||||
if info.needed_subscribe_power != 0 {
|
||||
needed.insert(v1::Power::Subscribe as u32, info.needed_subscribe_power);
|
||||
}
|
||||
let banner =
|
||||
(info.banner_gfx_url.is_some() || info.banner_mode != BannerMode::NoAdjust).then(|| {
|
||||
v1::Banner {
|
||||
image: info
|
||||
.banner_gfx_url
|
||||
.as_ref()
|
||||
.map(|url| v1::Image { url: url.clone(), ..Default::default() }),
|
||||
mode: banner_mode(info.banner_mode) as i32,
|
||||
..Default::default()
|
||||
}
|
||||
});
|
||||
v1::Channel {
|
||||
id: info.id,
|
||||
server_id: SERVER_ID,
|
||||
parent_id: info.parent,
|
||||
kind: v1::ChannelKind::Voice as i32,
|
||||
name: info.name.clone(),
|
||||
topic: info.topic.clone().unwrap_or_default(),
|
||||
position,
|
||||
has_password: info.has_password,
|
||||
// A limit of 0 cannot be said with `max_members` (0 is unlimited).
|
||||
max_members: info.max_clients.map_or(0, |n| u32::try_from(n).unwrap_or(0)),
|
||||
needed,
|
||||
icon: icon(info.icon),
|
||||
banner,
|
||||
is_default: info.is_default,
|
||||
foreign: (info.max_clients == Some(0))
|
||||
.then(|| foreign("channel", &json!({ "max_clients": 0 }))),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The user a client is. `Foreign` carries a unique id that is no base64.
|
||||
fn user(client: &ClientInfo, id: u64, ts6: bool) -> v1::User {
|
||||
let uid = client.uid.as_deref().filter(|u| !u.is_empty());
|
||||
let bytes = uid.and_then(ids::uid_bytes);
|
||||
let avatar = (client.avatar.is_some() || client.myts_avatar.is_some()).then(|| v1::Image {
|
||||
hash: client.avatar.clone().unwrap_or_default(),
|
||||
url: client.myts_avatar.clone().unwrap_or_default(),
|
||||
..Default::default()
|
||||
});
|
||||
v1::User {
|
||||
id,
|
||||
uid: bytes.clone().unwrap_or_default().into(),
|
||||
uid_kind: if ts6 { v1::IdKind::Ts6 } else { v1::IdKind::Ts3 } as i32,
|
||||
name: client.nickname.clone(),
|
||||
avatar,
|
||||
badges: client.badges.clone(),
|
||||
country: client.country.clone().unwrap_or_default(),
|
||||
foreign: uid.filter(|_| bytes.is_none()).map(|uid| foreign("user", &json!({ "uid": uid }))),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A user who is on no snapshot (the sender of a message or a poke): its
|
||||
/// unique id and name only. `None` for a unique id with no content.
|
||||
pub(crate) fn bare_user(uid: &str, name: &str, ts6: bool) -> v1::User {
|
||||
user(
|
||||
&ClientInfo { uid: Some(uid.to_owned()), nickname: name.to_owned(), ..Default::default() },
|
||||
ids::synthetic_user(uid),
|
||||
ts6,
|
||||
)
|
||||
}
|
||||
|
||||
/// A user who is on no snapshot and has no unique id (the sender of a poke
|
||||
/// or a message that the link names by its client id only): `id` and name.
|
||||
pub(crate) fn client_user(id: u64, name: &str, ts6: bool) -> v1::User {
|
||||
user(&ClientInfo { nickname: name.to_owned(), ..Default::default() }, id, ts6)
|
||||
}
|
||||
|
||||
/// Everything the snapshot `presence` says, as entities of the scopes of
|
||||
/// server 1. `ts6`: the server is TeamSpeak 6 (the kind of its unique ids).
|
||||
pub(crate) fn build(presence: &Presence, ts6: bool, own_client: Option<u16>) -> Built {
|
||||
let mut built = Built::default();
|
||||
let name =
|
||||
if presence.server.name.is_empty() { &presence.server_name } else { &presence.server.name };
|
||||
let default_channel =
|
||||
presence.channels.values().find(|c| c.is_default).map_or(0, |channel| channel.id);
|
||||
let put = |layer: &mut Layer, kind: Kind| {
|
||||
let entity = entity(kind);
|
||||
if let Some(key) = Key::of(&entity) {
|
||||
layer.insert(key, entity);
|
||||
}
|
||||
};
|
||||
put(&mut built.server, Kind::Server(server(&presence.server, name, default_channel)));
|
||||
put(
|
||||
&mut built.server,
|
||||
Kind::Channel(v1::Channel {
|
||||
id: SERVER_CHAT,
|
||||
server_id: SERVER_ID,
|
||||
kind: v1::ChannelKind::ServerChat as i32,
|
||||
name: "Server chat".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
let positions = positions(&presence.channels);
|
||||
for info in presence.channels.values() {
|
||||
let position = positions.get(&info.id).copied().unwrap_or_default();
|
||||
put(&mut built.server, Kind::Channel(channel(info, position)));
|
||||
}
|
||||
for info in presence.server_groups.values() {
|
||||
put(&mut built.server, Kind::Role(role(info, false)));
|
||||
}
|
||||
for info in presence.channel_groups.values() {
|
||||
put(&mut built.server, Kind::Role(role(info, true)));
|
||||
}
|
||||
// The own client first, then by client id.
|
||||
let mut clients: Vec<&ClientInfo> = presence.clients.values().collect();
|
||||
clients.sort_by_key(|client| (Some(client.id) != own_client, client.id));
|
||||
let mut used: HashSet<u64> = HashSet::new();
|
||||
for client in clients {
|
||||
// The same identity twice on a server has one database id: the own
|
||||
// client keeps it (it must stay the user we are, also while a ghost of
|
||||
// our old connection lingers), else the lower client id; the other is a
|
||||
// user of its own.
|
||||
let uid = client.uid.as_deref().filter(|u| !u.is_empty());
|
||||
let mut id = client.database_id.unwrap_or_else(|| {
|
||||
ids::synthetic_user(&uid.map_or_else(|| format!("client:{}", client.id), str::to_owned))
|
||||
});
|
||||
if !used.insert(id) {
|
||||
id = ids::synthetic_user(&format!("client:{}", client.id));
|
||||
used.insert(id);
|
||||
}
|
||||
let participant = u32::from(client.id);
|
||||
if let Some(uid) = uid {
|
||||
built.by_uid.entry(uid.to_owned()).or_insert((id, participant));
|
||||
}
|
||||
let user = user(client, id, ts6);
|
||||
if Some(client.id) == own_client {
|
||||
built.own_user = Some(user.clone());
|
||||
}
|
||||
put(&mut built.live, Kind::User(user));
|
||||
put(
|
||||
&mut built.live,
|
||||
Kind::Member(v1::Member {
|
||||
server_id: SERVER_ID,
|
||||
user_id: id,
|
||||
roles: client.server_groups.clone(),
|
||||
channel_roles: client
|
||||
.channel_group
|
||||
.map(|group| (client.channel, ids::channel_role(group)))
|
||||
.into_iter()
|
||||
.collect(),
|
||||
description: client.description.clone().unwrap_or_default(),
|
||||
foreign: (client.icon != 0)
|
||||
.then(|| foreign("client", &json!({ "icon": client.icon }))),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
put(
|
||||
&mut built.live,
|
||||
Kind::Presence(v1::Presence {
|
||||
user_id: id,
|
||||
status: if client.away.is_some() { v1::Status::Idle } else { v1::Status::Online }
|
||||
as i32,
|
||||
text: client.away.clone().unwrap_or_default(),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
put(
|
||||
&mut built.live,
|
||||
Kind::Voice(v1::VoiceState {
|
||||
server_id: SERVER_ID,
|
||||
participant_id: participant,
|
||||
user_id: id,
|
||||
channel_id: client.channel,
|
||||
slot: slot(client.id),
|
||||
nick: client.nickname.clone(),
|
||||
kind: if client.is_query {
|
||||
v1::ParticipantKind::Query
|
||||
} else {
|
||||
v1::ParticipantKind::User
|
||||
} as i32,
|
||||
self_mute: client.input_muted,
|
||||
self_deaf: client.output_muted,
|
||||
priority_speaker: client.priority_speaker,
|
||||
channel_commander: client.channel_commander,
|
||||
talker: client.talker,
|
||||
talk_power: client.talk_power,
|
||||
recording: client.recording,
|
||||
streaming: client.streaming.unwrap_or(false),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
}
|
||||
built
|
||||
}
|
||||
|
||||
/// The unique id of a user as the client's older model writes it: base64 for
|
||||
/// a TeamSpeak id, or the text kept in `Foreign` when it was no base64 (a
|
||||
/// ServerQuery client's login name). `None` for a user without one.
|
||||
pub(crate) fn user_uid(user: &v1::User) -> Option<String> {
|
||||
let kept = user
|
||||
.foreign
|
||||
.as_ref()
|
||||
.filter(|f| f.system == FOREIGN_SYSTEM && f.kind == "user")
|
||||
.and_then(|f| serde_json::from_slice::<serde_json::Value>(&f.json).ok())
|
||||
.and_then(|json| json.get("uid")?.as_str().map(str::to_owned));
|
||||
kept.or_else(|| voelin_model::replica::convert::uid_text(user))
|
||||
}
|
||||
|
||||
/// The media slot of a client: its id plus one (slot 0 is not a media source).
|
||||
pub(crate) fn slot(client: u16) -> u32 {
|
||||
u32::from(client) + 1
|
||||
}
|
||||
|
||||
/// The key of an entity, as a `Change` deletes it: the key fields only.
|
||||
pub(crate) fn key_only(entity: &Entity) -> Entity {
|
||||
let kind = match entity.kind.as_ref() {
|
||||
Some(Kind::Server(s)) => Kind::Server(v1::Server { id: s.id, ..Default::default() }),
|
||||
Some(Kind::Channel(c)) => Kind::Channel(v1::Channel { id: c.id, ..Default::default() }),
|
||||
Some(Kind::Role(r)) => {
|
||||
Kind::Role(v1::Role { server_id: r.server_id, id: r.id, ..Default::default() })
|
||||
}
|
||||
Some(Kind::Member(m)) => Kind::Member(v1::Member {
|
||||
server_id: m.server_id,
|
||||
user_id: m.user_id,
|
||||
..Default::default()
|
||||
}),
|
||||
Some(Kind::User(u)) => Kind::User(v1::User { id: u.id, ..Default::default() }),
|
||||
Some(Kind::Presence(p)) => {
|
||||
Kind::Presence(v1::Presence { user_id: p.user_id, ..Default::default() })
|
||||
}
|
||||
Some(Kind::Voice(v)) => Kind::Voice(v1::VoiceState {
|
||||
server_id: v.server_id,
|
||||
participant_id: v.participant_id,
|
||||
..Default::default()
|
||||
}),
|
||||
Some(Kind::Message(m)) => {
|
||||
Kind::Message(v1::Message { channel_id: m.channel_id, id: m.id, ..Default::default() })
|
||||
}
|
||||
Some(Kind::Mail(m)) => Kind::Mail(v1::Mail { id: m.id, ..Default::default() }),
|
||||
_ => return entity.clone(),
|
||||
};
|
||||
Entity { kind: Some(kind) }
|
||||
}
|
||||
|
||||
/// What changed from `old` to `new`: the entities to put (new or different)
|
||||
/// and the keys to delete.
|
||||
pub(crate) fn diff(old: &Layer, new: &Layer) -> (Vec<Entity>, Vec<Entity>) {
|
||||
let put = new.iter().filter(|(key, entity)| old.get(*key) != Some(*entity));
|
||||
let del = old.iter().filter(|(key, _)| !new.contains_key(*key));
|
||||
(put.map(|(_, e)| e.clone()).collect(), del.map(|(_, e)| key_only(e)).collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn channel_info(id: u64, parent: u64, order: u64) -> ChannelInfo {
|
||||
ChannelInfo { id, parent, order, name: format!("c{id}"), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_order_chain_becomes_positions() {
|
||||
// 3 first, then 1, then 2 under the same parent; 5 alone under 3.
|
||||
let channels: BTreeMap<_, _> = [
|
||||
channel_info(1, 0, 3),
|
||||
channel_info(2, 0, 1),
|
||||
channel_info(3, 0, 0),
|
||||
channel_info(5, 3, 0),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|c| (c.id, c))
|
||||
.collect();
|
||||
let positions = positions(&channels);
|
||||
assert!(positions[&3] < positions[&1] && positions[&1] < positions[&2]);
|
||||
assert_eq!(positions[&5], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn siblings_a_chain_does_not_reach_follow_by_id() {
|
||||
// Both claim the first place, and 4 follows nobody.
|
||||
let channels: BTreeMap<_, _> =
|
||||
[channel_info(1, 0, 0), channel_info(2, 0, 0), channel_info(4, 0, 77)]
|
||||
.into_iter()
|
||||
.map(|c| (c.id, c))
|
||||
.collect();
|
||||
let positions = positions(&channels);
|
||||
assert_eq!((positions[&1], positions[&2], positions[&4]), (0, 1024, 2048));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_identity_twice_keeps_both_clients() {
|
||||
let client = |id, db| ClientInfo {
|
||||
id,
|
||||
uid: Some("uXDkxSZbv0IoA0z/toW3guGpUbI=".into()),
|
||||
nickname: format!("n{id}"),
|
||||
database_id: Some(db),
|
||||
..Default::default()
|
||||
};
|
||||
let mut presence = Presence::default();
|
||||
for c in [client(3, 77), client(4, 77)] {
|
||||
presence.clients.insert(c.id, c);
|
||||
}
|
||||
let built = build(&presence, false, None);
|
||||
let voices = built.live.keys().filter(|k| matches!(k, Key::Voice { .. })).count();
|
||||
let users = built.live.keys().filter(|k| matches!(k, Key::User { .. })).count();
|
||||
assert_eq!((voices, users), (2, 2));
|
||||
}
|
||||
|
||||
/// The own client is the user whose database id the identity has, also when a
|
||||
/// ghost of the old connection (the lower client id) lingers.
|
||||
#[test]
|
||||
fn the_own_client_keeps_the_database_id_of_an_identity_that_is_there_twice() {
|
||||
let client = |id| ClientInfo {
|
||||
id,
|
||||
uid: Some("uXDkxSZbv0IoA0z/toW3guGpUbI=".into()),
|
||||
nickname: format!("n{id}"),
|
||||
database_id: Some(77),
|
||||
..Default::default()
|
||||
};
|
||||
let mut presence = Presence::default();
|
||||
for c in [client(3), client(4)] {
|
||||
presence.clients.insert(c.id, c);
|
||||
}
|
||||
let user_of = |built: &Built, client: u32| {
|
||||
let key = Key::Voice { server_id: SERVER_ID, participant_id: client };
|
||||
let Some(Entity { kind: Some(Kind::Voice(voice)) }) = built.live.get(&key) else {
|
||||
panic!("no voice state")
|
||||
};
|
||||
voice.user_id
|
||||
};
|
||||
// Nobody is us: the lower client id keeps it.
|
||||
let built = build(&presence, false, None);
|
||||
assert_eq!(user_of(&built, 3), 77);
|
||||
assert_ne!(user_of(&built, 4), 77);
|
||||
// The later client is us: it keeps it, and the ghost has the made-up id.
|
||||
let built = build(&presence, false, Some(4));
|
||||
assert_eq!(user_of(&built, 4), 77);
|
||||
assert_ne!(user_of(&built, 3), 77);
|
||||
assert_eq!(built.own_user.map(|u| u.id), Some(77));
|
||||
assert_eq!(built.by_uid["uXDkxSZbv0IoA0z/toW3guGpUbI="], (77, 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_deletes_by_key_and_puts_what_differs() {
|
||||
let mut presence = Presence::default();
|
||||
presence.channels.insert(1, channel_info(1, 0, 0));
|
||||
let before = build(&presence, false, None);
|
||||
presence.channels.insert(2, channel_info(2, 0, 1));
|
||||
presence.channels.get_mut(&1).unwrap().name = "renamed".into();
|
||||
let after = build(&presence, false, None);
|
||||
let (put, del) = diff(&before.server, &after.server);
|
||||
assert_eq!(put.len(), 2, "the renamed channel and the new one");
|
||||
assert!(del.is_empty());
|
||||
let (put, del) = diff(&after.server, &before.server);
|
||||
assert_eq!(put.len(), 1, "channel 1 is back to its old name");
|
||||
assert_eq!(del.len(), 1);
|
||||
let Some(Kind::Channel(gone)) = &del[0].kind else { panic!("a channel") };
|
||||
assert_eq!((gone.id, gone.name.as_str()), (2, ""));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//! Ids and unique ids as the TeamSpeak gateway writes them (protocol
|
||||
//! section 11.1, "Ids"): TeamSpeak's numbers as they are, and a few
|
||||
//! synthetic ones with bit 63 set.
|
||||
//!
|
||||
//! Both sides of the seam use these rules: the TeamSpeak `Session`
|
||||
//! ([`super::LinkSession`]) writes entities with them, and the engine's
|
||||
//! projection (`link/project.rs`) undoes the few that the client's older
|
||||
//! model has no room for.
|
||||
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
|
||||
/// The only server of a TeamSpeak connection (its virtual server).
|
||||
pub(crate) const SERVER_ID: u64 = 1;
|
||||
|
||||
/// Marks the ids the gateway makes up: the server chat, direct-message
|
||||
/// channels and users it knows by their unique id only.
|
||||
pub(crate) const SYNTHETIC: u64 = 1 << 63;
|
||||
|
||||
/// The channel of the server chat, in the SERVER scope.
|
||||
pub(crate) const SERVER_CHAT: u64 = SYNTHETIC;
|
||||
|
||||
/// Set on the id of a channel group, so that a role id does not mean a server
|
||||
/// group and a channel group at once.
|
||||
pub(crate) const CHANNEL_ROLE: u64 = 1 << 62;
|
||||
|
||||
/// The `Foreign.system` of what the protocol has no field for.
|
||||
pub(crate) const FOREIGN_SYSTEM: &str = "teamspeak";
|
||||
|
||||
/// The role id of a channel group.
|
||||
pub(crate) fn channel_role(group: u64) -> u64 {
|
||||
group | CHANNEL_ROLE
|
||||
}
|
||||
|
||||
/// The channel group a role id stands for (the reverse of [`channel_role`]).
|
||||
pub(crate) fn channel_group(role: u64) -> u64 {
|
||||
role & !CHANNEL_ROLE
|
||||
}
|
||||
|
||||
/// FNV-1a, 64 bits.
|
||||
fn fnv1a(bytes: &[u8]) -> u64 {
|
||||
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for byte in bytes {
|
||||
hash ^= u64::from(*byte);
|
||||
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
hash
|
||||
}
|
||||
|
||||
/// A synthetic id for something known by a name only: bit 63 set and the
|
||||
/// hash of `name` in the low 63 bits (1 if they come out 0, so it is never
|
||||
/// [`SERVER_CHAT`]).
|
||||
fn synthetic(name: &str) -> u64 {
|
||||
let low = fnv1a(name.as_bytes()) & !SYNTHETIC;
|
||||
SYNTHETIC | low.max(1)
|
||||
}
|
||||
|
||||
/// The direct-message channel with the client of this unique id.
|
||||
pub(crate) fn dm_channel(uid: &str) -> u64 {
|
||||
synthetic(uid)
|
||||
}
|
||||
|
||||
/// The user id of a client that has no database id (or that the snapshot
|
||||
/// does not hold): by unique id, else by whatever names it.
|
||||
pub(crate) fn synthetic_user(uid: &str) -> u64 {
|
||||
synthetic(uid)
|
||||
}
|
||||
|
||||
/// The bytes of a unique id, when it is canonical base64 (what TeamSpeak
|
||||
/// writes): decoding and encoding again gives the same text. A ServerQuery
|
||||
/// client's login name, or anything else, is not, and goes into
|
||||
/// [`Foreign`](voelin_proto::v1::Foreign) instead.
|
||||
pub(crate) fn uid_bytes(uid: &str) -> Option<Vec<u8>> {
|
||||
let bytes = STANDARD.decode(uid).ok()?;
|
||||
(STANDARD.encode(&bytes) == uid && !bytes.is_empty()).then_some(bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn channel_groups_keep_their_number_below_the_flag() {
|
||||
assert_eq!(channel_role(8), 8 | (1 << 62));
|
||||
assert_eq!(channel_group(channel_role(8)), 8);
|
||||
assert_eq!(channel_group(channel_role(0)), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synthetic_ids_have_bit_63_and_are_never_the_server_chat() {
|
||||
for name in ["", "alice=", "client:7", "a-very-long-name-that-hashes-to-something"] {
|
||||
let id = dm_channel(name);
|
||||
assert_ne!(id & SYNTHETIC, 0, "{name}");
|
||||
assert_ne!(id, SERVER_CHAT, "{name}");
|
||||
}
|
||||
assert_eq!(dm_channel("alice="), dm_channel("alice="));
|
||||
assert_ne!(dm_channel("alice="), dm_channel("bob="));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_canonical_base64_is_a_unique_id() {
|
||||
// A TeamSpeak 3 unique id (SHA-1) and a TeamSpeak 6 one (SHA-256).
|
||||
assert_eq!(uid_bytes("uXDkxSZbv0IoA0z/toW3guGpUbI=").map(|b| b.len()), Some(20));
|
||||
assert_eq!(
|
||||
uid_bytes("xEZDkyeGdZ4bOSBCKqzTw8jVz2jsZCrJDRl9F8WWd3M=").map(|b| b.len()),
|
||||
Some(32)
|
||||
);
|
||||
// A ServerQuery login name, a fixture's name, the empty string.
|
||||
for not in ["serveradmin", "alice=", "me=", "", "Af4"] {
|
||||
assert_eq!(uid_bytes(not), None, "{not:?}");
|
||||
}
|
||||
// Non-canonical trailing bits decode but do not round trip.
|
||||
assert_eq!(uid_bytes("Af5="), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,862 @@
|
||||
//! The TeamSpeak `Session` against the development servers
|
||||
//! (`dev/docker-compose.yml`; `docs/session-seam.md` sections 9.3 and 16).
|
||||
//! Runs only with `VOELIN_LIVE=1`:
|
||||
//!
|
||||
//! ```text
|
||||
//! VOELIN_LIVE=1 cargo test -p voelin-core --lib ts_session::live_tests -- --test-threads=1
|
||||
//! ```
|
||||
//!
|
||||
//! Two kinds of test, each on TeamSpeak 3 and on TeamSpeak 6:
|
||||
//!
|
||||
//! - the link conformance suite of the protocol repository, the cases that
|
||||
//! apply to a TeamSpeak session, with the verdict of every case asserted
|
||||
//! and the reason of every case that cannot pass or cannot run in
|
||||
//! [`EXPECTED`];
|
||||
//! - what the suite cannot reach, as a session of its own does it: a message
|
||||
//! in the own channel answered, then pushed to the other session and back to
|
||||
//! ours, the refusals of a move, a poke between two sessions, voice RTP from
|
||||
//! one session's slot to the other's media sink, and a channel file written
|
||||
//! and read back from an offset.
|
||||
//!
|
||||
//! The sessions are made by [`TsConnector`] through the plain `Connector`
|
||||
//! interface, as a client of the seam outside an engine would make them.
|
||||
//!
|
||||
//! The servers ban an address that connects as often as these tests do
|
||||
//! (`ConnectFailedBanned` after three or four connections) unless their
|
||||
//! anti-flood limits are raised first. `scripts/it-smoke.sh` raises them when it
|
||||
//! prepares its admin identity; this module raises them itself, once per server
|
||||
//! and run, through the ServerQuery admin login that `refused_moves` uses
|
||||
//! ([`raise_flood_limits`]), so that the command above works on a freshly
|
||||
//! started stack. It needs that login (the development servers of
|
||||
//! `dev/docker-compose.yml` have it) and does not lower the limits again.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::sync::mpsc;
|
||||
use voelin_proto::link::{Connector, FlowId, MediaClass, MediaPacket, voice_sub};
|
||||
use voelin_proto::media::payload::PT_OPUS;
|
||||
use voelin_proto::media::{RtpHeader, RtpView};
|
||||
use voelin_proto::test_util::conformance::{self, Fixture, Verdict};
|
||||
use voelin_proto::test_util::{FakeConnector, MediaReceiver, media_channel};
|
||||
use voelin_proto::v1::request::Op;
|
||||
use voelin_proto::v1::{self, entity::Kind};
|
||||
|
||||
use super::*;
|
||||
use crate::link::{Backends, VoiceOptions, connect_params};
|
||||
|
||||
fn live() -> bool {
|
||||
std::env::var("VOELIN_LIVE").is_ok_and(|v| v == "1")
|
||||
}
|
||||
|
||||
/// How long a test waits for the server.
|
||||
const WAIT: Duration = Duration::from_secs(20);
|
||||
|
||||
async fn within<T>(what: &str, future: impl Future<Output = T>) -> T {
|
||||
match tokio::time::timeout(WAIT, future).await {
|
||||
Ok(value) => value,
|
||||
Err(_) => panic!("timed out after {WAIT:?} waiting for {what}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A development server: where to connect, and how to ask it as the admin.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Dev {
|
||||
name: &'static str,
|
||||
voice: &'static str,
|
||||
ssh: bool,
|
||||
query: &'static str,
|
||||
}
|
||||
|
||||
const TS3: Dev = Dev { name: "ts3", voice: "127.0.0.1:9987", ssh: false, query: "127.0.0.1:10011" };
|
||||
const TS6: Dev = Dev { name: "ts6", voice: "127.0.0.1:9988", ssh: true, query: "127.0.0.1:10022" };
|
||||
|
||||
impl Dev {
|
||||
fn query(&self) -> voelin_query::Connect {
|
||||
voelin_query::Connect {
|
||||
transport: if self.ssh {
|
||||
voelin_query::Transport::Ssh
|
||||
} else {
|
||||
voelin_query::Transport::Raw
|
||||
},
|
||||
addr: self.query.into(),
|
||||
user: "serveradmin".into(),
|
||||
secret: Some("voelin-dev-admin".into()),
|
||||
server_port: Some(9987),
|
||||
server_id: None,
|
||||
line: voelin_query::LineOptions { rate_limit: None, ..Default::default() },
|
||||
}
|
||||
}
|
||||
|
||||
/// A nickname no other client of this run has.
|
||||
fn nick(&self, role: &str) -> String {
|
||||
static COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
let n = COUNT.fetch_add(1, Ordering::Relaxed);
|
||||
format!("{role}-{}-{n}", std::process::id() % 10_000)
|
||||
}
|
||||
}
|
||||
|
||||
/// Raise the anti-flood limits of a development server, once per run, and
|
||||
/// lift the bans an earlier run left behind. The tests connect many times in
|
||||
/// a few seconds from one address, which a server with its default limits
|
||||
/// bans (`ConnectFailedBanned`); `scripts/it-smoke.sh` sets the same two
|
||||
/// values in `admin_args`. Done through the ServerQuery login of the admin,
|
||||
/// which the tests that create channels and keys use as well.
|
||||
async fn raise_flood_limits(dev: &Dev) {
|
||||
use tokio::sync::OnceCell;
|
||||
use voelin_query::{Command as Query, QueryClient};
|
||||
static TS3_READY: OnceCell<()> = OnceCell::const_new();
|
||||
static TS6_READY: OnceCell<()> = OnceCell::const_new();
|
||||
let ready = if dev.ssh { &TS6_READY } else { &TS3_READY };
|
||||
ready
|
||||
.get_or_init(|| async {
|
||||
let (admin, _) = within("the query login", QueryClient::connect(&dev.query()))
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("the query login of {}: {e}", dev.name));
|
||||
for key in [
|
||||
"virtualserver_antiflood_points_needed_ip_block",
|
||||
"virtualserver_antiflood_points_needed_command_block",
|
||||
] {
|
||||
let edit = Query::new("serveredit").arg(key, 100_000);
|
||||
within("the anti-flood limits", admin.send(&edit))
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("{} refused {key}: {e}", dev.name));
|
||||
}
|
||||
// A ban of an earlier run outlives the change of the limit.
|
||||
within("the ban list", admin.send(&Query::new("bandelall")))
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("{} did not lift its bans: {e}", dev.name));
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
/// A TeamSpeak session as a client of the seam sees it: made by the
|
||||
/// connector, with its push channel and media sink.
|
||||
async fn session(
|
||||
dev: &Dev,
|
||||
options: &VoiceOptions,
|
||||
) -> (Arc<dyn Session>, mpsc::Receiver<v1::Push>, MediaReceiver) {
|
||||
raise_flood_limits(dev).await;
|
||||
let (sink, media) = media_channel();
|
||||
let params = connect_params(options, sink, &Backends::empty()).expect("connect parameters");
|
||||
let connected =
|
||||
within(&format!("a connection to {}", dev.name), TsConnector::new().connect(params))
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("{} did not connect: {e}", dev.name));
|
||||
(connected.session, connected.pushes, media)
|
||||
}
|
||||
|
||||
/// A client of the TeamSpeak session that has done what an engine does after
|
||||
/// it connects (`docs/session-seam.md` 4.2, without the replica): the server
|
||||
/// listed, HOME, SERVER and LIVE subscribed and synced, a seat in voice.
|
||||
struct Client {
|
||||
session: Arc<dyn Session>,
|
||||
pushes: mpsc::Receiver<v1::Push>,
|
||||
media: MediaReceiver,
|
||||
server: u64,
|
||||
default_channel: u64,
|
||||
/// Our seat in voice (participant, slot, channel).
|
||||
seat: v1::VoiceState,
|
||||
/// The voice states of the server, as the pushes told them.
|
||||
voices: BTreeMap<u32, v1::VoiceState>,
|
||||
}
|
||||
|
||||
fn scope(kind: v1::ScopeKind, id: u64) -> v1::Scope {
|
||||
v1::Scope { kind: kind as i32, id }
|
||||
}
|
||||
|
||||
impl Client {
|
||||
async fn connect(dev: &Dev, nick: &str) -> Self {
|
||||
Self::connect_with(dev, VoiceOptions::new(dev.voice, nick)).await
|
||||
}
|
||||
|
||||
async fn connect_with(dev: &Dev, options: VoiceOptions) -> Self {
|
||||
let (session, pushes, media) = session(dev, &options).await;
|
||||
let mut client = Self {
|
||||
session,
|
||||
pushes,
|
||||
media,
|
||||
server: 0,
|
||||
default_channel: 0,
|
||||
seat: v1::VoiceState::default(),
|
||||
voices: BTreeMap::new(),
|
||||
};
|
||||
let list = Op::List(v1::List { kind: v1::EntityKind::Server as i32, ..Default::default() });
|
||||
let Answer::Entities(servers) = client.ask(list).await.expect("the server list") else {
|
||||
panic!("the server list is not entities")
|
||||
};
|
||||
let server = servers
|
||||
.items
|
||||
.iter()
|
||||
.find_map(|e| match &e.kind {
|
||||
Some(Kind::Server(server)) => Some(server.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the host lists its server");
|
||||
client.server = server.id;
|
||||
client.default_channel = server.default_channel_id;
|
||||
for scope in [
|
||||
scope(v1::ScopeKind::Home, 0),
|
||||
scope(v1::ScopeKind::Server, server.id),
|
||||
scope(v1::ScopeKind::Live, server.id),
|
||||
] {
|
||||
client.subscribe(scope).await;
|
||||
}
|
||||
client.seat = client.join(client.default_channel, "").await.expect("a seat in voice");
|
||||
client.settle().await;
|
||||
client
|
||||
}
|
||||
|
||||
/// A request, answered within [`WAIT`].
|
||||
async fn ask(&self, op: Op) -> Result<Answer, SessionError> {
|
||||
within("an answer", self.session.request(op)).await
|
||||
}
|
||||
|
||||
/// Subscribe `scope` and take its sync off the push channel.
|
||||
async fn subscribe(&mut self, scope: v1::Scope) {
|
||||
let op = Op::Subscribe(v1::Subscribe { scope: Some(scope), ..Default::default() });
|
||||
self.ask(op).await.expect("a subscription");
|
||||
self.until("the end of the sync", |push| match &push.body {
|
||||
Some(v1::push::Body::SyncEnd(end)) if end.scope == Some(scope) => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
/// `JoinVoice`: our seat, or why not.
|
||||
async fn join(&self, channel: u64, password: &str) -> Result<v1::VoiceState, SessionError> {
|
||||
let join = v1::JoinVoice {
|
||||
server_id: self.server,
|
||||
channel_id: channel,
|
||||
password: password.into(),
|
||||
..Default::default()
|
||||
};
|
||||
match self.ask(Op::JoinVoice(join)).await? {
|
||||
Answer::Entities(entities) => entities
|
||||
.items
|
||||
.into_iter()
|
||||
.find_map(|e| match e.kind {
|
||||
Some(Kind::Voice(voice)) => Some(voice),
|
||||
_ => None,
|
||||
})
|
||||
.ok_or_else(|| SessionError::Protocol("no voice state in the answer".into())),
|
||||
other => Err(SessionError::Protocol(format!("unexpected answer {other:?}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep track of what a push says about the server and its voice states.
|
||||
fn absorb(&mut self, push: &v1::Push) {
|
||||
let Some(v1::push::Body::Change(change)) = &push.body else { return };
|
||||
for entity in &change.put {
|
||||
match &entity.kind {
|
||||
Some(Kind::Voice(voice)) => {
|
||||
self.voices.insert(voice.participant_id, voice.clone());
|
||||
}
|
||||
Some(Kind::Server(server)) if server.default_channel_id != 0 => {
|
||||
self.default_channel = server.default_channel_id;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for entity in &change.del {
|
||||
if let Some(Kind::Voice(voice)) = &entity.kind {
|
||||
self.voices.remove(&voice.participant_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The next push `f` picks, skipping (and keeping track of) the others.
|
||||
async fn until<T>(&mut self, what: &str, mut f: impl FnMut(&v1::Push) -> Option<T>) -> T {
|
||||
within(what, async {
|
||||
loop {
|
||||
let push = self.pushes.recv().await.expect("the session lives");
|
||||
self.absorb(&push);
|
||||
if let Some(t) = f(&push) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Wait until the host shows our seat in LIVE: the first snapshot of the
|
||||
/// TeamSpeak link may come after the session was handed out, so the syncs
|
||||
/// can be empty and the voice states follow as changes. The seat then
|
||||
/// names the channel we are in.
|
||||
async fn settle(&mut self) {
|
||||
let participant = self.seat.participant_id;
|
||||
within("our voice state to appear", async {
|
||||
while !self.voices.contains_key(&participant) {
|
||||
let push = self.pushes.recv().await.expect("the session lives");
|
||||
self.absorb(&push);
|
||||
}
|
||||
})
|
||||
.await;
|
||||
self.seat = self.voices[&participant].clone();
|
||||
}
|
||||
|
||||
/// The next message `Change` of the CHAT scope of `channel` with `text`.
|
||||
async fn message(&mut self, channel: u64, text: &str) -> v1::Message {
|
||||
let chat = Some(scope(v1::ScopeKind::Chat, channel));
|
||||
self.until(&format!("the message {text:?}"), |push| match &push.body {
|
||||
Some(v1::push::Body::Change(change)) if change.scope == chat => {
|
||||
change.put.iter().find_map(|e| match &e.kind {
|
||||
Some(Kind::Message(message)) if message.text == text => Some(message.clone()),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn close(self) {
|
||||
self.session.close(v1::CloseCode::Normal, "");
|
||||
within("the session to close", self.session.closed()).await;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the conformance suite ----------------------------------------------------
|
||||
|
||||
/// What a case is expected to do against a TeamSpeak session, and why.
|
||||
enum Expect {
|
||||
/// Every assertion of the case holds.
|
||||
Passes,
|
||||
/// The session lacks the feature the case needs (`Verdict::Skipped`).
|
||||
Skipped(&'static str),
|
||||
/// The case does not apply: it cannot run, or cannot pass, for this reason
|
||||
/// (`cases_that_do_not_apply_fail` runs them and watches them fail).
|
||||
NotRun(&'static str),
|
||||
}
|
||||
use Expect::{NotRun, Passes, Skipped};
|
||||
|
||||
/// Every case of the suite of the protocol repository at `c8e0e5a`, in its
|
||||
/// order, with what a TeamSpeak session does with it. A case the suite gains
|
||||
/// fails `the_suite_is_known` until it is listed here.
|
||||
///
|
||||
/// The suite is written for a backend that is a `FakeHost`. A case that needs
|
||||
/// the backend gets the `FakeHandle` of an unrelated fake host, so the cases
|
||||
/// that hold, kill or read it, or push into it, cannot run against a session of
|
||||
/// a TeamSpeak server; the others write to places a TeamSpeak server does not
|
||||
/// have (the suite's channels, a server with another id, `ScheduledEvent`,
|
||||
/// `Emoji`, attachments). Each reason is what the case did when it was run.
|
||||
const EXPECTED: [(&str, Expect); 17] = [
|
||||
("welcome_matches_features", Passes),
|
||||
(
|
||||
"subscribe_syncs_the_scope",
|
||||
NotRun("writes to channel 4001: rejected (NotFound) no such channel"),
|
||||
),
|
||||
(
|
||||
"subscribe_resumes_from_a_cursor",
|
||||
NotRun("writes to channel 4002: rejected (NotFound) no such channel"),
|
||||
),
|
||||
(
|
||||
"put_answers_entities_and_pushes_the_change_with_the_same_rev",
|
||||
NotRun("writes to channel 4003: rejected (NotFound) no such channel"),
|
||||
),
|
||||
(
|
||||
"delete_answers_an_ack_and_pushes_the_removal",
|
||||
NotRun(
|
||||
"writes to channel 4004 first (no such channel); and TeamSpeak cannot delete a message, \
|
||||
where the case needs only `chat`, not `chat.delete` (P8)",
|
||||
),
|
||||
),
|
||||
(
|
||||
"a_key_names_an_entity_without_its_server",
|
||||
NotRun(
|
||||
"rejected (NotFound) no such server; and it creates a ScheduledEvent and an Emoji, \
|
||||
which TeamSpeak lacks, though it needs no feature (P8)",
|
||||
),
|
||||
),
|
||||
("a_stale_rev_conflicts_and_a_patch_writes_only_its_paths", Skipped("chat.edit")),
|
||||
("requests_apply_in_the_order_they_were_issued", Skipped("chat.edit")),
|
||||
("list_pages_history", Skipped("chat.history")),
|
||||
(
|
||||
"cancel_before_apply_is_cancelled",
|
||||
NotRun("holds the unrelated fake host, so the request is answered while it \"holds\""),
|
||||
),
|
||||
("idempotency_keys_apply_a_put_once", Skipped("idempotency")),
|
||||
(
|
||||
"notifications_are_fire_and_forget",
|
||||
NotRun("reads the request log of the unrelated fake host: the notification never arrives"),
|
||||
),
|
||||
(
|
||||
"renew_account_follows_the_feature",
|
||||
NotRun("pushes a HostUpdate into the unrelated fake session's closed push channel"),
|
||||
),
|
||||
(
|
||||
"media_loops_back",
|
||||
NotRun(
|
||||
"a TeamSpeak server does not return a client's own voice: the packet never loops back",
|
||||
),
|
||||
),
|
||||
(
|
||||
"files_round_trip",
|
||||
NotRun(
|
||||
"writes an AttachmentSlot: rejected (Unsupported) attachments are not offered; \
|
||||
TeamSpeak has channel files, and the case needs `files`, not `chat.attachments` (P8)",
|
||||
),
|
||||
),
|
||||
("close_ends_the_session", Passes),
|
||||
(
|
||||
"the_backend_can_end_the_session",
|
||||
NotRun(
|
||||
"kills the unrelated fake session, so closed() of this one never resolves; and a \
|
||||
kick is Network(text), not Remote{KICKED}, until H1",
|
||||
),
|
||||
),
|
||||
];
|
||||
|
||||
/// A fixture on a TeamSpeak session. The suite wants a `FakeHandle` on the
|
||||
/// backend behind the session; a TeamSpeak server has none, so it gets the one
|
||||
/// of an unrelated fake host, which the cases that are run never touch.
|
||||
async fn fixture(dev: Dev) -> Fixture {
|
||||
let (session, pushes, media) =
|
||||
session(&dev, &VoiceOptions::new(dev.voice, dev.nick("conf"))).await;
|
||||
let unrelated = FakeConnector::new();
|
||||
let (params, _media) = voelin_proto::test_util::connect_params("fake://unrelated");
|
||||
unrelated.connect(params).await.expect("a fake session");
|
||||
let backend = unrelated.last_session().expect("a fake session");
|
||||
Fixture::new(session, pushes, media, backend)
|
||||
}
|
||||
|
||||
fn the_suite_is_known() {
|
||||
let known: Vec<_> = EXPECTED.iter().map(|(name, _)| *name).collect();
|
||||
let cases: Vec<_> = conformance::CASES.iter().map(|case| case.name).collect();
|
||||
assert_eq!(known, cases, "the suite changed: list the new cases in EXPECTED");
|
||||
}
|
||||
|
||||
/// The cases that apply run and pass, the ones that need a feature the session
|
||||
/// lacks are skipped, and the rest are not run (their reason is in
|
||||
/// [`EXPECTED`]).
|
||||
async fn conformance_subset(dev: Dev) {
|
||||
the_suite_is_known();
|
||||
let harness = move || fixture(dev);
|
||||
let (mut passed, mut skipped) = (0, 0);
|
||||
for (case, (name, expect)) in conformance::CASES.iter().zip(&EXPECTED) {
|
||||
match expect {
|
||||
Passes => {
|
||||
let verdict = conformance::run_case(&harness, case).await;
|
||||
assert_eq!(verdict, Verdict::Passed, "{name} on {}", dev.name);
|
||||
passed += 1;
|
||||
}
|
||||
Skipped(feature) => {
|
||||
let verdict = conformance::run_case(&harness, case).await;
|
||||
assert_eq!(verdict, Verdict::Skipped(feature), "{name} on {}", dev.name);
|
||||
skipped += 1;
|
||||
}
|
||||
NotRun(reason) => eprintln!("{} {name}: not run: {reason}", dev.name),
|
||||
}
|
||||
}
|
||||
assert_eq!((passed, skipped), (2, 4));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_conformance_subset() {
|
||||
if live() {
|
||||
conformance_subset(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_conformance_subset() {
|
||||
if live() {
|
||||
conformance_subset(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- what the suite cannot reach ----------------------------------------------
|
||||
|
||||
/// A message in the own channel is answered with the message as written, and
|
||||
/// pushed to the CHAT scope of every session in the channel: to the other one
|
||||
/// as a `Change`, and back to ours (the ids agree only with the native
|
||||
/// session of H1: the answer has a local id, the echo the one of the
|
||||
/// `Change`).
|
||||
async fn chat_in_the_own_channel(dev: Dev) {
|
||||
let mut a = Client::connect(&dev, &dev.nick("chat-a")).await;
|
||||
let mut b = Client::connect(&dev, &dev.nick("chat-b")).await;
|
||||
assert_eq!(a.seat.channel_id, b.seat.channel_id, "both sessions are in the default channel");
|
||||
let channel = a.seat.channel_id;
|
||||
a.subscribe(scope(v1::ScopeKind::Chat, channel)).await;
|
||||
b.subscribe(scope(v1::ScopeKind::Chat, channel)).await;
|
||||
|
||||
let text = format!("live-chat-{}", std::process::id());
|
||||
let message = v1::Message { channel_id: channel, text: text.clone(), ..Default::default() };
|
||||
let write = v1::Write {
|
||||
entity: Some(v1::Entity { kind: Some(Kind::Message(message)) }),
|
||||
paths: Vec::new(),
|
||||
};
|
||||
let put = Op::Put(v1::Put { writes: vec![write], ..Default::default() });
|
||||
let Answer::Entities(answer) = a.ask(put).await.expect("the message is accepted") else {
|
||||
panic!("a message is answered with entities")
|
||||
};
|
||||
let written = match &answer.items[..] {
|
||||
[v1::Entity { kind: Some(Kind::Message(message)) }] => message.clone(),
|
||||
other => panic!("one message expected, got {other:?}"),
|
||||
};
|
||||
assert_eq!((written.channel_id, written.text.as_str()), (channel, text.as_str()));
|
||||
|
||||
let heard = b.message(channel, &text).await;
|
||||
assert_ne!(heard.id, 0);
|
||||
assert_eq!(heard.channel_id, channel);
|
||||
// And ours, back from the server: the same words, once.
|
||||
let echo = a.message(channel, &text).await;
|
||||
assert_ne!(echo.id, 0);
|
||||
a.close().await;
|
||||
b.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_chat_in_the_own_channel() {
|
||||
if live() {
|
||||
chat_in_the_own_channel(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_chat_in_the_own_channel() {
|
||||
if live() {
|
||||
chat_in_the_own_channel(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A move into a channel with a password or without room is refused with the
|
||||
/// code the seam names: `PASSWORD` and `FULL`.
|
||||
async fn refused_moves(dev: Dev) {
|
||||
use voelin_query::{Command as Query, QueryClient};
|
||||
let (admin, _) = QueryClient::connect(&dev.query()).await.expect("the query login");
|
||||
let tag = std::process::id() % 10_000;
|
||||
let create = |name: &str| {
|
||||
Query::new("channelcreate")
|
||||
.arg("channel_name", format!("{name}-{tag}"))
|
||||
.arg("channel_flag_semi_permanent", 1)
|
||||
};
|
||||
let locked =
|
||||
admin.send(&create("seam-locked").arg("channel_password", "secret")).await.unwrap()[0]
|
||||
.parse::<u64>("cid")
|
||||
.unwrap();
|
||||
let full = create("seam-full")
|
||||
.arg("channel_maxclients", 0)
|
||||
.arg("channel_flag_maxclients_unlimited", 0);
|
||||
let full = admin.send(&full).await.unwrap()[0].parse::<u64>("cid").unwrap();
|
||||
// A key for the Normal group, which has to keep to passwords and limits.
|
||||
let token = group_token(&admin, "Normal").await;
|
||||
|
||||
let check = {
|
||||
let token = token.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut options = VoiceOptions::new(dev.voice, dev.nick("moves"));
|
||||
options.token = Some(token);
|
||||
let client = Client::connect_with(&dev, options).await;
|
||||
let code = |result: Result<v1::VoiceState, SessionError>| match result {
|
||||
Err(SessionError::Rejected(error)) => error.code(),
|
||||
other => panic!("expected a refusal, got {other:?}"),
|
||||
};
|
||||
assert_eq!(code(client.join(locked, "").await), v1::ErrorCode::Password);
|
||||
assert_eq!(code(client.join(locked, "wrong").await), v1::ErrorCode::Password);
|
||||
let seat = client.join(locked, "secret").await.expect("the right password");
|
||||
assert_eq!(seat.channel_id, locked);
|
||||
assert_eq!(code(client.join(full, "").await), v1::ErrorCode::Full);
|
||||
client.close().await;
|
||||
})
|
||||
};
|
||||
let result = check.await;
|
||||
// Clean up before reporting a failure; the key is gone once used.
|
||||
let _ = admin.send(&Query::new("privilegekeydelete").arg("token", &token)).await;
|
||||
for cid in [locked, full] {
|
||||
admin.send(&Query::new("channeldelete").arg("cid", cid).arg("force", 1)).await.unwrap();
|
||||
}
|
||||
if let Err(error) = result {
|
||||
std::panic::resume_unwind(error.into_panic());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_refused_moves() {
|
||||
if live() {
|
||||
refused_moves(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_refused_moves() {
|
||||
if live() {
|
||||
refused_moves(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A poke is a `Signal` to a participant: the other session gets it, with
|
||||
/// the participant and the words of the sender.
|
||||
async fn poke_between_sessions(dev: Dev) {
|
||||
let a = Client::connect(&dev, &dev.nick("poke-a")).await;
|
||||
let mut b = Client::connect(&dev, &dev.nick("poke-b")).await;
|
||||
let text = format!("live-poke-{}", std::process::id());
|
||||
let target = v1::SignalTarget {
|
||||
server_id: a.server,
|
||||
participant_id: b.seat.participant_id,
|
||||
..Default::default()
|
||||
};
|
||||
let signal = v1::Signal {
|
||||
to: Some(target),
|
||||
body: Some(v1::signal::Body::Poke(v1::Poke { message: text.clone() })),
|
||||
..Default::default()
|
||||
};
|
||||
a.ask(Op::Signal(signal)).await.expect("the poke is accepted");
|
||||
let from = b
|
||||
.until("the poke", |push| match &push.body {
|
||||
Some(v1::push::Body::Signal(signal)) => match &signal.body {
|
||||
Some(v1::signal::Body::Poke(poke)) if poke.message == text => {
|
||||
Some(signal.from_participant)
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(from, a.seat.participant_id);
|
||||
a.close().await;
|
||||
b.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_poke_between_sessions() {
|
||||
if live() {
|
||||
poke_between_sessions(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_poke_between_sessions() {
|
||||
if live() {
|
||||
poke_between_sessions(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// One frame of Opus (20 ms, mono, fullband).
|
||||
const OPUS: [u8; 3] = [0xf8, 0xff, 0xfe];
|
||||
|
||||
fn rtp(flow: FlowId, sequence: u16, marker: bool, payload: &[u8]) -> MediaPacket {
|
||||
let mut header = RtpHeader::new(PT_OPUS, sequence, u32::from(sequence) * 960);
|
||||
header.marker = marker;
|
||||
let mut out = bytes::BytesMut::new();
|
||||
header.write(flow, &mut out).expect("a header");
|
||||
out.extend_from_slice(payload);
|
||||
MediaPacket { flow, rtp: out.freeze() }
|
||||
}
|
||||
|
||||
/// Voice sent on our slot arrives on the sender's slot at the other session's
|
||||
/// media sink: the frames in order (the sequence is TeamSpeak's packet id, so
|
||||
/// it only has to count up), the marker on the first, and an empty payload at
|
||||
/// the end.
|
||||
async fn voice_between_sessions(dev: Dev) {
|
||||
let a = Client::connect(&dev, &dev.nick("voice-a")).await;
|
||||
let mut b = Client::connect(&dev, &dev.nick("voice-b")).await;
|
||||
assert_eq!(a.seat.channel_id, b.seat.channel_id);
|
||||
let flow = FlowId::new(a.seat.slot, voice_sub::CHANNEL);
|
||||
for n in 0..5u8 {
|
||||
let frame = [0xf8, 0xff, 0xfe, n];
|
||||
let packet = rtp(flow, u16::from(n), n == 0, &frame);
|
||||
a.session.send_media(MediaClass::Voice, packet).expect("our own slot");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
a.session.send_media(MediaClass::Voice, rtp(flow, 5, false, &[])).expect("the end");
|
||||
|
||||
let mut heard = Vec::new();
|
||||
while let Some(packet) = b.media.recv_within(Duration::from_secs(5)).await {
|
||||
let view = RtpView::parse(&packet.rtp).expect("RTP");
|
||||
heard.push((packet.flow, view.sequence(), view.marker(), view.payload().to_vec()));
|
||||
if view.payload().is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(heard.len() >= 2, "{heard:?}");
|
||||
assert!(heard.iter().all(|(heard_flow, ..)| *heard_flow == flow), "{heard:?}");
|
||||
let (_, _, first_marker, first_payload) = &heard[0];
|
||||
assert!(*first_marker, "the first packet of the spurt carries the marker: {heard:?}");
|
||||
assert_eq!(&first_payload[..3], &OPUS[..], "{heard:?}");
|
||||
let (end_flow, _, end_marker, end_payload) = heard.last().expect("an end");
|
||||
assert!(
|
||||
end_payload.is_empty() && !*end_marker,
|
||||
"the spurt ends with an empty payload: {heard:?}"
|
||||
);
|
||||
assert_eq!(*end_flow, flow);
|
||||
let sequences: Vec<_> = heard.iter().map(|(_, sequence, ..)| *sequence).collect();
|
||||
assert!(
|
||||
sequences.windows(2).all(|pair| pair[1] == pair[0].wrapping_add(1)),
|
||||
"the sequence counts up by one: {sequences:?}"
|
||||
);
|
||||
// Voice on a slot that is not ours is refused before it reaches the server.
|
||||
let other = FlowId::new(a.seat.slot + 1000, voice_sub::CHANNEL);
|
||||
assert!(a.session.send_media(MediaClass::Voice, rtp(other, 0, true, &OPUS)).is_err());
|
||||
a.close().await;
|
||||
b.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_voice_between_sessions() {
|
||||
if live() {
|
||||
voice_between_sessions(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_voice_between_sessions() {
|
||||
if live() {
|
||||
voice_between_sessions(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A channel file written with `write_file` and read back from an offset with
|
||||
/// `read_file`: the head names the file and its size, the body starts where
|
||||
/// the offset says.
|
||||
async fn channel_file_from_an_offset(dev: Dev) {
|
||||
use voelin_query::{Command as Query, QueryClient};
|
||||
// Guests may not upload: a key for the Server Admin group.
|
||||
let (admin, _) = QueryClient::connect(&dev.query()).await.expect("the query login");
|
||||
let token = group_token(&admin, "Server Admin").await;
|
||||
let check = tokio::spawn({
|
||||
let token = token.clone();
|
||||
async move { channel_file_with_a_key(dev, token).await }
|
||||
});
|
||||
let result = check.await;
|
||||
let _ = admin.send(&Query::new("privilegekeydelete").arg("token", &token)).await;
|
||||
if let Err(error) = result {
|
||||
std::panic::resume_unwind(error.into_panic());
|
||||
}
|
||||
}
|
||||
|
||||
/// A one-time key for the server group `name` (a template group, type 1).
|
||||
async fn group_token(admin: &voelin_query::QueryClient, name: &str) -> String {
|
||||
use voelin_query::Command as Query;
|
||||
let groups = admin.send(&Query::new("servergrouplist")).await.unwrap();
|
||||
let group = groups
|
||||
.iter()
|
||||
.find(|g| g.get("name") == Some(name) && g.get("type") == Some("1"))
|
||||
.and_then(|g| g.parse::<u64>("sgid"))
|
||||
.unwrap_or_else(|| panic!("a {name} server group"));
|
||||
let key =
|
||||
Query::new("privilegekeyadd").arg("tokentype", 0).arg("tokenid1", group).arg("tokenid2", 0);
|
||||
admin.send(&key).await.unwrap()[0].get("token").unwrap().to_owned()
|
||||
}
|
||||
|
||||
async fn channel_file_with_a_key(dev: Dev, token: String) {
|
||||
let mut options = VoiceOptions::new(dev.voice, dev.nick("files"));
|
||||
options.token = Some(token);
|
||||
let a = Client::connect_with(&dev, options).await;
|
||||
let channel = a.seat.channel_id;
|
||||
let name = format!("seam-{}.bin", std::process::id());
|
||||
let path = format!("/{name}");
|
||||
let data: Vec<u8> = (0..3_000usize).map(|i| (i * 7 % 251) as u8).collect();
|
||||
let target = v1::FilePath { channel_id: channel, path: path.clone(), password: String::new() };
|
||||
|
||||
let write = v1::FileWrite {
|
||||
target: Some(v1::file_write::Target::Path(target.clone())),
|
||||
size: data.len() as u64,
|
||||
offset: 0,
|
||||
overwrite: true,
|
||||
sha256: Default::default(),
|
||||
};
|
||||
let mut upload =
|
||||
within("the upload to open", a.session.write_file(write)).await.expect("an upload");
|
||||
upload.body.write_all(&data).await.expect("the body");
|
||||
upload.body.shutdown().await.expect("the end of the body");
|
||||
let stored = within("the server to keep it", upload.done).await.expect("the file is stored");
|
||||
assert!(
|
||||
stored.items.iter().any(|e| matches!(&e.kind, Some(Kind::File(f)) if f.name == name)),
|
||||
"{stored:?}"
|
||||
);
|
||||
|
||||
let read = v1::FileRead {
|
||||
target: Some(v1::file_read::Target::Path(target.clone())),
|
||||
offset: 1_000,
|
||||
length: 0,
|
||||
};
|
||||
let mut download =
|
||||
within("the download to open", a.session.read_file(read)).await.expect("a download");
|
||||
let size = download.head.items.iter().find_map(|e| match &e.kind {
|
||||
Some(Kind::File(file)) => Some(file.size),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(size, Some(3_000), "{:?}", download.head);
|
||||
let mut body = Vec::new();
|
||||
within("the body", download.body.read_to_end(&mut body)).await.expect("the body");
|
||||
assert_eq!(body, data[1_000..], "the body starts at the offset");
|
||||
|
||||
// Clean up what we put on the server.
|
||||
let key = v1::FileEntry { channel_id: channel, path: "/".into(), name, ..Default::default() };
|
||||
let delete = Op::Delete(v1::Delete {
|
||||
keys: vec![v1::Entity { kind: Some(Kind::File(key)) }],
|
||||
..Default::default()
|
||||
});
|
||||
let _ = a.ask(delete).await;
|
||||
a.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_channel_file_from_an_offset() {
|
||||
if live() {
|
||||
channel_file_from_an_offset(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_channel_file_from_an_offset() {
|
||||
if live() {
|
||||
channel_file_from_an_offset(TS6).await;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the cases that do not apply ----------------------------------------------
|
||||
|
||||
/// The cases of [`EXPECTED`] that do not apply fail against a session of a
|
||||
/// TeamSpeak server, each with a panic of its own (its first line is printed):
|
||||
/// the reasons of the table are what they did when they were run. A case that
|
||||
/// passes one day (with the native session of H1) is to be moved to `Passes`.
|
||||
///
|
||||
/// Ignored by default: the cases that wait for a backend that is not there
|
||||
/// take their three seconds each.
|
||||
async fn cases_that_do_not_apply_fail(dev: Dev) {
|
||||
// A case the suite gained is not in `EXPECTED`, and the zip below would leave
|
||||
// it out without a word.
|
||||
the_suite_is_known();
|
||||
for (case, (name, expect)) in conformance::CASES.iter().zip(&EXPECTED) {
|
||||
let NotRun(reason) = expect else { continue };
|
||||
let harness = move || async move {
|
||||
let mut fixture = fixture(dev).await;
|
||||
fixture.step = Duration::from_secs(3);
|
||||
fixture
|
||||
};
|
||||
match tokio::spawn(async move { conformance::run_case(&harness, case).await }).await {
|
||||
Err(error) if error.is_panic() => {
|
||||
let payload = error.into_panic();
|
||||
let message = payload
|
||||
.downcast_ref::<String>()
|
||||
.cloned()
|
||||
.or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_owned()))
|
||||
.unwrap_or_default();
|
||||
let first = message.lines().next().unwrap_or_default();
|
||||
eprintln!("{} {name}: failed as expected ({reason}): {first}", dev.name);
|
||||
}
|
||||
other => panic!("{name} on {} was expected to fail, and: {other:?}", dev.name),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "runs the conformance cases that cannot pass and waits for their timeouts"]
|
||||
async fn ts3_cases_that_do_not_apply_fail() {
|
||||
if live() {
|
||||
cases_that_do_not_apply_fail(TS3).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "runs the conformance cases that cannot pass and waits for their timeouts"]
|
||||
async fn ts6_cases_that_do_not_apply_fail() {
|
||||
if live() {
|
||||
cases_that_do_not_apply_fail(TS6).await;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
//! Voice across the seam, TeamSpeak side (`docs/session-seam.md` section
|
||||
//! 6.2): TeamSpeak's Opus packets as RTP on the talker's slot, and RTP on our
|
||||
//! own slot as TeamSpeak's `EncodedVoice`. Nothing is transcoded
|
||||
//! (protocol section 1.2): the Opus payload is the same bytes both ways.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::BytesMut;
|
||||
use voelin_audio::{EncodedVoice, VoiceCodec, VoicePacket};
|
||||
use voelin_proto::link::{FlowId, MediaPacket, voice_sub};
|
||||
use voelin_proto::media::opus::{self, Toc};
|
||||
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, OPUS_CLOCK_RATE, PT_OPUS};
|
||||
use voelin_proto::media::{RtpHeader, RtpView};
|
||||
|
||||
use super::entities::slot;
|
||||
|
||||
/// Silence this long between two packets of a talker starts a new talk spurt
|
||||
/// (the marker bit is set on the first packet of it).
|
||||
const SPURT_GAP: Duration = Duration::from_millis(250);
|
||||
|
||||
/// What is kept of the last packet of a talker.
|
||||
struct Talker {
|
||||
timestamp: u32,
|
||||
sequence: u16,
|
||||
at: Instant,
|
||||
/// The 48 kHz ticks the last packet spans.
|
||||
ticks: u32,
|
||||
/// The last packet ended the spurt.
|
||||
ended: bool,
|
||||
}
|
||||
|
||||
/// Wraps what a TeamSpeak connection receives into RTP.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Downlink {
|
||||
talkers: HashMap<u16, Talker>,
|
||||
}
|
||||
|
||||
impl Downlink {
|
||||
/// `packet` as the RTP packet of its talker's slot. The sequence number is
|
||||
/// TeamSpeak's packet id (both 16 bits); the timestamp advances by each
|
||||
/// packet's duration (its Opus table-of-contents byte) on the packet id's
|
||||
/// counter, so it never goes back when the id wraps, and by wall-clock time
|
||||
/// across silences, so a silence is not compressed. The marker is set on
|
||||
/// the first packet after an end or a gap, and an end is an empty payload.
|
||||
pub(super) fn wrap(&mut self, packet: &VoicePacket, now: Instant) -> Option<MediaPacket> {
|
||||
let id = packet.talker.0;
|
||||
let sub = if packet.whisper { voice_sub::FIRST_TALK_TARGET } else { voice_sub::CHANNEL };
|
||||
let flow = FlowId::new(slot(id), sub);
|
||||
let end = packet.is_end();
|
||||
let (timestamp, marker) = match self.talkers.get(&id) {
|
||||
None => (0, !end),
|
||||
Some(last) => {
|
||||
let gap = now.saturating_duration_since(last.at);
|
||||
if last.ended || gap > SPURT_GAP {
|
||||
// A new spurt: the time that passed since the last packet.
|
||||
let wall = (gap.as_micros() * u128::from(OPUS_CLOCK_RATE) / 1_000_000) as u32;
|
||||
(last.timestamp.wrapping_add(last.ticks.max(wall)), !end)
|
||||
} else {
|
||||
let ahead = packet.seq.wrapping_sub(last.sequence);
|
||||
if ahead == 0 || ahead >= 0x8000 {
|
||||
// A duplicate or a late packet: where it belongs, and the
|
||||
// state keeps what the latest packet said.
|
||||
let back = u32::from(last.sequence.wrapping_sub(packet.seq));
|
||||
let at = last.timestamp.wrapping_sub(back * last.ticks);
|
||||
return self.finish(flow, packet, at, false);
|
||||
}
|
||||
(last.timestamp.wrapping_add(u32::from(ahead) * last.ticks), false)
|
||||
}
|
||||
}
|
||||
};
|
||||
let ticks =
|
||||
if end { 0 } else { opus::packet_ticks(&packet.payload).unwrap_or(OPUS_20_MS_TICKS) };
|
||||
self.talkers
|
||||
.insert(id, Talker { timestamp, sequence: packet.seq, at: now, ticks, ended: end });
|
||||
self.finish(flow, packet, timestamp, marker)
|
||||
}
|
||||
|
||||
fn finish(
|
||||
&self,
|
||||
flow: FlowId,
|
||||
packet: &VoicePacket,
|
||||
timestamp: u32,
|
||||
marker: bool,
|
||||
) -> Option<MediaPacket> {
|
||||
let mut header = RtpHeader::new(PT_OPUS, packet.seq, timestamp);
|
||||
header.marker = marker;
|
||||
// An end is an empty payload, also where the server sent one byte.
|
||||
let payload = if packet.is_end() { &[][..] } else { &packet.payload[..] };
|
||||
let mut out = BytesMut::with_capacity(header.encoded_len() + payload.len());
|
||||
header.write(flow, &mut out).ok()?;
|
||||
out.extend_from_slice(payload);
|
||||
Some(MediaPacket { flow, rtp: out.freeze() })
|
||||
}
|
||||
|
||||
/// Forget a talker (it left the server).
|
||||
pub(super) fn forget(&mut self, client: u16) {
|
||||
self.talkers.remove(&client);
|
||||
}
|
||||
}
|
||||
|
||||
/// The voice a media packet of our own slot carries, for TeamSpeak: its
|
||||
/// payload, and `Music` when the Opus packet is stereo. `None` for a packet
|
||||
/// that is no RTP.
|
||||
pub(super) fn uplink(packet: &MediaPacket) -> Option<EncodedVoice> {
|
||||
let view = RtpView::parse(&packet.rtp).ok()?;
|
||||
let payload = view.payload();
|
||||
let codec = match Toc::parse(payload) {
|
||||
Ok(toc) if toc.stereo() => VoiceCodec::Music,
|
||||
_ => VoiceCodec::Voice,
|
||||
};
|
||||
Some(EncodedVoice { codec, payload: payload.to_vec() })
|
||||
}
|
||||
|
||||
/// An RTP packet of voice, for tests of both sides.
|
||||
#[cfg(test)]
|
||||
pub(super) fn rtp_packet(
|
||||
flow: FlowId,
|
||||
sequence: u16,
|
||||
timestamp: u32,
|
||||
marker: bool,
|
||||
payload: &[u8],
|
||||
) -> bytes::Bytes {
|
||||
let mut header = RtpHeader::new(PT_OPUS, sequence, timestamp);
|
||||
header.marker = marker;
|
||||
let mut out = BytesMut::new();
|
||||
header.write(flow, &mut out).unwrap();
|
||||
out.extend_from_slice(payload);
|
||||
out.freeze()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use bytes::Bytes;
|
||||
use voelin_audio::TalkerId;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn voice(talker: u16, seq: u16, payload: &[u8], whisper: bool) -> VoicePacket {
|
||||
VoicePacket {
|
||||
talker: TalkerId(talker),
|
||||
seq,
|
||||
codec: VoiceCodec::Voice,
|
||||
whisper,
|
||||
payload: payload.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
/// An Opus packet of 20 ms in a CELT-only frame (config 16 is 2.5 ms; 19
|
||||
/// is 20 ms), mono, one frame.
|
||||
const OPUS_20_MS: [u8; 3] = [0x98, 0x01, 0x02];
|
||||
|
||||
fn view(packet: &MediaPacket) -> RtpView<'_> {
|
||||
RtpView::parse(&packet.rtp).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spurt_is_sequenced_by_the_packet_id_with_a_marker_on_its_first_packet() {
|
||||
let mut down = Downlink::default();
|
||||
let t0 = Instant::now();
|
||||
let first = down.wrap(&voice(7, 65_534, &OPUS_20_MS, false), t0).unwrap();
|
||||
let v = view(&first);
|
||||
assert!(v.marker());
|
||||
assert_eq!((v.ssrc(), first.flow), (FlowId::new(8, 0).0, FlowId::new(8, 0)));
|
||||
assert_eq!((v.sequence(), v.timestamp()), (65_534, 0));
|
||||
// The id wraps; the timestamp keeps counting.
|
||||
let t1 = t0 + Duration::from_millis(20);
|
||||
let second = down.wrap(&voice(7, 65_535, &OPUS_20_MS, false), t1).unwrap();
|
||||
let third =
|
||||
down.wrap(&voice(7, 0, &OPUS_20_MS, false), t1 + Duration::from_millis(20)).unwrap();
|
||||
assert!(!view(&second).marker() && !view(&third).marker());
|
||||
assert_eq!(view(&second).timestamp(), OPUS_20_MS_TICKS);
|
||||
assert_eq!((view(&third).sequence(), view(&third).timestamp()), (0, 2 * OPUS_20_MS_TICKS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_is_an_empty_payload_and_the_next_packet_has_a_marker() {
|
||||
let mut down = Downlink::default();
|
||||
let t0 = Instant::now();
|
||||
down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
|
||||
let end = down.wrap(&voice(7, 2, &[], false), t0 + Duration::from_millis(20)).unwrap();
|
||||
assert!(view(&end).payload().is_empty() && !view(&end).marker());
|
||||
// TeamSpeak's single byte after a talk is an end too.
|
||||
let mut down = Downlink::default();
|
||||
down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
|
||||
let end = down.wrap(&voice(7, 2, &[0], false), t0 + Duration::from_millis(20)).unwrap();
|
||||
assert!(view(&end).payload().is_empty());
|
||||
let next =
|
||||
down.wrap(&voice(7, 3, &OPUS_20_MS, false), t0 + Duration::from_millis(60)).unwrap();
|
||||
assert!(view(&next).marker());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_silence_is_not_compressed() {
|
||||
let mut down = Downlink::default();
|
||||
let t0 = Instant::now();
|
||||
let first = down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
|
||||
let again =
|
||||
down.wrap(&voice(7, 2, &OPUS_20_MS, false), t0 + Duration::from_secs(2)).unwrap();
|
||||
assert!(view(&again).marker(), "a gap starts a spurt");
|
||||
// Two seconds of wall-clock time are 96,000 ticks of the 48 kHz clock.
|
||||
assert_eq!(view(&again).timestamp() - view(&first).timestamp(), 96_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whispers_ride_sub_flow_1_and_talkers_have_slots_of_their_own() {
|
||||
let mut down = Downlink::default();
|
||||
let now = Instant::now();
|
||||
let whisper = down.wrap(&voice(300, 1, &OPUS_20_MS, true), now).unwrap();
|
||||
assert_eq!((whisper.flow.slot(), whisper.flow.sub()), (301, 1));
|
||||
let channel = down.wrap(&voice(300, 2, &OPUS_20_MS, false), now).unwrap();
|
||||
assert_eq!((channel.flow.slot(), channel.flow.sub()), (301, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_packet_that_is_not_in_order_keeps_the_state_of_the_latest() {
|
||||
let mut down = Downlink::default();
|
||||
let t0 = Instant::now();
|
||||
down.wrap(&voice(7, 10, &OPUS_20_MS, false), t0).unwrap();
|
||||
down.wrap(&voice(7, 11, &OPUS_20_MS, false), t0 + Duration::from_millis(20)).unwrap();
|
||||
let late =
|
||||
down.wrap(&voice(7, 10, &OPUS_20_MS, false), t0 + Duration::from_millis(25)).unwrap();
|
||||
assert_eq!(view(&late).timestamp(), 0, "where packet 10 belongs");
|
||||
let next =
|
||||
down.wrap(&voice(7, 12, &OPUS_20_MS, false), t0 + Duration::from_millis(40)).unwrap();
|
||||
assert_eq!(view(&next).timestamp(), 2 * OPUS_20_MS_TICKS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn our_voice_loses_its_header_and_stereo_is_music() {
|
||||
let flow = FlowId::new(8, 0);
|
||||
let mono = MediaPacket { flow, rtp: rtp_packet(flow, 0, 0, true, &OPUS_20_MS) };
|
||||
let voice = uplink(&mono).unwrap();
|
||||
assert_eq!((voice.codec, voice.payload.as_slice()), (VoiceCodec::Voice, &OPUS_20_MS[..]));
|
||||
// The same TOC with the stereo bit.
|
||||
let stereo_toc = [OPUS_20_MS[0] | 0x04, 1, 2];
|
||||
let stereo = MediaPacket { flow, rtp: rtp_packet(flow, 1, 960, false, &stereo_toc) };
|
||||
assert_eq!(uplink(&stereo).unwrap().codec, VoiceCodec::Music);
|
||||
// The end of a spurt: an empty payload.
|
||||
let end = MediaPacket { flow, rtp: rtp_packet(flow, 2, 1920, false, &[]) };
|
||||
assert!(uplink(&end).unwrap().is_end());
|
||||
// Not RTP.
|
||||
assert!(uplink(&MediaPacket { flow, rtp: Bytes::from_static(&[1, 2, 3]) }).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,855 @@
|
||||
//! A TeamSpeak connection as a `voelin_proto::link::Session`
|
||||
//! (`docs/session-seam.md`, "the TeamSpeak side").
|
||||
//!
|
||||
//! [`LinkSession`] is a `Session` over any [`ServerLink`]:
|
||||
//! it turns the link's `LinkCmd`s and `LinkEvent`s (the client's older,
|
||||
//! TeamSpeak-shaped vocabulary) into v1 entities, pushes and answers. With
|
||||
//! `TsLink` inside it is the in-process TeamSpeak `Session`; with a fake link
|
||||
//! inside it is what the link tests of the engine run through. [`TsConnector`]
|
||||
//! is the `Connector` that makes them for `ts3server://` and `teamspeak://`
|
||||
//! addresses.
|
||||
//!
|
||||
//! This module and the files it is made of are TeamSpeak's: they keep the
|
||||
//! TeamSpeak types (`tsclientlib`'s identity and client version) in
|
||||
//! [`inner_options`], the reverse of what the engine's `connect_params` wrote,
|
||||
//! and everything else is v1 and the client's own model. In the second half
|
||||
//! of the decoupling plan they move, with `TsLink`, to the TeamSpeak gateway
|
||||
//! (`voelin-gateway-ts` of VoelinGateWay).
|
||||
|
||||
mod driver;
|
||||
pub(crate) mod entities;
|
||||
pub(crate) mod ids;
|
||||
#[cfg(test)]
|
||||
mod live_tests;
|
||||
mod media;
|
||||
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::Duration;
|
||||
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use bytes::Bytes;
|
||||
use tokio::io::{AsyncReadExt, AsyncWrite};
|
||||
use tokio::sync::{broadcast, mpsc, oneshot, watch};
|
||||
use voelin_model::{Link, ServerDetails};
|
||||
use voelin_proto::link::{
|
||||
BoxFuture, CloseReason, ConnectParams, Connected, Connector, Credential, Download, Features,
|
||||
LinkStats, MAX_RTP, MediaClass, MediaError, MediaPacket, Placement, Sent, Session,
|
||||
SessionError, Upload, placement, voice_sub,
|
||||
};
|
||||
use voelin_proto::v1::{self, response::Result as Answer};
|
||||
|
||||
use self::driver::{Cmd, Config, Driver, Parts, rejected};
|
||||
use super::{ConnectOptions, ServerLink, TsLink, versions};
|
||||
use crate::BackendInfo;
|
||||
use crate::link::{
|
||||
BoxDuplex, LinkCmd, LinkCtx, LinkEvent, LocalConnected, LocalConnector, LocalCtx, StreamPort,
|
||||
VERSION_PARAM,
|
||||
};
|
||||
|
||||
/// The `Credential::Foreign` kind of a stored TeamSpeak identity.
|
||||
const IDENTITY_KIND: &str = voelin_identity::KIND_TEAMSPEAK;
|
||||
/// How long the link may take to report its first snapshot after it said it
|
||||
/// is connected; the snapshot gives the `Welcome` its own user.
|
||||
const FIRST_SNAPSHOT: Duration = Duration::from_millis(250);
|
||||
|
||||
static SESSIONS: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
fn now_ms() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_millis() as i64)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
// ---- what the engine hands a connector ------------------------------------
|
||||
|
||||
/// The options a TeamSpeak link is connected with: the reverse of
|
||||
/// `link::connect_params`. A client version spec that [`versions::resolve`]
|
||||
/// refuses fails the connect, in words.
|
||||
fn inner_options(params: &ConnectParams, ctx: &LocalCtx) -> Result<ConnectOptions, SessionError> {
|
||||
let link = match Link::parse(¶ms.address) {
|
||||
Some(Link::Server(link)) => link,
|
||||
_ => {
|
||||
// Without the query: a channel password rides in it.
|
||||
let shown = crate::link::without_query(¶ms.address);
|
||||
return Err(SessionError::Protocol(format!("not a TeamSpeak server address: {shown}")));
|
||||
}
|
||||
};
|
||||
let identity = match ¶ms.credential {
|
||||
Credential::Foreign { kind: IDENTITY_KIND, blob } if blob.is_empty() => None,
|
||||
Credential::Foreign { kind: IDENTITY_KIND, blob } => {
|
||||
Some(serde_json::from_slice(blob).map_err(|e| {
|
||||
SessionError::Protocol(format!("the TeamSpeak identity cannot be read: {e}"))
|
||||
})?)
|
||||
}
|
||||
_ => {
|
||||
return Err(SessionError::Protocol(
|
||||
"a TeamSpeak server needs a TeamSpeak identity".into(),
|
||||
));
|
||||
}
|
||||
};
|
||||
let spec = params
|
||||
.address
|
||||
.split_once('?')
|
||||
.and_then(|(_, query)| {
|
||||
query.split('&').find_map(|pair| pair.strip_prefix(&format!("{VERSION_PARAM}=")))
|
||||
})
|
||||
.map(|text| {
|
||||
URL_SAFE_NO_PAD
|
||||
.decode(text)
|
||||
.ok()
|
||||
.and_then(|bytes| String::from_utf8(bytes).ok())
|
||||
.ok_or_else(|| SessionError::Protocol("the client version cannot be read".into()))
|
||||
})
|
||||
.transpose()?;
|
||||
let client_version = match spec {
|
||||
None => None,
|
||||
Some(spec) => versions::resolve(&spec).map_err(|e| {
|
||||
SessionError::Protocol(format!("invalid client compatibility version: {e}"))
|
||||
})?,
|
||||
};
|
||||
let nonempty = |text: &str| (!text.is_empty()).then(|| text.to_owned());
|
||||
Ok(ConnectOptions {
|
||||
address: link.address(),
|
||||
nickname: nonempty(¶ms.hello.nickname).or(link.nickname.clone()).unwrap_or_default(),
|
||||
identity,
|
||||
client_version,
|
||||
server_password: nonempty(¶ms.hello.password).or(link.password.clone()),
|
||||
channel: link.channel.clone(),
|
||||
channel_password: link.channel_password.clone(),
|
||||
token: nonempty(¶ms.hello.invite_code).or(link.token.clone()),
|
||||
audio: ctx.audio,
|
||||
stream_peer: ctx.stream_peer.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
// ---- backend and features ---------------------------------------------------
|
||||
|
||||
/// The server software as v1 names it (table 4.7): `teamspeak` with the
|
||||
/// flavor `ts3` or `ts6`; what is not a TeamSpeak product as it is.
|
||||
pub(crate) fn backend_to_v1(backend: &BackendInfo) -> v1::BackendInfo {
|
||||
let (product, flavor) = match backend.product.as_str() {
|
||||
"TeamSpeak 3" => ("teamspeak", "ts3"),
|
||||
"TeamSpeak 6" => ("teamspeak", "ts6"),
|
||||
// A TeamSpeak server the engine does not recognise: the version it
|
||||
// sent, no flavor.
|
||||
"" => ("teamspeak", ""),
|
||||
other => (other, ""),
|
||||
};
|
||||
v1::BackendInfo {
|
||||
product: product.into(),
|
||||
version: backend.version.clone(),
|
||||
flavor: flavor.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The features a TeamSpeak connection offers, from what its link can do
|
||||
/// (`docs/session-seam.md` section 4.7).
|
||||
pub(crate) fn features_of(capabilities: &voelin_model::Capabilities) -> Vec<&'static str> {
|
||||
let mut features =
|
||||
vec!["voice", "chat", "chat.bbcode", "dm", "sync.delta", "roles", "roles.channel"];
|
||||
if capabilities.file_transfer {
|
||||
features.extend(["files", "files.upload"]);
|
||||
}
|
||||
if capabilities.offline_messages {
|
||||
features.push("mailbox");
|
||||
}
|
||||
if capabilities.streams {
|
||||
features.extend(["streams", "streams.p2p", "streams.audio", "streams.approval"]);
|
||||
}
|
||||
features
|
||||
}
|
||||
|
||||
// ---- the session ------------------------------------------------------------
|
||||
|
||||
/// A `Session` over a [`ServerLink`]: the TeamSpeak side of the seam.
|
||||
pub(crate) struct LinkSession {
|
||||
welcome: v1::Welcome,
|
||||
features: Features,
|
||||
cmds: mpsc::UnboundedSender<Cmd>,
|
||||
closed: watch::Receiver<Option<CloseReason>>,
|
||||
/// The media slot of our client; the driver changes it when we are another
|
||||
/// client after TeamSpeak's own reconnect.
|
||||
own_slot: Arc<AtomicU32>,
|
||||
}
|
||||
|
||||
fn closed_reason(closed: &watch::Receiver<Option<CloseReason>>) -> CloseReason {
|
||||
closed.borrow().clone().unwrap_or_else(|| CloseReason::Network("the connection ended".into()))
|
||||
}
|
||||
|
||||
impl Session for LinkSession {
|
||||
fn welcome(&self) -> &v1::Welcome {
|
||||
&self.welcome
|
||||
}
|
||||
|
||||
fn features(&self) -> Features {
|
||||
self.features.clone()
|
||||
}
|
||||
|
||||
fn request(&self, op: v1::request::Op) -> BoxFuture<Result<Answer, SessionError>> {
|
||||
let closed = self.closed.clone();
|
||||
match placement(&op) {
|
||||
Placement::Invalid => {
|
||||
return Box::pin(async {
|
||||
Err(SessionError::Protocol("a Hello is part of connecting".into()))
|
||||
});
|
||||
}
|
||||
Placement::OwnStream
|
||||
if matches!(op, v1::request::Op::FileRead(_) | v1::request::Op::FileWrite(_)) =>
|
||||
{
|
||||
return Box::pin(async {
|
||||
Err(SessionError::Protocol("files go through read_file and write_file".into()))
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// Queued now, in the order of the calls, not when the future is polled.
|
||||
let (reply, answer) = oneshot::channel();
|
||||
if self.cmds.send(Cmd::Request { op, reply }).is_err() {
|
||||
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
|
||||
}
|
||||
Box::pin(async move {
|
||||
match answer.await {
|
||||
Ok(answer) => answer,
|
||||
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn notify(&self, op: v1::request::Op) -> Result<(), SessionError> {
|
||||
// Only an op of the control stream can go without an answer: a Hello is
|
||||
// part of connecting, and a List and the file transfers have streams
|
||||
// (and answers) of their own.
|
||||
match placement(&op) {
|
||||
Placement::Control => {}
|
||||
Placement::Invalid => {
|
||||
return Err(SessionError::Protocol("a Hello is part of connecting".into()));
|
||||
}
|
||||
Placement::OwnStream => {
|
||||
return Err(SessionError::Protocol(
|
||||
"a List and the file transfers have a stream and an answer of their own, \
|
||||
they cannot be sent without one"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
// The task may be on its way out and not have dropped its queue yet.
|
||||
if self.closed.borrow().is_some() {
|
||||
return Err(SessionError::Closed(closed_reason(&self.closed)));
|
||||
}
|
||||
self.cmds
|
||||
.send(Cmd::Notify(op))
|
||||
.map_err(|_| SessionError::Closed(closed_reason(&self.closed)))
|
||||
}
|
||||
|
||||
fn read_file(&self, request: v1::FileRead) -> BoxFuture<Result<Download, SessionError>> {
|
||||
let closed = self.closed.clone();
|
||||
let (reply, answer) = oneshot::channel();
|
||||
if self.cmds.send(Cmd::Read { request, reply }).is_err() {
|
||||
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
|
||||
}
|
||||
Box::pin(async move {
|
||||
match answer.await {
|
||||
Ok(answer) => answer,
|
||||
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn write_file(&self, request: v1::FileWrite) -> BoxFuture<Result<Upload, SessionError>> {
|
||||
let closed = self.closed.clone();
|
||||
let (reply, answer) = oneshot::channel();
|
||||
if self.cmds.send(Cmd::Write { request, reply }).is_err() {
|
||||
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
|
||||
}
|
||||
Box::pin(async move {
|
||||
match answer.await {
|
||||
Ok(answer) => answer,
|
||||
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn send_media(&self, class: MediaClass, packet: MediaPacket) -> Result<Sent, MediaError> {
|
||||
let flow = packet.flow;
|
||||
if self.closed.borrow().is_some() {
|
||||
return Err(MediaError::Closed);
|
||||
}
|
||||
if packet.rtp.len() > MAX_RTP {
|
||||
return Err(MediaError::TooLarge { len: packet.rtp.len(), max: MAX_RTP });
|
||||
}
|
||||
// Only our voice to the channel: TeamSpeak whispers and priority voice,
|
||||
// like video, are not offered here.
|
||||
if class != MediaClass::Voice
|
||||
|| flow.slot() != self.own_slot.load(Ordering::Relaxed)
|
||||
|| flow.sub() != voice_sub::CHANNEL
|
||||
{
|
||||
return Err(MediaError::NotOwned(flow));
|
||||
}
|
||||
let voice = media::uplink(&packet).ok_or(MediaError::NotOwned(flow))?;
|
||||
self.cmds.send(Cmd::Audio(voice)).map_err(|_| MediaError::Closed)?;
|
||||
Ok(Sent::Queued)
|
||||
}
|
||||
|
||||
fn stats(&self) -> LinkStats {
|
||||
LinkStats { max_rtp: MAX_RTP, ..Default::default() }
|
||||
}
|
||||
|
||||
fn close(&self, code: v1::CloseCode, reason: &str) {
|
||||
let _ = self.cmds.send(Cmd::Close { code, reason: reason.to_owned() });
|
||||
}
|
||||
|
||||
fn closed(&self) -> BoxFuture<CloseReason> {
|
||||
let mut closed = self.closed.clone();
|
||||
Box::pin(async move {
|
||||
let reason = closed.wait_for(Option::is_some).await.ok().and_then(|r| r.clone());
|
||||
reason.unwrap_or_else(|| closed_reason(&closed))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The write half of an upload: ending it tells the other half of the
|
||||
/// upload that the file is all there.
|
||||
struct UploadBody {
|
||||
inner: tokio::io::WriteHalf<BoxDuplex>,
|
||||
ended: Option<oneshot::Sender<()>>,
|
||||
}
|
||||
|
||||
impl AsyncWrite for UploadBody {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<std::io::Result<usize>> {
|
||||
Pin::new(&mut self.inner).poll_write(cx, buf)
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
Pin::new(&mut self.inner).poll_flush(cx)
|
||||
}
|
||||
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
let done = Pin::new(&mut self.inner).poll_shutdown(cx);
|
||||
if matches!(done, Poll::Ready(Ok(())))
|
||||
&& let Some(ended) = self.ended.take()
|
||||
{
|
||||
let _ = ended.send(());
|
||||
}
|
||||
done
|
||||
}
|
||||
}
|
||||
|
||||
/// An upload over the transfer connection `stream`: the body writes to it,
|
||||
/// and `done` resolves once the body is shut down and the server has closed
|
||||
/// the connection (or 30 s passed), with the file as `stored`.
|
||||
fn upload(stream: BoxDuplex, stored: v1::FileEntry) -> Upload {
|
||||
let (mut read, write) = tokio::io::split(stream);
|
||||
let (ended, shut) = oneshot::channel();
|
||||
let done: BoxFuture<Result<v1::Entities, SessionError>> = Box::pin(async move {
|
||||
if shut.await.is_err() {
|
||||
return Err(rejected(v1::ErrorCode::Cancelled, "the upload was dropped"));
|
||||
}
|
||||
// The server closes the connection once it has everything.
|
||||
let _ = tokio::time::timeout(Duration::from_secs(30), read.read(&mut [0u8; 1])).await;
|
||||
Ok(v1::Entities {
|
||||
items: vec![v1::Entity { kind: Some(v1::entity::Kind::File(stored)) }],
|
||||
..Default::default()
|
||||
})
|
||||
});
|
||||
Upload { body: Box::pin(UploadBody { inner: write, ended: Some(ended) }), done }
|
||||
}
|
||||
|
||||
// ---- the connector ----------------------------------------------------------
|
||||
|
||||
/// The `Connector` of a [`ServerLink`]: its sessions are [`LinkSession`]s.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct LinkConnector {
|
||||
link: Arc<dyn ServerLink>,
|
||||
schemes: &'static [&'static str],
|
||||
/// Serves every scheme (the engine's tests give a link of their own).
|
||||
any: bool,
|
||||
}
|
||||
|
||||
impl LinkConnector {
|
||||
/// A connector for `schemes`.
|
||||
pub(crate) fn new(link: Arc<dyn ServerLink>, schemes: &'static [&'static str]) -> Self {
|
||||
Self { link, schemes, any: false }
|
||||
}
|
||||
|
||||
/// A connector for addresses of every scheme.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn any(link: Arc<dyn ServerLink>) -> Self {
|
||||
Self { link, schemes: &[], any: true }
|
||||
}
|
||||
}
|
||||
|
||||
impl Connector for LinkConnector {
|
||||
fn schemes(&self) -> &'static [&'static str] {
|
||||
self.schemes
|
||||
}
|
||||
|
||||
fn connect(&self, params: ConnectParams) -> BoxFuture<Result<Connected, SessionError>> {
|
||||
let connect = connect_link(self.link.clone(), params, LocalCtx::standalone());
|
||||
Box::pin(async move { Ok(connect.await?.connected) })
|
||||
}
|
||||
}
|
||||
|
||||
impl LocalConnector for LinkConnector {
|
||||
fn accepts(&self, scheme: &str) -> bool {
|
||||
self.any || self.schemes.contains(&scheme)
|
||||
}
|
||||
|
||||
fn connect_local(
|
||||
&self,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> BoxFuture<Result<LocalConnected, SessionError>> {
|
||||
Box::pin(connect_link(self.link.clone(), params, ctx))
|
||||
}
|
||||
}
|
||||
|
||||
/// Connects to TeamSpeak 3 and 6 servers (`ts3server://` and `teamspeak://`)
|
||||
/// with `tsclientlib`: a `LinkSession` over a `TsLink` for every connection.
|
||||
///
|
||||
/// Clones share one account: the main myTeamSpeak account that every
|
||||
/// connection of the connector presents ([`TsConnector::set_myts_identity`],
|
||||
/// [`TsConnector::set_myts_data`]), also those made before it was set.
|
||||
/// Register a connector in the engine's registry with
|
||||
/// [`Backends::register_teamspeak`](crate::Backends::register_teamspeak) and
|
||||
/// keep a clone to set the account.
|
||||
#[derive(Clone)]
|
||||
pub struct TsConnector {
|
||||
connector: LinkConnector,
|
||||
link: Arc<TsLink>,
|
||||
}
|
||||
|
||||
impl Default for TsConnector {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl TsConnector {
|
||||
/// A connector that presents no account until it is given one.
|
||||
pub fn new() -> Self {
|
||||
let link = Arc::new(TsLink::new());
|
||||
Self { connector: LinkConnector::new(link.clone(), &["ts3server", "teamspeak"]), link }
|
||||
}
|
||||
|
||||
/// The main account's proof for every current and future connection of
|
||||
/// this connector (and its clones): a myTS ID signed with the account's
|
||||
/// key. Connections that are up show the server the new proof, and those
|
||||
/// that connect later present it from the start; `None` is a sign-out.
|
||||
pub fn set_myts_identity(&self, identity: Option<Arc<tsproto::myts::Identity>>) {
|
||||
self.link.account().set_identity(identity);
|
||||
}
|
||||
|
||||
/// What servers are shown of the main account: its avatar and badges with
|
||||
/// their certificates, its User Tag (TeamSpeak 6). It is sent to every
|
||||
/// connection that presents the account's myTS ID, once connected and when
|
||||
/// it changes; cleared on a sign-out (`None`).
|
||||
pub fn set_myts_data(&self, data: Option<Arc<tsclientlib::MytsData>>) {
|
||||
self.link.account().set_data(data);
|
||||
}
|
||||
}
|
||||
|
||||
impl Connector for TsConnector {
|
||||
fn schemes(&self) -> &'static [&'static str] {
|
||||
self.connector.schemes()
|
||||
}
|
||||
|
||||
fn connect(&self, params: ConnectParams) -> BoxFuture<Result<Connected, SessionError>> {
|
||||
self.connector.connect(params)
|
||||
}
|
||||
}
|
||||
|
||||
impl LocalConnector for TsConnector {
|
||||
fn connect_local(
|
||||
&self,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> BoxFuture<Result<LocalConnected, SessionError>> {
|
||||
self.connector.connect_local(params, ctx)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the link told when it connected.
|
||||
struct Joined {
|
||||
name: String,
|
||||
backend: BackendInfo,
|
||||
capabilities: voelin_model::Capabilities,
|
||||
own_client: u16,
|
||||
server_uid: String,
|
||||
own_uid: Option<String>,
|
||||
}
|
||||
|
||||
fn ended_error(reason: Option<String>) -> SessionError {
|
||||
SessionError::Closed(match reason {
|
||||
Some(reason) => CloseReason::Network(reason),
|
||||
None => CloseReason::Remote { code: v1::CloseCode::Normal as u64, reason: String::new() },
|
||||
})
|
||||
}
|
||||
|
||||
/// Wait for the link to say it is connected (or that it failed).
|
||||
async fn wait_connected(
|
||||
events: &mut mpsc::UnboundedReceiver<LinkEvent>,
|
||||
) -> Result<Joined, SessionError> {
|
||||
loop {
|
||||
match events.recv().await {
|
||||
Some(LinkEvent::Connected {
|
||||
name,
|
||||
backend,
|
||||
capabilities,
|
||||
own_client,
|
||||
server_uid,
|
||||
own_uid,
|
||||
}) => {
|
||||
return Ok(Joined { name, backend, capabilities, own_client, server_uid, own_uid });
|
||||
}
|
||||
Some(LinkEvent::Disconnected(reason)) => return Err(ended_error(reason)),
|
||||
Some(_) => {}
|
||||
None => return Err(ended_error(Some("the connection ended".into()))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a [`LinkSession`] over `link` to the address in `params`.
|
||||
async fn connect_link(
|
||||
link: Arc<dyn ServerLink>,
|
||||
params: ConnectParams,
|
||||
ctx: LocalCtx,
|
||||
) -> Result<LocalConnected, SessionError> {
|
||||
let options = inner_options(¶ms, &ctx)?;
|
||||
let nickname = options.nickname.clone();
|
||||
let (inner_tx, inner_rx) = mpsc::unbounded_channel();
|
||||
let (events_tx, mut events) = mpsc::unbounded_channel();
|
||||
// The link answers requests on a bus of its own: this session reads the
|
||||
// answers, and passes on the rest to the engine's.
|
||||
let (bus_tx, bus) = broadcast::channel(4096);
|
||||
let inner_ctx = LinkCtx { events: bus_tx, ..ctx.link.clone() };
|
||||
link.spawn(options, inner_ctx, inner_rx, events_tx);
|
||||
|
||||
let joined = match tokio::time::timeout(params.timeout, wait_connected(&mut events)).await {
|
||||
Ok(joined) => joined?,
|
||||
Err(_) => {
|
||||
let _ = inner_tx.send(LinkCmd::Disconnect);
|
||||
return Err(SessionError::Timeout);
|
||||
}
|
||||
};
|
||||
// The link reports its first snapshot right after it says it is connected;
|
||||
// the session needs it to know the own user.
|
||||
let mut early: Vec<LinkEvent> = Vec::new();
|
||||
let _ = tokio::time::timeout(FIRST_SNAPSHOT, async {
|
||||
while let Some(event) = events.recv().await {
|
||||
let stop = matches!(event, LinkEvent::Presence(_) | LinkEvent::Disconnected(_));
|
||||
early.push(event);
|
||||
if stop {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
if let Some(LinkEvent::Disconnected(reason)) = early.last() {
|
||||
return Err(ended_error(reason.clone()));
|
||||
}
|
||||
let own_database_id = early.iter().find_map(|event| match event {
|
||||
LinkEvent::Presence(presence) => {
|
||||
presence.clients.get(&joined.own_client).and_then(|c| c.database_id)
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
|
||||
let ts6 = joined.backend.product == "TeamSpeak 6";
|
||||
let own_user =
|
||||
own_database_id.or_else(|| joined.own_uid.as_deref().map(ids::synthetic_user)).unwrap_or(0);
|
||||
let features = features_of(&joined.capabilities);
|
||||
let welcome = v1::Welcome {
|
||||
user_id: own_user,
|
||||
session_id: SESSIONS.fetch_add(1, Ordering::Relaxed),
|
||||
uid: joined.own_uid.as_deref().and_then(ids::uid_bytes).unwrap_or_default().into(),
|
||||
host: Some(v1::HostInfo {
|
||||
host_key: Bytes::new(),
|
||||
name: joined.name.clone(),
|
||||
product: joined.backend.product.clone(),
|
||||
version: joined.backend.version.clone(),
|
||||
backend: Some(backend_to_v1(&joined.backend)),
|
||||
icon: None,
|
||||
}),
|
||||
features: features.iter().map(|f| (*f).to_owned()).collect(),
|
||||
limits: Some(v1::Limits {
|
||||
max_message_chars: 1024,
|
||||
max_page: 100,
|
||||
// HOME, SERVER and LIVE, and the chats.
|
||||
max_subscriptions: driver::MAX_CHAT_SUBSCRIPTIONS + 3,
|
||||
max_chat_subscriptions: driver::MAX_CHAT_SUBSCRIPTIONS,
|
||||
max_live_subscriptions: 8,
|
||||
..Default::default()
|
||||
}),
|
||||
time_ms: now_ms(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let (cmds_tx, cmds_rx) = mpsc::unbounded_channel();
|
||||
let own_slot = Arc::new(AtomicU32::new(entities::slot(joined.own_client)));
|
||||
let (pushes_tx, pushes_rx) = mpsc::channel(params.push_capacity.max(16));
|
||||
let (closed_tx, closed_rx) = watch::channel(None);
|
||||
let (port, streams) = if joined.capabilities.streams {
|
||||
let (events_tx, events_rx) = mpsc::unbounded_channel();
|
||||
let cmds = cmds_tx.clone();
|
||||
let send = move |cmd| {
|
||||
let _ = cmds.send(Cmd::Stream(cmd));
|
||||
};
|
||||
(Some(events_tx), Some(StreamPort::new(send, events_rx)))
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
let details = ServerDetails { uid: Some(joined.server_uid.clone()), ..Default::default() };
|
||||
let driver = Driver::new(Parts {
|
||||
cfg: Config {
|
||||
ts6,
|
||||
own_client: joined.own_client,
|
||||
nickname,
|
||||
own_uid: joined.own_uid.clone(),
|
||||
files: joined.capabilities.file_transfer,
|
||||
mail: joined.capabilities.offline_messages,
|
||||
},
|
||||
inner: inner_tx,
|
||||
events,
|
||||
early,
|
||||
bus,
|
||||
engine_bus: ctx.link.events.clone(),
|
||||
pushes: pushes_tx,
|
||||
media: params.media.clone(),
|
||||
port,
|
||||
closed: closed_tx,
|
||||
own_slot: own_slot.clone(),
|
||||
server: entities::server(&details, &joined.name, 0),
|
||||
epoch: u64::try_from(now_ms()).unwrap_or(1).max(1),
|
||||
});
|
||||
let session = LinkSession {
|
||||
welcome,
|
||||
features: Features::new(features),
|
||||
cmds: cmds_tx,
|
||||
closed: closed_rx,
|
||||
own_slot,
|
||||
};
|
||||
tokio::spawn(driver.run(cmds_rx));
|
||||
Ok(LocalConnected {
|
||||
connected: Connected {
|
||||
session: Arc::new(session),
|
||||
pushes: pushes_rx,
|
||||
// A TeamSpeak server has no host key to pin.
|
||||
host_uid: [0; 32],
|
||||
},
|
||||
streams,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::link::{Backends, VoiceOptions, connect_params};
|
||||
use voelin_proto::link::IssuerTrust;
|
||||
|
||||
fn params(options: &VoiceOptions) -> ConnectParams {
|
||||
let (media, _rx) = voelin_proto::test_util::media_channel();
|
||||
connect_params(options, media, &Backends::empty()).unwrap()
|
||||
}
|
||||
|
||||
fn back(options: &VoiceOptions) -> ConnectOptions {
|
||||
inner_options(¶ms(options), &LocalCtx::standalone()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_options_of_a_bookmark_come_back_as_they_went() {
|
||||
let mut options = VoiceOptions::new("ts.example.com:9988", "nick");
|
||||
let same = back(&options);
|
||||
assert_eq!(
|
||||
(same.address.as_str(), same.nickname.as_str()),
|
||||
("ts.example.com:9988", "nick")
|
||||
);
|
||||
assert!(same.identity.is_none() && same.client_version.is_none());
|
||||
assert!(same.channel.is_none() && same.server_password.is_none() && same.token.is_none());
|
||||
|
||||
// Everything a connection can be told: the server password and the
|
||||
// privilege key go in the hello, the channel and its password in the
|
||||
// link, the identity as a credential.
|
||||
options.server_password = Some("s3cret pass&word".into());
|
||||
options.channel = Some("Games/Raid Night".into());
|
||||
options.channel_password = Some("p w+%".into());
|
||||
options.token = Some("tokenvalue".into());
|
||||
let identity = tsclientlib::Identity::create();
|
||||
options.identity = Some(crate::ts::identity::to_blob(&identity));
|
||||
// A spec the user can give; the connector resolves it.
|
||||
options.client_version = Some("generic".into());
|
||||
options.audio = false;
|
||||
let sent = params(&options);
|
||||
assert_eq!(sent.hello.password, "s3cret pass&word");
|
||||
assert_eq!(sent.hello.invite_code, "tokenvalue");
|
||||
assert_eq!(sent.hello.nickname, "nick");
|
||||
assert!(
|
||||
sent.address.starts_with("ts3server://ts.example.com?port=9988"),
|
||||
"{}",
|
||||
sent.address
|
||||
);
|
||||
assert!(!sent.address.contains("s3cret") && !sent.address.contains("tokenvalue"));
|
||||
let got = back(&options);
|
||||
assert_eq!(got.address, "ts.example.com:9988");
|
||||
assert_eq!(got.server_password, options.server_password);
|
||||
assert_eq!(got.channel.as_deref(), Some("Games/Raid Night"));
|
||||
assert_eq!(got.channel_password, options.channel_password);
|
||||
assert_eq!(got.token.as_deref(), Some("tokenvalue"));
|
||||
assert_eq!(got.client_version, versions::resolve("generic").unwrap());
|
||||
assert!(got.client_version.is_some());
|
||||
// The identity is the same key and counters.
|
||||
let b = got.identity.as_ref().unwrap();
|
||||
assert_eq!(serde_json::to_value(&identity).unwrap(), serde_json::to_value(b).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_channel_by_id_and_an_address_that_is_a_link_are_kept() {
|
||||
let mut options = VoiceOptions::new("[::1]:9987", "nick");
|
||||
options.channel = Some("/12".into());
|
||||
let got = back(&options);
|
||||
assert_eq!(got.address, "[::1]:9987");
|
||||
assert_eq!(got.channel.as_deref(), Some("/12"));
|
||||
|
||||
// A bookmark that is a link keeps its own parameters.
|
||||
let options = VoiceOptions::new("ts3server://ts.example.com?port=1&channel=Lobby", "nick");
|
||||
let got = back(&options);
|
||||
assert_eq!(
|
||||
(got.address.as_str(), got.channel.as_deref()),
|
||||
("ts.example.com:1", Some("Lobby"))
|
||||
);
|
||||
// Another scheme is left as it is for the connector of that scheme.
|
||||
let options = VoiceOptions::new("voelin://host/i/code", "nick");
|
||||
assert_eq!(params(&options).address, "voelin://host/i/code");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_no_teamspeak_identity_is_refused() {
|
||||
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
|
||||
sent.credential = Credential::Voelin(Arc::new(voelin_proto::test_util::FakeSigner));
|
||||
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
|
||||
assert!(matches!(error, SessionError::Protocol(_)));
|
||||
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
|
||||
sent.credential =
|
||||
Credential::Account { kind: "teamspeak", integration_id: Bytes::from_static(b"id") };
|
||||
assert!(inner_options(&sent, &LocalCtx::standalone()).is_err());
|
||||
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
|
||||
sent.credential =
|
||||
Credential::Foreign { kind: "teamspeak", blob: Bytes::from_static(b"not json") };
|
||||
assert!(inner_options(&sent, &LocalCtx::standalone()).is_err());
|
||||
// A host that wants trust is refused: TeamSpeak has no host key.
|
||||
let backends = Backends::empty();
|
||||
let confirm = backends.trust().confirm(voelin_proto::link::HostIdentity {
|
||||
address: "x".into(),
|
||||
uid: [0; 32],
|
||||
previous: None,
|
||||
});
|
||||
assert!(!futures::executor::block_on(confirm));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_params_carry_what_the_session_needs_and_no_account_yet() {
|
||||
let sent = params(&VoiceOptions::new("ts.example.com", "nick"));
|
||||
assert!(sent.account.is_none());
|
||||
assert_eq!(sent.issuer_trust, IssuerTrust::Unknown);
|
||||
assert!(sent.linked.is_empty() && sent.host_pin.is_none());
|
||||
assert_eq!((sent.push_capacity, sent.timeout), (1024, Duration::from_secs(35)));
|
||||
let client = sent.hello.client.unwrap();
|
||||
assert_eq!(client.name, "Voelin");
|
||||
assert_eq!(sent.hello.version, 1);
|
||||
}
|
||||
|
||||
/// Why `connect_params` refused an address, if it did.
|
||||
fn refused(address: &str) -> Option<String> {
|
||||
let (media, _rx) = voelin_proto::test_util::media_channel();
|
||||
match connect_params(&VoiceOptions::new(address, "nick"), media, &Backends::empty()) {
|
||||
Ok(_) => None,
|
||||
Err(SessionError::Protocol(text)) => Some(text),
|
||||
Err(other) => panic!("{address}: {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bookmark_the_link_would_change_is_refused() {
|
||||
// A port that is no port, in any shape: the link would drop it and the
|
||||
// connection would go to the default port.
|
||||
for address in [
|
||||
"ts.example.com:99999",
|
||||
"ts.example.com:65536",
|
||||
"ts.example.com:0",
|
||||
"ts.example.com:abc",
|
||||
"ts.example.com:",
|
||||
"[::1]:70000",
|
||||
"[::1]:",
|
||||
"[::1]x",
|
||||
] {
|
||||
let text = refused(address).unwrap_or_else(|| panic!("{address} was accepted"));
|
||||
assert!(text.contains("65535") && text.contains(address), "{text}");
|
||||
}
|
||||
// A host the link would cut or decode: a `?` hides the channel behind the
|
||||
// next one, a `/` or `#` ends the host, a `%` is decoded.
|
||||
for address in [
|
||||
"",
|
||||
" ",
|
||||
"ts.example.com?x",
|
||||
"ts.example.com#x",
|
||||
"ts.example.com/x",
|
||||
"a b",
|
||||
"h%41",
|
||||
"[::1",
|
||||
] {
|
||||
let text = refused(address).unwrap_or_else(|| panic!("{address:?} was accepted"));
|
||||
assert!(text.starts_with("not a server address"), "{text}");
|
||||
}
|
||||
// The text names no query: a link keeps secrets in it.
|
||||
let text = refused("ts.example.com?password=hunter2").unwrap();
|
||||
assert!(!text.contains("hunter2"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bookmarks_a_server_has_come_back_with_their_channel() {
|
||||
for (address, host) in [
|
||||
("ts.example.com", "ts.example.com"),
|
||||
("ts.example.com:9987", "ts.example.com:9987"),
|
||||
(" ts.example.com:1 ", "ts.example.com:1"),
|
||||
("127.0.0.1:65535", "127.0.0.1:65535"),
|
||||
("[::1]:9987", "[::1]:9987"),
|
||||
// The brackets of a v6 address without a port are the link's to drop;
|
||||
// the TeamSpeak library reads both forms.
|
||||
("[::1]", "::1"),
|
||||
("::1", "::1"),
|
||||
("2001:db8::1", "2001:db8::1"),
|
||||
] {
|
||||
let mut options = VoiceOptions::new(address, "nick");
|
||||
options.channel = Some("Games/Raid".into());
|
||||
let got = back(&options);
|
||||
assert_eq!((got.address.as_str(), got.channel.as_deref()), (host, Some("Games/Raid")));
|
||||
}
|
||||
}
|
||||
|
||||
/// The normalisations of the round trip, listed in `docs/session-seam.md`
|
||||
/// (13): an empty option is none, and an empty nickname stays empty.
|
||||
#[test]
|
||||
fn empty_options_come_back_as_none() {
|
||||
let mut options = VoiceOptions::new("ts.example.com", "");
|
||||
options.server_password = Some(String::new());
|
||||
options.channel = Some(String::new());
|
||||
options.channel_password = Some(String::new());
|
||||
options.token = Some(String::new());
|
||||
let got = back(&options);
|
||||
assert!(got.nickname.is_empty());
|
||||
assert!(
|
||||
got.server_password.is_none()
|
||||
&& got.channel.is_none()
|
||||
&& got.channel_password.is_none()
|
||||
&& got.token.is_none()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -8,10 +8,12 @@ use anyhow::{Context, Result, bail};
|
||||
use base64::prelude::*;
|
||||
use tsclientlib::Version;
|
||||
|
||||
const VERSIONS_CSV: &str = include_str!("../../proto/tsproto-structs/declarations/Versions.csv");
|
||||
const VERSIONS_CSV: &str = include_str!("../../../proto/tsproto-structs/declarations/Versions.csv");
|
||||
|
||||
/// The signed generic version of every platform, tsclientlib's default.
|
||||
const GENERIC_VERSION: &str = "3.?.? [Build: 5680278000]";
|
||||
/// The client generation claimed where a signed build of it exists.
|
||||
const CLIENT_GENERATION: &str = "6.";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct KnownVersion {
|
||||
@@ -52,12 +54,17 @@ pub fn known_versions() -> Vec<KnownVersion> {
|
||||
|
||||
/// Resolve a `--client-version` argument.
|
||||
///
|
||||
/// Accepts `default` (the core native-platform default), an index into [`known_versions`],
|
||||
/// or `<platform>@<version>` with the exact strings from `voelinctl versions`.
|
||||
/// Accepts `default` (the core native-platform default), `generic` (the
|
||||
/// generic `3.?.?` version of the native platform, as before 6.x builds were
|
||||
/// claimed), an index into [`known_versions`], or `<platform>@<version>` with
|
||||
/// the exact strings from `voelinctl versions`.
|
||||
pub fn resolve(spec: &str) -> Result<Option<Version>> {
|
||||
if spec == "default" {
|
||||
return Ok(None);
|
||||
}
|
||||
if spec == "generic" {
|
||||
return generic_version(std::env::consts::OS).map(Some);
|
||||
}
|
||||
let versions = known_versions();
|
||||
if let Ok(i) = spec.parse::<usize>() {
|
||||
let Some(v) = versions.get(i) else {
|
||||
@@ -74,10 +81,13 @@ pub fn resolve(spec: &str) -> Result<Option<Version>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The signed compatibility tuple for the native operating system.
|
||||
/// The signed compatibility tuple for the native operating system: the
|
||||
/// newest TeamSpeak 6 client build signed for it, so servers and other
|
||||
/// clients see a 6.x client (its build is recent enough for any server's
|
||||
/// minimum client version); where none is signed for the platform, the
|
||||
/// generic version, whose build passes every minimum.
|
||||
///
|
||||
/// The generic version retains the library's minimum-version compatibility.
|
||||
/// Its version, platform and signature must stay together: the signature does
|
||||
/// Version, platform and signature must stay together: the signature does
|
||||
/// not authorize renaming the client or changing its platform.
|
||||
///
|
||||
/// Unsupported operating systems return an error rather than claiming another
|
||||
@@ -87,6 +97,31 @@ pub fn native_version() -> Result<Version> {
|
||||
}
|
||||
|
||||
fn compatibility_version(os: &str) -> Result<Version> {
|
||||
// TeamSpeak 5 and 6 call macOS "macOS", TeamSpeak 3 "OS X".
|
||||
let platforms: &[&str] = match os {
|
||||
"linux" => &["Linux"],
|
||||
"windows" => &["Windows"],
|
||||
"macos" => &["macOS", "OS X"],
|
||||
"android" => &["Android"],
|
||||
"ios" => &["iOS"],
|
||||
_ => bail!("no signed compatibility version for operating system {os:?}"),
|
||||
};
|
||||
let versions = known_versions();
|
||||
let newest = versions
|
||||
.iter()
|
||||
.filter(|v| platforms.contains(&v.platform.as_str()))
|
||||
.filter(|v| v.version.starts_with(CLIENT_GENERATION))
|
||||
.filter_map(|v| Some((build(&v.version)?, v)))
|
||||
.max_by_key(|(build, _)| *build)
|
||||
.map(|(_, v)| v);
|
||||
match newest {
|
||||
Some(version) => version.to_version(),
|
||||
None => generic_version(os),
|
||||
}
|
||||
}
|
||||
|
||||
/// The generic version of the operating system's platform.
|
||||
fn generic_version(os: &str) -> Result<Version> {
|
||||
let platform = match os {
|
||||
"linux" => "Linux",
|
||||
"windows" => "Windows",
|
||||
@@ -95,15 +130,18 @@ fn compatibility_version(os: &str) -> Result<Version> {
|
||||
"ios" => "iOS",
|
||||
_ => bail!("no signed compatibility version for operating system {os:?}"),
|
||||
};
|
||||
// The library's generic version: its build passes servers' minimum client
|
||||
// version, which a real (older) build such as 3.6.0 may not.
|
||||
known_versions()
|
||||
.into_iter()
|
||||
.find(|version| version.platform == platform && version.version == GENERIC_VERSION)
|
||||
.find(|v| v.platform == platform && v.version == GENERIC_VERSION)
|
||||
.with_context(|| format!("missing signed compatibility version for {platform}"))?
|
||||
.to_version()
|
||||
}
|
||||
|
||||
/// The build number of a version string (`6.0.0 [Build: 1737468425]`).
|
||||
fn build(version: &str) -> Option<u64> {
|
||||
version.split_once("[Build: ")?.1.strip_suffix(']')?.parse().ok()
|
||||
}
|
||||
|
||||
/// Truthful product identity, separate from the signed compatibility tuple.
|
||||
pub fn client_metadata() -> String {
|
||||
serde_json::json!({
|
||||
@@ -121,16 +159,19 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn native_platform_preserves_complete_signed_tuple() {
|
||||
for (os, platform) in [
|
||||
("linux", "Linux"),
|
||||
("windows", "Windows"),
|
||||
("macos", "OS X"),
|
||||
("android", "Android"),
|
||||
("ios", "iOS"),
|
||||
for (os, platform, version) in [
|
||||
// The newest TeamSpeak 6 build signed for the platform.
|
||||
("linux", "Linux", "6.0.0-beta4.1 [Build: 1779880475]"),
|
||||
("windows", "Windows", "6.0.0-beta2 [Build: 1737468425]"),
|
||||
// None signed: the generic version.
|
||||
("macos", "OS X", GENERIC_VERSION),
|
||||
("android", "Android", GENERIC_VERSION),
|
||||
("ios", "iOS", GENERIC_VERSION),
|
||||
] {
|
||||
let expected = version;
|
||||
let version = compatibility_version(os).unwrap();
|
||||
assert_eq!(version.get_platform(), platform);
|
||||
assert_eq!(version.get_version_string(), "3.?.? [Build: 5680278000]");
|
||||
assert_eq!(version.get_version_string(), expected);
|
||||
assert_eq!(version.get_signature().len(), 64);
|
||||
let known = known_versions()
|
||||
.into_iter()
|
||||
@@ -156,6 +197,14 @@ mod tests {
|
||||
assert_eq!(metadata["platform"], std::env::consts::OS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_build_numbers() {
|
||||
assert_eq!(build("6.0.0-beta2 [Build: 1737468425]"), Some(1_737_468_425));
|
||||
assert_eq!(build(GENERIC_VERSION), Some(5_680_278_000));
|
||||
assert_eq!(build("3.0.0 [Build: x]"), None);
|
||||
assert_eq!(build("6.0.0"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_all_rows() {
|
||||
let versions = known_versions();
|
||||
@@ -169,6 +218,10 @@ mod tests {
|
||||
#[test]
|
||||
fn resolves_specs() {
|
||||
assert!(resolve("default").unwrap().is_none());
|
||||
if let Ok(generic) = generic_version(std::env::consts::OS) {
|
||||
assert_eq!(resolve("generic").unwrap(), Some(generic.clone()));
|
||||
assert_eq!(generic.get_version_string(), GENERIC_VERSION);
|
||||
}
|
||||
let by_index = resolve("0").unwrap().unwrap();
|
||||
let first = &known_versions()[0];
|
||||
let by_name = resolve(&format!("{}@{}", first.platform, first.version)).unwrap().unwrap();
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+1400
-93
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,7 @@
|
||||
//! Chat history and gateway features through the engine, against a fake
|
||||
//! gateway (a WebSocket server speaking the tsgw protocol from memory).
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet, VecDeque};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -16,6 +16,7 @@ use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
|
||||
use voelin_core::gateway::{GatewayRequest, GatewayUpdate};
|
||||
use voelin_core::history::MessageSource;
|
||||
use voelin_core::settings::Settings;
|
||||
use voelin_core::ts::identity::to_blob;
|
||||
use voelin_core::{Command, Engine, Event, History, HistoryMessage, HistorySource, ObserveState};
|
||||
use voelin_gateway_proto::{
|
||||
ClientMsg, Envelope, ErrorCode, HistoryEntry, HistoryPage, PinInfo, ReactionCount, ServerMsg,
|
||||
@@ -43,6 +44,10 @@ struct State {
|
||||
requests: Vec<String>,
|
||||
/// Close connections at once (the gateway is down).
|
||||
refuse: bool,
|
||||
/// Answers to the next logins, in turn, instead of logging in.
|
||||
login_errors: VecDeque<ErrorCode>,
|
||||
/// Logins asked for.
|
||||
logins: usize,
|
||||
}
|
||||
|
||||
impl State {
|
||||
@@ -127,7 +132,12 @@ struct FakeGateway {
|
||||
|
||||
impl FakeGateway {
|
||||
async fn start() -> Self {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
Self::start_on(0).await
|
||||
}
|
||||
|
||||
/// A gateway at `port` of the loopback address (0: any free port).
|
||||
async fn start_on(port: u16) -> Self {
|
||||
let listener = TcpListener::bind(("127.0.0.1", port)).await.unwrap();
|
||||
let url = format!("ws://{}/v1", listener.local_addr().unwrap());
|
||||
let state: Arc<Mutex<State>> = Arc::default();
|
||||
let st = state.clone();
|
||||
@@ -146,6 +156,10 @@ impl FakeGateway {
|
||||
fn requests(&self) -> Vec<String> {
|
||||
self.state.lock().unwrap().requests.clone()
|
||||
}
|
||||
|
||||
fn logins(&self) -> usize {
|
||||
self.state.lock().unwrap().logins
|
||||
}
|
||||
}
|
||||
|
||||
fn caps() -> Vec<String> {
|
||||
@@ -231,6 +245,10 @@ fn answer(
|
||||
) -> ServerMsg {
|
||||
match msg {
|
||||
ClientMsg::Auth { .. } => {
|
||||
st.logins += 1;
|
||||
if let Some(code) = st.login_errors.pop_front() {
|
||||
return ServerMsg::Error { code, message: "not now".into() };
|
||||
}
|
||||
*logged_in = true;
|
||||
st.sessions.push((push.clone(), open.clone()));
|
||||
ServerMsg::AuthOk {
|
||||
@@ -363,7 +381,8 @@ fn answer(
|
||||
st.topics.push(topic.clone());
|
||||
ServerMsg::Topic { topic }
|
||||
}
|
||||
ClientMsg::SubscribeEvents | ClientMsg::Ping => ServerMsg::Ok,
|
||||
ClientMsg::Ping => ServerMsg::Pong,
|
||||
ClientMsg::SubscribeEvents => ServerMsg::Ok,
|
||||
_ => ServerMsg::Error { code: ErrorCode::UnknownType, message: "not in the fake".into() },
|
||||
}
|
||||
}
|
||||
@@ -429,8 +448,8 @@ fn observe(engine: &Engine, session: u64, gw: &FakeGateway) {
|
||||
let identity = tsclientlib::Identity::create();
|
||||
engine.send(Command::ObserveGateway {
|
||||
session,
|
||||
url: gw.url.clone(),
|
||||
identity: Box::new(identity),
|
||||
urls: vec![gw.url.clone()],
|
||||
identity: Box::new(to_blob(&identity)),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -545,7 +564,9 @@ async fn live_messages_and_gateway_requests() {
|
||||
};
|
||||
assert_eq!((server_uid.as_str(), uid.as_str()), ("fake-server", ME));
|
||||
assert!(capabilities.iter().any(|c| c == feature::PINS));
|
||||
// In sync (the chat is empty).
|
||||
// In sync (the chat is empty): the latest page, then what changed since
|
||||
// (else our message may come back with the sync instead of live).
|
||||
batch(&mut rx, HistorySource::Gateway).await;
|
||||
batch(&mut rx, HistorySource::Gateway).await;
|
||||
|
||||
// Our message: stored at once, then merged with the gateway's copy.
|
||||
@@ -707,3 +728,271 @@ async fn store_history_off_keeps_the_database_empty() {
|
||||
drop((engine, history));
|
||||
let _ = std::fs::remove_dir_all(path.parent().unwrap());
|
||||
}
|
||||
|
||||
/// A gateway that is away is tried again by itself and quietly: no error for
|
||||
/// the user, "connecting" meanwhile, then observing once it is there, with
|
||||
/// the open chats opened again.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_unreachable_gateway_is_tried_again_quietly() {
|
||||
// Nothing listens there yet: the connection is refused.
|
||||
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
|
||||
let path = temp_db("retry");
|
||||
let engine = Engine::start_with(Settings::in_memory(), History::open(&path).unwrap());
|
||||
let mut rx = engine.subscribe();
|
||||
engine.send(Command::OpenChat { session: 3, target: LOBBY });
|
||||
engine.send(Command::ObserveGateway {
|
||||
session: 3,
|
||||
urls: vec![format!("ws://127.0.0.1:{port}/v1")],
|
||||
identity: Box::new(to_blob(&tsclientlib::Identity::create())),
|
||||
});
|
||||
// The first attempts fail (the next ones about 1 s, then 2 s later):
|
||||
// still connecting, and the user is told nothing.
|
||||
let mut connecting = false;
|
||||
let quiet = timeout(Duration::from_millis(1500), async {
|
||||
loop {
|
||||
match rx.recv().await {
|
||||
Ok(Event::Error { message, .. }) => panic!("the user was told: {message}"),
|
||||
Ok(Event::State { session: 3, state }) => {
|
||||
// (Off before observing starts.)
|
||||
assert!(!connecting || state.observe != ObserveState::Off, "gave up");
|
||||
connecting |= state.observe == ObserveState::Connecting;
|
||||
}
|
||||
Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
|
||||
Err(e) => panic!("{e}"),
|
||||
}
|
||||
}
|
||||
});
|
||||
assert!(quiet.await.is_err(), "the event stream ended");
|
||||
assert!(connecting, "never started observing");
|
||||
// The gateway comes up: observing, and the open chat is opened again.
|
||||
let gw = FakeGateway::start_on(port).await;
|
||||
wait(&mut rx, "observing", |e| match e {
|
||||
Event::Error { message, .. } => panic!("the user was told: {message}"),
|
||||
Event::State { session: 3, state } if state.observe == ObserveState::Observing => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
timeout(Duration::from_secs(5), async {
|
||||
while !gw.requests().contains(&"open_chat".to_owned()) {
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|_| panic!("the chat was not opened again: {:?}", gw.requests()));
|
||||
drop(engine);
|
||||
let _ = std::fs::remove_dir_all(path.parent().unwrap());
|
||||
}
|
||||
|
||||
/// A reverse proxy without a rule for the gateway's host, as Zoraxy's
|
||||
/// default site answers: 404 to everything.
|
||||
async fn not_found_proxy() -> String {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("ws://{}/v1", listener.local_addr().unwrap());
|
||||
tokio::spawn(async move {
|
||||
while let Ok((mut tcp, _)) = listener.accept().await {
|
||||
tokio::spawn(async move {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let mut request = [0; 4096];
|
||||
let _ = tcp.read(&mut request).await;
|
||||
let _ = tcp
|
||||
.write_all(
|
||||
b"HTTP/1.1 404 Not Found\r\nContent-Type: text/plain; charset=utf-8\r\n\
|
||||
Content-Length: 19\r\n\r\n404 page not found\n",
|
||||
)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
});
|
||||
url
|
||||
}
|
||||
|
||||
/// Every published gateway is tried in turn, without waiting: a TLS proxy
|
||||
/// that answers 404 and a port nothing listens on are passed over, and the
|
||||
/// plain gateway published after them is used, quietly.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_next_published_gateway_is_used_when_one_fails() {
|
||||
let proxy = not_found_proxy().await;
|
||||
let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
|
||||
let gw = FakeGateway::start().await;
|
||||
let path = temp_db("fallback");
|
||||
let engine = Engine::start_with(Settings::in_memory(), History::open(&path).unwrap());
|
||||
let mut rx = engine.subscribe();
|
||||
engine.send(Command::ObserveGateway {
|
||||
session: 4,
|
||||
urls: vec![proxy, format!("ws://127.0.0.1:{closed}/v1"), gw.url.clone()],
|
||||
identity: Box::new(to_blob(&tsclientlib::Identity::create())),
|
||||
});
|
||||
// Within one round: sooner than the shortest wait after a failed round
|
||||
// (1 s, less 30 %).
|
||||
let url = timeout(Duration::from_millis(650), async {
|
||||
loop {
|
||||
match rx.recv().await {
|
||||
Ok(Event::Error { message, .. }) => panic!("the user was told: {message}"),
|
||||
Ok(Event::Gateway { session: 4, update: GatewayUpdate::Connected { url, .. } }) => {
|
||||
return url;
|
||||
}
|
||||
Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
|
||||
Err(e) => panic!("{e}"),
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("the plain gateway was not used within a round");
|
||||
assert_eq!(url, gw.url);
|
||||
wait(&mut rx, "observing", |e| match e {
|
||||
Event::Error { message, .. } => panic!("the user was told: {message}"),
|
||||
Event::State { session: 4, state } if state.observe == ObserveState::Observing => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
drop(engine);
|
||||
let _ = std::fs::remove_dir_all(path.parent().unwrap());
|
||||
}
|
||||
|
||||
/// Events until `until` matches one, within `within`: never an error for
|
||||
/// the user, never observing `session` off once it started.
|
||||
async fn quietly_until(
|
||||
rx: &mut Receiver<Event>,
|
||||
session: u64,
|
||||
within: Duration,
|
||||
what: &str,
|
||||
mut until: impl FnMut(&Event) -> bool,
|
||||
) {
|
||||
let mut started = false;
|
||||
timeout(within, async {
|
||||
loop {
|
||||
let e = match rx.recv().await {
|
||||
Ok(e) => e,
|
||||
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
|
||||
Err(e) => panic!("{e}"),
|
||||
};
|
||||
if let Event::Error { message, .. } = &e {
|
||||
panic!("the user was told: {message}");
|
||||
}
|
||||
if let Event::State { session: s, state } = &e
|
||||
&& *s == session
|
||||
{
|
||||
// (Off before observing starts.)
|
||||
assert!(!started || state.observe != ObserveState::Off, "gave up");
|
||||
started |= state.observe != ObserveState::Off;
|
||||
}
|
||||
if until(&e) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|_| panic!("timed out waiting for {what}"));
|
||||
}
|
||||
|
||||
fn observing(session: u64) -> impl FnMut(&Event) -> bool {
|
||||
move |e| {
|
||||
matches!(e, Event::State { session: s, state }
|
||||
if *s == session && state.observe == ObserveState::Observing)
|
||||
}
|
||||
}
|
||||
|
||||
/// A gateway that cannot log us in yet (its TeamSpeak server is away; the
|
||||
/// server does not know the identity before voice connected once) is tried
|
||||
/// again, quietly, and observed through once it can.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_login_the_gateway_cannot_do_yet_is_tried_again() {
|
||||
for (session, code) in [(5, ErrorCode::Unavailable), (6, ErrorCode::UnknownIdentity)] {
|
||||
let gw = FakeGateway::start().await;
|
||||
gw.state.lock().unwrap().login_errors.push_back(code);
|
||||
let engine = Engine::start();
|
||||
let mut rx = engine.subscribe();
|
||||
engine.send(Command::ObserveGateway {
|
||||
session,
|
||||
urls: vec![gw.url.clone()],
|
||||
identity: Box::new(to_blob(&tsclientlib::Identity::create())),
|
||||
});
|
||||
// After the first wait: about 1 s.
|
||||
quietly_until(&mut rx, session, Duration::from_secs(3), "observing", observing(session))
|
||||
.await;
|
||||
assert_eq!(gw.logins(), 2, "{code:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A login the gateway refuses (banned, not allowed, a bad signature or
|
||||
/// security level) is not tried again.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_refused_login_ends_observing() {
|
||||
let gw = FakeGateway::start().await;
|
||||
gw.state.lock().unwrap().login_errors.push_back(ErrorCode::Banned);
|
||||
let engine = Engine::start();
|
||||
let mut rx = engine.subscribe();
|
||||
observe(&engine, 8, &gw);
|
||||
wait(&mut rx, "observing off", |e| match e {
|
||||
Event::Error { message, .. } => panic!("the user was told: {message}"),
|
||||
Event::State { session: 8, state } if state.observe == ObserveState::Off => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
tokio::time::sleep(Duration::from_millis(1500)).await;
|
||||
assert_eq!(gw.logins(), 1);
|
||||
}
|
||||
|
||||
/// An identity that cannot be read will not be better tomorrow: like a refused
|
||||
/// login, observing ends, and the gateway is not even asked.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_identity_that_cannot_be_read_ends_observing_without_a_login() {
|
||||
let gw = FakeGateway::start().await;
|
||||
let engine = Engine::start();
|
||||
let mut rx = engine.subscribe();
|
||||
let not_an_identity = voelin_core::IdentityBlob::teamspeak("x", 0, "not an identity");
|
||||
engine.send(Command::ObserveGateway {
|
||||
session: 10,
|
||||
urls: vec![gw.url.clone()],
|
||||
identity: Box::new(not_an_identity),
|
||||
});
|
||||
wait(&mut rx, "connecting", |e| match e {
|
||||
Event::State { session: 10, state } if state.observe == ObserveState::Connecting => {
|
||||
Some(())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
wait(&mut rx, "observing off", |e| match e {
|
||||
Event::State { session: 10, state } if state.observe == ObserveState::Off => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
assert_eq!(gw.logins(), 0);
|
||||
// The public entry refuses it the same way.
|
||||
let error = voelin_core::gateway::connect(
|
||||
&gw.url,
|
||||
&voelin_core::IdentityBlob::new("voelin", "x", 0, "{}"),
|
||||
)
|
||||
.await
|
||||
.err()
|
||||
.expect("a refusal");
|
||||
assert_eq!(error.code(), Some(ErrorCode::AuthFailed), "{error}");
|
||||
assert_eq!(gw.logins(), 0);
|
||||
}
|
||||
|
||||
/// Selecting the server again while its gateway is still connecting does
|
||||
/// not start it over, and ends the wait for the next attempt.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn asking_again_while_connecting_tries_at_once() {
|
||||
let gw = FakeGateway::start().await;
|
||||
gw.state.lock().unwrap().login_errors.extend([ErrorCode::UnknownIdentity; 3]);
|
||||
let engine = Engine::start();
|
||||
let mut rx = engine.subscribe();
|
||||
let identity = tsclientlib::Identity::create();
|
||||
let ask = || Command::ObserveGateway {
|
||||
session: 9,
|
||||
urls: vec![gw.url.clone()],
|
||||
identity: Box::new(to_blob(&identity)),
|
||||
};
|
||||
engine.send(ask());
|
||||
// Three logins fail (waits of about 1 and 2 s); the next wait is about 5 s.
|
||||
quietly_until(&mut rx, 9, Duration::from_secs(6), "three logins", |_| gw.logins() >= 3).await;
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert_eq!(gw.logins(), 3);
|
||||
engine.send(ask());
|
||||
// Sooner than the shortest such wait (3.5 s), without starting over.
|
||||
quietly_until(&mut rx, 9, Duration::from_secs(2), "observing", observing(9)).await;
|
||||
assert_eq!(gw.logins(), 4);
|
||||
}
|
||||
@@ -5,7 +5,10 @@ use std::time::Duration;
|
||||
|
||||
use tokio::sync::broadcast::Receiver;
|
||||
use tokio::time::{Instant, timeout_at};
|
||||
use voelin_core::{Command, Engine, Event, ObserveState, Source, VoiceOptions, VoiceState};
|
||||
use voelin_core::{
|
||||
Command, Engine, Event, ObserveState, QueryLogin, QueryTransport, Source, VoiceOptions,
|
||||
VoiceState,
|
||||
};
|
||||
use voelin_model::ChatTarget;
|
||||
|
||||
fn live() -> bool {
|
||||
@@ -45,7 +48,7 @@ async fn engine_roundtrip(voice_addr: &str, query: voelin_query::Connect) {
|
||||
.await;
|
||||
|
||||
// Session 2: invisible, through own query credentials.
|
||||
engine.send(Command::ObserveQuery { session: 2, connect: Box::new(query) });
|
||||
engine.send(Command::ObserveQuery { session: 2, connect: Box::new(login(&query)) });
|
||||
let (mut observing, mut sees_voice_client) = (false, false);
|
||||
wait_for(&mut events, "query presence with the voice client", |e| {
|
||||
match e {
|
||||
@@ -93,6 +96,24 @@ async fn engine_roundtrip(voice_addr: &str, query: voelin_query::Connect) {
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
|
||||
/// The credentials of a query connection, as the engine takes them.
|
||||
fn login(connect: &voelin_query::Connect) -> QueryLogin {
|
||||
QueryLogin {
|
||||
transport: match connect.transport {
|
||||
voelin_query::Transport::Raw => QueryTransport::Raw,
|
||||
voelin_query::Transport::Ssh => QueryTransport::Ssh,
|
||||
voelin_query::Transport::Http => QueryTransport::Http,
|
||||
},
|
||||
address: connect.addr.clone(),
|
||||
user: connect.user.clone(),
|
||||
secret: connect.secret.clone(),
|
||||
server_port: connect.server_port,
|
||||
server_id: connect.server_id,
|
||||
// The development servers allowlist their clients.
|
||||
allowlisted: connect.line.rate_limit.is_none(),
|
||||
}
|
||||
}
|
||||
|
||||
fn query(transport: voelin_query::Transport, addr: &str) -> voelin_query::Connect {
|
||||
voelin_query::Connect {
|
||||
transport,
|
||||
@@ -123,6 +144,131 @@ async fn ts3_engine() {
|
||||
.await;
|
||||
}
|
||||
|
||||
/// A channel password and a privilege key work when connecting; a refused
|
||||
/// move says why. One connection, as the servers refuse quick reconnects.
|
||||
async fn channel_joins(voice_addr: &str, query: voelin_query::Connect) {
|
||||
use voelin_core::JoinFailure;
|
||||
use voelin_query::{Command as Query, QueryClient};
|
||||
let (admin, _) = QueryClient::connect(&query).await.unwrap();
|
||||
let tag = std::process::id() % 10_000;
|
||||
let create = |name: &str| {
|
||||
Query::new("channelcreate")
|
||||
.arg("channel_name", format!("{name}-{tag}"))
|
||||
.arg("channel_flag_semi_permanent", 1)
|
||||
};
|
||||
let locked = admin.send(&create("locked").arg("channel_password", "secret")).await.unwrap()[0]
|
||||
.parse::<u64>("cid")
|
||||
.unwrap();
|
||||
let full =
|
||||
create("full").arg("channel_maxclients", 0).arg("channel_flag_maxclients_unlimited", 0);
|
||||
let full = admin.send(&full).await.unwrap()[0].parse::<u64>("cid").unwrap();
|
||||
// A key for the Normal group, which has to keep to passwords and limits.
|
||||
let groups = admin.send(&Query::new("servergrouplist")).await.unwrap();
|
||||
let normal = groups
|
||||
.iter()
|
||||
.find(|g| g.get("name") == Some("Normal") && g.get("type") == Some("1"))
|
||||
.and_then(|g| g.parse::<u64>("sgid"))
|
||||
.expect("a Normal server group");
|
||||
let key = Query::new("privilegekeyadd")
|
||||
.arg("tokentype", 0)
|
||||
.arg("tokenid1", normal)
|
||||
.arg("tokenid2", 0);
|
||||
let token = admin.send(&key).await.unwrap()[0].get("token").unwrap().to_owned();
|
||||
let channels = admin.send(&Query::new("channellist").flag("-flags")).await.unwrap();
|
||||
let lobby = channels
|
||||
.iter()
|
||||
.find(|c| c.flag("channel_flag_default") == Some(true))
|
||||
.and_then(|c| c.parse::<u64>("cid"))
|
||||
.expect("a default channel");
|
||||
|
||||
let engine = Engine::start();
|
||||
let check = {
|
||||
let (engine, voice_addr, token) = (engine.clone(), voice_addr.to_owned(), token.clone());
|
||||
tokio::spawn(async move {
|
||||
let mut events = engine.subscribe();
|
||||
let mut options = VoiceOptions::new(&voice_addr, format!("joins-{tag}"));
|
||||
options.channel = Some(format!("locked-{tag}"));
|
||||
options.channel_password = Some("secret".into());
|
||||
options.token = Some(token);
|
||||
engine.send(Command::ConnectVoice { session: 1, options: Box::new(options) });
|
||||
let (mut own, mut presence) = (None, None);
|
||||
wait_for(&mut events, "connected into the channel, in the key's group", |e| {
|
||||
match e {
|
||||
Event::State { session: 1, state } => own = state.own_client,
|
||||
Event::Presence { session: 1, presence: p } => presence = Some(p.clone()),
|
||||
_ => {}
|
||||
}
|
||||
let client = own.and_then(|id| presence.as_ref()?.clients.get(&id).cloned());
|
||||
client.is_some_and(|c| c.channel == locked && c.server_groups.contains(&normal))
|
||||
})
|
||||
.await;
|
||||
let moved = async |events: &mut Receiver<Event>, channel: u64| {
|
||||
wait_for(
|
||||
events,
|
||||
"a move",
|
||||
|e| matches!(e, Event::State { session: 1, state } if state.own_channel == Some(channel)),
|
||||
)
|
||||
.await;
|
||||
};
|
||||
let refused =
|
||||
async |events: &mut Receiver<Event>, channel: u64, reason: JoinFailure| {
|
||||
let failed = wait_for(events, "a refused move", |e| {
|
||||
matches!(e, Event::JoinFailed { session: 1, .. })
|
||||
})
|
||||
.await;
|
||||
let Event::JoinFailed { channel: c, reason: r, .. } = failed else {
|
||||
unreachable!()
|
||||
};
|
||||
assert_eq!((c, r), (channel, reason));
|
||||
};
|
||||
let move_to = |channel, password: Option<&str>| Command::MoveToChannel {
|
||||
session: 1,
|
||||
channel,
|
||||
password: password.map(Into::into),
|
||||
};
|
||||
engine.send(move_to(lobby, None));
|
||||
moved(&mut events, lobby).await;
|
||||
engine.send(move_to(locked, None));
|
||||
refused(&mut events, locked, JoinFailure::Password).await;
|
||||
engine.send(move_to(locked, Some("wrong")));
|
||||
refused(&mut events, locked, JoinFailure::Password).await;
|
||||
engine.send(move_to(locked, Some("secret")));
|
||||
moved(&mut events, locked).await;
|
||||
// Moving where we are says nothing: the next refusal is the full channel's.
|
||||
engine.send(move_to(locked, Some("secret")));
|
||||
engine.send(move_to(full, None));
|
||||
refused(&mut events, full, JoinFailure::Full).await;
|
||||
})
|
||||
};
|
||||
let result = check.await;
|
||||
engine.send(Command::CloseSession { session: 1 });
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
// Clean up everything before reporting a failure; the key is gone once used.
|
||||
let _ = admin.send(&Query::new("privilegekeydelete").arg("token", &token)).await;
|
||||
for cid in [locked, full] {
|
||||
admin.send(&Query::new("channeldelete").arg("cid", cid).arg("force", 1)).await.unwrap();
|
||||
}
|
||||
if let Err(error) = result {
|
||||
std::panic::resume_unwind(error.into_panic());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts6_channel_joins() {
|
||||
if !live() {
|
||||
return;
|
||||
}
|
||||
channel_joins("127.0.0.1:9988", query(voelin_query::Transport::Ssh, "127.0.0.1:10022")).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ts3_channel_joins() {
|
||||
if !live() {
|
||||
return;
|
||||
}
|
||||
channel_joins("127.0.0.1:9987", query(voelin_query::Transport::Raw, "127.0.0.1:10011")).await;
|
||||
}
|
||||
|
||||
/// A 1×1 PNG.
|
||||
const PNG: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
|
||||
|
||||
|
||||
@@ -1,149 +0,0 @@
|
||||
//! Opt-in account + isolated server interoperability check. No keys are saved.
|
||||
//! Requires VOELIN_MYTS_LIVE=1, EMAIL/PASSWORD/DEVICE_ID and optional OTP under
|
||||
//! the VOELIN_MYTS_ prefix; TEST_TS3/TEST_TS6 and QUERY_TS3/QUERY_TS6 give
|
||||
//! loopback voice/query addresses. QUERY_PASSWORD authenticates local query.
|
||||
#![cfg(not(target_os = "android"))]
|
||||
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::{Context, Result, bail, ensure};
|
||||
use tokio::{sync::broadcast, time::timeout};
|
||||
use voelin_core::{Command, Engine, Event, VoiceOptions, VoiceState};
|
||||
use voelin_myts::{Client, ServerIdentity};
|
||||
use voelin_query::{Command as QueryCommand, QueryClient, Row};
|
||||
|
||||
fn env(name: &str) -> Result<String> {
|
||||
std::env::var(format!("VOELIN_MYTS_{name}")).with_context(|| format!("missing {name}"))
|
||||
}
|
||||
|
||||
async fn connected(events: &mut broadcast::Receiver<Event>, session_id: u64) -> Result<u16> {
|
||||
timeout(Duration::from_secs(35), async {
|
||||
loop {
|
||||
match events.recv().await? {
|
||||
Event::State { session, state }
|
||||
if session == session_id && state.voice == VoiceState::Connected =>
|
||||
{
|
||||
if let Some(id) = state.own_client {
|
||||
return Ok(id);
|
||||
}
|
||||
}
|
||||
Event::Error { message, .. } => bail!("engine: {message}"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
async fn info(query: &QueryClient, client: u16) -> Result<Row> {
|
||||
query
|
||||
.send(&QueryCommand::new("clientinfo").arg("clid", client))
|
||||
.await?
|
||||
.into_iter()
|
||||
.next()
|
||||
.context("clientinfo missing")
|
||||
}
|
||||
|
||||
async fn wait_id(query: &QueryClient, client: u16, expected: &str) -> Result<()> {
|
||||
timeout(Duration::from_secs(12), async {
|
||||
loop {
|
||||
let row = info(query, client).await?;
|
||||
if row.get("client_myteamspeak_id") == Some(expected) {
|
||||
return Ok(());
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.context("server did not report the expected myTS association")?
|
||||
}
|
||||
|
||||
async fn server(identity: Arc<ServerIdentity>, kind: &str) -> Result<()> {
|
||||
let address = env(&format!("TEST_{kind}"))?;
|
||||
let query_address = env(&format!("QUERY_{kind}"))?;
|
||||
// This test is deliberately limited to caller-owned loopback test servers.
|
||||
ensure!(address.starts_with("127.0.0.1:"), "voice endpoint must be loopback");
|
||||
ensure!(query_address.starts_with("127.0.0.1:"), "query endpoint must be loopback");
|
||||
let (query, _) = QueryClient::connect(&voelin_query::Connect {
|
||||
transport: if kind == "TS3" {
|
||||
voelin_query::Transport::Raw
|
||||
} else {
|
||||
voelin_query::Transport::Ssh
|
||||
},
|
||||
addr: query_address,
|
||||
user: "serveradmin".into(),
|
||||
secret: Some(env("QUERY_PASSWORD")?),
|
||||
server_id: Some(1),
|
||||
server_port: None,
|
||||
line: voelin_query::LineOptions { rate_limit: None, ..Default::default() },
|
||||
})
|
||||
.await?;
|
||||
let engine = Engine::start();
|
||||
let mut events = engine.subscribe();
|
||||
let result = async {
|
||||
engine.send(Command::SetMytsIdentity(Some(identity.clone())));
|
||||
for session in 1..=2 {
|
||||
engine.send(Command::ConnectVoice {
|
||||
session,
|
||||
options: Box::new(VoiceOptions::new(&address, format!("myts-proof-{session}"))),
|
||||
});
|
||||
let client = connected(&mut events, session).await?;
|
||||
let row = info(&query, client).await?;
|
||||
let version = voelin_core::versions::native_version()?;
|
||||
ensure!(row.get("client_platform") == Some(version.get_platform()), "wrong platform");
|
||||
ensure!(
|
||||
row.get("client_version") == Some(version.get_version_string()),
|
||||
"wrong version"
|
||||
);
|
||||
let metadata: serde_json::Value =
|
||||
serde_json::from_str(row.get("client_meta_data").context("missing metadata")?)?;
|
||||
ensure!(metadata["name"] == "Voelin", "wrong client metadata");
|
||||
ensure!(metadata["platform"] == std::env::consts::OS, "wrong metadata platform");
|
||||
eprintln!("{kind}: native platform/Voelin metadata passed");
|
||||
wait_id(&query, client, &identity.id()).await?;
|
||||
eprintln!("{kind}: signed clientinit myTS ID passed");
|
||||
// Two fresh connections prove the signature is bound to each handshake.
|
||||
engine.send(Command::SetMytsIdentity(None));
|
||||
wait_id(&query, client, "").await?;
|
||||
engine.send(Command::SetMytsIdentity(Some(identity.clone())));
|
||||
wait_id(&query, client, &identity.id()).await?;
|
||||
eprintln!("{kind}: live clear and reattach passed");
|
||||
engine.send(Command::CloseSession { session });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
engine.send(Command::SetMytsIdentity(None));
|
||||
for session in 1..=2 {
|
||||
engine.send(Command::CloseSession { session });
|
||||
}
|
||||
query.quit().await;
|
||||
result
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires owner-authorized account and isolated loopback servers"]
|
||||
async fn authenticated_account_and_server_lifecycle() -> Result<()> {
|
||||
ensure!(env("LIVE")? == "1", "explicit live opt-in required");
|
||||
let client = Client::new()?;
|
||||
let login = client
|
||||
.login(&env("EMAIL")?, &env("PASSWORD")?, env("OTP").ok().as_deref(), &env("DEVICE_ID")?)
|
||||
.await?;
|
||||
// Capture every result before deleting the newly created remote session.
|
||||
let result = async {
|
||||
client.validate_session(&login.token).await?;
|
||||
let identity = Arc::new(login.identity.context("server identity unlock failed")?);
|
||||
let mut failures = Vec::new();
|
||||
for kind in ["TS3", "TS6"] {
|
||||
if let Err(error) = server(identity.clone(), kind).await {
|
||||
failures.push(format!("{kind}: {error:#}"));
|
||||
}
|
||||
}
|
||||
ensure!(failures.is_empty(), "{}", failures.join("; "));
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
let logout = client.logout(&login.token).await;
|
||||
logout.context("remote test session revocation failed")?;
|
||||
result
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
//! The engine on a `voelin_proto::link::Session` that no TeamSpeak code
|
||||
//! made: `Engine::start_with_backends` takes the connector registry, and the
|
||||
//! scheme of a session's address picks the connector. The fake host of the
|
||||
//! protocol repository stands for a Voelin host here (the fuller tests of the
|
||||
//! seam on the fake host come with the next slice of
|
||||
//! `docs/session-seam.md`).
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::sync::broadcast;
|
||||
use voelin_core::settings::Settings;
|
||||
use voelin_core::{
|
||||
Backends, Command, Engine, Event, History, SessionState, VoiceOptions, VoiceState,
|
||||
};
|
||||
use voelin_proto::test_util::FakeConnector;
|
||||
use voelin_proto::v1::{self, entity::Kind};
|
||||
|
||||
const SESSION: u64 = 1;
|
||||
|
||||
async fn next<T>(
|
||||
events: &mut broadcast::Receiver<Event>,
|
||||
mut f: impl FnMut(Event) -> Option<T>,
|
||||
) -> T {
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
if let Some(t) = f(events.recv().await.expect("engine events")) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("an event in time")
|
||||
}
|
||||
|
||||
fn host_with_two_channels(connector: &FakeConnector) {
|
||||
let host = connector.host();
|
||||
let put = |kind: Kind| host.put(v1::Entity { kind: Some(kind) }).unwrap();
|
||||
put(Kind::Server(v1::Server {
|
||||
id: 1,
|
||||
name: "Fake Host".into(),
|
||||
uid: "fake-host".into(),
|
||||
default_channel_id: 10,
|
||||
..Default::default()
|
||||
}));
|
||||
for (id, name, position) in [(10, "Lobby", 0), (11, "Games", 1024)] {
|
||||
put(Kind::Channel(v1::Channel {
|
||||
id,
|
||||
server_id: 1,
|
||||
kind: v1::ChannelKind::Voice as i32,
|
||||
name: name.into(),
|
||||
position,
|
||||
..Default::default()
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_session_of_a_registered_connector_is_the_engines_voice_source() {
|
||||
let connector = FakeConnector::new();
|
||||
host_with_two_channels(&connector);
|
||||
let mut backends = Backends::empty();
|
||||
backends.register(Arc::new(connector.clone()));
|
||||
let engine = Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends);
|
||||
let mut events = engine.subscribe();
|
||||
|
||||
engine.send(Command::ConnectVoice {
|
||||
session: SESSION,
|
||||
options: Box::new(VoiceOptions::new("fake://host", "tester")),
|
||||
});
|
||||
let (name, backend) = next(&mut events, |e| match e {
|
||||
Event::ServerInfo { name, backend, .. } => Some((name, backend)),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!((name.as_str(), backend.product.as_str()), ("Fake Host", "voelin-fake"));
|
||||
let presence = next(&mut events, |e| match e {
|
||||
Event::Presence { presence, .. } if !presence.channels.is_empty() => Some(presence),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
let channels: Vec<_> =
|
||||
presence.channels.values().map(|c| (c.id, c.name.as_str(), c.order)).collect();
|
||||
assert_eq!(channels, [(10, "Lobby", 0), (11, "Games", 10)]);
|
||||
// The host was asked once, with the nickname and the TeamSpeak-shaped
|
||||
// credential the engine makes of its options for now.
|
||||
let connects = connector.connects();
|
||||
assert_eq!(connects.len(), 1);
|
||||
assert_eq!(connects[0].address, "fake://host");
|
||||
assert_eq!(connects[0].hello.nickname, "tester");
|
||||
|
||||
// A move is a request to the host; the host's voice state is where we are.
|
||||
engine.send(Command::MoveToChannel { session: SESSION, channel: 11, password: None });
|
||||
let state: SessionState = next(&mut events, |e| match e {
|
||||
Event::State { state, .. } if state.own_channel == Some(11) => Some(state),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(state.voice, VoiceState::Connected);
|
||||
|
||||
engine.send(Command::DisconnectVoice { session: SESSION });
|
||||
next(&mut events, |e| match e {
|
||||
Event::State { state, .. } if state.voice == VoiceState::Disconnected => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_address_no_connector_serves_fails_with_the_registry_s_words() {
|
||||
let engine =
|
||||
Engine::start_with_backends(Settings::in_memory(), History::in_memory(), Backends::empty());
|
||||
let mut events = engine.subscribe();
|
||||
engine.send(Command::ConnectVoice {
|
||||
session: SESSION,
|
||||
options: Box::new(VoiceOptions::new("voelin://host/i/code", "tester")),
|
||||
});
|
||||
let error = next(&mut events, |e| match e {
|
||||
Event::Error { message, .. } => Some(message),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(error, "voice: no connector for voelin://host/i/code");
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -167,7 +167,7 @@ async fn ts6_stream_between_sessions() {
|
||||
Event::StreamViewers { session: 1, viewers }
|
||||
if viewers
|
||||
.iter()
|
||||
.any(|v| v.client.0 == viewer && v.state == ViewerState::Connected) =>
|
||||
.any(|v| v.client == viewer && v.state == ViewerState::Connected) =>
|
||||
{
|
||||
Some(())
|
||||
}
|
||||
|
||||
@@ -20,11 +20,11 @@ serde_json = "1"
|
||||
sha1 = { package = "sha-1", version = "0.10" }
|
||||
sha2 = "0.10"
|
||||
thiserror = "2"
|
||||
tokio = { version = "1", features = ["macros", "rt", "sync"], optional = true }
|
||||
tokio = { version = "1", features = ["macros", "net", "rt", "sync"], optional = true }
|
||||
# TLS (`wss://`, as gateways run behind a proxy) with the system's
|
||||
# certificates; rustls and its crates are in the tree already (reqwest).
|
||||
tokio-tungstenite = { version = "0.30", optional = true, features = ["rustls-tls-native-roots"] }
|
||||
voelin-model = { path = "../voelin-model" }
|
||||
voelin-model = { workspace = true }
|
||||
tsproto-types = { path = "../proto/tsproto-types" }
|
||||
|
||||
[lints]
|
||||
|
||||
@@ -20,10 +20,14 @@
|
||||
//! ```
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use futures_util::{Sink, SinkExt, Stream, StreamExt};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tokio_tungstenite::tungstenite::{self, Message};
|
||||
use tsproto_types::crypto::EccKeyPrivP256;
|
||||
@@ -196,15 +200,163 @@ pub struct GatewayClient {
|
||||
pub async fn connect(
|
||||
url: &str,
|
||||
login: Login,
|
||||
) -> Result<(GatewayClient, mpsc::UnboundedReceiver<Push>), ClientError> {
|
||||
connect_watched(url, login, &Progress::default()).await
|
||||
}
|
||||
|
||||
/// [`connect`], telling `progress` each step as it is reached, so a
|
||||
/// timeout around it can say which step hung, and how long each took.
|
||||
pub async fn connect_watched(
|
||||
url: &str,
|
||||
login: Login,
|
||||
progress: &Progress,
|
||||
) -> Result<(GatewayClient, mpsc::UnboundedReceiver<Push>), ClientError> {
|
||||
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
||||
use tokio_tungstenite::tungstenite::error::UrlError;
|
||||
let mut request = url.into_client_request()?;
|
||||
request.headers_mut().insert(
|
||||
"Sec-WebSocket-Protocol",
|
||||
tungstenite::http::HeaderValue::from_static(crate::SUBPROTOCOL),
|
||||
);
|
||||
let (ws, _) = tokio_tungstenite::connect_async(request).await?;
|
||||
GatewayClient::start(ws, login).await
|
||||
// As tokio-tungstenite's connect_async, a step at a time.
|
||||
let uri = request.uri();
|
||||
let host = uri.host().ok_or(tungstenite::Error::Url(UrlError::NoHostName))?;
|
||||
let host = host.strip_prefix('[').and_then(|h| h.strip_suffix(']')).unwrap_or(host);
|
||||
let port = uri
|
||||
.port_u16()
|
||||
.or_else(|| match uri.scheme_str() {
|
||||
Some("wss") => Some(443),
|
||||
Some("ws") => Some(80),
|
||||
_ => None,
|
||||
})
|
||||
.ok_or(tungstenite::Error::Url(UrlError::UnsupportedUrlScheme))?;
|
||||
let tcp = open(host, port, progress).await?;
|
||||
progress.enter(Stage::WebSocket);
|
||||
let (ws, _) = tokio_tungstenite::client_async_tls_with_config(request, tcp, None, None).await?;
|
||||
GatewayClient::login(ws, login, progress).await
|
||||
}
|
||||
|
||||
/// The TCP connection to `host`: each of its addresses in turn.
|
||||
async fn open(host: &str, port: u16, progress: &Progress) -> Result<TcpStream, ClientError> {
|
||||
let io = |e| ClientError::WebSocket(tungstenite::Error::Io(e));
|
||||
progress.enter(Stage::Dns);
|
||||
let addrs: Vec<SocketAddr> = tokio::net::lookup_host((host, port)).await.map_err(io)?.collect();
|
||||
progress.enter(Stage::Tcp);
|
||||
let mut error = None;
|
||||
for addr in addrs {
|
||||
progress.peer(addr);
|
||||
match TcpStream::connect(addr).await {
|
||||
Ok(tcp) => {
|
||||
// Small frames, each answered: no waiting to fill packets.
|
||||
let _ = tcp.set_nodelay(true);
|
||||
return Ok(tcp);
|
||||
}
|
||||
Err(e) => error = Some(e),
|
||||
}
|
||||
}
|
||||
Err(io(error.unwrap_or_else(|| {
|
||||
std::io::Error::new(std::io::ErrorKind::NotFound, format!("no address for {host}"))
|
||||
})))
|
||||
}
|
||||
|
||||
/// A step of logging in to a gateway ([`connect_watched`]).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Stage {
|
||||
/// Looking up the host's addresses.
|
||||
#[default]
|
||||
Dns,
|
||||
/// The TCP connection.
|
||||
Tcp,
|
||||
/// TLS (`wss://`) and the WebSocket upgrade.
|
||||
WebSocket,
|
||||
/// Waiting for the gateway's `hello`.
|
||||
Hello,
|
||||
/// Waiting for the answer to the login.
|
||||
Auth,
|
||||
/// Logged in.
|
||||
Done,
|
||||
}
|
||||
|
||||
impl Stage {
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Stage::Dns => "dns",
|
||||
Stage::Tcp => "tcp",
|
||||
Stage::WebSocket => "websocket",
|
||||
Stage::Hello => "hello",
|
||||
Stage::Auth => "auth",
|
||||
Stage::Done => "done",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Stage {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(self.name())
|
||||
}
|
||||
}
|
||||
|
||||
/// How far a login ([`connect_watched`]) got and how long each step took;
|
||||
/// clones share it. Shown as e.g. `dns 2 ms, tcp 31 ms, websocket 64 ms,
|
||||
/// hello 1 ms, auth 134 ms`, a step still under way as `hello for 19900 ms`.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Progress(Arc<Mutex<Steps>>);
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct Steps {
|
||||
/// The step under way, since when.
|
||||
stage: Stage,
|
||||
since: Option<Instant>,
|
||||
/// The steps done, with how long they took.
|
||||
done: Vec<(Stage, Duration)>,
|
||||
/// The address connected to (or being tried).
|
||||
peer: Option<SocketAddr>,
|
||||
}
|
||||
|
||||
impl Progress {
|
||||
/// The step under way (the one that hung, after a timeout), or
|
||||
/// [`Stage::Done`].
|
||||
pub fn stage(&self) -> Stage {
|
||||
self.0.lock().unwrap().stage
|
||||
}
|
||||
|
||||
/// The gateway's address, once the TCP connection is being made.
|
||||
pub fn peer_addr(&self) -> Option<SocketAddr> {
|
||||
self.0.lock().unwrap().peer
|
||||
}
|
||||
|
||||
fn enter(&self, stage: Stage) {
|
||||
let mut steps = self.0.lock().unwrap();
|
||||
let now = Instant::now();
|
||||
if let Some(since) = steps.since {
|
||||
let step = steps.stage;
|
||||
steps.done.push((step, now - since));
|
||||
}
|
||||
steps.stage = stage;
|
||||
steps.since = (stage != Stage::Done).then_some(now);
|
||||
}
|
||||
|
||||
fn peer(&self, addr: SocketAddr) {
|
||||
self.0.lock().unwrap().peer = Some(addr);
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Progress {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let steps = self.0.lock().unwrap();
|
||||
let mut parts: Vec<String> = steps
|
||||
.done
|
||||
.iter()
|
||||
.map(|(stage, took)| format!("{stage} {} ms", took.as_millis()))
|
||||
.collect();
|
||||
if let Some(since) = steps.since {
|
||||
parts.push(format!("{} for {} ms", steps.stage, since.elapsed().as_millis()));
|
||||
}
|
||||
if parts.is_empty() {
|
||||
return f.write_str("not started");
|
||||
}
|
||||
f.write_str(&parts.join(", "))
|
||||
}
|
||||
}
|
||||
|
||||
fn now_secs() -> i64 {
|
||||
@@ -241,7 +393,7 @@ impl GatewayClient {
|
||||
/// Log in over an open WebSocket (subprotocol [`crate::SUBPROTOCOL`]) and
|
||||
/// start the connection task.
|
||||
pub async fn start<S>(
|
||||
mut ws: S,
|
||||
ws: S,
|
||||
login: Login,
|
||||
) -> Result<(Self, mpsc::UnboundedReceiver<Push>), ClientError>
|
||||
where
|
||||
@@ -251,12 +403,29 @@ impl GatewayClient {
|
||||
+ Send
|
||||
+ 'static,
|
||||
{
|
||||
Self::login(ws, login, &Progress::default()).await
|
||||
}
|
||||
|
||||
async fn login<S>(
|
||||
mut ws: S,
|
||||
login: Login,
|
||||
progress: &Progress,
|
||||
) -> Result<(Self, mpsc::UnboundedReceiver<Push>), ClientError>
|
||||
where
|
||||
S: Stream<Item = Result<Message, tungstenite::Error>>
|
||||
+ Sink<Message, Error = tungstenite::Error>
|
||||
+ Unpin
|
||||
+ Send
|
||||
+ 'static,
|
||||
{
|
||||
progress.enter(Stage::Hello);
|
||||
let (gateway_id, server_uid, server_name, nonce) = match recv(&mut ws).await?.msg {
|
||||
ServerMsg::Hello { gateway_id, server_uid, server_name, nonce, .. } => {
|
||||
(gateway_id, server_uid, server_name, nonce)
|
||||
}
|
||||
other => return Err(ClientError::unexpected(other)),
|
||||
};
|
||||
progress.enter(Stage::Auth);
|
||||
let msg = match login {
|
||||
Login::Identity { key, key_offset } => {
|
||||
let ts = now_secs();
|
||||
@@ -280,6 +449,7 @@ impl GatewayClient {
|
||||
}
|
||||
other => return Err(ClientError::unexpected(other)),
|
||||
};
|
||||
progress.enter(Stage::Done);
|
||||
let info = Arc::new(SessionInfo {
|
||||
gateway_id,
|
||||
server_uid,
|
||||
@@ -732,3 +902,104 @@ async fn run<S>(
|
||||
};
|
||||
let _ = pushes.send(Push::Disconnected(reason));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tokio::net::TcpListener;
|
||||
use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Wait (without a clock: tokio's `time` is not enabled here) until the
|
||||
/// login in progress reaches `stage`.
|
||||
async fn reaches(progress: &Progress, stage: Stage) {
|
||||
for _ in 0..100_000 {
|
||||
if progress.stage() == stage {
|
||||
return;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
panic!("at {} instead of {stage}", progress.stage());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_closed_port_fails_at_the_tcp_step() {
|
||||
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
|
||||
let progress = Progress::default();
|
||||
assert_eq!(progress.to_string(), "not started");
|
||||
let login = Login::Token("t".into());
|
||||
let result = connect_watched(&format!("ws://127.0.0.1:{port}/v1"), login, &progress).await;
|
||||
assert!(matches!(result, Err(ClientError::WebSocket(_))));
|
||||
assert_eq!(progress.stage(), Stage::Tcp);
|
||||
assert_eq!(progress.peer_addr(), Some(([127, 0, 0, 1], port).into()));
|
||||
assert!(progress.to_string().starts_with("dns "), "{progress}");
|
||||
}
|
||||
|
||||
/// A gateway that takes each step only when told: the login waits at
|
||||
/// each, and tells which.
|
||||
#[tokio::test]
|
||||
async fn each_step_is_told_until_logged_in() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("ws://{}/v1", listener.local_addr().unwrap());
|
||||
let (go, mut steps) = mpsc::unbounded_channel::<()>();
|
||||
let server = tokio::spawn(async move {
|
||||
let (tcp, _) = listener.accept().await.unwrap();
|
||||
steps.recv().await;
|
||||
#[allow(clippy::result_large_err)] // tungstenite's callback type
|
||||
let callback = |_: &Request, mut response: Response| {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("Sec-WebSocket-Protocol", crate::SUBPROTOCOL.parse().unwrap());
|
||||
Ok(response)
|
||||
};
|
||||
let mut ws = tokio_tungstenite::accept_hdr_async(tcp, callback).await.unwrap();
|
||||
steps.recv().await;
|
||||
let hello = ServerMsg::Hello {
|
||||
gateway_id: "gw".into(),
|
||||
server_uid: "server".into(),
|
||||
server_name: "Server".into(),
|
||||
nonce: "n".into(),
|
||||
capabilities: Vec::new(),
|
||||
};
|
||||
let text = serde_json::to_string(&Envelope::new(hello)).unwrap();
|
||||
ws.send(Message::Text(text.into())).await.unwrap();
|
||||
let Some(Ok(Message::Text(auth))) = ws.next().await else { panic!("no login") };
|
||||
let auth: Envelope<ClientMsg> = serde_json::from_str(auth.as_str()).unwrap();
|
||||
assert!(matches!(auth.msg, ClientMsg::Resume { .. }));
|
||||
steps.recv().await;
|
||||
let ok = ServerMsg::AuthOk {
|
||||
uid: "me".into(),
|
||||
token: "t".into(),
|
||||
token_expires: 0,
|
||||
capabilities: Vec::new(),
|
||||
};
|
||||
let text = serde_json::to_string(&Envelope::with_id(auth.id.unwrap(), ok)).unwrap();
|
||||
ws.send(Message::Text(text.into())).await.unwrap();
|
||||
// Open until the client is done.
|
||||
while let Some(Ok(_)) = ws.next().await {}
|
||||
});
|
||||
let progress = Progress::default();
|
||||
let login = {
|
||||
let progress = progress.clone();
|
||||
tokio::spawn(async move {
|
||||
connect_watched(&url, Login::Token("t".into()), &progress).await.map(|(c, _)| c)
|
||||
})
|
||||
};
|
||||
reaches(&progress, Stage::WebSocket).await;
|
||||
go.send(()).unwrap();
|
||||
reaches(&progress, Stage::Hello).await;
|
||||
go.send(()).unwrap();
|
||||
reaches(&progress, Stage::Auth).await;
|
||||
assert!(progress.to_string().contains(", auth for "), "{progress}");
|
||||
go.send(()).unwrap();
|
||||
let client = login.await.unwrap().expect("logged in");
|
||||
assert_eq!(client.uid(), "me");
|
||||
assert_eq!(progress.stage(), Stage::Done);
|
||||
let shown = progress.to_string();
|
||||
let names: Vec<&str> =
|
||||
shown.split(", ").map(|step| step.split(' ').next().unwrap()).collect();
|
||||
assert_eq!(names, ["dns", "tcp", "websocket", "hello", "auth"], "{shown}");
|
||||
drop(client);
|
||||
server.await.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ toml = "1.1.6"
|
||||
tracing = "0.1.44"
|
||||
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
|
||||
voelin-gateway-proto = { path = "../voelin-gateway-proto" }
|
||||
voelin-model = { path = "../voelin-model" }
|
||||
voelin-model = { workspace = true }
|
||||
voelin-observer = { path = "../voelin-observer" }
|
||||
voelin-query = { path = "../voelin-query" }
|
||||
|
||||
|
||||
@@ -1,14 +1,35 @@
|
||||
# Build: docker build -f crates/voelin-gateway/Dockerfile -t tsgw .
|
||||
# Run: docker run -v ./tsgw.toml:/etc/tsgw/tsgw.toml -p 7788:7788 tsgw
|
||||
# syntax=docker/dockerfile:1
|
||||
# Build: docker build --ssh default -f crates/voelin-gateway/Dockerfile -t tsgw .
|
||||
# (--ssh default hands the build your ssh-agent, which must hold a key that
|
||||
# can read the private VoelinProtocol repository: docs/building.md,
|
||||
# "Depending on VoelinProtocol". The gateway itself does not use it, but
|
||||
# Cargo resolves the whole workspace, which includes voelin-identity.)
|
||||
# Run: docker run -d --name tsgw --init --restart unless-stopped \
|
||||
# -v ./tsgw.toml:/etc/tsgw/tsgw.toml:ro -v tsgw-data:/var/lib/tsgw \
|
||||
# -e TSGW_QUERY_PASSWORD=… -p 7788:7788 tsgw
|
||||
# Logs: docker logs -f tsgw (more: -e TSGW_LOG_LEVEL=debug; also to a file in
|
||||
# the volume: -e TSGW_LOG_FILE=logs/tsgw.log). See docs/gateway-admin.md.
|
||||
FROM rust:1.94-bookworm AS build
|
||||
ENV CARGO_BUILD_JOBS=1 CARGO_INCREMENTAL=0
|
||||
WORKDIR /src
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends cmake libasound2-dev && rm -rf /var/lib/apt/lists/*
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends cmake git libasound2-dev openssh-client && rm -rf /var/lib/apt/lists/*
|
||||
# voelin-identity comes from the private VoelinProtocol repository, fetched
|
||||
# over SSH by Cargo through the system git, with the agent that
|
||||
# `docker build --ssh default` forwards (scripts/docker-build.sh passes it):
|
||||
# the key stays in the agent and never reaches a layer. The host key is the
|
||||
# reviewed line from .gitea/known_hosts. Cargo resolves the whole workspace, so
|
||||
# every cargo command needs this, although this crate does not use
|
||||
# voelin-identity.
|
||||
COPY .gitea/known_hosts /etc/ssh/ssh_known_hosts
|
||||
ENV CARGO_NET_GIT_FETCH_WITH_CLI=true
|
||||
COPY . .
|
||||
RUN cargo build --release --locked -p voelin-gateway && cp target/release/tsgw /tsgw
|
||||
RUN --mount=type=ssh,required=true \
|
||||
cargo build --release --locked -p voelin-gateway && cp target/release/tsgw /tsgw && mkdir /data
|
||||
|
||||
FROM gcr.io/distroless/cc-debian12:nonroot
|
||||
COPY --from=build /tsgw /usr/local/bin/tsgw
|
||||
# The database (and a log file, if set) live here; owned by the image's user
|
||||
# (nonroot, 65532), so a new volume mounted here is writable too.
|
||||
COPY --from=build --chown=65532:65532 /data /var/lib/tsgw
|
||||
ENV TSGW_CONFIG=/etc/tsgw/tsgw.toml
|
||||
WORKDIR /var/lib/tsgw
|
||||
EXPOSE 7788
|
||||
|
||||
@@ -130,6 +130,18 @@ pub static KEYS: &[KeyDef] = &[
|
||||
"null",
|
||||
"URL clients use, e.g. wss://gw.example.org/v1",
|
||||
),
|
||||
boot(
|
||||
"log.level",
|
||||
Kind::OptStr,
|
||||
"null",
|
||||
"What to log, e.g. \"debug\" or \"info,voelin_query=trace\"; default: RUST_LOG, else \"info\"",
|
||||
),
|
||||
boot(
|
||||
"log.file",
|
||||
Kind::OptStr,
|
||||
"null",
|
||||
"Also write the log to this file (appended; at 20 MB it moves to <name>.1.log, 5 files kept)",
|
||||
),
|
||||
boot(
|
||||
"history.path",
|
||||
Kind::Str,
|
||||
@@ -160,7 +172,7 @@ pub static KEYS: &[KeyDef] = &[
|
||||
"relay.format",
|
||||
Kind::Str,
|
||||
"\"[{nick}] {text}\"",
|
||||
"How posts appear in TeamSpeak; {nick} and {text} are replaced",
|
||||
"How posts appear when the relay cannot take the user's nickname; {nick} and {text} are replaced",
|
||||
),
|
||||
key(
|
||||
"relay.idle_teardown_secs",
|
||||
@@ -493,6 +505,10 @@ impl Layers {
|
||||
bind: self.get::<String>("listen.bind")?.parse().context("listen.bind")?,
|
||||
public_url: self.get("listen.public_url")?,
|
||||
db_path: self.get("history.path")?,
|
||||
log_level: self.get::<Option<String>>("log.level")?.filter(|l| !l.trim().is_empty()),
|
||||
log_file: self
|
||||
.get::<Option<PathBuf>>("log.file")?
|
||||
.filter(|p| !p.as_os_str().is_empty()),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -514,6 +530,10 @@ pub struct Bootstrap {
|
||||
pub bind: SocketAddr,
|
||||
pub public_url: Option<String>,
|
||||
pub db_path: PathBuf,
|
||||
/// Log filter (`log.level`); `None`: `RUST_LOG`, else the default.
|
||||
pub log_level: Option<String>,
|
||||
/// Log file (`log.file`), on top of standard output.
|
||||
pub log_file: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Bootstrap {
|
||||
@@ -524,6 +544,8 @@ impl Bootstrap {
|
||||
.unwrap_or_else(|| format!("tsgw@{}", self.addr))
|
||||
}
|
||||
|
||||
/// How to open query connections. Connections opened with clones of
|
||||
/// the result share one flood count, as the server counts them.
|
||||
pub fn query_connect(&self) -> voelin_query::Connect {
|
||||
voelin_query::Connect {
|
||||
transport: self.transport,
|
||||
@@ -751,4 +773,21 @@ mod tests {
|
||||
assert!(cli_values(&["nope=1".into()]).is_err());
|
||||
assert!(cli_values(&["history.retention_days=-1".into()]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn log_settings_are_bootstrap_keys() {
|
||||
let file = file_values(
|
||||
"[query]\ntransport = \"ssh\"\naddr = \"127.0.0.1:10022\"\n\
|
||||
[log]\nfile = \"logs/tsgw.log\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
let env = env_values(|name| (name == "TSGW_LOG_LEVEL").then(|| "debug".into())).unwrap();
|
||||
let boot = Layers { file, env, ..Default::default() }.bootstrap().unwrap();
|
||||
assert_eq!(boot.log_level.as_deref(), Some("debug"));
|
||||
assert_eq!(boot.log_file, Some(PathBuf::from("logs/tsgw.log")));
|
||||
assert!(key_def("log.level").unwrap().bootstrap);
|
||||
let none = file_values("[query]\ntransport = \"raw\"\naddr = \"h:1\"\n").unwrap();
|
||||
let boot = Layers { file: none, ..Default::default() }.bootstrap().unwrap();
|
||||
assert_eq!((boot.log_level, boot.log_file), (None, None));
|
||||
}
|
||||
}
|
||||
@@ -367,6 +367,7 @@ impl Db {
|
||||
}
|
||||
|
||||
/// Whether `uid` reacted with `emoji`.
|
||||
#[cfg(test)]
|
||||
pub fn has_reaction(&self, message_id: i64, emoji: &str, uid: &str) -> rusqlite::Result<bool> {
|
||||
self.lock()
|
||||
.conn
|
||||
|
||||
@@ -253,6 +253,7 @@ impl Db {
|
||||
self.0.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn schema_version(&self) -> rusqlite::Result<i64> {
|
||||
self.lock().conn.pragma_query_value(None, "user_version", |r| r.get(0))
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
//! feed are in `features.rs`, the stream directory in `streams.rs`, the
|
||||
//! background tasks in `tasks.rs`.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
use std::time::Instant;
|
||||
|
||||
@@ -19,12 +19,13 @@ use voelin_gateway_proto::{
|
||||
Action, ActivityEntry, ErrorCode, EventInfo, HistoryEntry, PinInfo, StreamEntry, TopicInfo,
|
||||
UniqueIds, UserRef, feature, identity_level, verify_auth,
|
||||
};
|
||||
use voelin_model::{ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor, relay_text};
|
||||
use voelin_observer::{Observer, ObserverConfig, RelayConfig, RelayPool};
|
||||
use voelin_query::{Command, Connect, QueryClient};
|
||||
use voelin_model::{ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor};
|
||||
use voelin_observer::{Observer, ObserverConfig, RelayConfig, RelayPool, post_as};
|
||||
use voelin_query::{Command, Connect};
|
||||
|
||||
use crate::config::{Bootstrap, Layers, Runtime};
|
||||
use crate::config::{Layers, Runtime};
|
||||
use crate::db::{Db, TokenInfo};
|
||||
use crate::lookup::Lookup;
|
||||
use crate::perms::{
|
||||
ChannelAccess, GroupResolver, PermIds, PermResolver, UserGroups, channel_access, effective,
|
||||
granted, rule_allows,
|
||||
@@ -192,7 +193,6 @@ impl Feature {
|
||||
}
|
||||
|
||||
pub struct Hub {
|
||||
pub boot: Bootstrap,
|
||||
pub settings: Settings,
|
||||
pub gateway_id: String,
|
||||
pub server_uid: String,
|
||||
@@ -205,83 +205,78 @@ pub struct Hub {
|
||||
relays: RwLock<RelayPool>,
|
||||
/// Serializes rebuilding the relay pool.
|
||||
relay_rebuild: tokio::sync::Mutex<()>,
|
||||
lookup: QueryClient,
|
||||
pub(crate) lookup: Arc<Lookup>,
|
||||
/// One server-chat post at a time: each borrows the poster's nickname.
|
||||
lookup_posting: tokio::sync::Mutex<()>,
|
||||
perms: PermResolver,
|
||||
groups: GroupResolver,
|
||||
pub db: Db,
|
||||
events: broadcast::Sender<Arc<HubEvent>>,
|
||||
/// Readers per relayed channel, and when the last one left.
|
||||
readers: Mutex<HashMap<ChannelId, (usize, Instant)>>,
|
||||
/// Our own query clients, whose messages are echoes.
|
||||
own_clients: Mutex<HashSet<u16>>,
|
||||
/// Message ids while history is off.
|
||||
next_message_id: Mutex<i64>,
|
||||
pub(crate) directory: Mutex<Directory>,
|
||||
}
|
||||
|
||||
impl Hub {
|
||||
/// Connect to the server, open the database and start the background tasks.
|
||||
/// Connect to the server, open the database and start the background
|
||||
/// tasks. Waits for the TeamSpeak server as long as it takes.
|
||||
pub async fn start(layers: Layers) -> Result<Arc<Self>> {
|
||||
let started = Instant::now();
|
||||
let boot = layers.bootstrap()?;
|
||||
let db = Db::open(&boot.db_path)
|
||||
.with_context(|| format!("failed to open {}", boot.db_path.display()))?;
|
||||
let settings = Settings::new(layers, &db)?;
|
||||
let rt = settings.current();
|
||||
|
||||
// Clones share the count of commands for the flood protection.
|
||||
let connect = boot.query_connect();
|
||||
let (lookup, _) =
|
||||
QueryClient::connect(&connect).await.context("query login for lookups failed")?;
|
||||
let info = lookup.send(&Command::new("serverinfo")).await?;
|
||||
let info = info.first().context("empty serverinfo")?;
|
||||
let version = info.get("virtualserver_version").unwrap_or_default();
|
||||
let is_ts6 = matches!(ServerFlavor::from_version_string(version), ServerFlavor::Ts6(_));
|
||||
let server_uid =
|
||||
info.get("virtualserver_unique_identifier").unwrap_or_default().to_string();
|
||||
let server_name = info.get("virtualserver_name").unwrap_or_default().to_string();
|
||||
let needed_level = info.parse("virtualserver_needed_identity_security_level").unwrap_or(8);
|
||||
let channels = lookup.send(&Command::new("channellist").flag("flags")).await?;
|
||||
let default_channel = channels
|
||||
.iter()
|
||||
.find(|r| r.flag("channel_flag_default") == Some(true))
|
||||
.and_then(|r| r.parse("cid"))
|
||||
.unwrap_or(1);
|
||||
let perms = PermResolver::new(PermIds::load(&lookup).await?);
|
||||
let own_id = lookup.own_client_id().await?;
|
||||
set_lookup_nickname(&lookup, &rt.relay.nickname).await;
|
||||
let lookup = Lookup::open(connect.clone(), lookup_nickname(&rt.relay.nickname)).await;
|
||||
lookup.log_address(boot.allowlisted).await;
|
||||
let server = ServerFacts::load_until_it_works(&lookup, &connect).await;
|
||||
let perms = PermResolver::new(server.perm_ids);
|
||||
|
||||
let observer = Observer::spawn(ObserverConfig::new(connect.clone()));
|
||||
let relays = new_relay_pool(&connect, &rt.relay.nickname);
|
||||
let directory = Directory::load(&db);
|
||||
|
||||
info!(%server_name, %server_uid, version, is_ts6, "gateway connected to server");
|
||||
info!(
|
||||
server_name = %server.name,
|
||||
server_uid = %server.uid,
|
||||
version = %server.version,
|
||||
is_ts6 = server.is_ts6,
|
||||
default_channel = server.default_channel,
|
||||
needed_level = server.needed_level,
|
||||
elapsed_ms = started.elapsed().as_millis() as u64,
|
||||
"gateway connected to server"
|
||||
);
|
||||
let hub = Arc::new(Self {
|
||||
gateway_id: boot.gateway_id(),
|
||||
boot,
|
||||
settings,
|
||||
server_uid,
|
||||
server_name,
|
||||
is_ts6,
|
||||
needed_level,
|
||||
default_channel,
|
||||
server_uid: server.uid,
|
||||
server_name: server.name,
|
||||
is_ts6: server.is_ts6,
|
||||
needed_level: server.needed_level,
|
||||
default_channel: server.default_channel,
|
||||
observer,
|
||||
connect,
|
||||
relays: RwLock::new(relays),
|
||||
relay_rebuild: Default::default(),
|
||||
lookup,
|
||||
lookup_posting: Default::default(),
|
||||
perms,
|
||||
groups: GroupResolver::default(),
|
||||
db,
|
||||
events: broadcast::channel(4096).0,
|
||||
readers: Default::default(),
|
||||
own_clients: Mutex::new([own_id].into()),
|
||||
next_message_id: Mutex::new(0),
|
||||
directory: Mutex::new(directory),
|
||||
});
|
||||
crate::tasks::spawn_all(&hub);
|
||||
// Apps may log in meanwhile.
|
||||
for &cid in &rt.relay.pinned_channels {
|
||||
if let Err(error) = hub.relays().open(cid).await {
|
||||
warn!(cid, %error, "could not open pinned relay");
|
||||
}
|
||||
hub.open_relay_soon(cid);
|
||||
}
|
||||
Ok(hub)
|
||||
}
|
||||
@@ -303,7 +298,7 @@ impl Hub {
|
||||
}
|
||||
|
||||
pub(crate) fn is_own_client(&self, id: u16) -> bool {
|
||||
self.own_clients.lock().unwrap().contains(&id)
|
||||
self.lookup.is_own(id)
|
||||
}
|
||||
|
||||
/// Features for the `hello` message.
|
||||
@@ -347,26 +342,37 @@ impl Hub {
|
||||
let pool = new_relay_pool(&self.connect, nickname);
|
||||
tokio::spawn(crate::tasks::pump_relays(self.clone(), pool.subscribe()));
|
||||
let old = std::mem::replace(&mut *self.relays.write().unwrap(), pool);
|
||||
let channels = old.channels().await;
|
||||
old.close_all().await;
|
||||
// Also the relays being opened now, which open no more in the old pool.
|
||||
let channels = old.close_all().await;
|
||||
drop(old);
|
||||
set_lookup_nickname(&self.lookup, nickname).await;
|
||||
self.lookup.set_nickname(&lookup_nickname(nickname)).await;
|
||||
let pool = self.relays();
|
||||
for cid in channels {
|
||||
if let Err(error) = pool.open(cid).await {
|
||||
warn!(cid, %error, "could not reopen relay");
|
||||
// A failure is logged by the pool.
|
||||
if pool.open(cid).await.is_err() && self.relay_wanted(cid) {
|
||||
let hub = self.clone();
|
||||
tokio::spawn(async move { hub.reopen_relay(cid).await });
|
||||
}
|
||||
}
|
||||
info!(nickname, "relays renamed");
|
||||
}
|
||||
|
||||
/// Pinned channels changed: open new ones, let removed ones idle out.
|
||||
pub(crate) async fn apply_pinned_channels(&self, old: &[u64], new: &[u64]) {
|
||||
let pool = self.relays();
|
||||
for cid in new.iter().filter(|c| !old.contains(c)) {
|
||||
if let Err(error) = pool.open(*cid).await {
|
||||
warn!(cid, %error, "could not open pinned relay");
|
||||
/// Open a channel's relay in the background, and while that fails, again
|
||||
/// for as long as it is wanted ([`Hub::reopen_relay`]).
|
||||
fn open_relay_soon(self: &Arc<Self>, cid: ChannelId) {
|
||||
let hub = self.clone();
|
||||
tokio::spawn(async move {
|
||||
// A failure is logged by the pool.
|
||||
if hub.relays().open(cid).await.is_err() {
|
||||
hub.reopen_relay(cid).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Pinned channels changed: open new ones, let removed ones idle out.
|
||||
pub(crate) fn apply_pinned_channels(self: &Arc<Self>, old: &[u64], new: &[u64]) {
|
||||
for cid in new.iter().filter(|c| !old.contains(c)) {
|
||||
self.open_relay_soon(*cid);
|
||||
}
|
||||
for cid in old.iter().filter(|c| !new.contains(c)) {
|
||||
// The idle teardown closes it once nobody reads it.
|
||||
@@ -374,6 +380,27 @@ impl Hub {
|
||||
}
|
||||
}
|
||||
|
||||
/// Someone reads the channel, or it is pinned.
|
||||
pub(crate) fn relay_wanted(&self, cid: ChannelId) -> bool {
|
||||
self.runtime().relay.pinned_channels.contains(&cid)
|
||||
|| self.readers.lock().unwrap().get(&cid).is_some_and(|(n, _)| *n > 0)
|
||||
}
|
||||
|
||||
/// Open a relay the server dropped again, waiting longer after each
|
||||
/// failure, for as long as it is wanted.
|
||||
pub(crate) async fn reopen_relay(&self, cid: ChannelId) {
|
||||
let mut attempt = 0;
|
||||
while self.relay_wanted(cid) {
|
||||
attempt += 1;
|
||||
tokio::time::sleep(self.connect.retry_delay(attempt)).await;
|
||||
// A failure is logged by the pool.
|
||||
if self.relays().open(cid).await.is_ok() {
|
||||
info!(channel = cid, attempt, "relay reopened");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Channels whose relay nobody needs any more.
|
||||
pub(crate) fn idle_relays(&self, rt: &Runtime) -> Vec<ChannelId> {
|
||||
let idle = std::time::Duration::from_secs(rt.relay.idle_teardown_secs);
|
||||
@@ -708,7 +735,15 @@ impl Hub {
|
||||
));
|
||||
}
|
||||
}
|
||||
self.relays().open(cid).await?;
|
||||
loop {
|
||||
let pool = self.relays();
|
||||
match pool.open(cid).await {
|
||||
// Replaced on the way (a new nickname): open in the new pool.
|
||||
Err(_) if pool.is_closed() => continue,
|
||||
result => result?,
|
||||
}
|
||||
break;
|
||||
}
|
||||
self.readers.lock().unwrap().entry(cid).or_insert((0, Instant::now())).0 += 1;
|
||||
Ok(())
|
||||
}
|
||||
@@ -751,16 +786,20 @@ impl Hub {
|
||||
}
|
||||
None => text.to_string(),
|
||||
};
|
||||
let full = relay_text(&rt.relay.format, &user.nickname, &relayed);
|
||||
// Posts go out under the user's nickname; `relay.format` only when the
|
||||
// session cannot take it.
|
||||
match target {
|
||||
ChatTarget::Server => {
|
||||
for part in voelin_model::split_message(&full, 1024) {
|
||||
self.lookup
|
||||
.send(
|
||||
&Command::new("sendtextmessage").arg("targetmode", 3).arg("msg", part),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
let _posting = self.lookup_posting.lock().await;
|
||||
post_as(
|
||||
&self.lookup.client().await,
|
||||
&lookup_nickname(&rt.relay.nickname),
|
||||
&user.nickname,
|
||||
&relayed,
|
||||
&rt.relay.format,
|
||||
|part| Command::new("sendtextmessage").arg("targetmode", 3).arg("msg", part),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
ChatTarget::Channel(cid) => {
|
||||
if !self.readers.lock().unwrap().contains_key(cid) {
|
||||
@@ -768,8 +807,7 @@ impl Hub {
|
||||
self.add_reader(*cid).await?;
|
||||
self.remove_reader(*cid);
|
||||
}
|
||||
// The pool's format is `{text}`: `full` is already formatted.
|
||||
self.relays().send(*cid, &user.nickname, &full).await?;
|
||||
self.relays().post(*cid, &user.nickname, &relayed, &rt.relay.format).await?;
|
||||
}
|
||||
ChatTarget::Private(_) => unreachable!("checked by require_post"),
|
||||
}
|
||||
@@ -797,15 +835,69 @@ impl Hub {
|
||||
fn new_relay_pool(connect: &Connect, nickname: &str) -> RelayPool {
|
||||
let mut config = RelayConfig::new(connect.clone());
|
||||
config.nickname = nickname.to_string();
|
||||
// Posts are formatted by the hub, with the current settings.
|
||||
config.format = "{text}".into();
|
||||
RelayPool::new(config)
|
||||
}
|
||||
|
||||
async fn set_lookup_nickname(lookup: &QueryClient, nickname: &str) {
|
||||
let _ = lookup
|
||||
.send(&Command::new("clientupdate").arg("client_nickname", format!("{nickname} Gateway")))
|
||||
.await;
|
||||
/// The lookup session's own name, given `relay.nickname`.
|
||||
fn lookup_nickname(nickname: &str) -> String {
|
||||
format!("{nickname} Gateway")
|
||||
}
|
||||
|
||||
/// What the gateway reads from the server once, at start.
|
||||
struct ServerFacts {
|
||||
version: String,
|
||||
is_ts6: bool,
|
||||
uid: String,
|
||||
name: String,
|
||||
needed_level: u8,
|
||||
default_channel: ChannelId,
|
||||
perm_ids: PermIds,
|
||||
}
|
||||
|
||||
impl ServerFacts {
|
||||
async fn load_until_it_works(lookup: &Lookup, connect: &Connect) -> Self {
|
||||
let mut attempt = 0;
|
||||
loop {
|
||||
attempt += 1;
|
||||
match Self::load(lookup).await {
|
||||
Ok(facts) => return facts,
|
||||
Err(error) => {
|
||||
let retry_in = connect.retry_delay(attempt);
|
||||
warn!(
|
||||
error = format!("{error:#}"),
|
||||
attempt,
|
||||
retry_in_s = retry_in.as_secs_f32(),
|
||||
"could not read the server's settings; trying again"
|
||||
);
|
||||
tokio::time::sleep(retry_in).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn load(lookup: &Lookup) -> Result<Self> {
|
||||
// Failures are logged by the caller.
|
||||
let info = lookup.send_quiet(&Command::new("serverinfo")).await.context("serverinfo")?;
|
||||
let info = info.first().context("empty serverinfo")?;
|
||||
let version = info.get("virtualserver_version").unwrap_or_default().to_string();
|
||||
let channels = lookup
|
||||
.send_quiet(&Command::new("channellist").flag("flags"))
|
||||
.await
|
||||
.context("channellist")?;
|
||||
Ok(Self {
|
||||
is_ts6: matches!(ServerFlavor::from_version_string(&version), ServerFlavor::Ts6(_)),
|
||||
version,
|
||||
uid: info.get("virtualserver_unique_identifier").unwrap_or_default().to_string(),
|
||||
name: info.get("virtualserver_name").unwrap_or_default().to_string(),
|
||||
needed_level: info.parse("virtualserver_needed_identity_security_level").unwrap_or(8),
|
||||
default_channel: channels
|
||||
.iter()
|
||||
.find(|r| r.flag("channel_flag_default") == Some(true))
|
||||
.and_then(|r| r.parse("cid"))
|
||||
.unwrap_or(1),
|
||||
perm_ids: PermIds::load(lookup).await.context("looking up permission ids")?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Split `text` by a topic format like `[#{topic}] {text}` into title and
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
//! Where the log goes: standard output (journald, `docker logs`) and, with
|
||||
//! `log.file`, a file as well.
|
||||
//!
|
||||
//! What is logged comes from `log.level` (`TSGW_LOG_LEVEL`), else
|
||||
//! `RUST_LOG`, else [`DEFAULT_FILTER`]. The libraries that log every packet
|
||||
//! stay at warnings unless the filter names them, so `debug` stays readable.
|
||||
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{self, IsTerminal, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use tracing::warn;
|
||||
use tracing_subscriber::prelude::*;
|
||||
use tracing_subscriber::{EnvFilter, fmt};
|
||||
|
||||
use crate::config::Bootstrap;
|
||||
|
||||
/// What is logged when nothing says otherwise.
|
||||
pub const DEFAULT_FILTER: &str = "info,russh=warn,hyper=warn,h2=warn,tower=warn,tungstenite=warn";
|
||||
|
||||
/// Libraries kept at warnings unless a filter names them.
|
||||
const NOISY: &[&str] = &["russh", "hyper", "h2", "tower", "tungstenite", "tokio_tungstenite"];
|
||||
|
||||
/// One log file's limit before it moves aside.
|
||||
const MAX_BYTES: u64 = 20 << 20;
|
||||
/// Files kept: the one written and the ones moved aside.
|
||||
const KEEP: usize = 5;
|
||||
|
||||
/// Start logging. Problems with the filter or the file are logged, not
|
||||
/// fatal. Returns the log file in use.
|
||||
pub fn init(boot: &Bootstrap) -> Option<PathBuf> {
|
||||
let rust_log = std::env::var("RUST_LOG").ok();
|
||||
let (directives, from) = match (&boot.log_level, &rust_log) {
|
||||
(Some(level), _) => (level.as_str(), "log.level"),
|
||||
(None, Some(rust_log)) if !rust_log.trim().is_empty() => (rust_log.as_str(), "RUST_LOG"),
|
||||
_ => (DEFAULT_FILTER, "default"),
|
||||
};
|
||||
let (filter, bad_filter) = match EnvFilter::try_new(quiet_noisy(directives)) {
|
||||
Ok(filter) => (filter, None),
|
||||
Err(error) => (EnvFilter::new(DEFAULT_FILTER), Some(error)),
|
||||
};
|
||||
let ansi = io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none();
|
||||
let console = fmt::layer().with_ansi(ansi);
|
||||
let file = boot.log_file.as_deref().map(|path| (path, LogFile::open(path, KEEP, MAX_BYTES)));
|
||||
let to_file = match &file {
|
||||
Some((_, Ok(log))) => {
|
||||
let log = log.clone();
|
||||
Some(fmt::layer().with_ansi(false).with_writer(move || log.clone()))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
tracing_subscriber::registry().with(filter).with(console).with(to_file).init();
|
||||
if let Some(error) = bad_filter {
|
||||
warn!(filter = directives, from, %error, "not a log filter; using the default");
|
||||
}
|
||||
match file {
|
||||
Some((path, Ok(_))) => Some(path.to_path_buf()),
|
||||
Some((path, Err(error))) => {
|
||||
warn!(
|
||||
file = %path.display(),
|
||||
%error,
|
||||
"cannot write the log file; logging to standard output only"
|
||||
);
|
||||
None
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `directives` with the libraries in [`NOISY`] it does not name at
|
||||
/// warnings.
|
||||
fn quiet_noisy(directives: &str) -> String {
|
||||
let named = |lib: &str| {
|
||||
directives.split(',').any(|d| {
|
||||
let target = d.trim().split(['=', '[']).next().unwrap_or_default();
|
||||
target == lib || target.starts_with(&format!("{lib}::"))
|
||||
})
|
||||
};
|
||||
let mut filter = directives.trim().trim_end_matches(',').to_string();
|
||||
for lib in NOISY.iter().filter(|lib| !named(lib)) {
|
||||
filter.push_str(&format!(",{lib}=warn"));
|
||||
}
|
||||
filter
|
||||
}
|
||||
|
||||
/// A log file written by appending, also across restarts. When it would
|
||||
/// grow past its limit it moves to `<name>.1.<ext>` (the older ones one
|
||||
/// further along, the oldest dropped) and a new one starts. Clones write to
|
||||
/// the same file.
|
||||
#[derive(Clone)]
|
||||
pub struct LogFile(Arc<Mutex<Inner>>);
|
||||
|
||||
struct Inner {
|
||||
path: PathBuf,
|
||||
file: File,
|
||||
written: u64,
|
||||
keep: usize,
|
||||
max: u64,
|
||||
}
|
||||
|
||||
impl LogFile {
|
||||
pub fn open(path: &Path, keep: usize, max: u64) -> io::Result<Self> {
|
||||
if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let file = append(path)?;
|
||||
let written = file.metadata()?.len();
|
||||
let inner = Inner { path: path.to_path_buf(), file, written, keep: keep.max(1), max };
|
||||
Ok(Self(Arc::new(Mutex::new(inner))))
|
||||
}
|
||||
}
|
||||
|
||||
impl Write for LogFile {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
let mut inner = self.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if inner.written > 0 && inner.written + buf.len() as u64 > inner.max {
|
||||
rotate(&inner.path, inner.keep);
|
||||
// If no new file can be made, the moved one goes on: moving the
|
||||
// files along on every line would soon drop them all.
|
||||
if let Ok(file) = append(&inner.path) {
|
||||
inner.file = file;
|
||||
}
|
||||
inner.written = 0;
|
||||
}
|
||||
let n = inner.file.write(buf)?;
|
||||
inner.written += n as u64;
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
self.0.lock().unwrap_or_else(PoisonError::into_inner).file.flush()
|
||||
}
|
||||
}
|
||||
|
||||
fn append(path: &Path) -> io::Result<File> {
|
||||
OpenOptions::new().create(true).append(true).open(path)
|
||||
}
|
||||
|
||||
/// `tsgw.log` as the `n`th one moved aside: `tsgw.1.log`.
|
||||
fn moved_aside(path: &Path, n: usize) -> PathBuf {
|
||||
let stem = path.file_stem().unwrap_or_default().to_string_lossy();
|
||||
let name = match path.extension() {
|
||||
Some(ext) => format!("{stem}.{n}.{}", ext.to_string_lossy()),
|
||||
None => format!("{stem}.{n}"),
|
||||
};
|
||||
path.with_file_name(name)
|
||||
}
|
||||
|
||||
/// Move the files one along; the oldest goes.
|
||||
fn rotate(path: &Path, keep: usize) {
|
||||
if keep <= 1 {
|
||||
let _ = std::fs::remove_file(path);
|
||||
return;
|
||||
}
|
||||
let _ = std::fs::remove_file(moved_aside(path, keep - 1));
|
||||
for n in (1..keep - 1).rev() {
|
||||
let _ = std::fs::rename(moved_aside(path, n), moved_aside(path, n + 1));
|
||||
}
|
||||
let _ = std::fs::rename(path, moved_aside(path, 1));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn noisy_libraries_stay_quiet_unless_named() {
|
||||
assert_eq!(
|
||||
quiet_noisy("debug"),
|
||||
"debug,russh=warn,hyper=warn,h2=warn,tower=warn,tungstenite=warn,tokio_tungstenite=warn"
|
||||
);
|
||||
let named = quiet_noisy("info,voelin_query=trace,russh=debug,hyper::proto=info,");
|
||||
assert!(named.starts_with("info,voelin_query=trace,russh=debug,hyper::proto=info,h2=warn"));
|
||||
assert!(!named.contains("russh=warn") && !named.contains("hyper=warn"));
|
||||
assert!(EnvFilter::try_new(quiet_noisy(DEFAULT_FILTER)).is_ok());
|
||||
assert_eq!(quiet_noisy(DEFAULT_FILTER).matches("russh").count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_is_appended_to_and_moved_aside_when_full() {
|
||||
let dir = std::env::temp_dir().join(format!("tsgw-log-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let path = dir.join("logs").join("tsgw.log");
|
||||
let read = |p: PathBuf| std::fs::read_to_string(p).ok();
|
||||
LogFile::open(&path, 3, 12).unwrap().write_all(b"start 1\n").unwrap();
|
||||
// A restart goes on in the same file.
|
||||
let log = LogFile::open(&path, 3, 12).unwrap();
|
||||
log.clone().write_all(b"two\n").unwrap();
|
||||
assert_eq!(read(path.clone()).as_deref(), Some("start 1\ntwo\n"));
|
||||
// Full: moved aside, and the oldest goes.
|
||||
log.clone().write_all(b"three\n").unwrap();
|
||||
log.clone().write_all(b"four 4\n").unwrap();
|
||||
log.clone().write_all(b"five 5\n").unwrap();
|
||||
assert_eq!(read(path.clone()).as_deref(), Some("five 5\n"));
|
||||
assert_eq!(read(dir.join("logs/tsgw.1.log")).as_deref(), Some("four 4\n"));
|
||||
assert_eq!(read(dir.join("logs/tsgw.2.log")).as_deref(), Some("three\n"));
|
||||
assert_eq!(read(dir.join("logs/tsgw.3.log")), None, "three files in all");
|
||||
assert_eq!(moved_aside(Path::new("/var/log/tsgw"), 2), Path::new("/var/log/tsgw.2"));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
//! The lookup query connection: logins, permission checks and server chat
|
||||
//! posts go through it. When the TeamSpeak server drops it (a restart, a
|
||||
//! network problem) it is opened again, and commands sent meanwhile wait
|
||||
//! for it a little.
|
||||
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use tokio::sync::watch;
|
||||
use tracing::{debug, error, info, warn};
|
||||
use voelin_query::{Command, Connect, QueryClient, Row, Transport, attempt_worth_a_warning};
|
||||
|
||||
/// How long a command waits for a lost connection to come back.
|
||||
const RECONNECT_WAIT: Duration = Duration::from_secs(5);
|
||||
|
||||
pub struct Lookup {
|
||||
connect: Connect,
|
||||
client: watch::Sender<QueryClient>,
|
||||
/// The session's nickname, set again on every new connection.
|
||||
nickname: Mutex<String>,
|
||||
/// The connection's client id while it is up: server chat from it is the
|
||||
/// gateway's own. Not kept across reconnects: after a server restart the
|
||||
/// old id may be a user's.
|
||||
own_id: Mutex<Option<u16>>,
|
||||
}
|
||||
|
||||
impl Lookup {
|
||||
/// Log in, trying until it works, and keep the connection open from
|
||||
/// then on.
|
||||
pub async fn open(mut connect: Connect, nickname: String) -> Arc<Self> {
|
||||
connect.line.label = "lookup".into();
|
||||
let (client, own_id) = open_until_it_works(&connect, &nickname).await;
|
||||
let lookup = Arc::new(Self {
|
||||
connect,
|
||||
client: watch::channel(client).0,
|
||||
nickname: Mutex::new(nickname),
|
||||
own_id: Mutex::new(Some(own_id)),
|
||||
});
|
||||
tokio::spawn(keep_open(Arc::downgrade(&lookup)));
|
||||
lookup
|
||||
}
|
||||
|
||||
/// The connection is up.
|
||||
pub fn is_up(&self) -> bool {
|
||||
!self.client.borrow().is_closed()
|
||||
}
|
||||
|
||||
/// The connection's client id, while it is up.
|
||||
pub fn own_id(&self) -> Option<u16> {
|
||||
*self.own_id.lock().unwrap()
|
||||
}
|
||||
|
||||
/// The id is the connection's own.
|
||||
pub fn is_own(&self, id: u16) -> bool {
|
||||
self.own_id() == Some(id)
|
||||
}
|
||||
|
||||
/// Send a command; when the connection is lost on the way, once more
|
||||
/// on the new one. A failure is logged with the command's name.
|
||||
pub async fn send(&self, cmd: &Command) -> voelin_query::Result<Vec<Row>> {
|
||||
let result = self.send_quiet(cmd).await;
|
||||
if let Err(error) = &result {
|
||||
warn!(command = %cmd.name, %error, "ServerQuery command failed");
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// [`Lookup::send`] for callers that log a failure themselves.
|
||||
pub async fn send_quiet(&self, cmd: &Command) -> voelin_query::Result<Vec<Row>> {
|
||||
let mut current = self.client.subscribe();
|
||||
let client = current.borrow_and_update().clone();
|
||||
match client.send(cmd).await {
|
||||
Err(error) if lost(&error, &client) => {
|
||||
match tokio::time::timeout(RECONNECT_WAIT, current.changed()).await {
|
||||
Ok(Ok(())) => {
|
||||
let client = current.borrow_and_update().clone();
|
||||
client.send(cmd).await
|
||||
}
|
||||
_ => Err(error),
|
||||
}
|
||||
}
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
|
||||
/// The connection, after waiting a little for it if it is lost.
|
||||
pub async fn client(&self) -> QueryClient {
|
||||
let mut current = self.client.subscribe();
|
||||
let client = current.borrow_and_update().clone();
|
||||
if !client.is_closed() {
|
||||
return client;
|
||||
}
|
||||
match tokio::time::timeout(RECONNECT_WAIT, current.changed()).await {
|
||||
Ok(Ok(())) => current.borrow_and_update().clone(),
|
||||
_ => client,
|
||||
}
|
||||
}
|
||||
|
||||
/// Rename the session, now and after reconnects.
|
||||
pub async fn set_nickname(&self, nickname: &str) {
|
||||
*self.nickname.lock().unwrap() = nickname.to_string();
|
||||
set_nickname(&self.client().await, nickname).await;
|
||||
}
|
||||
|
||||
/// Log the address the server sees the gateway's queries come from: it
|
||||
/// counts the commands of each address for its flood protection, unless
|
||||
/// the address is in its `query_ip_allowlist.txt`.
|
||||
pub async fn log_address(&self, allowlisted: bool) {
|
||||
let Some(own) = self.own_id() else { return };
|
||||
let Ok(rows) = self.send(&Command::new("clientlist").flag("ip")).await else { return };
|
||||
let address = rows
|
||||
.iter()
|
||||
.find(|r| r.parse::<u16>("clid") == Some(own))
|
||||
.and_then(|r| r.get("connection_client_ip"));
|
||||
let Some(address) = address.filter(|a| !a.is_empty()) else {
|
||||
debug!("the server did not say where the gateway's queries come from");
|
||||
return;
|
||||
};
|
||||
let loopback = address.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback());
|
||||
match (allowlisted, loopback) {
|
||||
(true, _) => info!(
|
||||
address,
|
||||
"the TeamSpeak server sees the gateway's queries coming from this address"
|
||||
),
|
||||
(false, true) => info!(
|
||||
address,
|
||||
hint = "the server's query_ip_allowlist.txt has this address by default; if it still \
|
||||
does, set query.allowlisted = true so the gateway stops slowing itself down",
|
||||
"the TeamSpeak server sees the gateway's queries coming from this address"
|
||||
),
|
||||
(false, false) => info!(
|
||||
address,
|
||||
hint = "add this address to the server's query_ip_allowlist.txt (read again within \
|
||||
seconds) and set query.allowlisted = true; until then the server's flood \
|
||||
protection limits the gateway",
|
||||
"the TeamSpeak server sees the gateway's queries coming from this address"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The error means the connection is gone, not that the command failed.
|
||||
fn lost(error: &voelin_query::Error, client: &QueryClient) -> bool {
|
||||
use voelin_query::Error;
|
||||
matches!(error, Error::Closed | Error::Io(_) | Error::Ssh(_)) || client.is_closed()
|
||||
}
|
||||
|
||||
/// Wait for the connection to close, open it again, repeat.
|
||||
async fn keep_open(lookup: Weak<Lookup>) {
|
||||
loop {
|
||||
let Some(client) = lookup.upgrade().map(|l| l.client.borrow().clone()) else { return };
|
||||
client.closed().await;
|
||||
let Some(lookup) = lookup.upgrade() else { return };
|
||||
let lost_at = Instant::now();
|
||||
*lookup.own_id.lock().unwrap() = None;
|
||||
warn!(addr = %lookup.connect.addr, "lookup query connection lost; reconnecting");
|
||||
let nickname = lookup.nickname.lock().unwrap().clone();
|
||||
let (client, own_id) = open_until_it_works(&lookup.connect, &nickname).await;
|
||||
*lookup.own_id.lock().unwrap() = Some(own_id);
|
||||
lookup.client.send_replace(client);
|
||||
info!(down_ms = lost_at.elapsed().as_millis() as u64, "lookup query connection restored");
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a connection, waiting longer after each failure.
|
||||
async fn open_until_it_works(connect: &Connect, nickname: &str) -> (QueryClient, u16) {
|
||||
let started = Instant::now();
|
||||
let transport = match connect.transport {
|
||||
Transport::Ssh => "ssh",
|
||||
Transport::Raw => "raw",
|
||||
Transport::Http => "http",
|
||||
};
|
||||
let mut attempt = 0;
|
||||
loop {
|
||||
attempt += 1;
|
||||
match open_once(connect, nickname).await {
|
||||
Ok(opened) => {
|
||||
let elapsed_ms = started.elapsed().as_millis() as u64;
|
||||
info!(addr = %connect.addr, transport, attempt, elapsed_ms, "query login ok");
|
||||
return opened;
|
||||
}
|
||||
Err(e) => {
|
||||
let retry_in = connect.retry_delay(attempt);
|
||||
let retry_in_s = retry_in.as_secs_f32();
|
||||
let refused = matches!(&e, voelin_query::Error::SshAuth)
|
||||
|| matches!(&e, voelin_query::Error::Query(q) if q.id == ERR_INVALID_LOGIN);
|
||||
if refused {
|
||||
error!(
|
||||
addr = %connect.addr,
|
||||
user = %connect.user,
|
||||
attempt,
|
||||
retry_in_s,
|
||||
"the TeamSpeak server refused the query login; check query.user and the password"
|
||||
);
|
||||
} else if attempt_worth_a_warning(attempt) {
|
||||
warn!(
|
||||
addr = %connect.addr,
|
||||
error = %e,
|
||||
attempt,
|
||||
retry_in_s,
|
||||
"query login failed; trying again"
|
||||
);
|
||||
} else {
|
||||
debug!(
|
||||
addr = %connect.addr,
|
||||
error = %e,
|
||||
attempt,
|
||||
retry_in_s,
|
||||
"query login failed; trying again"
|
||||
);
|
||||
}
|
||||
tokio::time::sleep(retry_in).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `login` with a wrong name or password.
|
||||
const ERR_INVALID_LOGIN: u32 = 520;
|
||||
|
||||
async fn open_once(connect: &Connect, nickname: &str) -> voelin_query::Result<(QueryClient, u16)> {
|
||||
let (client, _) = QueryClient::connect(connect).await?;
|
||||
let own_id = client.own_client_id().await?;
|
||||
set_nickname(&client, nickname).await;
|
||||
Ok((client, own_id))
|
||||
}
|
||||
|
||||
/// The name is cosmetic: failing keeps the server-assigned one.
|
||||
async fn set_nickname(client: &QueryClient, nickname: &str) {
|
||||
let _ = client.send(&Command::new("clientupdate").arg("client_nickname", nickname)).await;
|
||||
}
|
||||
@@ -9,6 +9,8 @@ mod config;
|
||||
mod db;
|
||||
mod features;
|
||||
mod hub;
|
||||
mod logging;
|
||||
mod lookup;
|
||||
mod perms;
|
||||
mod session;
|
||||
mod settings;
|
||||
@@ -17,20 +19,27 @@ mod tasks;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::future::IntoFuture;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::Result;
|
||||
use axum::extract::{State, WebSocketUpgrade};
|
||||
use axum::http::{HeaderMap, header};
|
||||
use axum::response::IntoResponse;
|
||||
use anyhow::{Context, Result};
|
||||
use axum::extract::{ConnectInfo, State, WebSocketUpgrade};
|
||||
use axum::http::{HeaderMap, StatusCode, header};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::get;
|
||||
use axum::{Json, Router};
|
||||
use axum::{Extension, Json, Router};
|
||||
use clap::Parser;
|
||||
use tracing::info;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
use tokio::sync::watch;
|
||||
use tracing::{debug, info, warn};
|
||||
use voelin_query::Transport;
|
||||
|
||||
use crate::config::Bootstrap;
|
||||
use crate::hub::Hub;
|
||||
use crate::session::Peer;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(version, about)]
|
||||
@@ -44,54 +53,207 @@ struct Args {
|
||||
set: Vec<String>,
|
||||
}
|
||||
|
||||
/// How long a WebSocket connection made while the gateway starts waits for
|
||||
/// the TeamSpeak server before it is refused.
|
||||
const START_WAIT: Duration = Duration::from_secs(10);
|
||||
/// How long open connections get to close at shutdown.
|
||||
const CLOSE_WAIT: Duration = Duration::from_secs(2);
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(
|
||||
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")),
|
||||
)
|
||||
.init();
|
||||
let args = Args::parse();
|
||||
let layers = config::Layers::load(&args.config, &args.set)?;
|
||||
let bind = layers.bootstrap()?.bind;
|
||||
let hub = Hub::start(layers).await?;
|
||||
tokio::spawn(reload_on_hangup(hub.clone()));
|
||||
let listener = tokio::net::TcpListener::bind(bind).await?;
|
||||
info!(%bind, "listening");
|
||||
axum::serve(listener, router(hub)).with_graceful_shutdown(shutdown()).await?;
|
||||
let boot = layers.bootstrap()?;
|
||||
let log_file = logging::init(&boot);
|
||||
info!(
|
||||
version = env!("CARGO_PKG_VERSION"),
|
||||
config = %args.config.display(),
|
||||
bind = %boot.bind,
|
||||
public_url = boot.public_url.as_deref(),
|
||||
gateway_id = %boot.gateway_id(),
|
||||
voice_port = boot.voice_port,
|
||||
query_transport = transport_name(boot.transport),
|
||||
query_addr = %boot.addr,
|
||||
query_user = %boot.user,
|
||||
query_password = if boot.password.is_some() { "set" } else { "none" },
|
||||
allowlisted = boot.allowlisted,
|
||||
db = %boot.db_path.display(),
|
||||
log_file = log_file.as_ref().map(|p| p.display().to_string()),
|
||||
"tsgw starting"
|
||||
);
|
||||
// Listen at once: apps that come while the TeamSpeak server is not
|
||||
// reachable yet wait for it a little instead of being turned away.
|
||||
let listener = tokio::net::TcpListener::bind(boot.bind)
|
||||
.await
|
||||
.with_context(|| format!("cannot listen on {}", boot.bind))?;
|
||||
info!(
|
||||
bind = %boot.bind,
|
||||
public_url = boot.public_url.as_deref(),
|
||||
well_known = boot.public_url.as_deref().unwrap_or("ws://<host the app asked for>/v1"),
|
||||
"listening"
|
||||
);
|
||||
let app = App::new(boot);
|
||||
let service = router(app.clone()).into_make_service_with_connect_info::<SocketAddr>();
|
||||
let server = axum::serve(listener, service).with_graceful_shutdown(shutdown(app.clone()));
|
||||
let mut server = std::pin::pin!(server.into_future());
|
||||
tokio::select! {
|
||||
// Stopped before the TeamSpeak server answered.
|
||||
served = &mut server => return served.context("serving failed"),
|
||||
hub = Hub::start(layers) => {
|
||||
let hub = hub?;
|
||||
app.hub.send_replace(Some(hub.clone()));
|
||||
tokio::spawn(reload_on_hangup(hub));
|
||||
}
|
||||
}
|
||||
server.await.context("serving failed")?;
|
||||
app.closed_within(CLOSE_WAIT).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn router(hub: Arc<Hub>) -> Router {
|
||||
fn transport_name(transport: Transport) -> &'static str {
|
||||
match transport {
|
||||
Transport::Ssh => "ssh",
|
||||
Transport::Raw => "raw",
|
||||
Transport::Http => "http",
|
||||
}
|
||||
}
|
||||
|
||||
/// What the HTTP handlers share.
|
||||
pub struct App {
|
||||
boot: Bootstrap,
|
||||
/// The hub, once the gateway is logged in to the TeamSpeak server.
|
||||
hub: watch::Sender<Option<Arc<Hub>>>,
|
||||
/// Turns true at shutdown, which closes the WebSocket connections.
|
||||
stop: watch::Sender<bool>,
|
||||
/// WebSocket connections open now, and since the start.
|
||||
open: AtomicUsize,
|
||||
connections: AtomicU64,
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn new(boot: Bootstrap) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
boot,
|
||||
hub: watch::channel(None).0,
|
||||
stop: watch::channel(false).0,
|
||||
open: AtomicUsize::new(0),
|
||||
connections: AtomicU64::new(0),
|
||||
})
|
||||
}
|
||||
|
||||
/// An app for a hub that has started.
|
||||
#[cfg(test)]
|
||||
fn started(boot: Bootstrap, hub: Arc<Hub>) -> Arc<Self> {
|
||||
let app = Self::new(boot);
|
||||
app.hub.send_replace(Some(hub));
|
||||
app
|
||||
}
|
||||
|
||||
fn hub(&self) -> Option<Arc<Hub>> {
|
||||
self.hub.borrow().clone()
|
||||
}
|
||||
|
||||
/// The hub, waiting up to `wait` for it to start.
|
||||
async fn hub_within(&self, wait: Duration) -> Option<Arc<Hub>> {
|
||||
let mut hub = self.hub.subscribe();
|
||||
let started = tokio::time::timeout(wait, hub.wait_for(Option::is_some)).await;
|
||||
started.ok()?.ok()?.clone()
|
||||
}
|
||||
|
||||
/// Wait for the WebSocket connections to close, at most `wait`.
|
||||
async fn closed_within(&self, wait: Duration) {
|
||||
let deadline = Instant::now() + wait;
|
||||
while self.open.load(Ordering::Relaxed) > 0 && Instant::now() < deadline {
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn router(app: Arc<App>) -> Router {
|
||||
Router::new()
|
||||
.route("/v1", get(ws))
|
||||
.route("/health", get(|| async { "ok" }))
|
||||
.route("/health", get(health))
|
||||
.route("/.well-known/tsgw", get(well_known))
|
||||
.with_state(hub)
|
||||
.with_state(app)
|
||||
}
|
||||
|
||||
/// `ok` while the gateway is logged in to the TeamSpeak server and watching
|
||||
/// it; otherwise 503 and what is missing.
|
||||
async fn health(State(app): State<Arc<App>>) -> (StatusCode, String) {
|
||||
let Some(hub) = app.hub() else {
|
||||
let starting = "starting: not logged in to the TeamSpeak server yet";
|
||||
return (StatusCode::SERVICE_UNAVAILABLE, starting.into());
|
||||
};
|
||||
let (query, observer) = (hub.lookup.is_up(), hub.observer.is_connected());
|
||||
if query && observer {
|
||||
return (StatusCode::OK, "ok".into());
|
||||
}
|
||||
let state = |up| if up { "up" } else { "down" };
|
||||
let text = format!("query: {}, observer: {}", state(query), state(observer));
|
||||
(StatusCode::SERVICE_UNAVAILABLE, text)
|
||||
}
|
||||
|
||||
/// Where apps reach this gateway, for those that find it by asking the
|
||||
/// server's host on the default port (docs/gateway-admin.md): the
|
||||
/// configured public URL, else this listener as the request reached it.
|
||||
async fn well_known(State(hub): State<Arc<Hub>>, headers: HeaderMap) -> Json<serde_json::Value> {
|
||||
let url = hub.boot.public_url.clone().unwrap_or_else(|| {
|
||||
let host = headers.get(header::HOST).and_then(|h| h.to_str().ok()).unwrap_or("localhost");
|
||||
format!("ws://{host}/v1")
|
||||
});
|
||||
async fn well_known(State(app): State<Arc<App>>, headers: HeaderMap) -> Json<serde_json::Value> {
|
||||
let host = headers.get(header::HOST).and_then(|h| h.to_str().ok());
|
||||
let url = app
|
||||
.boot
|
||||
.public_url
|
||||
.clone()
|
||||
.unwrap_or_else(|| format!("ws://{}/v1", host.unwrap_or("localhost")));
|
||||
debug!(host, answer = %url, "asked where the gateway is");
|
||||
Json(serde_json::json!({ "url": url }))
|
||||
}
|
||||
|
||||
async fn ws(State(hub): State<Arc<Hub>>, upgrade: WebSocketUpgrade) -> impl IntoResponse {
|
||||
async fn ws(
|
||||
State(app): State<Arc<App>>,
|
||||
connect_info: Option<Extension<ConnectInfo<SocketAddr>>>,
|
||||
headers: HeaderMap,
|
||||
upgrade: WebSocketUpgrade,
|
||||
) -> Response {
|
||||
let text = |name: header::HeaderName| {
|
||||
headers.get(name).and_then(|v| v.to_str().ok()).map(str::to_owned)
|
||||
};
|
||||
let peer = Peer {
|
||||
id: app.connections.fetch_add(1, Ordering::Relaxed) + 1,
|
||||
addr: connect_info.map(|Extension(ConnectInfo(addr))| addr),
|
||||
forwarded_for: text(header::HeaderName::from_static("x-forwarded-for")),
|
||||
user_agent: text(header::USER_AGENT),
|
||||
};
|
||||
let mut stop = app.stop.subscribe();
|
||||
// Not held up by the wait at shutdown, which waits for open requests.
|
||||
let hub = tokio::select! {
|
||||
hub = app.hub_within(START_WAIT) => hub,
|
||||
_ = stop.wait_for(|stopping| *stopping) => None,
|
||||
};
|
||||
if *stop.borrow_and_update() {
|
||||
debug!(id = peer.id, peer = %peer.address(), "websocket refused: shutting down");
|
||||
return (StatusCode::SERVICE_UNAVAILABLE, "the gateway is stopping").into_response();
|
||||
}
|
||||
let Some(hub) = hub else {
|
||||
warn!(
|
||||
id = peer.id,
|
||||
peer = %peer.address(),
|
||||
"websocket refused: not logged in to the TeamSpeak server yet"
|
||||
);
|
||||
return (StatusCode::SERVICE_UNAVAILABLE, "the gateway is starting").into_response();
|
||||
};
|
||||
upgrade
|
||||
.protocols([voelin_gateway_proto::SUBPROTOCOL])
|
||||
.on_upgrade(move |socket| session::run(hub, socket))
|
||||
.on_upgrade(move |socket| async move {
|
||||
app.open.fetch_add(1, Ordering::Relaxed);
|
||||
session::run(hub, socket, peer, stop).await;
|
||||
app.open.fetch_sub(1, Ordering::Relaxed);
|
||||
})
|
||||
.into_response()
|
||||
}
|
||||
|
||||
/// `SIGHUP` reads the configuration file again.
|
||||
#[cfg(unix)]
|
||||
async fn reload_on_hangup(hub: Arc<Hub>) {
|
||||
use tokio::signal::unix::{SignalKind, signal};
|
||||
use tracing::warn;
|
||||
let Ok(mut hangup) = signal(SignalKind::hangup()) else { return };
|
||||
while hangup.recv().await.is_some() {
|
||||
if let Err(error) = hub.settings.reload() {
|
||||
@@ -103,7 +265,31 @@ async fn reload_on_hangup(hub: Arc<Hub>) {
|
||||
#[cfg(not(unix))]
|
||||
async fn reload_on_hangup(_hub: Arc<Hub>) {}
|
||||
|
||||
async fn shutdown() {
|
||||
async fn shutdown(app: Arc<App>) {
|
||||
terminated().await;
|
||||
info!(connections = app.open.load(Ordering::Relaxed), "shutting down");
|
||||
app.stop.send_replace(true);
|
||||
}
|
||||
|
||||
/// Ctrl-C, or `SIGTERM` (`systemctl stop`, `docker stop`: as the
|
||||
/// container's first process tsgw gets no default handling of it).
|
||||
#[cfg(unix)]
|
||||
async fn terminated() {
|
||||
use tokio::signal::unix::{SignalKind, signal};
|
||||
match signal(SignalKind::terminate()) {
|
||||
Ok(mut term) => {
|
||||
tokio::select! {
|
||||
_ = tokio::signal::ctrl_c() => {}
|
||||
_ = term.recv() => {}
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
async fn terminated() {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
info!("shutting down");
|
||||
}
|
||||
@@ -10,7 +10,9 @@ use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use voelin_gateway_proto::PermRule;
|
||||
use voelin_query::{Command, QueryClient, Row};
|
||||
use voelin_query::{Command, Row};
|
||||
|
||||
use crate::lookup::Lookup;
|
||||
|
||||
const CACHE_TTL: Duration = Duration::from_secs(60);
|
||||
|
||||
@@ -87,7 +89,8 @@ pub struct PermIds {
|
||||
}
|
||||
|
||||
impl PermIds {
|
||||
pub async fn load(client: &QueryClient) -> voelin_query::Result<Self> {
|
||||
/// Look the ids up. Failures are logged here or by the caller.
|
||||
pub async fn load(client: &Lookup) -> voelin_query::Result<Self> {
|
||||
let names = [
|
||||
"i_channel_join_power",
|
||||
"i_channel_needed_join_power",
|
||||
@@ -98,7 +101,8 @@ impl PermIds {
|
||||
];
|
||||
let mut ids = [0u32; 6];
|
||||
for (i, name) in names.iter().enumerate() {
|
||||
let rows = client.send(&Command::new("permidgetbyname").arg("permsid", name)).await?;
|
||||
let rows =
|
||||
client.send_quiet(&Command::new("permidgetbyname").arg("permsid", name)).await?;
|
||||
ids[i] = rows.first().and_then(|r| r.parse("permid")).ok_or_else(|| {
|
||||
voelin_query::Error::Protocol(format!("unknown permission {name}"))
|
||||
})?;
|
||||
@@ -108,8 +112,16 @@ impl PermIds {
|
||||
let mut optional = [0u32; 2];
|
||||
for (i, name) in ["b_channel_modify_name", "b_virtualserver_modify_name"].iter().enumerate()
|
||||
{
|
||||
match client.send(&Command::new("permidgetbyname").arg("permsid", name)).await {
|
||||
match client.send_quiet(&Command::new("permidgetbyname").arg("permsid", name)).await {
|
||||
Ok(rows) => optional[i] = rows.first().and_then(|r| r.parse("permid")).unwrap_or(0),
|
||||
// More commands now would get the gateway banned.
|
||||
Err(voelin_query::Error::Query(e)) if e.is_flood() => {
|
||||
tracing::warn!(
|
||||
name,
|
||||
"the server's flood protection refused looking up a permission; its default grants nobody"
|
||||
);
|
||||
break;
|
||||
}
|
||||
Err(error) => tracing::warn!(%error, name, "unknown permission"),
|
||||
}
|
||||
}
|
||||
@@ -160,7 +172,7 @@ pub struct GroupResolver {
|
||||
impl GroupResolver {
|
||||
pub async fn server_groups(
|
||||
&self,
|
||||
client: &QueryClient,
|
||||
client: &Lookup,
|
||||
cldbid: u64,
|
||||
) -> voelin_query::Result<Vec<u64>> {
|
||||
if let Some((at, groups)) = self.server.lock().unwrap().get(&cldbid)
|
||||
@@ -177,7 +189,7 @@ impl GroupResolver {
|
||||
|
||||
pub async fn channel_groups(
|
||||
&self,
|
||||
client: &QueryClient,
|
||||
client: &Lookup,
|
||||
cldbid: u64,
|
||||
cid: u64,
|
||||
) -> voelin_query::Result<Vec<u64>> {
|
||||
@@ -231,7 +243,7 @@ impl PermResolver {
|
||||
|
||||
pub async fn entries(
|
||||
&self,
|
||||
client: &QueryClient,
|
||||
client: &Lookup,
|
||||
cldbid: u64,
|
||||
cid: u64,
|
||||
) -> voelin_query::Result<Vec<Entry>> {
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
//! One WebSocket client.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use axum::extract::ws::{Message, WebSocket};
|
||||
use axum::extract::ws::{CloseFrame, Message, WebSocket, close_code};
|
||||
use base64::prelude::*;
|
||||
use rand::RngExt;
|
||||
use serde::Deserialize;
|
||||
use tokio::sync::broadcast::error::RecvError;
|
||||
use tracing::{debug, info};
|
||||
use tokio::sync::watch;
|
||||
use tracing::{Instrument, Level, debug, info, info_span, warn};
|
||||
use voelin_gateway_proto::{ClientMsg, Envelope, ErrorCode, EventInfo, ServerMsg, feature};
|
||||
use voelin_model::{ChatTarget, Presence};
|
||||
use voelin_observer::ObserverEvent;
|
||||
@@ -53,13 +55,50 @@ struct Session {
|
||||
actions: RateLimit,
|
||||
}
|
||||
|
||||
/// Enough of an envelope to answer one that did not parse.
|
||||
/// Enough of an envelope to answer one that did not parse, and to name it
|
||||
/// in the log.
|
||||
#[derive(Deserialize)]
|
||||
struct RawEnvelope {
|
||||
id: Option<u64>,
|
||||
/// Any JSON value: a `type` that is no string must not cost the `id`.
|
||||
#[serde(rename = "type")]
|
||||
kind: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
pub async fn run(hub: Arc<Hub>, mut socket: WebSocket) {
|
||||
/// Requests that take longer are logged.
|
||||
const SLOW: Duration = Duration::from_secs(1);
|
||||
|
||||
/// Where a connection comes from, for the log.
|
||||
#[derive(Debug)]
|
||||
pub struct Peer {
|
||||
/// Counts connections since the start.
|
||||
pub id: u64,
|
||||
/// The address the connection came from (a proxy's, behind one).
|
||||
pub addr: Option<SocketAddr>,
|
||||
pub forwarded_for: Option<String>,
|
||||
pub user_agent: Option<String>,
|
||||
}
|
||||
|
||||
impl Peer {
|
||||
/// [`Peer::addr`] for the log.
|
||||
pub fn address(&self) -> String {
|
||||
self.addr.map_or_else(|| "unknown".to_string(), |a| a.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Serve one connection until it closes or `stop` turns true.
|
||||
pub async fn run(hub: Arc<Hub>, socket: WebSocket, peer: Peer, stop: watch::Receiver<bool>) {
|
||||
let span = info_span!("ws", id = peer.id, peer = %peer.address());
|
||||
serve(hub, socket, peer, stop).instrument(span).await;
|
||||
}
|
||||
|
||||
async fn serve(hub: Arc<Hub>, mut socket: WebSocket, peer: Peer, mut stop: watch::Receiver<bool>) {
|
||||
let connected = Instant::now();
|
||||
info!(
|
||||
forwarded_for = peer.forwarded_for.as_deref(),
|
||||
user_agent = peer.user_agent.as_deref(),
|
||||
"websocket connected"
|
||||
);
|
||||
let nonce_bytes: [u8; 24] = rand::rng().random();
|
||||
let mut session = Session {
|
||||
nonce: BASE64_URL_SAFE_NO_PAD.encode(nonce_bytes),
|
||||
@@ -83,22 +122,29 @@ pub async fn run(hub: Arc<Hub>, mut socket: WebSocket) {
|
||||
capabilities: hub.capabilities(),
|
||||
};
|
||||
if send(&mut socket, None, hello).await.is_err() {
|
||||
info!(reason = "could not send", "websocket closed");
|
||||
return;
|
||||
}
|
||||
let mut observer = hub.observer.subscribe();
|
||||
let mut events = hub.subscribe();
|
||||
|
||||
'outer: loop {
|
||||
let reason = 'outer: loop {
|
||||
tokio::select! {
|
||||
msg = socket.recv() => {
|
||||
let Some(Ok(msg)) = msg else { break };
|
||||
let text = match msg {
|
||||
Message::Text(t) => t,
|
||||
Message::Close(_) => break,
|
||||
_ => continue,
|
||||
Some(Ok(Message::Text(t))) => t,
|
||||
Some(Ok(Message::Close(_))) => break "closed by the app".to_string(),
|
||||
Some(Ok(_)) => continue,
|
||||
Some(Err(e)) => break format!("connection failed: {e}"),
|
||||
None => break "connection ended".to_string(),
|
||||
};
|
||||
let replies = match serde_json::from_str::<Envelope<ClientMsg>>(text.as_str()) {
|
||||
Ok(env) => session.handle(env.msg).await.into_iter().map(|m| (env.id, m)).collect(),
|
||||
Ok(env) => {
|
||||
let started = Instant::now();
|
||||
let replies = session.handle(env.msg).await;
|
||||
log_request(text.as_str(), started.elapsed(), &replies);
|
||||
replies.into_iter().map(|m| (env.id, m)).collect()
|
||||
}
|
||||
Err(e) => {
|
||||
let id = serde_json::from_str::<RawEnvelope>(text.as_str()).ok().and_then(|r| r.id);
|
||||
let code = if e.to_string().starts_with("unknown variant") {
|
||||
@@ -111,18 +157,18 @@ pub async fn run(hub: Arc<Hub>, mut socket: WebSocket) {
|
||||
};
|
||||
for (id, reply) in replies {
|
||||
if send(&mut socket, id, reply).await.is_err() {
|
||||
break 'outer;
|
||||
break 'outer "could not send".to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
event = observer.recv(), if session.presence.is_some() => {
|
||||
let resync = matches!(event, Err(RecvError::Lagged(_)) | Ok(ObserverEvent::Snapshot(_)));
|
||||
if let Err(RecvError::Closed) = event {
|
||||
break;
|
||||
break "the gateway stopped".to_string();
|
||||
}
|
||||
for msg in session.presence_update(resync) {
|
||||
if send(&mut socket, None, msg).await.is_err() {
|
||||
break 'outer;
|
||||
break 'outer "could not send".to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,19 +176,59 @@ pub async fn run(hub: Arc<Hub>, mut socket: WebSocket) {
|
||||
let event = match event {
|
||||
Ok(event) => event,
|
||||
Err(RecvError::Lagged(_)) => continue,
|
||||
Err(RecvError::Closed) => break,
|
||||
Err(RecvError::Closed) => break "the gateway stopped".to_string(),
|
||||
};
|
||||
for msg in session.push(&event).await {
|
||||
if send(&mut socket, None, msg).await.is_err() {
|
||||
break 'outer;
|
||||
break 'outer "could not send".to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
// Turns true once, at shutdown.
|
||||
_ = stop.changed() => {
|
||||
// Apps connect again at once instead of finding out later.
|
||||
let frame = CloseFrame { code: close_code::AWAY, reason: "the gateway is restarting".into() };
|
||||
let _ = socket.send(Message::Close(Some(frame))).await;
|
||||
break "the gateway is shutting down".to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
info!(
|
||||
uid = session.user.as_ref().map(|u| u.uid.as_str()),
|
||||
connected_s = connected.elapsed().as_secs(),
|
||||
%reason,
|
||||
open_chats = session.open_chats.len(),
|
||||
"websocket closed"
|
||||
);
|
||||
session.close();
|
||||
}
|
||||
|
||||
/// Log a request that failed on the gateway's side or took long, and every
|
||||
/// request at debug level.
|
||||
fn log_request(text: &str, elapsed: Duration, replies: &[ServerMsg]) {
|
||||
let failure = replies.iter().find_map(|m| match m {
|
||||
ServerMsg::Error {
|
||||
code: code @ (ErrorCode::Unavailable | ErrorCode::Internal),
|
||||
message,
|
||||
} => Some((code, message.as_str())),
|
||||
_ => None,
|
||||
});
|
||||
let slow = elapsed >= SLOW;
|
||||
if !slow && failure.is_none() && !tracing::enabled!(Level::DEBUG) {
|
||||
return;
|
||||
}
|
||||
let kind = serde_json::from_str::<RawEnvelope>(text).ok().and_then(|r| r.kind);
|
||||
let request = kind.as_ref().and_then(serde_json::Value::as_str).unwrap_or("unknown");
|
||||
let elapsed_ms = elapsed.as_millis() as u64;
|
||||
match failure {
|
||||
// Logged as a refused login.
|
||||
Some(_) if matches!(request, "auth" | "resume") => {}
|
||||
Some((code, error)) => warn!(request, ?code, error, elapsed_ms, "request failed"),
|
||||
None if slow => warn!(request, elapsed_ms, "slow request"),
|
||||
None => debug!(request, elapsed_ms, "request"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn send(socket: &mut WebSocket, id: Option<u64>, msg: ServerMsg) -> Result<(), axum::Error> {
|
||||
let env = Envelope { v: voelin_gateway_proto::VERSION, id, msg };
|
||||
let text = serde_json::to_string(&env).expect("messages serialize");
|
||||
@@ -175,9 +261,21 @@ fn is_action(msg: &ClientMsg) -> bool {
|
||||
|
||||
impl Session {
|
||||
async fn handle(&mut self, msg: ClientMsg) -> Vec<ServerMsg> {
|
||||
let login = match &msg {
|
||||
ClientMsg::Auth { .. } => Some("signature"),
|
||||
ClientMsg::Resume { .. } => Some("token"),
|
||||
_ => None,
|
||||
};
|
||||
let started = Instant::now();
|
||||
match self.handle_inner(msg).await {
|
||||
Ok(msgs) => msgs,
|
||||
Err(Denied(code, message)) => vec![error(code, &message)],
|
||||
Err(Denied(code, message)) => {
|
||||
if let Some(via) = login {
|
||||
let elapsed_ms = started.elapsed().as_millis() as u64;
|
||||
warn!(?code, %message, via, elapsed_ms, "login refused");
|
||||
}
|
||||
vec![error(code, &message)]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,14 +301,15 @@ impl Session {
|
||||
match msg {
|
||||
ClientMsg::Ping => Ok(vec![ServerMsg::Pong]),
|
||||
ClientMsg::Auth { omega, key_offset, ts, signature, .. } => {
|
||||
let started = Instant::now();
|
||||
let (user, token, token_expires) =
|
||||
hub.authenticate(&omega, key_offset, ts, &signature, &self.nonce).await?;
|
||||
info!(uid = %user.uid, nickname = %user.nickname, "user logged in");
|
||||
self.logged_in(user, token, token_expires).await
|
||||
self.logged_in(user, token, token_expires, "signature", started).await
|
||||
}
|
||||
ClientMsg::Resume { token, .. } => {
|
||||
let started = Instant::now();
|
||||
let (user, token, token_expires) = hub.resume(&token).await?;
|
||||
self.logged_in(user, token, token_expires).await
|
||||
self.logged_in(user, token, token_expires, "token", started).await
|
||||
}
|
||||
ClientMsg::SubscribePresence => {
|
||||
self.user()?;
|
||||
@@ -437,9 +536,13 @@ impl Session {
|
||||
user: User,
|
||||
token: String,
|
||||
token_expires: i64,
|
||||
via: &str,
|
||||
started: Instant,
|
||||
) -> Result<Vec<ServerMsg>, Denied> {
|
||||
let capabilities = self.hub.user_capabilities(&user).await;
|
||||
let uid = user.uid.clone();
|
||||
let elapsed_ms = started.elapsed().as_millis() as u64;
|
||||
info!(uid = %user.uid, nickname = %user.nickname, via, elapsed_ms, "user logged in");
|
||||
self.user = Some(user);
|
||||
Ok(vec![ServerMsg::AuthOk { uid, token, token_expires, capabilities }])
|
||||
}
|
||||
@@ -571,3 +674,16 @@ impl Session {
|
||||
self.hub.session_streams_closed(&self.own_streams);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_bad_request_keeps_its_id() {
|
||||
let raw = |text: &str| serde_json::from_str::<RawEnvelope>(text).unwrap();
|
||||
assert_eq!(raw(r#"{"id":7,"type":5}"#).id, Some(7));
|
||||
assert_eq!(raw(r#"{"id":8,"type":"ping","extra":[]}"#).id, Some(8));
|
||||
assert_eq!(raw(r#"{"type":"ping"}"#).id, None);
|
||||
}
|
||||
}
|
||||
@@ -81,8 +81,12 @@ pub async fn pump_relays(hub: Arc<Hub>, mut events: broadcast::Receiver<RelayEve
|
||||
hub.publish_incoming(msg);
|
||||
}
|
||||
}
|
||||
Ok(RelayEvent::Closed { channel, reason }) => {
|
||||
warn!(channel, %reason, "relay closed");
|
||||
// Logged by the pool.
|
||||
Ok(RelayEvent::Closed { channel, .. }) => {
|
||||
if hub.relay_wanted(channel) {
|
||||
let hub = hub.clone();
|
||||
tokio::spawn(async move { hub.reopen_relay(channel).await });
|
||||
}
|
||||
}
|
||||
Err(RecvError::Lagged(_)) => {}
|
||||
Err(RecvError::Closed) => return,
|
||||
@@ -196,7 +200,7 @@ async fn apply_settings(hub: Arc<Hub>) {
|
||||
hub.rebuild_relays(&new.relay.nickname).await;
|
||||
}
|
||||
if new.relay.pinned_channels != old.relay.pinned_channels {
|
||||
hub.apply_pinned_channels(&old.relay.pinned_channels, &new.relay.pinned_channels).await;
|
||||
hub.apply_pinned_channels(&old.relay.pinned_channels, &new.relay.pinned_channels);
|
||||
}
|
||||
let features_changed = Feature::ALL.iter().any(|f| f.enabled(&old) != f.enabled(&new));
|
||||
if features_changed || new.perm.admin != old.perm.admin {
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::sync::{Arc, Mutex};
|
||||
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::{broadcast, mpsc};
|
||||
use voelin_query::{Command, escape};
|
||||
|
||||
/// Permission ids the fake server uses.
|
||||
@@ -49,19 +49,29 @@ pub struct State {
|
||||
pub server_groups: HashMap<u64, Vec<u64>>,
|
||||
/// (target mode, channel of the posting connection, text)
|
||||
pub posted: Vec<(u8, u64, String)>,
|
||||
/// The nickname of the posting connection, for each of `posted`.
|
||||
pub posters: Vec<String>,
|
||||
/// Nicknames set with clientupdate.
|
||||
pub nicknames: Vec<String>,
|
||||
/// The current nickname of each query connection.
|
||||
names: HashMap<u16, String>,
|
||||
/// Connections that registered for server events (the observer).
|
||||
observers: Vec<mpsc::UnboundedSender<String>>,
|
||||
/// Relay connections by channel.
|
||||
relays: Vec<(u64, mpsc::UnboundedSender<String>)>,
|
||||
next_clid: u16,
|
||||
/// Permission lookups (`permsid`) to refuse for flooding, and how often.
|
||||
refusals: HashMap<String, usize>,
|
||||
/// The commands received, in order (`login` left out).
|
||||
commands: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct FakeServer {
|
||||
pub addr: SocketAddr,
|
||||
pub state: Arc<Mutex<State>>,
|
||||
/// Ends every open connection, like a server restart.
|
||||
kick: broadcast::Sender<()>,
|
||||
}
|
||||
|
||||
impl FakeServer {
|
||||
@@ -69,7 +79,7 @@ impl FakeServer {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let state = Arc::new(Mutex::new(State { next_clid: 100, ..Default::default() }));
|
||||
let server = Self { addr, state };
|
||||
let server = Self { addr, state, kick: broadcast::channel(1).0 };
|
||||
let s = server.clone();
|
||||
tokio::spawn(async move {
|
||||
while let Ok((stream, _)) = listener.accept().await {
|
||||
@@ -116,14 +126,50 @@ impl FakeServer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Answer looking up permission `permsid` with the flood protection's
|
||||
/// refusal, the next `times` times.
|
||||
pub fn refuse(&self, permsid: &str, times: usize) {
|
||||
self.state.lock().unwrap().refusals.insert(permsid.to_string(), times);
|
||||
}
|
||||
|
||||
/// The commands received so far, in order (`login` left out).
|
||||
pub fn commands(&self) -> Vec<String> {
|
||||
self.state.lock().unwrap().commands.clone()
|
||||
}
|
||||
|
||||
/// An observer connection is registered for server events.
|
||||
pub fn observed(&self) -> bool {
|
||||
!self.state.lock().unwrap().observers.is_empty()
|
||||
}
|
||||
|
||||
/// Channels with a relay listening.
|
||||
pub fn relayed_channels(&self) -> Vec<u64> {
|
||||
self.state.lock().unwrap().relays.iter().map(|(c, _)| *c).collect()
|
||||
}
|
||||
|
||||
/// Drop every query connection, as a restarting server does.
|
||||
pub fn drop_connections(&self) {
|
||||
let mut s = self.state.lock().unwrap();
|
||||
s.observers.clear();
|
||||
s.relays.clear();
|
||||
let _ = self.kick.send(());
|
||||
}
|
||||
|
||||
pub fn posted(&self) -> Vec<(u8, u64, String)> {
|
||||
self.state.lock().unwrap().posted.clone()
|
||||
}
|
||||
|
||||
/// What was posted as `(nickname of the poster, text)`.
|
||||
pub fn posted_by(&self) -> Vec<(String, String)> {
|
||||
let s = self.state.lock().unwrap();
|
||||
s.posters.iter().cloned().zip(s.posted.iter().map(|p| p.2.clone())).collect()
|
||||
}
|
||||
|
||||
async fn connection(self, stream: tokio::net::TcpStream) {
|
||||
let (r, mut w) = stream.into_split();
|
||||
let mut lines = BufReader::new(r).lines();
|
||||
let (tx, mut rx) = mpsc::unbounded_channel::<String>();
|
||||
let mut kicked = self.kick.subscribe();
|
||||
let clid = {
|
||||
let mut s = self.state.lock().unwrap();
|
||||
s.next_clid += 1;
|
||||
@@ -138,6 +184,9 @@ impl FakeServer {
|
||||
line = lines.next_line() => {
|
||||
let Ok(Some(line)) = line else { return };
|
||||
let Some(cmd) = Command::parse(&line) else { continue };
|
||||
if cmd.name != "login" {
|
||||
self.state.lock().unwrap().commands.push(line.clone());
|
||||
}
|
||||
let reply = self.answer(&cmd, clid, &mut channel, &tx);
|
||||
if w.write_all(reply.as_bytes()).await.is_err() {
|
||||
return;
|
||||
@@ -148,6 +197,7 @@ impl FakeServer {
|
||||
return;
|
||||
}
|
||||
}
|
||||
_ = kicked.recv() => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -184,6 +234,12 @@ impl FakeServer {
|
||||
]),
|
||||
"permidgetbyname" => {
|
||||
let name = arg("permsid").unwrap_or_default();
|
||||
if let Some(left @ 1..) = s.refusals.get_mut(&name) {
|
||||
*left -= 1;
|
||||
return "error id=524 msg=client\\sis\\sflooding \
|
||||
extra_msg=please\\swait\\s1\\sseconds\n\r"
|
||||
.into();
|
||||
}
|
||||
match PERMS.iter().find(|(n, _)| *n == name) {
|
||||
Some((_, id)) => data(vec![format!("permsid={name} permid={id}")]),
|
||||
None => "error id=2 msg=invalid\\spermission\n\r".into(),
|
||||
@@ -192,6 +248,12 @@ impl FakeServer {
|
||||
"whoami" => data(vec![format!("client_id={clid} client_channel_id={channel}")]),
|
||||
"clientupdate" => {
|
||||
if let Some(nick) = arg("client_nickname") {
|
||||
let in_use = s.online.iter().any(|c| c.nickname == nick)
|
||||
|| s.names.iter().any(|(id, n)| *id != clid && *n == nick);
|
||||
if in_use {
|
||||
return "error id=513 msg=nickname\\sis\\salready\\sin\\suse\n\r".into();
|
||||
}
|
||||
s.names.insert(clid, nick.clone());
|
||||
s.nicknames.push(nick);
|
||||
}
|
||||
ok
|
||||
@@ -262,6 +324,8 @@ impl FakeServer {
|
||||
"sendtextmessage" => {
|
||||
let mode = num("targetmode") as u8;
|
||||
s.posted.push((mode, *channel, arg("msg").unwrap_or_default()));
|
||||
let poster = s.names.get(&clid).cloned().unwrap_or_default();
|
||||
s.posters.push(poster);
|
||||
ok
|
||||
}
|
||||
_ => ok,
|
||||
|
||||
@@ -26,6 +26,7 @@ const LOBBY: ChatTarget = ChatTarget::Channel(1);
|
||||
|
||||
struct Fixture {
|
||||
fake: FakeServer,
|
||||
boot: crate::config::Bootstrap,
|
||||
hub: Arc<Hub>,
|
||||
url: String,
|
||||
dir: std::path::PathBuf,
|
||||
@@ -80,6 +81,7 @@ impl Fixture {
|
||||
});
|
||||
}
|
||||
let layers = Layers { file: file_values(&toml).unwrap(), ..Default::default() };
|
||||
let boot = layers.bootstrap().unwrap();
|
||||
let hub = Hub::start(layers).await.unwrap();
|
||||
// Wait for the observer's first snapshot.
|
||||
for _ in 0..100 {
|
||||
@@ -90,9 +92,10 @@ impl Fixture {
|
||||
}
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("ws://{}/v1", listener.local_addr().unwrap());
|
||||
let app = crate::router(hub.clone());
|
||||
let app = crate::router(crate::App::started(boot.clone(), hub.clone()))
|
||||
.into_make_service_with_connect_info::<std::net::SocketAddr>();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await });
|
||||
Self { fake, hub, url, dir, people }
|
||||
Self { fake, boot, hub, url, dir, people }
|
||||
}
|
||||
|
||||
fn people(&self) -> (&Person, &Person, &Person) {
|
||||
@@ -173,7 +176,11 @@ async fn chat_pins_reactions_topics() {
|
||||
unreachable!()
|
||||
};
|
||||
assert_eq!((id, message.text.as_str()), (hello.id, "hello"));
|
||||
assert!(fx.fake.posted().contains(&(2, 1, "[Bob] hello".into())));
|
||||
// Under Bob's name: "Bob1", as Bob is online with voice as "Bob". The
|
||||
// relay takes its own name back after the post.
|
||||
assert!(fx.fake.posted().contains(&(2, 1, "hello".into())));
|
||||
assert!(fx.fake.posted_by().contains(&("Bob1".into(), "hello".into())));
|
||||
assert_eq!(fx.fake.state.lock().unwrap().nicknames.last().unwrap(), "Chat Relay 1");
|
||||
|
||||
// Pins: moderators only by default; Alice is an admin.
|
||||
assert_eq!(code(b.pin(hello.id).await), ErrorCode::Forbidden);
|
||||
@@ -213,7 +220,7 @@ async fn chat_pins_reactions_topics() {
|
||||
assert_eq!(t.id, topic.id);
|
||||
let in_topic = b.post(LOBBY, "saturday?".into(), Some(topic.id)).await.unwrap();
|
||||
assert_eq!(in_topic.topic_id, Some(topic.id));
|
||||
assert!(fx.fake.posted().contains(&(2, 1, "[Bob] [#Plans] saturday?".into())));
|
||||
assert!(fx.fake.posted_by().contains(&("Bob1".into(), "[#Plans] saturday?".into())));
|
||||
expect(
|
||||
&mut c_rx,
|
||||
"prefixed chat event",
|
||||
@@ -456,7 +463,7 @@ async fn admin_settings_apply_live() {
|
||||
|
||||
// Feature switches reach connected clients at once.
|
||||
let first = b.post(LOBBY, "one".into(), None).await.unwrap();
|
||||
assert!(fx.fake.posted().contains(&(2, 1, "<Bob> one".into())));
|
||||
assert!(fx.fake.posted_by().contains(&("Bob1".into(), "one".into())));
|
||||
let entry = a.config_set("features.pins".into(), json!(false)).await.unwrap();
|
||||
assert_eq!(entry.source, voelin_gateway_proto::ConfigSource::Db);
|
||||
expect(
|
||||
@@ -506,10 +513,22 @@ async fn admin_settings_apply_live() {
|
||||
// 0: no limit.
|
||||
a.config_set("limits.posts_per_window".into(), json!(0)).await.unwrap();
|
||||
|
||||
// Relay settings apply without a restart.
|
||||
// Relay settings apply without a restart. The format is for posts the
|
||||
// relay cannot make under Bob's name: every variant of it is taken.
|
||||
for (clid, nick) in [(21, "Bob1"), (22, "Bob2"), (23, "Bob3")] {
|
||||
fx.fake.add_online(Online {
|
||||
clid,
|
||||
cid: 2,
|
||||
uid: format!("other-{nick}"),
|
||||
nickname: nick.into(),
|
||||
server_groups: Vec::new(),
|
||||
streaming: false,
|
||||
});
|
||||
}
|
||||
a.config_set("relay.format".into(), json!("{nick}: {text}")).await.unwrap();
|
||||
b.post(LOBBY, "two".into(), None).await.unwrap();
|
||||
assert!(fx.fake.posted().contains(&(2, 1, "Bob: two".into())));
|
||||
assert!(fx.fake.posted_by().contains(&("Chat Relay 1".into(), "Bob: two".into())));
|
||||
a.config_set("relay.nickname".into(), json!("Bridge")).await.unwrap();
|
||||
for _ in 0..100 {
|
||||
if fx.fake.state.lock().unwrap().nicknames.iter().any(|n| n == "Bridge 1") {
|
||||
@@ -567,3 +586,100 @@ async fn tells_apps_where_it_is() {
|
||||
let fx = Fixture::start("well-known-public", public).await;
|
||||
assert_eq!(well_known(&fx).await, "wss://gw.example.test/v1");
|
||||
}
|
||||
|
||||
/// The TeamSpeak server drops the gateway's query connections (a restart):
|
||||
/// logins go on working, through a new lookup connection.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn logins_work_after_the_server_dropped_the_gateway() {
|
||||
let fx = Fixture::start("reconnect", "").await;
|
||||
let (alice, bob, _) = fx.people();
|
||||
let (b, mut b_rx) = bob.connect(&fx).await;
|
||||
b.open_chat(LOBBY).await.unwrap();
|
||||
b.open_chat(ChatTarget::Server).await.unwrap();
|
||||
assert!(fx.hub.lookup.is_up());
|
||||
let old_id = fx.hub.lookup.own_id().unwrap();
|
||||
fx.fake.drop_connections();
|
||||
// At once: the login waits for the new connection.
|
||||
let (a, _a_rx) = alice.connect(&fx).await;
|
||||
assert!(a.has(feature::ADMIN));
|
||||
assert!(fx.hub.lookup.is_up());
|
||||
a.post(ChatTarget::Server, "back again".into(), None).await.unwrap();
|
||||
assert!(fx.fake.posted().contains(&(3, 1, "back again".into())));
|
||||
|
||||
// Bob still reads the lobby: its relay comes back.
|
||||
for _ in 0..100 {
|
||||
if fx.fake.relayed_channels().contains(&1) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
fx.fake.say_in_channel(1, "Dave", "dave", "after the restart");
|
||||
expect(
|
||||
&mut b_rx,
|
||||
"relayed after the restart",
|
||||
|p| matches!(p, Push::Chat { message, .. } if message.text == "after the restart"),
|
||||
)
|
||||
.await;
|
||||
|
||||
// A restarted server hands out client ids from 1 again: a user may get
|
||||
// the one the gateway had. Their server chat is not the gateway's own.
|
||||
assert_ne!(fx.hub.lookup.own_id(), Some(old_id));
|
||||
for _ in 0..100 {
|
||||
if fx.fake.observed() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
fx.fake.notify_observers(&format!(
|
||||
"notifytextmessage targetmode=3 msg=hi\\sall invokerid={old_id} invokername=Erin \
|
||||
invokeruid=erin"
|
||||
));
|
||||
expect(
|
||||
&mut b_rx,
|
||||
"server chat from the gateway's old id",
|
||||
|p| matches!(p, Push::Chat { message, .. } if message.text == "hi all"),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// The server's flood protection refuses looking up an optional permission,
|
||||
/// also when asked again after the wait: the gateway asks for no more, which
|
||||
/// would get it banned for 10 minutes.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn optional_permissions_stop_at_the_flood_protection() {
|
||||
let fake = FakeServer::start().await;
|
||||
fake.refuse("b_channel_modify_name", 2);
|
||||
let connect = voelin_query::Connect {
|
||||
transport: voelin_query::Transport::Raw,
|
||||
addr: fake.addr.to_string(),
|
||||
user: "serveradmin".into(),
|
||||
secret: None,
|
||||
server_port: None,
|
||||
server_id: None,
|
||||
// Taken to be on the allowlist.
|
||||
line: voelin_query::LineOptions { rate_limit: None, ..Default::default() },
|
||||
};
|
||||
let lookup = crate::lookup::Lookup::open(connect, "Gateway".into()).await;
|
||||
let ids = crate::perms::PermIds::load(&lookup).await.unwrap();
|
||||
assert_eq!(ids.subscribe_power, fake::SUBSCRIBE_POWER);
|
||||
assert_eq!((ids.channel_modify_name, ids.server_modify_name), (0, 0));
|
||||
let asked = fake.commands();
|
||||
let count =
|
||||
|name: &str| asked.iter().filter(|c| c.ends_with(&format!("permsid={name}"))).count();
|
||||
assert_eq!(count("b_channel_modify_name"), 2, "{asked:?}");
|
||||
assert_eq!(count("b_virtualserver_modify_name"), 0, "{asked:?}");
|
||||
}
|
||||
|
||||
/// `/health` says what is missing until the gateway is logged in.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn health_tells_whether_the_gateway_is_up() {
|
||||
use axum::extract::State;
|
||||
use axum::http::StatusCode;
|
||||
let fx = Fixture::start("health", "").await;
|
||||
let app = crate::App::started(fx.boot.clone(), fx.hub.clone());
|
||||
assert_eq!(crate::health(State(app)).await, (StatusCode::OK, "ok".to_string()));
|
||||
let starting = crate::App::new(fx.boot.clone());
|
||||
let (status, text) = crate::health(State(starting)).await;
|
||||
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
|
||||
assert!(text.starts_with("starting"), "{text}");
|
||||
}
|
||||
@@ -33,6 +33,14 @@ allowlisted = false
|
||||
bind = "0.0.0.0:7788"
|
||||
# public_url = "wss://gw.example.org/v1"
|
||||
|
||||
# BOOTSTRAP. The log goes to standard output (journalctl -u tsgw, docker logs).
|
||||
# Uncomment to change it; tsgw versions before these keys refuse the section.
|
||||
# [log]
|
||||
# What to log (TSGW_LOG_LEVEL); default: RUST_LOG, else info.
|
||||
# level = "info,voelin_query=trace"
|
||||
# Also write it to this file: appended, moved aside at 20 MB, 5 files kept.
|
||||
# file = "logs/tsgw.log"
|
||||
|
||||
[auth]
|
||||
# Only these server groups may use the gateway (empty: everyone known to the server).
|
||||
require_server_groups = []
|
||||
@@ -42,6 +50,8 @@ token_ttl_hours = 720
|
||||
|
||||
[relay]
|
||||
nickname = "Chat Relay"
|
||||
# Posts go out under the user's nickname; this form only when the relay
|
||||
# cannot take it.
|
||||
format = "[{nick}] {text}"
|
||||
idle_teardown_secs = 120
|
||||
# Each relay is one query connection; stay below the server's per-IP limit.
|
||||
|
||||
Loaded 100 of 284 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user