init
This commit is contained in:
247 files changed
+35538
No files matched your search
@@ -0,0 +1,18 @@
|
|||||||
|
# Deployment/operator settings only. Enter TeamSpeak connections in the signed-in app.
|
||||||
|
APP_ORIGIN=http://localhost:3000
|
||||||
|
# Optional reserved owner login; preserve an existing value. Generate with npm run owner:hash.
|
||||||
|
OWNER_PASSWORD_HASH=
|
||||||
|
# Public signup: 1 enables registration; 0 closes signup without disabling existing accounts.
|
||||||
|
ALLOW_REGISTRATION=1
|
||||||
|
# Generate once: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
|
||||||
|
SESSION_SECRET=
|
||||||
|
# Required in production: one complete owner-controlled Redis REST credential pair.
|
||||||
|
UPSTASH_REDIS_REST_URL=
|
||||||
|
UPSTASH_REDIS_REST_TOKEN=
|
||||||
|
# Vercel Marketplace KV_REST_API_URL + KV_REST_API_TOKEN are also supported.
|
||||||
|
# Development only; rejected in production. Redis is required for persistence.
|
||||||
|
ALLOW_LOCAL_MEMORY_STORE=1
|
||||||
|
# Generate once with npm run identity:key. Preserve across redeployments.
|
||||||
|
IDENTITY_ENCRYPTION_KEY=
|
||||||
|
# Only during explicit key rotation; see docs/IDENTITY.md.
|
||||||
|
IDENTITY_PREVIOUS_ENCRYPTION_KEY=
|
||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
# Private configuration and runtime data
|
||||||
|
.env*
|
||||||
|
!.env.example
|
||||||
|
.local/
|
||||||
|
.vercel/
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.code-workspace
|
||||||
|
.DS_Store
|
||||||
|
*.log
|
||||||
|
coverage/
|
||||||
|
evidence/
|
||||||
|
docs/verification/
|
||||||
|
# Reproducible dependencies and builds
|
||||||
|
**/node_modules/
|
||||||
|
**/target/
|
||||||
|
native/bin/
|
||||||
|
# Upstream editor/CI metadata is not needed to build vendored libraries
|
||||||
|
native/vendor/**/.*
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
.git/
|
||||||
|
.env*
|
||||||
|
!.env.example
|
||||||
|
.local/
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
node_modules/
|
||||||
|
native/target/
|
||||||
|
native/bin/
|
||||||
|
tests/
|
||||||
|
docs/verification/
|
||||||
|
coverage/
|
||||||
|
evidence/
|
||||||
|
*.log
|
||||||
|
.DS_Store
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
# VoxHarbor agent guide
|
||||||
|
|
||||||
|
## Git and GitHub: strictly read-only
|
||||||
|
|
||||||
|
Use Git and GitHub only to inspect information. Leave project file changes uncommitted.
|
||||||
|
|
||||||
|
- Allowed: read status, diffs, logs, commits, branches, tags, remotes, pull requests, issues, releases, and Actions runs/checks/logs.
|
||||||
|
- Never stage, commit, push, pull, fetch, merge, rebase, reset, restore, clean, stash, switch branches, create/delete branches or tags, manage worktrees, change Git configuration, or modify Git metadata directly.
|
||||||
|
- Never create, edit, close, merge, approve, comment on, or delete GitHub resources. Never trigger, rerun, cancel, or modify GitHub workflows or deployments.
|
||||||
|
- `gh api` may perform read operations only. GraphQL queries are allowed; mutations are forbidden. HTTP POST is allowed only for a read-only GraphQL query.
|
||||||
|
- Do not bypass these restrictions through scripts, libraries, integrations, or the browser. If prohibited work is necessary, explain the manual step for the user.
|
||||||
|
|
||||||
|
A source upload to the operator's existing Vercel project is separate from GitHub operations. Perform it only within the user's deployment authorization.
|
||||||
|
|
||||||
|
## Start with the existing project
|
||||||
|
|
||||||
|
Continue the existing implementation; do not restart it, replace it with a scaffold, or overwrite unrelated work. Inspect current files and read:
|
||||||
|
|
||||||
|
1. `IMPLEMENTATION_PLAN.md` and `README.md`.
|
||||||
|
2. `docs/FEASIBILITY.md` and `docs/AUDIO.md`.
|
||||||
|
3. `docs/MANUAL_DEPLOYMENT.md` before packaging or deployment.
|
||||||
|
4. The relevant detailed documents: `docs/ARCHITECTURE.md`, `docs/MULTIUSER.md`, `docs/WORKSPACE.md`, `docs/DESIGN_IMPLEMENTATION.md`, `docs/FEATURE_MATRIX.md`, and `docs/TESTING.md`.
|
||||||
|
|
||||||
|
Use source code and current checks to establish behavior. Documentation and old deployment reports can describe historical results; do not turn them into claims that the current release was tested. Keep the implementation plan and feature matrix honest about unfinished work.
|
||||||
|
|
||||||
|
## Product and architecture
|
||||||
|
|
||||||
|
VoxHarbor is an experimental, self-hosted TeamSpeak 3 browser client with separate application accounts. Each account owns its identity, nickname, encrypted connections/bookmarks, preferences, and protocol lease. Application accounts are distinct from TeamSpeak identities and vendor accounts. One active native server session per account is supported; server permissions remain authoritative.
|
||||||
|
|
||||||
|
Application compute belongs in the operator's Vercel deployment, with durable operator-controlled Redis storage. Preserve the full-client TS3 protocol architecture. ServerQuery alone is not a voice client. Do not silently introduce a VPS, vendor gateway, desktop companion, or shared central account service.
|
||||||
|
|
||||||
|
| Location | Responsibility |
|
||||||
|
| --- | --- |
|
||||||
|
| `api/server.mjs` | Deployment entry point |
|
||||||
|
| `src/http-adapter.mjs` | HTTP routes, static asset allowlist, security headers, WebSocket upgrades |
|
||||||
|
| `src/auth/` | Accounts, password hashing, sessions, storage, authenticated user context |
|
||||||
|
| `src/identity/vault.mjs`, `src/preferences.mjs` | Encrypted identities, connections and bookmarks |
|
||||||
|
| `src/protocol/`, `src/platform/`, `src/transport/` | Typed commands/events, native sessions, leases and destination policy |
|
||||||
|
| `native/src/` | Rust full-client protocol adapter |
|
||||||
|
| `native/vendor/` | Pinned upstream sources and notices |
|
||||||
|
| `public/app.mjs` | Authentication and diagnostic export |
|
||||||
|
| `public/workspace.mjs`, `public/workspace-model.mjs` | Page navigation, destinations, channels, participants and conversations |
|
||||||
|
| `public/protocol.mjs`, `public/protocol-connection.mjs` | Browser protocol integration, commands and bounded reconnection |
|
||||||
|
| `public/voice*.mjs`, `public/audio-recovery.mjs`, `public/jitter-buffer.mjs` | Capture/playback, Opus workers/worklets and audio recovery |
|
||||||
|
| `tests/`, `scripts/` | Automated tests, synthetic fixtures, development and packaging utilities |
|
||||||
|
|
||||||
|
Use the existing vanilla HTML/CSS/browser ES module stack and Node.js 22 backend. Match nearby JavaScript conventions: `.mjs`, two-space indentation, single quotes and semicolons. Follow existing Rust conventions. Keep protocol logic separate from interface rendering. TeamSpeak channel ordering uses the preceding sibling ID; reuse `public/channel-order.mjs` instead of sorting the order field as a numeric rank. Preserve third-party licenses and record vendor patches explicitly.
|
||||||
|
|
||||||
|
## Account, storage and privacy invariants
|
||||||
|
|
||||||
|
- Derive workspace ownership from the authenticated session, never from a browser-supplied account ID. Preserve account-scoped storage keys, encryption associated data, leases and rate limits.
|
||||||
|
- Preserve the reserved legacy `owner` account and its original encrypted records. Do not migrate or replace them merely to change the interface.
|
||||||
|
- Keep HTTP/WebSocket authentication, origin validation, CSRF checks, secure cookies, destination validation and bounded inputs/queues intact.
|
||||||
|
- Connections and credentials belong on the backend. Reconnect using an opaque saved-settings ID. Never hardcode real servers, channels, nicknames, passwords, UIDs, or account data into source or product examples.
|
||||||
|
- Ordinary responses redact passwords and private identity material. Blank saved passwords preserve credentials only for the same destination; explicit clearing removes them. Distinguish current-connection recovery credentials from optional bookmark password storage.
|
||||||
|
- Preserve existing environment values, Redis data and identities. Never regenerate an identity after a storage/decryption error or rotate encryption/session secrets as routine troubleshooting.
|
||||||
|
- `.env.local`, `.local/`, identity exports, credentials, cookies, private screenshots/logs and recordings must stay outside public source and upload packages. Never print secret values or copy private evidence into documentation.
|
||||||
|
- Render server names, participant names and messages as literal text. Keep drafts separated by conversation. Preserve recipient ID/UID checks and asynchronous account/generation guards. Never automatically resend unconfirmed messages or commands.
|
||||||
|
|
||||||
|
Read `SECURITY.md`, `docs/PUBLICATION.md` and `THIRD_PARTY_NOTICES.md` when changing security, distribution or dependencies.
|
||||||
|
|
||||||
|
## UX and design requirements
|
||||||
|
|
||||||
|
Implement the supplied design's page structure, sectioning and interactions, not just its colors and typography. Follow `docs/DESIGN_IMPLEMENTATION.md` and inspect the relevant design screens before interface changes.
|
||||||
|
|
||||||
|
- Connections is the starting page after sign-in. Saved destinations need visible, direct connection and editing actions.
|
||||||
|
- Keep the complete connection form together. Save returns to the list; Save & connect saves first and opens the console. Protect unsaved edits and preserve clear password semantics.
|
||||||
|
- The console represents the actual joined room. Its recent-room strip is capped at four; never squeeze the full server hierarchy into horizontal tabs.
|
||||||
|
- The Channels page provides hierarchy, parent paths, occupancy, room/participant search and a separate preview/join flow. Previewing must not move the user or redirect channel messages.
|
||||||
|
- Private conversations, identity, audio, presence and diagnostics are separate pages. Use dialogs for short confirmations and pokes, not as the main page architecture.
|
||||||
|
- Page navigation must preserve the live connection and audio choices. Keep connection/transmission state understandable outside the console. Browser Back/Forward and Skip to content must work without unexpected navigation or data loss.
|
||||||
|
- Adapt phone workflows, not just widths: complete form before save actions, usable channel previews, bounded lists, compact participants and accessible voice controls.
|
||||||
|
- Use genuine account/server data in product flows. Keep simulated people, destinations and messages confined to clearly identified test fixtures. Do not add controls for unimplemented capabilities.
|
||||||
|
|
||||||
|
New public modules, fonts and icons require explicit routes in `src/http-adapter.mjs`. Keep its content security policy consistent with `vercel.json`; prefer local assets and retain their licenses. Verify actual page transitions and representative desktop/phone layouts in the browser.
|
||||||
|
|
||||||
|
## Audio and recovery invariants
|
||||||
|
|
||||||
|
New sessions start with listening and microphone off. Listening may resume after automatic recovery if previously enabled; microphone recovery requires explicit opt-in and a previously enabled microphone. Choices live only in the signed-in page and clear on reload/sign-out. Never restore a held push-to-talk press.
|
||||||
|
|
||||||
|
Hidden pages, device loss and sign-out stop transmission. Successful channel changes turn audio off; a denied join preserves the current channel/audio. Pending permission or initialization work must not resurrect a stopped audio instance. Preserve codec validation, per-speaker volume bounds, jitter buffering and backpressure.
|
||||||
|
|
||||||
|
The native session cap is currently 240 seconds, inside a 300-second Function limit. Periodic reconnects can therefore be intentional. Use bounded, privacy-filtered diagnostics to distinguish session caps, transport loss, heartbeat timeouts and server errors. Do not log credentials, destinations, identities, message contents or media.
|
||||||
|
|
||||||
|
## Development and verification
|
||||||
|
|
||||||
|
| Command | Purpose |
|
||||||
|
| --- | --- |
|
||||||
|
| `npm ci` | Install locked JavaScript dependencies |
|
||||||
|
| `npm run native:build` | Prepare audio assets and build the native adapter |
|
||||||
|
| `npm run dev` | Start local development using existing `.env.local` |
|
||||||
|
| `npm run check` | JavaScript syntax checks; not a formatter, type checker or full verification |
|
||||||
|
| `npm test` | Node's built-in test suite |
|
||||||
|
| `npm run audio:qa` | Separate silent browser audio fixture |
|
||||||
|
| `npm run publication:check` | Audit public-source candidates without changing Git state |
|
||||||
|
| `npm run deployment:package` | Create an audited clean deployment folder |
|
||||||
|
| `npm run publication:package` | Create an audited public-source folder; does not push |
|
||||||
|
|
||||||
|
`owner:setup` and `identity:key` are installation/bootstrap tools. Do not run them against an existing setup as ordinary development preparation. The development memory store is volatile; never treat its accounts or identities as durable production records.
|
||||||
|
|
||||||
|
Use `node:test` in `tests/*.test.mjs` with synthetic secrets, temporary files, local sockets and simulated adapters. Add meaningful coverage for changed behavior. Run syntax checks and relevant tests for code changes, native builds for native changes, and browser/audio checks when those flows change. Documentation-only edits need reference/content checks rather than an unrelated full build. Report actual results, not a remembered test count.
|
||||||
|
|
||||||
|
For UX work, verify populated and empty states, large channel lists, long/untrusted names, direct connect/edit/save flows, denied actions, private/channel draft separation, reconnection, keyboard navigation and phone layouts as applicable. Keep local fixtures separate from private production configuration.
|
||||||
|
|
||||||
|
Generated Opus exchange, simulated UI tests and a successful deployment do not certify actual microphone conversations, audible playback, browser/device compatibility, concurrent multi-user voice capacity, Function-kill recovery or server restart recovery. Treat timeouts as inconclusive. Live server/audio tests require an authorized destination and consenting participants; never broadcast test tones or record others without authorization.
|
||||||
|
|
||||||
|
## Deployment and handoff
|
||||||
|
|
||||||
|
Follow `docs/MANUAL_DEPLOYMENT.md` and `docs/DEPLOYMENT.md`:
|
||||||
|
|
||||||
|
1. Finish the authorized changes and appropriate checks.
|
||||||
|
2. Run `npm run deployment:package`; upload only its printed clean folder. Exclude private files, dependencies, Git metadata and local native binaries. Build native code for Linux on Vercel.
|
||||||
|
3. Reuse the intended existing project and preserve its private production configuration. Do not download environment values into the source package or expose authentication tokens in output.
|
||||||
|
4. Verify the production alias, current release assets, security gates and affected signed-in flows. Check identity and saved-connection continuity without recreating data. Test additional accounts when account isolation changes; do not manufacture unnecessary production test data for unrelated edits.
|
||||||
|
5. Distinguish local, simulated, deployed and real-server verification. Keep private deployment IDs, evidence and account details in excluded local records.
|
||||||
|
|
||||||
|
Respect explicit browser/tool access denials. Do not bypass them or repeat permission-reset troubleshooting loops. Use authorized supported tools when available, and report concrete blockers when necessary.
|
||||||
|
|
||||||
|
Leave changes uncommitted. In the handoff, state what changed, what was verified, whether it is deployed, and any remaining material limits. Do not claim the overall implementation plan is complete while its required milestones remain open.
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# Contributing
|
||||||
|
|
||||||
|
Read README.md, IMPLEMENTATION_PLAN.md and docs/FEATURE_MATRIX.md. Keep implemented, verified, simulated and planned behavior distinct. Use synthetic fixtures and reserved example names in tests; live destinations and identities belong in private owner settings, never source.
|
||||||
|
|
||||||
|
Run `npm run check`, `npm test` and `npm run publication:check` for changes. Build the native adapter for native/identity changes and use the silent browser fixture for audio changes. Test real servers only with authorization and consenting participants; never create channels, alter permissions, upload files or broadcast messages/audio as an incidental test.
|
||||||
|
|
||||||
|
Preserve origin/CSRF/session checks, destination pinning, queue/rate bounds, encrypted storage and fail-closed behavior. Never log keys, session tokens, passwords, private messages or voice contents. Retain upstream licenses/provenance and record vendor modifications as explicit patches. Changes to original project code are MIT licensed; third-party licenses remain separate.
|
||||||
|
|
||||||
|
Keep generated outputs, evidence, editor settings, dependencies, binaries and private configuration out of contributions. Publication and Git/GitHub operations are performed by the owner; no automatic commit/push workflow is included.
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
# VoxHarbor — Implementation Plan
|
||||||
|
|
||||||
|
Build VoxHarbor, a polished, self-hosted TeamSpeak web client. An operator can deploy an independent instance in their Vercel account and enable public registration. Every user has a private workspace and retains their own TeamSpeak identity, connections and nickname across sessions, redeployments and devices.
|
||||||
|
|
||||||
|
## Current scope
|
||||||
|
|
||||||
|
The experimental core implements account-isolated authentication with public registration, encrypted identity/settings/bookmark storage, full-client TS3 synchronization, Opus audio and bounded session recovery. Private deployment observations are summarized in docs/FEASIBILITY.md without account, destination, identity or private evidence details. Connections are stored on the backend. The multi-user production rollout passed two-account identity/settings/authentication/logout checks on 2026-11-01 while preserving the legacy owner. Real concurrent multi-user TeamSpeak/voice capacity remains unverified.
|
||||||
|
|
||||||
|
The plan remains unfinished. Actual microphone/device/browser verification, Function-kill/server-restart behavior, administration, file transfer, whisper, rich profiles, history and concurrent servers remain open. A private server denied messaging for the verification identities; permissions were not changed. Simulated fixtures never constitute a successful live interoperability test. See docs/FEATURE_MATRIX.md.
|
||||||
|
|
||||||
|
Act as a senior engineer responsible for architecture, implementation, security, interface design, and verification. Deliver working software, not a mockup or architecture proposal.
|
||||||
|
|
||||||
|
## Product requirements
|
||||||
|
|
||||||
|
- One deployment belongs to an operator; each registered account has its own private workspace.
|
||||||
|
- Each user connects to existing, unmodified TeamSpeak servers using their address, port, nickname, identity, and any required passwords.
|
||||||
|
- Support TeamSpeak 3 first. Treat compatibility with newer TeamSpeak servers and their additional features as separately verified capabilities.
|
||||||
|
- Aim for comprehensive feature coverage comparable to the official client, within the permissions granted by the server.
|
||||||
|
- No shared vendor-operated gateway, mandatory central account, analytics, or advertising.
|
||||||
|
- All application compute must run within the owner's Vercel deployment. Durable storage may use an owner-controlled integration supported by Vercel.
|
||||||
|
- Do not silently introduce a VPS, external protocol gateway, or required desktop companion.
|
||||||
|
|
||||||
|
## First milestone: prove Vercel feasibility
|
||||||
|
|
||||||
|
Do this before investing in the full interface.
|
||||||
|
|
||||||
|
Inspect current official Vercel documentation and build a minimal deployable experiment using an appropriate runtime. Verify on an actual Vercel deployment:
|
||||||
|
|
||||||
|
1. Bidirectional binary WebSocket communication with the browser.
|
||||||
|
2. Outbound UDP with validated responses from a non-DNS endpoint.
|
||||||
|
3. A real TeamSpeak protocol handshake and authenticated connection to an authorized test server.
|
||||||
|
4. Channel and participant synchronization.
|
||||||
|
5. Actual two-way voice with another client.
|
||||||
|
6. Connection behavior near the Function execution limit, including reconnection and recovery.
|
||||||
|
7. Whether the chosen protocol library and any native dependencies build and run in Vercel's production environment.
|
||||||
|
|
||||||
|
Local execution does not prove Vercel compatibility. A successful UDP send does not prove a response was received. A DNS-only UDP test does not establish TeamSpeak compatibility.
|
||||||
|
|
||||||
|
Document the exact deployment, runtime, configuration, test results, and remaining uncertainty. Treat timeouts as inconclusive until investigated.
|
||||||
|
|
||||||
|
If a hard platform limitation prevents the required architecture, report the evidence clearly. Do not claim the project meets the requirements, fabricate a successful test, or silently move compute elsewhere. Complete useful independent work and identify the smallest decision needed from the owner.
|
||||||
|
|
||||||
|
## Protocol core
|
||||||
|
|
||||||
|
Evaluate existing open-source full-client protocol implementations, including TS3J and tsclientlib and relevant maintained forks. Choose based on demonstrated compatibility, correctness, maintainability, licensing, and Vercel execution.
|
||||||
|
|
||||||
|
ServerQuery alone is not sufficient for a voice client.
|
||||||
|
|
||||||
|
Keep the protocol implementation independent of the UI. Separate:
|
||||||
|
|
||||||
|
- Identity management.
|
||||||
|
- Address resolution and connection establishment.
|
||||||
|
- Protocol transport, cryptography, packet ordering, acknowledgements, and reconnect behavior.
|
||||||
|
- Server session state and event processing.
|
||||||
|
- Commands, permissions, and capability detection.
|
||||||
|
- Voice processing and routing.
|
||||||
|
- File transfer.
|
||||||
|
- Platform-specific adapters.
|
||||||
|
|
||||||
|
Expose typed commands and events to the frontend. Keep authoritative server state synchronized through actual protocol events.
|
||||||
|
|
||||||
|
Do not invent cryptography or implement an incomplete protocol merely to avoid using a suitable library. Do not pretend a successful connection means full compatibility.
|
||||||
|
|
||||||
|
## Feature coverage
|
||||||
|
|
||||||
|
Maintain a feature matrix with these statuses: implemented and verified, implemented but unverified, planned, unsupported by the selected server/protocol, or blocked by the browser/platform.
|
||||||
|
|
||||||
|
Cover at least:
|
||||||
|
|
||||||
|
- Persistent identities, identity import/export, and required identity security levels.
|
||||||
|
- Server and channel passwords.
|
||||||
|
- Server bookmarks and connection history.
|
||||||
|
- Channel hierarchy, subscriptions, participant lists, and speaking indicators.
|
||||||
|
- Voice send/receive, push-to-talk, voice activation, microphone/output mute, and per-user volume.
|
||||||
|
- Whisper targets and lists.
|
||||||
|
- Private, channel, and server text messages.
|
||||||
|
- Poke, away status, nickname, descriptions, avatars, badges, and icons where supported.
|
||||||
|
- Channel creation, editing, ordering, deletion, and password handling.
|
||||||
|
- User movement, kick, ban, complaints, and ban management.
|
||||||
|
- Server groups, channel groups, privilege keys, and detailed permission management.
|
||||||
|
- Channel file browsing, upload, download, folders, and deletion.
|
||||||
|
- Connection quality, latency, packet loss, and actionable errors.
|
||||||
|
- Multiple server sessions with explicit active microphone and audio routing.
|
||||||
|
- Server information and editable settings permitted by the owner's identity.
|
||||||
|
|
||||||
|
Respect server-side permissions. Never imply that a custom client grants additional privileges.
|
||||||
|
|
||||||
|
Investigate video, screen sharing, newer TeamSpeak features, and proprietary account services separately. Do not confuse GreenTeaSpeak extensions with standard TeamSpeak capabilities. Clearly document unsupported functionality rather than creating nonfunctional controls.
|
||||||
|
|
||||||
|
## Audio requirements
|
||||||
|
|
||||||
|
Build a real audio pipeline with codec support appropriate to the compatibility target.
|
||||||
|
|
||||||
|
Include bounded queues, jitter buffering, packet-loss handling, per-speaker decoding and mixing, and protection against runaway latency.
|
||||||
|
|
||||||
|
Implement microphone permissions, device changes, echo cancellation and noise suppression where supported, and clear transmission indicators.
|
||||||
|
|
||||||
|
State browser limitations honestly: global push-to-talk shortcuts, background execution, output selection, and mobile behavior must be tested rather than assumed.
|
||||||
|
|
||||||
|
## Accounts and authentication
|
||||||
|
|
||||||
|
The operator controls registration; each user accesses only their own workspace. The requested multi-user scope supersedes the earlier owner-only requirement. See docs/MULTIUSER.md.
|
||||||
|
|
||||||
|
- Provide a secure, documented owner bootstrap process.
|
||||||
|
- Support username/password registration and login, with an operator switch to close new registrations. Preserve the reserved legacy owner account without migrating its encrypted records.
|
||||||
|
- Use server-enforced authentication for every sensitive HTTP route, WebSocket upgrade, file operation, and protocol action.
|
||||||
|
- Use secure, HttpOnly session cookies, appropriate SameSite settings, origin validation, and CSRF protection.
|
||||||
|
- Never rely solely on a hidden URL, frontend checks, or an obscure deployment address.
|
||||||
|
- Do not put credentials or bearer tokens in URLs.
|
||||||
|
- Handle expiration, logout, and session revocation.
|
||||||
|
- Protect any public deployment with a setup/authentication gate from its first request.
|
||||||
|
|
||||||
|
Because the backend makes network connections on the owner's behalf, validate destinations and prevent unauthenticated proxy use. Block internal and metadata-service destinations by default; make any intentional private-network support explicit.
|
||||||
|
|
||||||
|
## Durable TeamSpeak identity
|
||||||
|
|
||||||
|
The same identity must survive browser restarts, Function replacement, redeployment, and signing in from another device.
|
||||||
|
|
||||||
|
- Generate a proper TeamSpeak identity once and persist it.
|
||||||
|
- Support compatible import and owner-initiated export.
|
||||||
|
- Never regenerate an identity silently after a storage or decryption error.
|
||||||
|
- Encrypt private identity material at rest using authenticated encryption.
|
||||||
|
- Keep the encryption secret separate from stored ciphertext, using deployment secrets or an appropriate managed key facility.
|
||||||
|
- Do not store plaintext private keys or server passwords in browser localStorage.
|
||||||
|
- Do not expose private keys through ordinary API responses.
|
||||||
|
- Explain where signing occurs and which owner-controlled backend components can access decrypted material.
|
||||||
|
- Exclude keys, passwords, privilege tokens, voice contents, and private messages from logs.
|
||||||
|
- Provide documented backup, recovery, and key-rotation behavior.
|
||||||
|
|
||||||
|
Use durable storage, not the Function filesystem or process memory, for identity persistence. Store preferences and bookmarks appropriately, encrypting sensitive fields.
|
||||||
|
|
||||||
|
## Interface and experience
|
||||||
|
|
||||||
|
The user-approved Console design now supplies the page structure: destinations first, a unified connection editor, the voice console, searchable channel browser with preview, private conversation workspace, and separate identity/audio/presence/diagnostics pages. The console room strip contains a bounded recent-room list, not the full server hierarchy. See docs/DESIGN_IMPLEMENTATION.md for implemented flows and verification.
|
||||||
|
|
||||||
|
Create a distinctive, professional communication app with a calm visual style, excellent typography, restrained color, accessible contrast, and polished interaction states.
|
||||||
|
|
||||||
|
Suggested layout:
|
||||||
|
|
||||||
|
- Server connections and bookmarks on the left.
|
||||||
|
- A clear, searchable channel and participant tree.
|
||||||
|
- Conversation and activity views in the main area.
|
||||||
|
- A persistent voice control bar showing connection, microphone, output, and active transmission.
|
||||||
|
- Contextual user/channel actions and focused settings panels.
|
||||||
|
|
||||||
|
Support responsive desktop and mobile layouts, keyboard navigation, light/dark themes, and accessible controls.
|
||||||
|
|
||||||
|
Make connection progress, permission errors, reconnecting, unsupported codecs, unavailable features, and identity/storage failures understandable.
|
||||||
|
|
||||||
|
Use genuine server data in working flows. Keep any demonstration data explicitly separate.
|
||||||
|
|
||||||
|
## Vercel deployment and lifecycle
|
||||||
|
|
||||||
|
Provide a straightforward deployment process, ideally a Deploy to Vercel button when the repository is ready.
|
||||||
|
|
||||||
|
Document required secrets, owner authentication setup, durable storage integration, runtime configuration, region selection, and relevant account features.
|
||||||
|
|
||||||
|
Treat Function termination as a real operational boundary. Saving a snapshot in a database does not preserve a live UDP socket or an authenticated TeamSpeak session. Implement and verify reconnection accordingly, and disclose any unavoidable audio interruption.
|
||||||
|
|
||||||
|
Avoid a design that only works because a developer process remains running locally.
|
||||||
|
|
||||||
|
## Validation and delivery
|
||||||
|
|
||||||
|
Test the areas that can invalidate the product:
|
||||||
|
|
||||||
|
- Account isolation, authenticated HTTP/WebSocket access, registration controls, legacy owner continuity and independent logout.
|
||||||
|
- Identity persistence through redeployment and different browser sessions.
|
||||||
|
- Real TeamSpeak connection and two-way audio.
|
||||||
|
- Password-protected channels and insufficient permissions.
|
||||||
|
- Reconnection, server restart, and Function termination.
|
||||||
|
- Multiple speakers, jitter, and bounded audio queues.
|
||||||
|
- File-transfer authorization and destination validation.
|
||||||
|
- Malformed server packets and untrusted chat content.
|
||||||
|
- Current Chrome, Firefox, and Safari, with documented results.
|
||||||
|
|
||||||
|
Deliver the source, lockfiles, environment-variable template, deployment instructions, architecture notes, feature matrix, and reproducible verification evidence.
|
||||||
|
|
||||||
|
Work incrementally through verified milestones. Do not stop at a scaffold. Distinguish demonstrated behavior from assumptions and remaining work.
|
||||||
|
|
||||||
|
Do not create, modify, or delete GitHub resources, or commit, push, or change Git state automatically. Leave project changes uncommitted unless separately authorized.
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 MeghdadFadaee
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# VoxHarbor
|
||||||
|
|
||||||
|
A self-hosted TeamSpeak 3 web client with private user accounts. Anyone can register on an open instance; each user keeps their own encrypted identity, nickname, connections and bookmarks. Application compute runs in the operator’s Vercel deployment and uses their Redis database.
|
||||||
|
|
||||||
|
**Experimental software.** Native TS3 synchronization, generated two-way Opus audio, identity persistence and session recovery have been demonstrated in a private deployment. Actual microphone/device compatibility, uninterrupted conversation and comprehensive official-client feature coverage are not certified. See the [feature matrix](docs/FEATURE_MATRIX.md).
|
||||||
|
|
||||||
|
## Run locally
|
||||||
|
|
||||||
|
Requires Node.js 22, npm and a Rust toolchain for the native adapter.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npm ci
|
||||||
|
npm run owner:setup
|
||||||
|
npm run identity:key
|
||||||
|
npm run native:build
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Open the local address printed by the development server and create an account, or sign in as `owner` with the password from owner setup. Open **Identity** to create or import your TeamSpeak identity, then enter your server, voice port, nickname and optional channel/passwords in **Connection**. There is no built-in server or account.
|
||||||
|
|
||||||
|
**Connect saves the connection encrypted on the backend first.** Reconnects send only its saved-settings ID; the backend loads the address and credentials. Bookmarks also keep credentials on the backend. Ordinary API responses redact passwords, and secrets are never stored in browser storage. Audio starts muted. Automatic recovery remembers listening; microphone recovery requires an explicit opt-in in Audio settings. Choices last for the signed-in page. See [audio behavior and connection logs](docs/AUDIO.md).
|
||||||
|
|
||||||
|
The default development memory store is volatile: accounts, identities, connections and sessions disappear when that development process stops. Configure your own Redis credentials and disable the memory-store setting for local persistence. Production always requires Redis. Keep encryption keys stable and back up your identity securely.
|
||||||
|
|
||||||
|
## Deploy your own instance
|
||||||
|
|
||||||
|
Follow [deployment setup](docs/DEPLOYMENT.md). Configure the application origin, session secret, Redis credentials and separate identity encryption key as private environment variables. Public signup is enabled by default; set `ALLOW_REGISTRATION=0` to close signup. Existing `owner` credentials and records are preserved. See [accounts and rollout](docs/MULTIUSER.md). Configure TeamSpeak connections through the signed-in app, not source code or deployment variables.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npm run deployment:package
|
||||||
|
```
|
||||||
|
|
||||||
|
Upload only the printed clean folder. It excludes environment files, identities, local evidence, dependencies, Git metadata and build outputs. Native code builds for the deployment platform. A successful local build is not proof that another deployment/account works.
|
||||||
|
|
||||||
|
## Development and verification
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npm run check
|
||||||
|
npm test
|
||||||
|
npm run audio:qa
|
||||||
|
npm run publication:check
|
||||||
|
npm run publication:package
|
||||||
|
```
|
||||||
|
|
||||||
|
Tests use synthetic secrets, local sockets and fixtures. They do not connect to public TeamSpeak servers. Build the native adapter before testing its identity endpoints. The separate audio QA page uses generated sound with silent local output; it requests no microphone. See [testing](docs/TESTING.md) and [audio behavior](docs/AUDIO.md).
|
||||||
|
|
||||||
|
Implemented: registration/login, account-isolated HTTP/WebSocket access, encrypted identities/settings/bookmarks, live channel/participant state and search, channel movement, nickname/away/subscription controls, typed text/poke actions, experimental Opus/PTT/VAD and bounded automatic recovery. Server permissions apply; a private server denied messaging during verification, so successful live messaging remains unverified.
|
||||||
|
|
||||||
|
Pending: administration and detailed permissions, file transfer, whisper, richer profiles, history, concurrent servers, and broader hardware/browser testing. The [implementation plan](IMPLEMENTATION_PLAN.md) remains open.
|
||||||
|
|
||||||
|
## Public source and licensing
|
||||||
|
|
||||||
|
Target repository: [MeghdadFadaee/VoxHarbor](https://github.com/MeghdadFadaee/VoxHarbor). Original code is [MIT licensed](LICENSE); preserve the [third-party notices](THIRD_PARTY_NOTICES.md).
|
||||||
|
|
||||||
|
Before your first commit or public upload, read [publication preparation](docs/PUBLICATION.md). Private development records are intentionally excluded. Never commit actual environment values, identity backups, connection exports, cookies, screenshots of private accounts, or voice/chat recordings. See [security reporting](SECURITY.md) and [contributing](CONTRIBUTING.md).
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
# Security
|
||||||
|
|
||||||
|
VoxHarbor is experimental operator-hosted software with private user workspaces and optional public registration. The operator controls the deployment, Redis and encryption keys. All sensitive HTTP operations and WebSocket upgrades require account authentication; writes/controls also check origin and CSRF. Keep the exact HTTPS app origin configured. The app blocks private/reserved network destinations by default.
|
||||||
|
|
||||||
|
Keep `.env.local`, `.local`, Redis values, identity backups, deployment screenshots, HAR files, cookies, voice/chat contents and connection exports private. `.gitignore` is a convenience, not a secret manager. Run `npm run publication:check` before committing and inspect the files you stage. Do not bypass its findings by force-adding excluded material.
|
||||||
|
|
||||||
|
Preserve the separate identity encryption key and encrypted Redis records. Incorrect keys/corrupt records fail closed; do not generate a replacement identity to hide a recovery error. See [identity recovery](docs/IDENTITY.md). Saved connection/bookmark passwords are encrypted and never included in ordinary metadata responses. Runtime diagnostics must not contain credentials or private content.
|
||||||
|
|
||||||
|
Report vulnerabilities through GitHub's private security reporting for the intended repository if available. Otherwise ask the maintainer for a private reporting channel without posting exploit details or secrets publicly. Do not include real keys, tokens, private server/channel addresses, identities or recordings. If a secret was already published, revoke/rotate it and review repository history before making further public releases; deleting the working file alone does not remove it from history.
|
||||||
|
|
||||||
|
Known limits include finite Function lifetime, one simultaneous native session per account, audio restarting muted after recovery and incomplete hardware/browser/feature verification. See the feature matrix. No automated scan guarantees that publication is safe; review the publication report and source manifest before you push.
|
||||||
|
|
||||||
|
Registration is enabled by default and can be closed with `ALLOW_REGISTRATION=0`. New accounts cannot access the legacy owner or another account’s records. The operator remains trusted with encryption keys and backend signing. Password recovery, MFA and capacity certification are not included in this milestone; see [accounts](docs/MULTIUSER.md).
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# Third-party software
|
||||||
|
|
||||||
|
The root MIT license covers VoxHarbor's original code. Third-party code retains its own copyright and license terms.
|
||||||
|
|
||||||
|
| Component | Version / provenance | License and retained notices |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| ReSpeak tsclientlib, tsproto and bookkeeping/declaration sources | Exact revisions and source archive digests in `native/vendor/provenance.json`; local patches recorded there | MIT OR Apache-2.0; retain `native/vendor/tsclientlib/LICENSE-MIT`, `LICENSE-APACHE`, and declaration license files |
|
||||||
|
| libopus-wasm | 0.3.0, pinned in `package-lock.json` | MIT wrapper license at `public/vendor/opus/LICENSE`; upstream notices at `public/vendor/opus/THIRD_PARTY_NOTICES.md` |
|
||||||
|
| libopus compiled into the bundled WASM | 1.6.1, as documented by libopus-wasm 0.3.0 | BSD-style copyright, redistribution and patent notices retained in `public/vendor/opus/COPYING.libopus` |
|
||||||
|
| IBM Plex Sans and IBM Plex Mono | Official Google Fonts distribution; original fonts © IBM Corp. | SIL Open Font License 1.1 at `public/fonts/OFL.txt`; locally hosted font files are unmodified |
|
||||||
|
| ws, ipaddr.js and build dependencies | Pinned Node/Cargo lockfiles | Original package notices are supplied by their distributions; dependencies/build outputs are not vendored into this source export |
|
||||||
|
|
||||||
|
The libopus notice is copied from the [versioned upstream COPYING file](https://github.com/xiph/opus/blob/v1.6.1/COPYING). Build preparation preserves it alongside the generated browser codec. Vendored Rust sources are kept intact apart from the separately recorded patches. Upstream source references are not endorsements of VoxHarbor.
|
||||||
|
|
||||||
|
If you distribute compiled artifacts, preserve the notices required by all linked dependencies as well as these source notices. TeamSpeak names and marks belong to their respective owners; this project is independent.
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { readConfig } from '../src/config.mjs';
|
||||||
|
import { createApp } from '../src/http-adapter.mjs';
|
||||||
|
|
||||||
|
// Invalid configuration fails before any sensitive endpoint can be served.
|
||||||
|
const { server } = createApp(readConfig());
|
||||||
|
export default server;
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# App icons
|
||||||
|
|
||||||
|
VoxHarbor's orange waveform mark is provided as local assets for browser tabs, bookmarks and home-screen shortcuts:
|
||||||
|
|
||||||
|
- `/favicon.svg`: scalable browser favicon.
|
||||||
|
- `/favicon.ico`: 16, 32 and 48 pixel fallback images.
|
||||||
|
- `/favicon-16x16.png` and `/favicon-32x32.png`: PNG favicon fallbacks.
|
||||||
|
- `/apple-touch-icon.png`: opaque 180 pixel Apple touch icon.
|
||||||
|
- `/icons/app-192.png` and `/icons/app-512.png`: standard app icons.
|
||||||
|
- `/icons/app-maskable-512.png`: opaque icon with extra padding for platform masks.
|
||||||
|
- `/icons/safari-pinned-tab.svg`: monochrome pinned-tab mark.
|
||||||
|
- `/site.webmanifest`: application name, launch location, colors and home-screen icons.
|
||||||
|
|
||||||
|
The assets are linked from the document head and explicitly served by the HTTP adapter. Both application and deployment content policies allow the same-origin manifest. They require no sign-in or external asset requests.
|
||||||
|
|
||||||
|
Regenerate the artwork with `npm run icons:build`. The generator uses Node built-ins and the same waveform geometry for its SVG, PNG and ICO outputs. Generated assets are checked into the source tree as project files, so deployment does not require an image-processing dependency.
|
||||||
|
|
||||||
|
The manifest supplies shortcut/standalone presentation metadata; it does not add offline support, a service worker or a guarantee of installability on every browser. Accounts, identities and connections retain their existing backend ownership and storage rules.
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Architecture
|
||||||
|
|
||||||
|
- `public/`: account workspace, session/recovery controller, AudioWorklets and Opus worker. No default destination, account, private key or server password is bundled.
|
||||||
|
- `src/http-adapter.mjs`: account-isolated HTTP/WebSocket boundary, origin/CSRF checks, limits and fail-closed session revalidation.
|
||||||
|
- `src/auth/`: atomic username registration, scrypt verification, account-bound expiring cookies, Redis account/session records and server-selected workspace scoping.
|
||||||
|
- `src/preferences.mjs`: encrypted backend connection/bookmark settings, metadata redaction and revision checks.
|
||||||
|
- `src/identity/`: authenticated encryption, create-if-absent identity persistence and explicit import/export/rewrap.
|
||||||
|
- `src/protocol/`: typed controls/events, per-account lease, server acknowledgements and audio gates.
|
||||||
|
- `src/transport/destination.mjs`: public-address validation and DNS pinning.
|
||||||
|
- `src/platform/`: bounded private stdio supervision. Native children receive no deployment-secret environment variables.
|
||||||
|
- `native/`: pinned Rust tsclientlib bridge. The native child signs/encrypts the actual full TS3 protocol; ServerQuery is not used as a voice substitute.
|
||||||
|
|
||||||
|
`api/server.mjs` exports the Node server for Vercel; `scripts/dev.mjs` binds locally. Production uses the owner's Redis REST integration and rejects volatile memory. Cookies are HttpOnly/SameSite=Strict, Secure and `__Host-` scoped on HTTPS. WebSocket upgrades require account auth and exact origin; controls require CSRF. Revocation/storage failures close active transports. Frames, rates, state, audio queues and pending commands are bounded.
|
||||||
|
|
||||||
|
Connection settings are encrypted before a connect command. A socket references an opaque settings ID; the backend retrieves credentials and pins the public destination. Settings changes from another session for the same account cannot redirect a stale reconnect silently. The native session rotates at 240 seconds within the configured 300-second Function boundary. A renewed Redis lease limits overlapping identity use; abandoned leases expire after 35 seconds. Recovering a socket does not preserve UDP state or audio capture.
|
||||||
|
|
||||||
|
## Protocol source
|
||||||
|
|
||||||
|
The selected adapter is ReSpeak/tsclientlib, pinned by source archive revision/digest in `native/vendor/provenance.json` with Cargo lockfiles. Source and declaration snapshots are retained with their licenses. TS3J was considered but would require an independently proven JVM runtime/package. No claim is made that selecting a library establishes full feature parity.
|
||||||
|
|
||||||
|
Recorded vendor patches expose encoded audio while retaining transport crypto/permission behavior, and use bounded 2048-ID command reordering with duplicate suppression. The original archive digests and patches distinguish this source from unmodified upstream. The codec stays in the browser; native libopus/OpenSSL codec defaults are disabled.
|
||||||
|
|
||||||
|
See [verification scope](FEASIBILITY.md), [audio constraints](AUDIO.md), [identity recovery](IDENTITY.md) and [feature matrix](FEATURE_MATRIX.md). Historic private transport/account evidence is intentionally outside the public repository.
|
||||||
|
|
||||||
|
User record prefixes and authenticated encryption associated data both bind records to an account. Legacy owner keys/envelopes remain unchanged. HTTP request bodies never select an account scope. See [multi-user storage and rollout](MULTIUSER.md).
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# Experimental Opus audio
|
||||||
|
|
||||||
|
The browser uses 48 kHz AudioWorklets and the pinned `libopus-wasm` worker. Opus Voice (4) and Opus Music (5) with 20 ms frames are supported; outgoing capture is mono. Other codecs/frame durations are rejected. No media leaves until the owner explicitly enables listening, enables the microphone, and permits transmission with push-to-talk or voice activation.
|
||||||
|
|
||||||
|
Incoming speakers have independent decoders, 60 ms initial jitter buffering, at most 12 queued packets, FEC/PLC and bounded mixing. Three misses end a talk spurt. There are at most 32 active speakers; idle decoder state expires. Capture credits, worker queues, native stdin, WebSocket backlogs and playback queues are bounded; stale frames are dropped. These are implementation limits, not an end-to-end audio-quality guarantee. TCP/WebSocket head-of-line blocking remains a limitation.
|
||||||
|
|
||||||
|
Input/output start muted on new sessions. Disconnect, logout, hidden pages, input/device loss and suspended audio stop transmission. During automatic reconnection, listening resumes if it was enabled. The microphone resumes only when it was enabled and the user checked “Resume my enabled microphone after automatic reconnect.” These choices live only in the current signed-in page; reload/sign-out clears them. Hiding the page cancels pending recovery and mutes the microphone. Manual disconnect, successful channel changes, device errors and sign-out clear recovery. A denied channel join preserves current audio. Push-to-talk never restores a held press. Browser restrictions can still require a manual audio enable action. Pending permission/initialization work cannot resurrect a stopped instance. Concurrent startup shares codec initialization; participant volume chosen before startup is retained. Per-user gain is bounded from 0 to 2.
|
||||||
|
|
||||||
|
PTT works while the page has focus; it is not a global shortcut. Echo cancellation, noise suppression and gain control are requested from the browser. Output selection depends on `AudioContext.setSinkId`. A browser that cannot provide the required 48 kHz worklet is rejected; resampling is not implemented. Safari, Firefox, Bluetooth, mobile suspension, actual microphone hardware and audible browser playback need separate testing.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
`npm test` covers actual Opus encoding/decoding, independent speaker decoding/mixing, loss and sequence wrapping, malformed frames, bounded queues, PTT release and lifecycle races. Worklet processor tests do not simulate browser scheduling.
|
||||||
|
|
||||||
|
For a silent browser test, run `npm run audio:qa`, open the local address it prints and choose **Run silent pipeline test**. This uses generated audio, real worklets and the actual worker/codec with deliberate losses. It requests no microphone, emits silence to hardware and contacts no TeamSpeak server. Reports are synthetic diagnostics, not a real conversation pass.
|
||||||
|
|
||||||
|
Before cleanup, a private deployment passed generated two-way audio through a real authorized TS3 server and a second native client. Frame counts were bounded-window observations, not loss/latency benchmarks. Real microphone capture, browser speaker audibility, multiple live speakers and official-client conversational interoperability remain unverified. To test them, use an authorized test channel and consenting participants; never record voice contents or broadcast test tones into an unsuspecting channel.
|
||||||
|
|
||||||
|
## Connection diagnostics
|
||||||
|
|
||||||
|
Connection diagnostics → Download JSON (or account settings → Diagnostics) exports the last 1,000 bounded events for this signed-in page. It records native session status (including the current 240-second session cap), socket close codes, connection duration, time since the last message, heartbeat round-trip times, retry delays/attempts, protocol error codes and browser online/visibility changes. The log excludes server addresses, account identifiers, close-reason text, credentials, messages and media. It remains in memory, clears on sign-out/reload, and is never automatically uploaded. Download it after a problem and before reloading. A close code alone does not prove the underlying network or hosting cause.
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
# VoxHarbor — Capabilities and Requirements
|
||||||
|
|
||||||
|
## Product scope
|
||||||
|
|
||||||
|
VoxHarbor is a browser-based TeamSpeak 3 client. Users register on an independently operated instance and connect to existing TeamSpeak servers. Each user has a separate account, TeamSpeak identity, saved connections and nickname.
|
||||||
|
|
||||||
|
VoxHarbor accounts are separate from TeamSpeak identities and vendor accounts. Access to server functions depends on the connected server and the permissions assigned to the user's identity.
|
||||||
|
|
||||||
|
## Current capabilities and functional requirements
|
||||||
|
|
||||||
|
### Accounts and sessions
|
||||||
|
|
||||||
|
- Register with a username, password and password confirmation when registration is enabled.
|
||||||
|
- Sign in with an existing username and password.
|
||||||
|
- Sign out and revoke the current application session.
|
||||||
|
- Keep each account's identity, connections and saved data separate from other accounts.
|
||||||
|
- Support closed registration while allowing existing users to sign in.
|
||||||
|
- Preserve the reserved legacy `owner` account.
|
||||||
|
- Handle invalid credentials, duplicate usernames, registration closure, request limits, expired sessions and unavailable account storage.
|
||||||
|
- Clear account-specific session data when signing out or changing accounts.
|
||||||
|
|
||||||
|
| Field | Requirement |
|
||||||
|
| --- | --- |
|
||||||
|
| Username | 3–32 characters; letters, numbers, underscores or hyphens; starts with a letter or number; case-insensitive |
|
||||||
|
| Password | 16–256 characters for registration |
|
||||||
|
| Password confirmation | Must match the registration password |
|
||||||
|
|
||||||
|
Email collection, email verification, password recovery, multi-factor authentication and account deletion are not currently available.
|
||||||
|
|
||||||
|
### TeamSpeak identity
|
||||||
|
|
||||||
|
- Explicitly create a persistent TeamSpeak identity or import an existing identity file.
|
||||||
|
- Retain the same identity across sign-ins, browser sessions and application deployments.
|
||||||
|
- Access the identity's public UID and security level.
|
||||||
|
- Export a private identity backup.
|
||||||
|
- Preserve an existing identity rather than silently replacing it.
|
||||||
|
- Support server-required identity security-level increases without changing the identity's UID.
|
||||||
|
- Distinguish a missing identity from an unreadable identity, failed import, storage failure or unavailable identity service.
|
||||||
|
- Require an identity before connecting to a TeamSpeak server.
|
||||||
|
|
||||||
|
### Connections and saved destinations
|
||||||
|
|
||||||
|
- Connect to a TeamSpeak server using an address, voice port and nickname.
|
||||||
|
- Support an optional server password, destination channel ID and channel password.
|
||||||
|
- Save connection settings and passwords encrypted on the backend for the authenticated account.
|
||||||
|
- Create, name, edit, select and delete saved connections.
|
||||||
|
- Retain saved connections and nicknames across sign-ins.
|
||||||
|
- Preserve saved passwords when no replacement is supplied for the same destination.
|
||||||
|
- Explicitly remove saved passwords.
|
||||||
|
- Keep saved passwords from being reused for a different destination after an address or channel change.
|
||||||
|
- Disconnect an active connection or stop an ongoing connection attempt.
|
||||||
|
- Support one active TeamSpeak connection per account. Separate accounts have independent connections.
|
||||||
|
- Restrict destinations to permitted public IPv4 addresses and voice ports from 1024 to 65535.
|
||||||
|
|
||||||
|
### Server, channels and participants
|
||||||
|
|
||||||
|
- Synchronize the connected server's name, channel hierarchy and visible participants.
|
||||||
|
- Search channels and participants.
|
||||||
|
- Access channel names, topics, password requirements, subscriptions and codec information.
|
||||||
|
- Access participant names, channel membership, mute states, away messages and speaking activity where available.
|
||||||
|
- Distinguish the current user and their current channel.
|
||||||
|
- Join another channel, including password-protected channels when authorized.
|
||||||
|
- Subscribe to and unsubscribe from channel updates when permitted.
|
||||||
|
- Change the current nickname.
|
||||||
|
- Set an away message and return from away status.
|
||||||
|
- Retain acknowledged nickname and channel changes in the backend connection settings for recovery.
|
||||||
|
|
||||||
|
### Voice communication
|
||||||
|
|
||||||
|
- Receive and transmit audio in Opus Voice and Opus Music channels.
|
||||||
|
- Enable and disable listening independently from microphone activation.
|
||||||
|
- Enable and mute the microphone.
|
||||||
|
- Support push-to-talk and hands-free voice activation.
|
||||||
|
- Adjust the voice activation threshold.
|
||||||
|
- Select an available microphone.
|
||||||
|
- Select an audio output device where the browser supports it.
|
||||||
|
- Adjust individual participants' playback volume from 0% to 200%.
|
||||||
|
- Track local transmission and remote speaking activity.
|
||||||
|
- Request browser-supported echo cancellation, noise suppression and automatic gain control.
|
||||||
|
- Handle denied microphone permission, missing devices, device changes, suspended audio and unsupported codecs.
|
||||||
|
- Start new sessions with listening and the microphone off.
|
||||||
|
- Stop microphone transmission when the page is hidden, the connection ends, the user signs out or an audio/device failure occurs.
|
||||||
|
- Restrict push-to-talk keyboard operation to the focused page; no global shortcut is available.
|
||||||
|
|
||||||
|
### Automatic recovery and audio choices
|
||||||
|
|
||||||
|
- Attempt bounded automatic recovery after recoverable connection interruptions.
|
||||||
|
- Reuse the account's existing identity and backend-saved connection settings.
|
||||||
|
- Recheck account authentication during recovery.
|
||||||
|
- Restore listening after automatic reconnection when it was previously enabled.
|
||||||
|
- Resume a previously enabled microphone only when the user has explicitly opted into automatic microphone recovery.
|
||||||
|
- Retain transmission mode, threshold and selected devices during automatic recovery within the same signed-in page.
|
||||||
|
- Cancel pending audio recovery on manual disconnect, sign-out, channel changes, device errors or page hiding.
|
||||||
|
- Never restore a previously held push-to-talk press.
|
||||||
|
- Start with audio off after reload or a new sign-in.
|
||||||
|
- Handle browser restrictions that prevent automatic audio resumption.
|
||||||
|
|
||||||
|
### Text communication and participant contact
|
||||||
|
|
||||||
|
- Send and receive channel, server and private text messages when permitted.
|
||||||
|
- Send and receive participant pokes when permitted.
|
||||||
|
- Associate private conversations with the intended participant.
|
||||||
|
- Distinguish pending actions, confirmed actions, denied actions and unconfirmed results.
|
||||||
|
- Do not automatically resend messages or participant actions after a timeout or disconnect.
|
||||||
|
- Keep messages in the current browser session, with a maximum of 200 retained entries.
|
||||||
|
- Clear messages on sign-out. Durable message history is not available.
|
||||||
|
|
||||||
|
### Connection diagnostics
|
||||||
|
|
||||||
|
- Record connection status changes, native session-limit events, socket close codes, connection duration and retry attempts/delays.
|
||||||
|
- Record heartbeat round-trip timing, time since the last transport message, protocol error codes and browser network/visibility changes.
|
||||||
|
- Export diagnostic data as a JSON file.
|
||||||
|
- Retain up to 1,000 events in memory for the current signed-in page.
|
||||||
|
- Clear diagnostics on reload or sign-out.
|
||||||
|
- Exclude server addresses, account identifiers, passwords, private identity material, messages and audio contents.
|
||||||
|
- Do not automatically upload diagnostic logs.
|
||||||
|
|
||||||
|
## Required operational states
|
||||||
|
|
||||||
|
- Signed out; registering; signing in; authenticated; session expired or revoked.
|
||||||
|
- Registration available or closed.
|
||||||
|
- No identity; identity available; identity operation pending; identity operation failed.
|
||||||
|
- No saved connection; saved connections available; settings being saved; conflicting or stale settings; settings storage failure.
|
||||||
|
- Disconnected; connecting; connected; reconnecting with a retry delay; network offline; recovery exhausted; connection rejected.
|
||||||
|
- Connection already active for the account.
|
||||||
|
- Live server data available; no participants; no search matches; previously received data no longer live.
|
||||||
|
- Listening off or on; microphone off, ready, idle or transmitting; microphone permission pending or denied.
|
||||||
|
- Unsupported channel codec; unavailable audio device; audio initialization or recovery failure.
|
||||||
|
- Action pending, confirmed, denied by server permissions, timed out or interrupted.
|
||||||
|
|
||||||
|
## Privacy and data requirements
|
||||||
|
|
||||||
|
- Require authentication for private account data and server actions.
|
||||||
|
- Keep private identities and connection credentials encrypted in durable backend storage.
|
||||||
|
- Keep credentials out of URLs, ordinary account responses and browser local storage.
|
||||||
|
- Restrict private identity export to an explicit action by the authenticated account.
|
||||||
|
- Preserve saved identities and connections through application updates.
|
||||||
|
- Stop account activity when its session expires or is revoked.
|
||||||
|
- Enforce server permissions for every supported action.
|
||||||
|
- Treat the instance operator as trusted with backend access; encryption at rest does not prevent operator access.
|
||||||
|
|
||||||
|
## Planned capabilities — not currently available
|
||||||
|
|
||||||
|
| Area | Required capabilities |
|
||||||
|
| --- | --- |
|
||||||
|
| Connection history and quality | Durable connection history; connection latency, packet loss and quality information |
|
||||||
|
| Multiple servers | Concurrent server connections with an explicit active microphone destination and audio routing |
|
||||||
|
| Advanced voice | Whisper targets, whisper lists and advanced audio routing |
|
||||||
|
| Channel management | Channel creation, editing, ordering, deletion and password management |
|
||||||
|
| Moderation | Authorized participant movement, kick, ban, complaints and ban management |
|
||||||
|
| Groups and permissions | Server groups, channel groups, privilege keys and detailed permission management |
|
||||||
|
| Files | Channel file browsing, upload, download, folders and deletion |
|
||||||
|
| Profiles and presence | Descriptions, avatars, badges and icons where supported |
|
||||||
|
| Server administration | Server information and authorized changes to server settings |
|
||||||
|
|
||||||
|
## Compatibility and verification boundaries
|
||||||
|
|
||||||
|
- TeamSpeak 3 is the current protocol target.
|
||||||
|
- Video, screen sharing, newer protocols and proprietary account services remain separate investigations.
|
||||||
|
- Server-side permissions can prevent otherwise supported operations.
|
||||||
|
- Native sessions currently have a 240-second lifetime before automatic reconnection; uninterrupted audio across that boundary is not guaranteed.
|
||||||
|
- Generated two-way Opus audio has been demonstrated through a real server. Actual microphone conversations, audible browser playback and microphone recovery still require live verification.
|
||||||
|
- Private messaging and poke interoperability remain unverified where server permissions prevented testing.
|
||||||
|
- Concurrent multi-user voice capacity, broad browser/device compatibility and reliable mobile background audio remain unverified.
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# Deploying an operator-hosted instance
|
||||||
|
|
||||||
|
Use your own Vercel project and Redis REST integration. The application targets Node.js 22, Linux native execution, and a finite Function lifetime. This is experimental; verify the deployed account rather than assuming every platform configuration works.
|
||||||
|
|
||||||
|
## Private deployment settings
|
||||||
|
|
||||||
|
| Variable | Purpose |
|
||||||
|
| --- | --- |
|
||||||
|
| `APP_ORIGIN` | Exact HTTPS origin of your application, with no trailing slash/path |
|
||||||
|
| `OWNER_PASSWORD_HASH` | Optional reserved `owner` login; preserve existing values; generate privately with `npm run owner:hash` |
|
||||||
|
| `ALLOW_REGISTRATION` | `1` (default) enables signup; `0` closes new signups while existing users can sign in |
|
||||||
|
| `SESSION_SECRET` | Independent random 32-byte hex secret; keep stable unless revoking all sessions |
|
||||||
|
| `IDENTITY_ENCRYPTION_KEY` | Independent random 32-byte hex key for identities and connection preferences |
|
||||||
|
| `UPSTASH_REDIS_REST_URL` + `UPSTASH_REDIS_REST_TOKEN` | A complete owner-controlled Redis REST credential pair |
|
||||||
|
| `KV_REST_API_URL` + `KV_REST_API_TOKEN` | Alternative Marketplace-provided credential pair; do not mix pairs |
|
||||||
|
| `IDENTITY_PREVIOUS_ENCRYPTION_KEY` | Only during deliberate encryption-key rotation |
|
||||||
|
|
||||||
|
Do not enable `ALLOW_LOCAL_MEMORY_STORE` in production. There is no TeamSpeak host, channel, identity, owner password or Redis endpoint bundled into the source. Earlier experimental `TS3_SERVER_*`, UDP probe and rotation variables are no longer used; configure connections through the authenticated app. Existing unrelated environment values are not modified by this cleanup.
|
||||||
|
|
||||||
|
## Build and upload
|
||||||
|
|
||||||
|
1. Configure the required private variables. Keep them out of source, issue reports and logs.
|
||||||
|
2. Run `npm ci`, `npm run check`, `npm test` and `npm run deployment:package` locally.
|
||||||
|
3. Upload the printed clean source folder to your intended Vercel project. Do not upload the working directory or connect a private evidence folder.
|
||||||
|
4. Use framework **Other**, Node **22**, and the `vercel.json` build command. The pinned native adapter is built with Cargo's lockfile and packaged for Linux; never upload a local macOS binary.
|
||||||
|
5. Confirm startup and account isolation on the real URL. Register or sign in, create/import an identity once, then enter and connect to a server you are authorized to use.
|
||||||
|
6. Confirm the same UID and saved connection survive reload and redeployment. Test audio only in an appropriate authorized channel with consenting participants.
|
||||||
|
|
||||||
|
If your account changes Fluid Compute, WebSocket support, execution duration, region, architecture or networking behavior, re-run deployment checks. The configured Function limit is 300 seconds; native sessions rotate at 240 seconds. Recovery interrupts audio and restarts it muted. A dead transport may require waiting for its 35-second ownership lease to expire. One simultaneous native session per account is supported locally; production concurrency/capacity must be verified.
|
||||||
|
|
||||||
|
## Operations
|
||||||
|
|
||||||
|
Preserve your Redis database and encryption key across redeployments. Do not recreate an identity to hide a decryption/storage error. Account sessions expire after 15 minutes. Restore storage before reconnecting after an outage. See [identity recovery](IDENTITY.md), [workspace storage](WORKSPACE.md) and [testing](TESTING.md).
|
||||||
|
|
||||||
|
Read [multi-user rollout](MULTIUSER.md) before opening signup. Preserve the legacy owner records and verify separate users. Encryption-key rotation must cover every account before retiring the previous key.
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# Console workflow implementation
|
||||||
|
|
||||||
|
The client follows the supplied Console / Product UI's page structure using separate hash routes. Only short confirmations and pokes are dialogs. All live transport, identity and encrypted storage operations remain attached to the signed-in account.
|
||||||
|
|
||||||
|
## Pages and transitions
|
||||||
|
|
||||||
|
- **Connections** is the starting page after sign-in. Saved destinations expose nickname, connection status, direct Connect/Open console, Edit and active Disconnect actions. Add opens a complete editor. A backend-saved last connection remains available even without a bookmark. One active server per account is enforced in the interface and backend.
|
||||||
|
- **Connection editor** keeps name, destination, nickname, optional channel and password handling in one form. Save returns to the destination list. Save & connect saves first and then opens the console. Leaving unsaved edits requires an explicit discard choice. Blank saved passwords retain their existing meaning; the explicit removal control clears them. Delete requires confirmation and never removes the identity.
|
||||||
|
- **Console** shows the actual current room, participant mixer, conversation and voice panel. The room strip contains only the current and recently visited rooms, capped at four. The complete hierarchy is in All channels. Mixer and compact layouts share playback volume state.
|
||||||
|
- **Channels** provides ordered hierarchy, parent paths, occupancy, current-room and password labels, and search by room or participant. Selection previews the topic and participants in a separate panel. Previewing does not move the user. A denied join retains current audio; a successful channel change turns audio off. Phone selection brings the preview into view.
|
||||||
|
- **Private conversations** have a participant/thread list, message pane and recipient playback/poke controls. Selecting a participant binds the recipient to their current ID and UID. Incoming messages have unread counts. Reconnection invalidates recipient bindings; they must be selected again. Returning to the console restores channel conversation scope. Phone participant controls expand separately.
|
||||||
|
- **Identity** provides distinct creation/import choices for a new account and stored-identity/backup actions once an identity exists.
|
||||||
|
- **Audio**, **Presence** and **Diagnostics** are individual pages. Navigation does not disconnect the server or reset audio. An active-session ribbon exposes connection/audio state and microphone muting while outside the console.
|
||||||
|
|
||||||
|
Browser Back/Forward follows the page routes. Hashes contain page names only; credentials and destinations are not placed in URLs. Editor secrets clear on leaving the editor. Sign-out clears temporary audio, messages, recipients, unread counts and private fields. Messages remain bounded and are not automatically resent. Drafts are kept separately by conversation in bounded page memory, so a private draft never appears in channel chat. They clear on sign-out or a manual server change.
|
||||||
|
|
||||||
|
## Assets and responsive behavior
|
||||||
|
|
||||||
|
The console palette, locally hosted IBM Plex fonts and exported 22 × 22 microphone/headphone SVGs are retained. Font licenses remain in `public/fonts/OFL.txt`.
|
||||||
|
|
||||||
|
Phone layouts adapt the flows: destination actions stay visible, the complete connection form precedes save actions, channel results have bounded scrolling, participant cards become compact rows, and the console keeps accessible voice controls. Notifications are dismissible. All server, room, participant and account data are dynamic; simulation data is confined to local verification fixtures.
|
||||||
|
|
||||||
|
## Verification limits
|
||||||
|
|
||||||
|
Automated coverage includes large channel lists, hierarchy/participant search, bounded recent-room navigation and route validation, together with the protocol, storage, audio and account regression tests. Browser checks use a disposable simulated backend with 123 channels. They cover direct connections, saving/editing, discard/cancel, channel previews and joins, preserved listening after a denied join, private messaging, audio preferences and phone layouts.
|
||||||
|
|
||||||
|
These UI checks do not establish new real microphone/device or TeamSpeak interoperability results. See `AUDIO.md`, `TESTING.md` and `FEASIBILITY.md` for those limits.
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# Feasibility and verification scope
|
||||||
|
|
||||||
|
A private owner-operated Vercel deployment demonstrated the following before the public-source cleanup. Raw account screenshots, private deployment URLs/IDs, destination details, UIDs and session evidence are kept outside the public source.
|
||||||
|
|
||||||
|
| Area | Observed result | Limits |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Binary WebSocket / outbound UDP | Bidirectional binary transport and validated non-DNS STUN responses | Historical transport experiments; their product endpoints were removed during cleanup |
|
||||||
|
| Native runtime | Linux x64 Node 22 deployment build and native execution; local macOS build | Re-verify your account/runtime; no universal hosting claim |
|
||||||
|
| Full TS3 session | Real handshake, authentication, channel and participant synchronization | Existing unmodified authorized TS3 server; newer server features are separate |
|
||||||
|
| Identity and settings | Same encrypted identity across sign-ins/redeployments; durable encrypted preferences | Production restore/key-rotation drills are not certified |
|
||||||
|
| Opus | Browser/native peer exchanged generated audio through the real server; nonzero decode/playback energy | No microphone permission requested; local hardware output stayed silent; real capture/browser audibility unverified |
|
||||||
|
| Recovery | Recovered after the 240-second native cap and deliberate socket loss; identity unchanged and audio off | Roughly 8.5 seconds at cap and 41 seconds after the dropped socket in one final run, including lease expiry; no actual process-kill/server-restart attribution |
|
||||||
|
| Permissions | Server denied private messages for the test identities | No successful live messaging pass; permissions were preserved |
|
||||||
|
| Browser rendering | Literal markup-like names/text in an isolated local simulated fixture | Simulation is UI integration evidence, not real messaging interoperability |
|
||||||
|
|
||||||
|
The subsequent public-source cleanup replaces environment-based connection defaults and browser-held reconnect credentials with encrypted backend settings and an opaque settings reference. It also removes the superseded echo/STUN product experiments and production test-tone controls. Its current test results are described in [testing](TESTING.md); changes validated locally are not automatically a new production verification pass.
|
||||||
|
|
||||||
|
The architecture uses an owner-controlled native Function adapter, not ServerQuery, a vendor gateway, a VPS or a desktop companion. No hard platform prohibition was proven in the tested configuration. Finite Function lifetime still interrupts audio. Local source now supports restoring listening and opt-in microphone recovery; deployment and real-device verification of that change are separate. Comprehensive official-client parity, hardware/browser certification and uninterrupted conversation remain unfinished. See the [feature matrix](FEATURE_MATRIX.md).
|
||||||
|
|
||||||
|
Relevant primary platform references: [WebSocket Functions](https://vercel.com/docs/functions/websockets), [Function limitations](https://vercel.com/docs/functions/limitations). Check current documentation and actual account behavior before deploying; historical observations do not override platform changes.
|
||||||
|
|
||||||
|
The subsequent multi-user milestone adds registration, account-bound sessions, per-user encrypted records and independent protocol leases. Local tests include separate real native identity generation/export and simultaneous simulated protocol sessions. A production deployment on 2026-11-01 passed two-account registration, distinct native identity creation, connection/bookmark isolation, authenticated WebSocket heartbeat and independent logout/persistence checks, with legacy owner continuity preserved. Real multi-user voice/capacity remains unverified. See [accounts and rollout](MULTIUSER.md).
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# Feature matrix
|
||||||
|
|
||||||
|
Statuses distinguish implemented code, observed private-deployment results and pending verification. The public-source cleanup changes connection storage and removes old experiment endpoints; it is not automatically a new production certification.
|
||||||
|
|
||||||
|
| Capability | Status / scope |
|
||||||
|
| --- | --- |
|
||||||
|
| Registration/login, account isolation, origin/CSRF, revocation | Implemented; local isolation/concurrent simulated session tests and production two-account registration/settings/identity/WebSocket/logout checks; real concurrent native voice/capacity unverified |
|
||||||
|
| Durable encrypted TS3 identity | Persistence demonstrated across sign-ins/redeployments; import/export/rotation tested locally; official-client restore drill pending |
|
||||||
|
| Backend connection settings and bookmarks | Implemented; encrypted/redacted, stale-edit and destination isolation tests; cleanup flow verified locally |
|
||||||
|
| Real TS3 connection / synchronized channels and participants | Demonstrated in a private Vercel deployment |
|
||||||
|
| Channel/participant search and previews | Implemented; browser checks with real and simulated state |
|
||||||
|
| Channel movement / subscriptions | Implemented; password-protected self-movement verified; server permissions apply |
|
||||||
|
| Nickname and away/return | Implemented; previous production server acknowledgements verified |
|
||||||
|
| Opus send/receive | Generated two-way network audio demonstrated; actual microphone/audible browser conversation unverified |
|
||||||
|
| PTT, VAD, microphone/output mute, per-user volume | Implemented with codec/worker/lifecycle tests; comprehensive live device verification pending |
|
||||||
|
| Speaking indicators and bounded queues | Implemented; worker tests and browser integration checks; broader live multi-speaker testing pending |
|
||||||
|
| Private/channel/server text, poke | Typed acknowledged controls implemented; private live test was server-denied; successful real messaging/poke interoperability remains unverified |
|
||||||
|
| Responsive workspace and themes | Implemented; partial in-app Chromium narrow/desktop checks; comprehensive accessibility/mobile/browser testing pending |
|
||||||
|
| Automatic recovery | Native-cap/socket-drop recovery demonstrated; identity retained and audio muted; actual Function kill/server restart unverified |
|
||||||
|
| Durable connection history / quality metrics | Planned; worker loss counters are not a full TS3 quality dashboard |
|
||||||
|
| Whisper / advanced routing / concurrent servers | Planned |
|
||||||
|
| Channel management / moderation / groups / permissions | Planned |
|
||||||
|
| File browsing/transfer/management | Planned |
|
||||||
|
| Rich profiles, icons, avatars, badges | Planned |
|
||||||
|
| Video, screen sharing, newer protocols / proprietary accounts | Separate investigation; no compatibility claim |
|
||||||
|
|
||||||
|
A custom client grants no additional server privileges. No control is represented as verified merely because it builds or passes a simulated fixture. The [implementation plan](../IMPLEMENTATION_PLAN.md) remains unfinished.
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# Persistent TeamSpeak identity
|
||||||
|
|
||||||
|
The native child inside the owner's Node Function uses tsclientlib to generate a real P-256 TeamSpeak identity and security-level offset, and to sign protocol packets. Node persists each private identity in its account-scoped Redis record (the legacy owner retains `voxharbor:identity:v1:owner`), encrypted with AES-256-GCM and a fresh random 96-bit nonce per write. The envelope has a version, key ID, ciphertext and authentication tag. AAD binds the record to its purpose, account and key ID. Legacy owner associated data remains unchanged.
|
||||||
|
|
||||||
|
`IDENTITY_ENCRYPTION_KEY` is a separate 32-byte deployment secret. It is not derived from `SESSION_SECRET`, stored in Redis, inherited by the native child, or sent to the browser. Node decrypts the identity and gives it to the child through private stdin for signing. Those trusted backend components can access private material while active. Ordinary authenticated API responses expose only the signed-in account’s UID, security level and creation time.
|
||||||
|
|
||||||
|
Creation/import requires an explicit authenticated, same-origin, CSRF-protected owner action. Atomic create-if-absent prevents concurrent replacement. Storage errors are distinct from missing records; decryption errors stop the operation without regenerating an identity. Counter upgrades must preserve both the private key and UID.
|
||||||
|
|
||||||
|
One live protocol session per account is allowed in this milestone. An account-scoped Redis lease renews every ten seconds and expires after 35 seconds if abandoned. Socket closure, account logout/expiration, or lease failure stops the child. Sessions have a deliberate 240-second cap before the configured 300-second Function boundary. Automatic full-protocol recovery at that cap and after an abrupt socket drop is verified in production, as is two-way synthetic Opus through the real server. Actual microphone capture remains unverified. Recovery reuses the identity and loads the current encrypted connection record on the backend through an opaque settings ID. It checks account authentication again and keeps audio muted. Changing connection settings invalidates older recovery IDs. The experimental audio pipeline starts muted and requires explicit user actions.
|
||||||
|
|
||||||
|
## Local development
|
||||||
|
|
||||||
|
`npm run identity:key` adds a separate key to `.env.local` once, preserving a valid existing value and refusing to silently replace an invalid one. The development web app uses the explicitly volatile memory store unless configured with Redis; its identity will not survive process replacement in that mode. Production rejects volatile storage. Never upload `.env` or `.local` files.
|
||||||
|
|
||||||
|
## Backup and recovery
|
||||||
|
|
||||||
|
**Export private identity** makes an owner-initiated POST with CSRF and downloads a TeamSpeak-style INI containing a compatible obfuscated identity string. Obfuscation is not encryption; secure that backup. The library export/import round trip preserves UID and level in tests. Direct import into the official client remains unverified.
|
||||||
|
|
||||||
|
For infrastructure recovery, back up Redis ciphertext and its encryption secret separately. Both are required. Keep the encryption secret stable across redeployments, Functions and sign-ins. Rotating the login password/session secret revokes sessions without changing the TeamSpeak identity slot.
|
||||||
|
|
||||||
|
When storage is unavailable, restore it before reconnecting. When decryption fails, restore the correct secret and ciphertext. Do not generate a new identity to hide the failure; the creation route refuses to replace existing records.
|
||||||
|
|
||||||
|
## Deliberate encryption-key rotation
|
||||||
|
|
||||||
|
1. Securely back up the current ciphertext and key.
|
||||||
|
2. Set the new `IDENTITY_ENCRYPTION_KEY` and old `IDENTITY_PREVIOUS_ENCRYPTION_KEY`, then redeploy.
|
||||||
|
3. As the authenticated owner, POST `/api/identity/rotate` and `/api/preferences/rotate` with the current CSRF header and exact allowed Origin. These authenticate and atomically re-encrypt each record under the new key, preserving the identity key/UID and saved connections. Keep both encryption keys configured if either operation fails.
|
||||||
|
4. Repeat rewrapping and verification for every account, including dormant accounts, before retiring an old key. The endpoints affect only the signed-in account. Keep both keys until every identity/preference record is rewrapped. Verify UID, connectivity and reopening saved connections; then remove the previous-key variable, redeploy, and retire older deployments retaining old environment values.
|
||||||
|
|
||||||
|
Rotation is covered locally; production rotation and restore drills remain pending. Raw keys, import/export contents, passwords, private messages and voice contents remain excluded from logs.
|
||||||
|
|
||||||
|
## Saved connection encryption
|
||||||
|
|
||||||
|
The client workspace also encrypts owner preferences, current connection settings and bookmarks with the separate identity encryption key, using independent nonces and purpose-specific associated data. Identity and preference records remain separate. During key rotation, keep `IDENTITY_PREVIOUS_ENCRYPTION_KEY` until both records have been rewrapped and verified: use the existing owner-authenticated identity rotation action and POST `/api/preferences/rotate` with the same session/CSRF protection. Verify identity metadata and reopening saved connections before retiring the old key. Do not remove an old key after rewrapping only the identity. See WORKSPACE.md for bookmark credential access and clearing behavior.
|
||||||
|
|
||||||
|
See [multi-user storage and key rotation](MULTIUSER.md). The trusted operator controls the shared encryption key; user isolation does not imply encryption from that operator.
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# Manual deployment
|
||||||
|
|
||||||
|
Use the complete [deployment guide](DEPLOYMENT.md) for variables and platform constraints.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npm run deployment:package
|
||||||
|
```
|
||||||
|
|
||||||
|
Upload the generated folder to the intended project in your Vercel account. The allowlist excludes `.env.local`, `.local`, identities, private evidence, editor metadata, dependencies, local binaries and Git metadata. A source manifest records SHA-256 hashes. Build Linux native code on Vercel instead of copying a development binary.
|
||||||
|
|
||||||
|
Preserve existing secrets and encrypted records. Never rotate credentials merely to update source. After deployment, sign in as `owner` with the existing password, verify legacy continuity, then test two separate registered accounts and independent logout. See [multi-user rollout](MULTIUSER.md). In each account, open your backend-saved connection, verify identity continuity and test only an authorized destination. No hardcoded test server, channel, password, UID or account is required.
|
||||||
|
|
||||||
|
Git operations are separate from this upload workflow. See [public repository preparation](PUBLICATION.md) before publishing source.
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# Accounts and private workspaces
|
||||||
|
|
||||||
|
VoxHarbor supports username/password registration on one operator-controlled deployment. Each account has its own TeamSpeak identity, nickname, encrypted current connection, bookmarks, preferences and active protocol lease. Accounts are application accounts, not TeamSpeak/vendor accounts. Server permissions still apply.
|
||||||
|
|
||||||
|
## Sign in or register
|
||||||
|
|
||||||
|
Choose **Create an account**, enter a username and a password, and confirm the password. Usernames contain 3–32 ASCII letters, numbers, underscores or hyphens, starting with a letter or number. They are case-insensitive and stored lowercase. Passwords contain 16–256 characters and are stored as independently salted scrypt hashes. Registration signs in with a fresh opaque HttpOnly session cookie. Create/import a TeamSpeak identity in your private workspace once; the application never silently creates a replacement identity.
|
||||||
|
|
||||||
|
There is no email collection, email verification, password reset, account deletion UI or MFA in this milestone. Keep your password and private identity backup secure. Registration limits and generic login failures follow the principles in the [OWASP authentication guidance](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html). Username availability is observable through registration; usernames are not treated as private email addresses.
|
||||||
|
|
||||||
|
## Existing deployment compatibility
|
||||||
|
|
||||||
|
The reserved username **owner** uses the existing `OWNER_PASSWORD_HASH`. Existing password-only API login requests remain supported for this account; the browser uses an explicit username. Pre-account owner sessions continue to access only the legacy owner workspace. Existing owner identity/settings records keep their original storage keys, encryption associated data and ciphertext; no migration or key change is needed. Registration can never claim `owner`, even when no owner password is configured. The legacy owner login does not gain an application route to other users' records.
|
||||||
|
|
||||||
|
New accounts have random immutable IDs, separate from usernames. Account records are atomically created at `voxharbor:account:v1:<sha256-of-normalized-username>`; each contains its ID, canonical username, password hash and creation time. Account IDs are not accepted from browser requests to choose a workspace. Sessions contain the authenticated account ID and username; the account record is checked again on authenticated requests and active WebSocket revalidation. Missing/corrupt account storage fails closed.
|
||||||
|
|
||||||
|
## Storage and encryption boundaries
|
||||||
|
|
||||||
|
New users' application records, leases and authenticated rate counters are prefixed by `voxharbor:user:v1:<account-id>:`. The identity/preference envelope's associated data also includes that account ID, so moving ciphertext between accounts cannot decrypt successfully. A shared deployment encryption key is still required; the trusted operator and backend have access to decrypted material while processing a user's request. This is encryption at rest, not end-to-end encryption from the operator.
|
||||||
|
|
||||||
|
Only authenticated metadata exposes the current user's UID and connection fields; passwords remain backend-only. Export/import/rotation routes always operate on the session's workspace. Connection IDs from another account cannot select its saved settings. Each account can hold one live native session; separate users have separate leases and may connect concurrently. One account's logout revokes only its presented browser session and stops that session's sockets. Replacing a browser login revokes its previous session. Other tabs receive a sign-in-change notification and clear their workspace.
|
||||||
|
|
||||||
|
## Operator configuration and rollout
|
||||||
|
|
||||||
|
`ALLOW_REGISTRATION=1` enables public signup and is the default. Set `ALLOW_REGISTRATION=0` to close new signups while preserving existing accounts' sign-in. Registration also requires `IDENTITY_ENCRYPTION_KEY`. `OWNER_PASSWORD_HASH` is optional for new account-based deployments; preserve it unchanged on existing installations. Production still requires HTTPS, a stable session secret and durable Redis; the development memory store loses all accounts and their data when the process stops.
|
||||||
|
|
||||||
|
This source change does not modify private environment values, touch existing Redis data or deploy automatically. Before rollout, back up existing ciphertext and its encryption key separately. Verify the legacy owner UID and saved connections, register two disposable test accounts, check identity/connection separation, concurrent protocol sessions, independent logout and persistence across replacement of the deployed application. On 2026-11-01, production checks verified two-account registration, separate native identities/settings, authenticated WebSockets, independent logout and persistence after sign-in, while the legacy owner identity/settings matched a private pre-deployment baseline. Real concurrent TeamSpeak/voice sessions and hosting cost/capacity still need separate verification. Previous single-owner protocol verification is not multi-user voice certification.
|
||||||
|
|
||||||
|
Global limits currently allow 10 registration requests and 120 login requests per minute, with a shared per-username limit of 10 authentication requests per minute. Authenticated settings/identity/socket and connect limits are scoped per account. These limits bound an initial rollout; there is no verified capacity guarantee, billing quota system or bot challenge. Closing signup does not disconnect existing accounts.
|
||||||
|
|
||||||
|
For encryption-key rotation, every account's identity and preferences must be rewrapped and verified, including the legacy owner. The existing per-account rotation endpoints affect only the signed-in account. Keep the previous key until **all** records have been rewrapped; rotating only the owner and then removing the old key would strand other accounts. Account password hashes do not use the identity encryption key. Rotating `SESSION_SECRET` revokes all application sessions without changing account records or TS3 identities.
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# Preparing a public repository
|
||||||
|
|
||||||
|
Intended destination: [MeghdadFadaee/VoxHarbor](https://github.com/MeghdadFadaee/VoxHarbor). Original project code is MIT licensed; third-party notices remain separate.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npm run check
|
||||||
|
npm test
|
||||||
|
npm run publication:check
|
||||||
|
npm run publication:package
|
||||||
|
```
|
||||||
|
|
||||||
|
The checker reads current source and Git's tracked/unignored candidates, including staged content. It flags private paths, known local secret values (without printing them), credential/private-key formats, personal filesystem paths, private deployment URLs and files outside the source allowlist. Intentional published upstream crypto fixtures are distinguished from local secrets. The unchanged, hash-pinned upstream Opus artifact contains compiler paths from its original build; its provenance is recorded alongside the artifact. Known local secrets and this project’s filesystem path are still checked in every file, including vendored code. A generated source manifest records hashes for review.
|
||||||
|
|
||||||
|
The exported folder contains no Git history or metadata. Keep `.env.local`, `.local`, editor settings, dependencies, binaries, raw verification records/screenshots and identity backups out of the public repository. The cleanup privately archives old instance-specific material under `.local/private-archive/`; do not upload that directory. Examples and synthetic test fixtures are not real connection settings.
|
||||||
|
|
||||||
|
A scanner is not a guarantee. Review the exact files you stage and any existing Git history. If credentials ever entered history, removing a working file or adding an ignore rule is insufficient: revoke affected credentials and perform a deliberate history cleanup before publication. An empty history avoids that historical exposure, but still inspect the first commit.
|
||||||
|
|
||||||
|
## Owner publication steps
|
||||||
|
|
||||||
|
Git and GitHub operations are intentionally not automated by these scripts. If your workflow requires read-only Git/GitHub access for the coding agent, you must perform the final operations yourself:
|
||||||
|
|
||||||
|
1. Create or verify the intended public GitHub repository. Avoid adding a conflicting initial README/license when the local source is ready.
|
||||||
|
2. Review `git status`, then stage only reviewed files. Inspect `git diff --cached --stat` and `git diff --cached`; run `npm run publication:check` again so staged bytes are checked too.
|
||||||
|
3. Commit the reviewed source, set/verify the remote destination, and push it yourself. Do not force-push or rewrite existing history casually.
|
||||||
|
4. Confirm repository visibility, licensing and that no private configuration/evidence was included.
|
||||||
|
|
||||||
|
The clean export is also suitable for starting a separate fresh publication checkout if desired. It is not a reason to upload private local folders or bypass audit findings. The `private: true` flag in package.json prevents accidental npm-registry publication; it does not make a GitHub repository private.
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
# Testing
|
||||||
|
|
||||||
|
Run `npm ci`, `npm run native:build`, `npm run check` and `npm test`. Automated tests use synthetic credentials, temporary directories, local sockets and simulated native fixtures; they do not contact public TeamSpeak servers. Native identity endpoint tests require the built executable. Mock fixtures are not real server compatibility evidence.
|
||||||
|
|
||||||
|
`npm run audio:qa` starts a local silent AudioWorklet/Opus test with deliberately missing packets. It requests no microphone, sends no audio to a server and emits silence to local hardware. Close it after testing.
|
||||||
|
|
||||||
|
`node scripts/workspace-render-fixture.mjs` starts a clearly labelled local simulated workspace. Sign in as `owner`; its fixture-only password is in that source. It uses an ephemeral synthetic identity payload, no real TS3 network, and volatile storage. Test message/name markup remains literal text. Enter `quit` to remove its temporary executable and stop it. It is forbidden in production.
|
||||||
|
|
||||||
|
For an authorized deployment, configure the connection through its owner UI first. These optional scripts require an explicit HTTPS origin and hidden owner password:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
node scripts/verify-public-deployment.mjs https://your-project.vercel.app
|
||||||
|
node scripts/verify-production-protocol.mjs https://your-project.vercel.app 45 .local/protocol-result.json
|
||||||
|
node scripts/verify-recovery.mjs https://your-project.vercel.app 350 .local/recovery-result.json
|
||||||
|
```
|
||||||
|
|
||||||
|
They use the backend-saved connection, do not create/replace an identity, keep audio muted and revoke their own verification sessions. Results may contain private instance metadata: keep them under `.local`, not in a public issue or commit. Do not run concurrent native verification sessions against the same owner lease.
|
||||||
|
|
||||||
|
Real voice testing needs another authorized client and a suitable channel whose participants expect testing. Record outcomes/counters, not audio/chat contents. Verify microphone permission, audible receive/send, mute/deafen, denied talk power, devices, multiple speakers, background behavior and reconnects separately. Never infer hardware/browser compatibility from codec tests.
|
||||||
|
|
||||||
|
The current cleanup is tested locally; it has not been redeployed automatically. Previous production observations are summarized without private account/destination data in [FEASIBILITY.md](FEASIBILITY.md).
|
||||||
|
|
||||||
|
## Public-source cleanup verification
|
||||||
|
|
||||||
|
On 2026-10-31, JavaScript syntax checks and all 80 automated tests passed, with no skips. The macOS native release build passed. A disposable simulated workspace verified saving and reloading connection metadata while password inputs remained empty and backend-saved password indicators persisted; browser error logs were empty. The silent browser audio test passed with three simulated speakers, nonzero decoded/playback energy, deliberate packet loss handling and stopped transmission after PTT release. These are local checks, not a deployment or real microphone test.
|
||||||
|
|
||||||
|
Account tests cover atomic case-insensitive registration, reserved-owner compatibility, password hashing, session/account binding, ciphertext substitution rejection, independent identity/settings/bookmark/lease/rate scopes, HTTP origin/CSRF, cross-account connection IDs, simultaneous simulated native sessions and independent logout. These do not establish multi-user production capacity.
|
||||||
|
|
||||||
|
## Multi-user milestone verification
|
||||||
|
|
||||||
|
On 2026-11-01, syntax checks and all 90 automated tests passed, with no skips. New registered accounts generated different real native identities; exports restored to the correct account UID. Browser verification in a disposable volatile fixture confirmed registration, separate identities/bookmarks/default nicknames, restoration after sign-in and cross-tab logout cleanup, with no browser errors. No private environment, existing Redis or actual TeamSpeak server was used in these account tests.
|
||||||
|
|
||||||
|
## Production account rollout
|
||||||
|
|
||||||
|
On 2026-11-01, the Linux native release build and public HTTP/WebSocket access gates passed after deployment. Two new test accounts registered, generated distinct native identities, retained isolated connections/bookmarks/nicknames, rejected a cross-account connection reference, used authenticated WebSockets, logged out independently and retained identity/settings after signing in again. The legacy owner UID and saved preference digest matched a private baseline from before deployment. Reports and encrypted test-account credentials remain private under `.local`. These checks made no TeamSpeak server connections and transmitted no audio; real multi-user voice and capacity remain unverified.
|
||||||
|
|
||||||
|
## Audio recovery and connection diagnostics
|
||||||
|
|
||||||
|
The local suite now has 96 passing tests. Recovery tests cover listening/device restoration, microphone opt-in and opt-out, repeated disconnect notifications, muted/background state, cancellation during initialization, automatic-resume failures and diagnostics redaction. Transport fixtures distinguish the native session cap, heartbeat timeout, socket close duration and retry timing. A disposable browser fixture verified the recovery checkbox and sign-out reset without microphone access or TeamSpeak traffic. These are automated and UI checks, not a real microphone recovery pass.
|
||||||
|
|
||||||
|
The audio-recovery update was deployed on 2026-11-01. All six changed browser entry/module assets matched the tested source on the public domain, and public authentication/origin/WebSocket gates passed. Actual microphone recovery remains unverified.
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Workspace and connection storage
|
||||||
|
|
||||||
|
The destinations page opens after sign-in. The console shows the current and recently visited rooms, participant playback controls, conversation scopes and a separate voice panel. The full searchable hierarchy and room previews have a dedicated Channels page. Connection editing, private conversations, identity, presence, diagnostics and audio each have a separate page. There are no demonstration people/messages in the product. The default appearance follows the dark console design, with an explicitly saved light theme still supported. See [design implementation](DESIGN_IMPLEMENTATION.md).
|
||||||
|
|
||||||
|
## Backend-owned connections
|
||||||
|
|
||||||
|
Each user enters a server, voice port, nickname, optional channel and passwords. **Connect** performs an authenticated same-origin CSRF-protected `POST /api/connection`, encrypts the settings, then opens the protocol socket using only the returned opaque connection ID. Native reconnects load those settings from the backend; the browser reconnect controller holds no destination credentials. A stale connection ID cannot silently select settings saved by another session.
|
||||||
|
|
||||||
|
Settings/bookmarks use a per-account Redis namespace. The legacy owner retains `voxharbor:preferences:v1:owner`; new accounts add their immutable account prefix and encryption associated data. See [account isolation](MULTIUSER.md). AES-256-GCM uses the separate identity encryption key, independent random nonces and purpose-specific associated data. Identity and preference ciphertext remain separate. Wrong keys/corruption fail closed; unreadable records are never replaced with defaults. The explicit development memory store is volatile.
|
||||||
|
|
||||||
|
Ordinary metadata includes only password-presence flags. Opening a bookmark fills public connection fields and passes its ID when connecting; bookmark passwords are resolved on the backend and are never returned by a bookmark credential endpoint. Empty password inputs preserve a current password only for the same server/channel, or select the bookmarked credential. Passwords never follow an edited destination to another server. Use the explicit clear-password control to remove current saved credentials.
|
||||||
|
|
||||||
|
Acknowledged nickname/channel changes update the backend connection for recovery. A storage failure after a successful server action is reported separately; the action is not replayed. Bookmark/theme edits use revision checks and preserve omitted secrets. No connection data is stored in localStorage; only the non-sensitive theme is cached there.
|
||||||
|
|
||||||
|
## Commands and safety
|
||||||
|
|
||||||
|
Typed channel join/subscription, nickname, away, text and poke actions have bounded input and correlated server acknowledgements. Arbitrary protocol names/arguments are rejected. Timeouts and disconnects never automatically resend messages/actions. Private recipients are bound to their public UID when available; channel messages are bound to the channel observed by the user, so reused client numbers or a concurrent move cannot redirect a message silently.
|
||||||
|
|
||||||
|
Messages are literal DOM text, bounded to 200 entries in browser memory, and cleared on logout. They are not saved or logged. Diagnostic downloads exclude names, messages, audio, credentials and private keys. Device changes, hidden pages, disconnection and logout stop transmission. Automatic reconnection can restore listening and an explicitly opted-in, previously enabled microphone. Manual disconnect/sign-out clears recovery, and hiding the page cancels pending recovery. Choices live only in the signed-in page; browser restrictions can still require manual audio enablement. See [audio behavior and diagnostics](AUDIO.md).
|
||||||
|
|
||||||
|
## Destination policy
|
||||||
|
|
||||||
|
The backend validates every connection. It resolves only allowed public IPv4 destinations, rejects private/reserved/metadata addresses and mixed DNS answers, and passes a pinned numeric address to native code. A bookmark is not permission to bypass these checks. The current voice-port policy is 1024–65535. The application is authenticated and operator-hosted; it is not an unauthenticated proxy.
|
||||||
|
|
||||||
|
The full [feature matrix](FEATURE_MATRIX.md) remains open. The old production synthetic-tone UI and instance-specific live-test scripts were removed; use the separate silent browser fixture or an authorized two-client manual audio test.
|
||||||
Generated
+3883
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,24 @@
|
|||||||
|
[package]
|
||||||
|
name = "voxharbor-protocol"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
publish = false
|
||||||
|
license = "MIT"
|
||||||
|
repository = "https://github.com/MeghdadFadaee/VoxHarbor"
|
||||||
|
|
||||||
|
[workspace]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
tsclientlib = { path = "vendor/tsclientlib/tsclientlib", default-features = false, features = ["raw-audio"] }
|
||||||
|
tsproto-packets = { path = "vendor/tsclientlib/utils/tsproto-packets" }
|
||||||
|
tsproto = { path = "vendor/tsclientlib/tsproto" }
|
||||||
|
base64 = "0.22"
|
||||||
|
futures = "0.3"
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
serde_json = "1"
|
||||||
|
tokio = { version = "1", features = ["io-std", "io-util", "macros", "rt-multi-thread", "time"] }
|
||||||
|
|
||||||
|
[profile.release]
|
||||||
|
strip = true
|
||||||
|
lto = "thin"
|
||||||
|
codegen-units = 1
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# Native TS3 adapter
|
||||||
|
|
||||||
|
This executable implements a bounded private newline-JSON protocol for the owner's Node backend. It uses the pinned ReSpeak tsclientlib client stack for identity signing, handshake, encryption, transport and synchronized state. Identity material passes through private stdin, never deployment-secret environment variables or logs.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npm run native:build
|
||||||
|
```
|
||||||
|
|
||||||
|
The build uses Cargo's lockfile and release profile, then packages the current platform executable under ignored `native/bin/`. Vercel builds its own Linux executable; do not commit or upload a local binary. Compiler/download setup is in `scripts/build-native.mjs` and `scripts/bootstrap-rust.sh`. No project Git mutation is involved.
|
||||||
|
|
||||||
|
The owner configures the destination and credentials in the signed-in app. The backend decrypts stored settings, validates/pins a public numeric address, and supervises one native session with bounded stdio, timeout and lease ownership. There is no default test server in native code. The adapter does not write server files or private identity backups to disk.
|
||||||
|
|
||||||
|
Vendor provenance, exact source/declaration revisions, archive digests and local patches are in `vendor/provenance.json`. Retain the original MIT/Apache licenses. `raw-audio.patch` exposes encoded packets without native codec defaults. `bounded-reordering.patch` provides bounded 2048-ID command reordering and duplicate suppression while retaining packet authentication/encryption and ordering. Its native regression tests cover burst, duplicates, wraparound and priority isolation.
|
||||||
|
|
||||||
|
A Linux build, full TS3 state and generated two-way Opus were observed in a private deployment before source cleanup. See [feasibility limits](../docs/FEASIBILITY.md). Actual hardware conversation, complete official-client parity and all remaining features are not certified.
|
||||||
@@ -0,0 +1,432 @@
|
|||||||
|
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||||
|
use futures::StreamExt;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
use std::{
|
||||||
|
io::{self, Write},
|
||||||
|
net::SocketAddr,
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||||
|
use tsclientlib::{Connection, DisconnectOptions, Identity, OutCommandExt, StreamItem};
|
||||||
|
use tsclientlib::{ChannelId, ChannelType};
|
||||||
|
use tsclientlib::{ClientId, MessageTarget, messages::c2s};
|
||||||
|
use tsclientlib::prelude::M2BClientMoveExt;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use tsproto_packets::packets::{
|
||||||
|
AudioData, CodecType, Direction, Flags, OutAudio, OutCommand, PacketType,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
|
||||||
|
enum Control {
|
||||||
|
Disconnect,
|
||||||
|
Command { request_id: u32, command: ClientCommand },
|
||||||
|
AudioState {
|
||||||
|
input_muted: bool,
|
||||||
|
output_muted: bool,
|
||||||
|
},
|
||||||
|
Audio {
|
||||||
|
codec: u8,
|
||||||
|
data: String,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
|
||||||
|
enum ClientCommand {
|
||||||
|
JoinChannel { channel_id: u64, password: Option<String> },
|
||||||
|
Subscribe { channel_id: u64, subscribed: bool },
|
||||||
|
Nickname { name: String },
|
||||||
|
Away { away: bool, message: String },
|
||||||
|
TextMessage { target: String, channel_id: Option<u64>, client_id: Option<u16>, client_uid: Option<String>, message: String },
|
||||||
|
Poke { client_id: u16, client_uid: Option<String>, message: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
fn client_command(connection: &mut Connection, action: ClientCommand) -> Result<tsclientlib::MessageHandle, ()> {
|
||||||
|
let recipient = match &action {
|
||||||
|
ClientCommand::TextMessage { client_id: Some(id), client_uid: Some(uid), .. } | ClientCommand::Poke { client_id: id, client_uid: Some(uid), .. } => Some((*id, uid)),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
if let Some((id, expected)) = recipient {
|
||||||
|
let state = connection.get_state().map_err(|_| ())?;
|
||||||
|
if state.clients.get(&ClientId(id)).and_then(|client| client.uid.as_ref()).map(|uid| uid.to_string()).as_ref() != Some(expected) { return Err(()); }
|
||||||
|
}
|
||||||
|
let command = match action {
|
||||||
|
ClientCommand::JoinChannel { channel_id, password } => {
|
||||||
|
let state = connection.get_state().map_err(|_| ())?;
|
||||||
|
let own = state.clients.get(&state.own_client).ok_or(())?;
|
||||||
|
let mut part = own.client_move(ChannelId(channel_id));
|
||||||
|
if let Some(ref password) = password { part = part.set_password(password); }
|
||||||
|
c2s::OutClientMoveMessage::new(&mut std::iter::once(part))
|
||||||
|
}
|
||||||
|
ClientCommand::Subscribe { channel_id, subscribed } => {
|
||||||
|
let mut command = OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, if subscribed { "channelsubscribe" } else { "channelunsubscribe" });
|
||||||
|
command.write_arg("cid", &channel_id); command
|
||||||
|
}
|
||||||
|
ClientCommand::Nickname { name } => {
|
||||||
|
if name.is_empty() || name.chars().count() > 64 { return Err(()); }
|
||||||
|
let mut command = OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "clientupdate");
|
||||||
|
command.write_arg("client_nickname", &name); command
|
||||||
|
}
|
||||||
|
ClientCommand::Away { away, message } => {
|
||||||
|
let mut command = OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "clientupdate");
|
||||||
|
command.write_arg("client_away", &(away as u8)); command.write_arg("client_away_message", &message); command
|
||||||
|
}
|
||||||
|
ClientCommand::TextMessage { target, channel_id, client_id, message, .. } => {
|
||||||
|
if message.len() > 1000 { return Err(()); }
|
||||||
|
if target == "channel" {
|
||||||
|
let state = connection.get_state().map_err(|_| ())?;
|
||||||
|
if state.clients.get(&state.own_client).map(|client| client.channel.0) != channel_id { return Err(()); }
|
||||||
|
}
|
||||||
|
let target = match target.as_str() { "channel" => MessageTarget::Channel, "server" => MessageTarget::Server, "private" => MessageTarget::Client(ClientId(client_id.ok_or(())?)), _ => return Err(()) };
|
||||||
|
connection.get_state().map_err(|_| ())?.send_message(target, &message)
|
||||||
|
}
|
||||||
|
ClientCommand::Poke { client_id, message, .. } => {
|
||||||
|
connection.get_state().map_err(|_| ())?.send_message(MessageTarget::Poke(ClientId(client_id)), &message)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
command.send_with_result(connection).map_err(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn audio_status(connection: &Connection) -> io::Result<()> {
|
||||||
|
emit(
|
||||||
|
json!({"type":"audio_status", "canSend":connection.can_send_audio(), "canReceive":connection.can_receive_audio()}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn control(connection: &mut Connection, control: Control, pending: &mut HashMap<u16, u32>) -> Result<bool, ()> {
|
||||||
|
match control {
|
||||||
|
Control::Disconnect => return Ok(false),
|
||||||
|
Control::Command { request_id, command } => {
|
||||||
|
if pending.len() >= 64 { emit(json!({"type":"client_command_result","requestId":request_id,"ok":false})).map_err(|_| ())?; }
|
||||||
|
else {
|
||||||
|
match client_command(connection, command) {
|
||||||
|
Ok(handle) => { pending.insert(handle.0, request_id); },
|
||||||
|
Err(()) => { emit(json!({"type":"client_command_result","requestId":request_id,"ok":false,"code":"command_not_sent"})).map_err(|_| ())?; },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Control::AudioState {
|
||||||
|
input_muted,
|
||||||
|
output_muted,
|
||||||
|
} => {
|
||||||
|
if (input_muted || output_muted) && connection.can_send_audio() {
|
||||||
|
let _ = connection.send_audio(OutAudio::new(&AudioData::C2S {
|
||||||
|
id: 0,
|
||||||
|
codec: CodecType::OpusVoice,
|
||||||
|
data: &[],
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
let mut command = OutCommand::new(
|
||||||
|
Direction::C2S,
|
||||||
|
Flags::empty(),
|
||||||
|
PacketType::Command,
|
||||||
|
"clientupdate",
|
||||||
|
);
|
||||||
|
command.write_arg("client_input_muted", &(input_muted as u8));
|
||||||
|
command.write_arg("client_output_muted", &(output_muted as u8));
|
||||||
|
command.write_arg("client_input_hardware", &1);
|
||||||
|
command.write_arg("client_output_hardware", &1);
|
||||||
|
command.send_with_result(connection).map_err(|_| ())?;
|
||||||
|
audio_status(connection).map_err(|_| ())?;
|
||||||
|
}
|
||||||
|
Control::Audio { codec, data } => {
|
||||||
|
// The upstream send_audio warns but does not enforce this permission itself.
|
||||||
|
if !connection.can_send_audio() {
|
||||||
|
return Ok(true);
|
||||||
|
}
|
||||||
|
let codec = match codec {
|
||||||
|
4 => CodecType::OpusVoice,
|
||||||
|
5 => CodecType::OpusMusic,
|
||||||
|
_ => return Err(()),
|
||||||
|
};
|
||||||
|
let data = STANDARD.decode(data).map_err(|_| ())?;
|
||||||
|
if data.len() > 1275 {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
let state = connection.get_state().map_err(|_| ())?;
|
||||||
|
let own = state.clients.get(&state.own_client).ok_or(())?;
|
||||||
|
let channel = state.channels.get(&own.channel).ok_or(())?;
|
||||||
|
if channel.codec as u8 != codec as u8 {
|
||||||
|
return Ok(true);
|
||||||
|
}
|
||||||
|
connection
|
||||||
|
.send_audio(OutAudio::new(&AudioData::C2S {
|
||||||
|
id: 0,
|
||||||
|
codec,
|
||||||
|
data: &data,
|
||||||
|
}))
|
||||||
|
.map_err(|_| ())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
|
||||||
|
enum Request {
|
||||||
|
Generate,
|
||||||
|
Import {
|
||||||
|
value: String,
|
||||||
|
},
|
||||||
|
Inspect {
|
||||||
|
identity: Identity,
|
||||||
|
},
|
||||||
|
Export {
|
||||||
|
identity: Identity,
|
||||||
|
},
|
||||||
|
Connect {
|
||||||
|
identity: Identity,
|
||||||
|
address: SocketAddr,
|
||||||
|
nickname: String,
|
||||||
|
password: Option<String>,
|
||||||
|
channel_id: Option<u64>,
|
||||||
|
channel_password: Option<String>,
|
||||||
|
seconds: u64,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit(value: Value) -> io::Result<()> {
|
||||||
|
let mut out = io::stdout().lock();
|
||||||
|
serde_json::to_writer(&mut out, &value)?;
|
||||||
|
out.write_all(b"\n")?;
|
||||||
|
out.flush()
|
||||||
|
}
|
||||||
|
fn metadata(identity: &Identity) -> Value {
|
||||||
|
json!({"uid": identity.key().to_pub().get_uid(), "level": identity.level()})
|
||||||
|
}
|
||||||
|
fn private_identity(identity: &Identity) -> io::Result<()> {
|
||||||
|
// Private stdio protocol. The Node adapter must encrypt this and never forward it.
|
||||||
|
emit(json!({"type":"identity_internal", "identity":identity, "metadata":metadata(identity)}))
|
||||||
|
}
|
||||||
|
fn error_code(error: &tsclientlib::Error) -> &'static str {
|
||||||
|
match error {
|
||||||
|
tsclientlib::Error::ConnectTs(_) => "server_rejected_connection",
|
||||||
|
tsclientlib::Error::IdentityLevel(_) => "identity_level_required",
|
||||||
|
tsclientlib::Error::ServerUidMismatch(_) => "server_identity_changed",
|
||||||
|
tsclientlib::Error::InitserverTimeout => "server_initialization_timeout",
|
||||||
|
tsclientlib::Error::ConnectFailed { .. } => "connection_failed",
|
||||||
|
tsclientlib::Error::CommandError(_) => "server_permission_or_command_error",
|
||||||
|
tsclientlib::Error::ConnectionFailed(cause) | tsclientlib::Error::SendPacket(cause) => match cause {
|
||||||
|
tsproto::client::Error::TsProto(cause) => match cause {
|
||||||
|
tsproto::Error::NotInReceiveWindow { .. } => "packet_receive_window_exceeded",
|
||||||
|
tsproto::Error::WrongMac { .. } => "packet_authentication_failed",
|
||||||
|
tsproto::Error::DecompressPacket(_) => "packet_decompression_failed",
|
||||||
|
tsproto::Error::MaxLengthExceeded("command queue") => "command_reorder_capacity_exceeded",
|
||||||
|
tsproto::Error::MaxLengthExceeded("fragment queue") => "fragment_capacity_exceeded",
|
||||||
|
tsproto::Error::MaxLengthExceeded(_) => "packet_capacity_exceeded",
|
||||||
|
tsproto::Error::Network(_) => "protocol_network_error",
|
||||||
|
tsproto::Error::PacketParse(_, _) => "packet_parse_failed",
|
||||||
|
tsproto::Error::WrongClientId(_) => "packet_client_id_mismatch",
|
||||||
|
tsproto::Error::UnexpectedInitPacket => "unexpected_initialization_packet",
|
||||||
|
tsproto::Error::UnallowedUnencryptedPacket => "unencrypted_packet_rejected",
|
||||||
|
_ => "protocol_packet_error",
|
||||||
|
},
|
||||||
|
tsproto::client::Error::ConnectionEnd => "server_connection_ended",
|
||||||
|
_ => "protocol_connection_failed",
|
||||||
|
},
|
||||||
|
tsclientlib::Error::Io(_) => "protocol_io_error",
|
||||||
|
tsclientlib::Error::ConnectionGone => "server_connection_ended",
|
||||||
|
_ => "protocol_error",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn snapshot(connection: &Connection, sequence: u64) -> Option<Value> {
|
||||||
|
let state = connection.get_state().ok()?;
|
||||||
|
if state.channels.len() > 4096 || state.clients.len() > 4096 {
|
||||||
|
return Some(json!({"type":"error", "code":"server_state_capacity_exceeded"}));
|
||||||
|
}
|
||||||
|
let channels: Vec<Value> = state
|
||||||
|
.channels
|
||||||
|
.values()
|
||||||
|
.map(|channel| {
|
||||||
|
json!({
|
||||||
|
"id": channel.id.0, "parentId":channel.parent.0, "name":channel.name,
|
||||||
|
"order": channel.order.0, "subscribed": channel.subscribed,
|
||||||
|
"codec": channel.codec as u8,
|
||||||
|
"passwordProtected": channel.has_password,
|
||||||
|
"temporary": channel.channel_type == ChannelType::Temporary,
|
||||||
|
"topic": channel.topic,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let participants: Vec<Value> = state
|
||||||
|
.clients
|
||||||
|
.values()
|
||||||
|
.map(|client| {
|
||||||
|
json!({
|
||||||
|
"id":client.id.0, "channelId":client.channel.0, "name":client.name,
|
||||||
|
"uid":client.uid.as_ref().map(|uid| uid.to_string()),
|
||||||
|
"inputMuted": client.input_muted, "outputMuted":client.output_muted,
|
||||||
|
"awayMessage": client.away_message,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
Some(
|
||||||
|
json!({"type":"state", "sequence":sequence, "server":{"name":state.server.name},
|
||||||
|
"ownClientId":state.own_client.0, "channels":channels, "participants":participants}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run() -> Result<(), ()> {
|
||||||
|
let mut input = BufReader::new(tokio::io::stdin()).lines();
|
||||||
|
let line = input.next_line().await.map_err(|_| ())?.ok_or(())?;
|
||||||
|
if line.len() > 65536 {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
let request: Request = serde_json::from_str(&line).map_err(|_| ())?;
|
||||||
|
match request {
|
||||||
|
Request::Generate => {
|
||||||
|
let mut identity = Identity::create();
|
||||||
|
identity.upgrade_level(16);
|
||||||
|
private_identity(&identity).map_err(|_| ())?;
|
||||||
|
}
|
||||||
|
Request::Import { value } => {
|
||||||
|
if value.len() > 16384 {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
let identity = Identity::new_from_str(&value).map_err(|_| ())?;
|
||||||
|
private_identity(&identity).map_err(|_| ())?;
|
||||||
|
}
|
||||||
|
Request::Inspect { identity } => {
|
||||||
|
emit(json!({"type":"identity_metadata", "metadata":metadata(&identity)}))
|
||||||
|
.map_err(|_| ())?;
|
||||||
|
}
|
||||||
|
Request::Export { identity } => {
|
||||||
|
emit(json!({"type":"export_internal", "value":format!("{}V{}",identity.counter(),identity.key().to_ts_obfuscated())})).map_err(|_| ())?;
|
||||||
|
}
|
||||||
|
Request::Connect {
|
||||||
|
identity,
|
||||||
|
address,
|
||||||
|
nickname,
|
||||||
|
password,
|
||||||
|
channel_id,
|
||||||
|
channel_password,
|
||||||
|
seconds,
|
||||||
|
} => {
|
||||||
|
if nickname.is_empty() || nickname.chars().count() > 64 || !(1..=240).contains(&seconds)
|
||||||
|
{
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
let mut options = Connection::build(address)
|
||||||
|
.identity(identity)
|
||||||
|
.name(nickname)
|
||||||
|
.input_muted(true)
|
||||||
|
.output_muted(true)
|
||||||
|
.input_hardware_enabled(false)
|
||||||
|
.output_hardware_enabled(false)
|
||||||
|
.log_commands(false)
|
||||||
|
.log_packets(false)
|
||||||
|
.log_udp_packets(false);
|
||||||
|
if let Some(password) = password {
|
||||||
|
options = options.password(password);
|
||||||
|
}
|
||||||
|
if let Some(channel_id) = channel_id { options = options.channel_id(ChannelId(channel_id)); }
|
||||||
|
if let Some(password) = channel_password { if password.len() > 256 { return Err(()); } options = options.channel_password(password); }
|
||||||
|
let mut connection = options.connect().map_err(|_| ())?;
|
||||||
|
emit(json!({"type":"status", "status":"connecting"})).map_err(|_| ())?;
|
||||||
|
let lifetime = tokio::time::sleep(Duration::from_secs(seconds));
|
||||||
|
let handshake = tokio::time::sleep(Duration::from_secs(25));
|
||||||
|
tokio::pin!(lifetime, handshake);
|
||||||
|
let mut connected = false;
|
||||||
|
let mut sequence = 0u64;
|
||||||
|
let mut pending_commands = HashMap::new();
|
||||||
|
loop {
|
||||||
|
tokio::select! {
|
||||||
|
_ = &mut lifetime => { emit(json!({"type":"status","status":"session_limit"})).map_err(|_| ())?; break; }
|
||||||
|
_ = &mut handshake, if !connected => { emit(json!({"type":"error","code":"handshake_timeout","inconclusive":true})).map_err(|_| ())?; break; }
|
||||||
|
command = input.next_line() => {
|
||||||
|
match command {
|
||||||
|
Ok(Some(line)) if line.len() <= 4096 => {
|
||||||
|
let command = serde_json::from_str::<Control>(&line).map_err(|_| ())?;
|
||||||
|
if !control(&mut connection, command, &mut pending_commands)? { break; }
|
||||||
|
}
|
||||||
|
_ => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
event = async { connection.events().next().await } => {
|
||||||
|
match event {
|
||||||
|
Some(Ok(StreamItem::BookEvents(events))) => {
|
||||||
|
if !connected {
|
||||||
|
connected = true;
|
||||||
|
// Reconnection never re-enables audio without another owner action.
|
||||||
|
control(&mut connection, Control::AudioState { input_muted: true, output_muted: true }, &mut pending_commands)?;
|
||||||
|
emit(json!({"type":"status","status":"connected"})).map_err(|_| ())?;
|
||||||
|
let subscribe = connection.get_state().map_err(|_| ())?.server.set_subscribed(true);
|
||||||
|
if subscribe.send(&mut connection).is_err() {
|
||||||
|
emit(json!({"type":"warning","code":"subscription_unavailable"})).map_err(|_| ())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for event in events {
|
||||||
|
if let tsclientlib::events::Event::Message { target, invoker, message } = event {
|
||||||
|
let target_client_id = match target { MessageTarget::Client(id) | MessageTarget::Poke(id) => Some(id.0), _ => None };
|
||||||
|
let target_uid = target_client_id.and_then(|id| connection.get_state().ok().and_then(|state| state.clients.get(&ClientId(id)).and_then(|client| client.uid.as_ref()).map(|uid| uid.to_string())));
|
||||||
|
let target = match target { MessageTarget::Server => "server", MessageTarget::Channel => "channel", MessageTarget::Client(_) => "private", MessageTarget::Poke(_) => "poke" };
|
||||||
|
let channel_id = connection.get_state().ok().and_then(|state| state.clients.get(&state.own_client).map(|client| client.channel.0));
|
||||||
|
emit(json!({"type":"message","target":target,"clientId":invoker.id.0,"targetClientId":target_client_id,"uid":invoker.uid.as_ref().map(|uid| uid.to_string()),"targetUid":target_uid,"name":invoker.name,"message":message.chars().take(4096).collect::<String>(),"channelId":channel_id})).map_err(|_| ())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sequence += 1;
|
||||||
|
if let Some(state) = snapshot(&connection, sequence) { emit(state).map_err(|_| ())?; }
|
||||||
|
}
|
||||||
|
Some(Ok(StreamItem::Audio(audio))) => {
|
||||||
|
let packet = audio.data();
|
||||||
|
let data = packet.data();
|
||||||
|
let (from, whisper) = match &data {
|
||||||
|
AudioData::S2C { from, .. } => (*from, false),
|
||||||
|
AudioData::S2CWhisper { from, .. } => (*from, true),
|
||||||
|
_ => continue,
|
||||||
|
};
|
||||||
|
if data.data().len() <= 1275 {
|
||||||
|
emit(json!({"type":"audio", "clientId":from, "sequence":data.id(), "codec":data.codec() as u8, "whisper":whisper, "data":STANDARD.encode(data.data())})).map_err(|_| ())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(Ok(StreamItem::AudioChange(_))) => { audio_status(&connection).map_err(|_| ())?; }
|
||||||
|
Some(Ok(StreamItem::MessageResult(handle, result))) => {
|
||||||
|
if let Some(request_id) = pending_commands.remove(&handle.0) {
|
||||||
|
let server_error = result.as_ref().err().map(|error| error.error as u32);
|
||||||
|
let missing_permission = result.as_ref().err().and_then(|error| error.missing_permission.map(|permission| permission.0));
|
||||||
|
emit(json!({"type":"client_command_result", "requestId":request_id, "ok":result.is_ok(), "serverError":server_error,"missingPermission":missing_permission})).map_err(|_| ())?;
|
||||||
|
} else { emit(json!({"type":"command_result", "requestId":handle.0, "ok":result.is_ok()})).map_err(|_| ())?; }
|
||||||
|
}
|
||||||
|
Some(Ok(StreamItem::IdentityLevelIncreasing(level))) => {
|
||||||
|
emit(json!({"type":"status","status":"identity_level_increasing","requiredLevel":level})).map_err(|_| ())?;
|
||||||
|
if level > 24 { connection.cancel_identity_level_increase(); break; }
|
||||||
|
}
|
||||||
|
Some(Ok(StreamItem::IdentityLevelIncreased)) => {
|
||||||
|
if let Some(identity) = connection.get_options().get_identity() { private_identity(identity).map_err(|_| ())?; }
|
||||||
|
}
|
||||||
|
Some(Ok(StreamItem::DisconnectedTemporarily(_))) => {
|
||||||
|
connected = false;
|
||||||
|
emit(json!({"type":"status","status":"reconnecting"})).map_err(|_| ())?;
|
||||||
|
handshake.as_mut().reset(tokio::time::Instant::now()+Duration::from_secs(25));
|
||||||
|
}
|
||||||
|
Some(Err(error)) => {
|
||||||
|
emit(json!({"type":"error","code":error_code(&error)})).map_err(|_| ())?;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
None => break,
|
||||||
|
_ => {},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if connection.disconnect(DisconnectOptions::new()).is_ok() {
|
||||||
|
let _ = tokio::time::timeout(Duration::from_secs(1), async {
|
||||||
|
while connection.events().next().await.is_some() {}
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
emit(json!({"type":"status","status":"disconnected"})).map_err(|_| ())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() {
|
||||||
|
// No tracing subscriber: protocol packets, keys and passwords never enter logs.
|
||||||
|
if run().await.is_err() {
|
||||||
|
let _ = emit(json!({"type":"error","code":"invalid_request_or_native_failure"}));
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
+85
@@ -0,0 +1,85 @@
|
|||||||
|
--- a/tsproto/src/lib.rs
|
||||||
|
+++ b/tsproto/src/lib.rs
|
||||||
|
@@ -53,7 +53,9 @@
|
||||||
|
|
||||||
|
/// The maximum number of packets which are stored, if they are received
|
||||||
|
/// out-of-order.
|
||||||
|
-const MAX_QUEUE_LEN: u16 = 200;
|
||||||
|
+// A high-latency initial channel burst can span more than 200 packet IDs
|
||||||
|
+// before a missing command is retransmitted. Keep a bounded reorder window.
|
||||||
|
+const MAX_QUEUE_LEN: u16 = 2048;
|
||||||
|
|
||||||
|
/// The maximum decompressed size of a packet.
|
||||||
|
#[allow(clippy::unreadable_literal)]
|
||||||
|
--- a/tsproto/src/packet_codec.rs
|
||||||
|
+++ b/tsproto/src/packet_codec.rs
|
||||||
|
@@ -343,7 +343,13 @@
|
||||||
|
if (!next_gen && id >= cur_next && id < limit)
|
||||||
|
|| (next_gen && (id >= cur_next || id < limit))
|
||||||
|
{
|
||||||
|
- r_queue.push(packet_data);
|
||||||
|
+ // Retransmissions must not grow the queue or survive as stale duplicates.
|
||||||
|
+ if !r_queue.iter().any(|p| InHeader::new(dir, p).packet_id() == id) {
|
||||||
|
+ if r_queue.len() >= usize::from(MAX_QUEUE_LEN) {
|
||||||
|
+ return Err(Error::MaxLengthExceeded("command queue"));
|
||||||
|
+ }
|
||||||
|
+ r_queue.push(packet_data);
|
||||||
|
+ }
|
||||||
|
Ok(vec![])
|
||||||
|
} else {
|
||||||
|
Err(Error::MaxLengthExceeded("command queue"))
|
||||||
|
@@ -459,3 +465,54 @@
|
||||||
|
Ok(packets)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
+
|
||||||
|
+#[cfg(test)]
|
||||||
|
+mod reorder_tests {
|
||||||
|
+ use super::*;
|
||||||
|
+
|
||||||
|
+ fn packet(id: u16, kind: PacketType) -> Vec<u8> {
|
||||||
|
+ OutPacket::new([0; 8], id, None, Flags::empty(), kind).into_vec()
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ async fn connection() -> Connection {
|
||||||
|
+ let socket = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
+ Connection::new(true, "127.0.0.1:9987".parse().unwrap(), Box::new(socket))
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ #[tokio::test]
|
||||||
|
+ async fn burst_waits_for_missing_command_and_drains_in_order() {
|
||||||
|
+ let mut con = connection().await;
|
||||||
|
+ for id in (1..MAX_QUEUE_LEN).rev() {
|
||||||
|
+ assert!(PacketCodec::handle_command_packet(&mut con, packet(id, PacketType::Command)).unwrap().is_empty());
|
||||||
|
+ }
|
||||||
|
+ for _ in 0..100 {
|
||||||
|
+ PacketCodec::handle_command_packet(&mut con, packet(300, PacketType::Command)).unwrap();
|
||||||
|
+ }
|
||||||
|
+ assert_eq!(con.codec.receive_queue[0].len(), usize::from(MAX_QUEUE_LEN - 1));
|
||||||
|
+ assert!(matches!(PacketCodec::handle_command_packet(&mut con, packet(MAX_QUEUE_LEN, PacketType::Command)), Err(Error::MaxLengthExceeded("command queue"))));
|
||||||
|
+ let packets = PacketCodec::handle_command_packet(&mut con, packet(0, PacketType::Command)).unwrap();
|
||||||
|
+ assert_eq!(packets.len(), usize::from(MAX_QUEUE_LEN));
|
||||||
|
+ for (id, bytes) in packets.iter().enumerate() {
|
||||||
|
+ assert_eq!(InHeader::new(Direction::S2C, bytes).packet_id(), id as u16);
|
||||||
|
+ }
|
||||||
|
+ assert!(con.codec.receive_queue[0].is_empty());
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ #[tokio::test]
|
||||||
|
+ async fn reorder_window_wraps_and_command_priorities_remain_independent() {
|
||||||
|
+ let mut con = connection().await;
|
||||||
|
+ let start = u16::MAX - 100;
|
||||||
|
+ con.codec.incoming_p_ids[PacketType::Command as usize].packet_id = start;
|
||||||
|
+ for offset in (1..350u16).rev() {
|
||||||
|
+ PacketCodec::handle_command_packet(&mut con, packet(start.wrapping_add(offset), PacketType::Command)).unwrap();
|
||||||
|
+ }
|
||||||
|
+ PacketCodec::handle_command_packet(&mut con, packet(1, PacketType::CommandLow)).unwrap();
|
||||||
|
+ let packets = PacketCodec::handle_command_packet(&mut con, packet(start, PacketType::Command)).unwrap();
|
||||||
|
+ assert_eq!(packets.len(), 350);
|
||||||
|
+ for (offset, bytes) in packets.iter().enumerate() {
|
||||||
|
+ assert_eq!(InHeader::new(Direction::S2C, bytes).packet_id(), start.wrapping_add(offset as u16));
|
||||||
|
+ }
|
||||||
|
+ assert_eq!(con.codec.receive_queue[1].len(), 1);
|
||||||
|
+ assert_eq!(PacketCodec::handle_command_packet(&mut con, packet(0, PacketType::CommandLow)).unwrap().len(), 2);
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
Vendored
+24
@@ -0,0 +1,24 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"project": "ReSpeak/tsclientlib",
|
||||||
|
"revision": "ee3bc6f45a7137db7793ba5593a321df400d53e5",
|
||||||
|
"archiveSha256": "65c12cc22758985436242470974d497343df6077c946c8b874ca165f6044b092",
|
||||||
|
"method": "GitHub source archive; no Git checkout or metadata",
|
||||||
|
"localPatches": [
|
||||||
|
{
|
||||||
|
"path": "raw-audio.patch",
|
||||||
|
"purpose": "Expose encoded audio stream variants without the native codec module; preserve existing transport encryption and permission handling"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "bounded-reordering.patch",
|
||||||
|
"purpose": "Bounded 2048-packet command reordering with duplicate suppression for high-latency synchronization bursts; encryption and authentication unchanged; includes ordered-drain and sequence-wrap tests"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"project": "ReSpeak/tsdeclarations",
|
||||||
|
"revision": "83cb8a94b65021bb8ec4beb339e5bfbdd93df60f",
|
||||||
|
"archiveSha256": "3dcfb83b8474a851723a30e8baa2a22d8f44de9c130386c6a4501516edfded66",
|
||||||
|
"method": "GitHub source archive; no Git checkout or metadata"
|
||||||
|
}
|
||||||
|
]
|
||||||
Vendored
+78
@@ -0,0 +1,78 @@
|
|||||||
|
--- a/tsclientlib/src/lib.rs
|
||||||
|
+++ b/tsclientlib/src/lib.rs
|
||||||
|
@@ -38,7 +38,7 @@
|
||||||
|
use tsproto::connection::StreamItem as ProtoStreamItem;
|
||||||
|
use tsproto::resend::ResenderState;
|
||||||
|
use tsproto_packets::commands::{CommandItem, CommandParser};
|
||||||
|
-#[cfg(feature = "audio")]
|
||||||
|
+#[cfg(any(feature = "audio", feature = "raw-audio"))]
|
||||||
|
use tsproto_packets::packets::InAudioBuf;
|
||||||
|
use tsproto_packets::packets::{InCommandBuf, OutCommand, OutPacket, PacketType};
|
||||||
|
|
||||||
|
@@ -214,7 +214,7 @@
|
||||||
|
///
|
||||||
|
/// Audio packets can be handled by the [`AudioHandler`](audio::AudioHandler), which builds a
|
||||||
|
/// queue per client and handles packet loss and jitter.
|
||||||
|
- #[cfg(feature = "audio")]
|
||||||
|
+ #[cfg(any(feature = "audio", feature = "raw-audio"))]
|
||||||
|
Audio(InAudioBuf),
|
||||||
|
/// The needed level.
|
||||||
|
IdentityLevelIncreasing(u8),
|
||||||
|
@@ -1092,7 +1092,7 @@
|
||||||
|
/// If the current channel (and server) allow unencrypted voice packets.
|
||||||
|
///
|
||||||
|
/// For whisper packets, only the server setting is checked.
|
||||||
|
- #[cfg(feature = "audio")]
|
||||||
|
+ #[cfg(any(feature = "audio", feature = "raw-audio"))]
|
||||||
|
fn intern_can_receive_unencrypted_audio(book: &data::Connection, whisper: bool) -> bool {
|
||||||
|
match book.server.codec_encryption_mode {
|
||||||
|
CodecEncryptionMode::ForcedOn => false,
|
||||||
|
@@ -1215,7 +1215,7 @@
|
||||||
|
ProtoStreamItem::Error(error) => {
|
||||||
|
warn!(%error, "Connection got a non-fatal error");
|
||||||
|
}
|
||||||
|
- #[cfg(feature = "audio")]
|
||||||
|
+ #[cfg(any(feature = "audio", feature = "raw-audio"))]
|
||||||
|
ProtoStreamItem::Audio(audio) => {
|
||||||
|
if !Self::intern_can_receive_audio(book, &self.options) {
|
||||||
|
info!("Received audio packet while output is muted, ignoring");
|
||||||
|
--- a/tsclientlib/Cargo.toml
|
||||||
|
+++ b/tsclientlib/Cargo.toml
|
||||||
|
@@ -23,6 +23,8 @@
|
||||||
|
# Enable the unstable api
|
||||||
|
unstable = []
|
||||||
|
audio = ["audiopus"]
|
||||||
|
+# Forward encoded packets without linking a native audio codec.
|
||||||
|
+raw-audio = []
|
||||||
|
# Enable default reqwest features.
|
||||||
|
# Use default-features=false on tsclientlib to configure reqwest differently.
|
||||||
|
default-tls = ["reqwest/charset", "reqwest/default-tls", "reqwest/http2"]
|
||||||
|
--- a/tsclientlib/src/sync.rs
|
||||||
|
+++ b/tsclientlib/src/sync.rs
|
||||||
|
@@ -11,7 +11,7 @@
|
||||||
|
use tokio::sync::{mpsc, oneshot};
|
||||||
|
use tracing::{error, info};
|
||||||
|
use ts_bookkeeping::ChannelId;
|
||||||
|
-#[cfg(feature = "audio")]
|
||||||
|
+#[cfg(any(feature = "audio", feature = "raw-audio"))]
|
||||||
|
use tsproto_packets::packets::InAudioBuf;
|
||||||
|
#[cfg(feature = "unstable")]
|
||||||
|
use tsproto_packets::packets::OutCommand;
|
||||||
|
@@ -62,7 +62,7 @@
|
||||||
|
///
|
||||||
|
/// Audio packets can be handled by the [`AudioHandler`](crate::audio::AudioHandler), which
|
||||||
|
/// builds a queue per client and handles packet loss and jitter.
|
||||||
|
- #[cfg(feature = "audio")]
|
||||||
|
+ #[cfg(any(feature = "audio", feature = "raw-audio"))]
|
||||||
|
Audio(InAudioBuf),
|
||||||
|
/// The needed level.
|
||||||
|
IdentityLevelIncreasing(u8),
|
||||||
|
@@ -234,7 +234,7 @@
|
||||||
|
SyncStreamItem::BookEvents(i)
|
||||||
|
}
|
||||||
|
StreamItem::MessageEvent(i) => SyncStreamItem::MessageEvent(i),
|
||||||
|
- #[cfg(feature = "audio")]
|
||||||
|
+ #[cfg(any(feature = "audio", feature = "raw-audio"))]
|
||||||
|
StreamItem::Audio(i) => SyncStreamItem::Audio(i),
|
||||||
|
StreamItem::IdentityLevelIncreasing(i) => {
|
||||||
|
SyncStreamItem::IdentityLevelIncreasing(i)
|
||||||
+61
@@ -0,0 +1,61 @@
|
|||||||
|
# Changelog
|
||||||
|
All notable changes to this project will be documented in this file.
|
||||||
|
|
||||||
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||||
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
|
## [Unreleased]
|
||||||
|
### ℹ Changed
|
||||||
|
- Switched from `slog` to `tracing` for logging
|
||||||
|
- Update dependencies (updates some exposed types)
|
||||||
|
|
||||||
|
## [0.2.0] - 2021-05-12
|
||||||
|
### ✨ Added
|
||||||
|
- 🎵 An audio queue that automatically sort, decode and handle lost audio packets
|
||||||
|
- Audio example for `tsclientlib`
|
||||||
|
- Send audio packets with `Connection::send_audio`
|
||||||
|
- ⏫ Automatically improve identity level if it is not high enough
|
||||||
|
- 🔓 Add `channel`, `channel_password` and (server-)`password` to `ConnectOptions`
|
||||||
|
- 📂 Filetransfer: Download and upload files from and to TeamSpeak servers
|
||||||
|
- Most structs can be serialized with `serde` now
|
||||||
|
- `Reason` to events that support it, that allows distinguishing between client joins and subscription events
|
||||||
|
- Add ability to check server identity when connecting as `ConnectOptions::server`
|
||||||
|
- `StreamItem::MessageEvent` for non-book events
|
||||||
|
|
||||||
|
### ℹ Changed
|
||||||
|
- ➠ Upgrade from `futures` 0.1 to 0.3 and `tokio` 0.1 to 1.0 for `async`/`await` support
|
||||||
|
- 🔒 Rewrite `tsproto` and `tsclientlib` to be a single, non-cloneable object. This removes all locks
|
||||||
|
- 🚀 Many performance improvements
|
||||||
|
- New command parser, 2–2.5× faster than the old one
|
||||||
|
- New command serializer, 2× faster than the old one
|
||||||
|
- Switched error handling library from `failure` to `thiserror`
|
||||||
|
- Now licensed under MIT/Apache 2.0 (previously under OSL 2.0)
|
||||||
|
- Commands are now sent with `command.send(&mut connection)?`
|
||||||
|
- A new connection should now be created with `ConnectOptions::connect` instead of `Connection::new`
|
||||||
|
- Multiple renamings in the book
|
||||||
|
- Rename `StreamItem::ConEvents` to `StreamItem::BookEvents`
|
||||||
|
- Rename `UidRef` to `Uid` and make it a dynamically sized type. The previously owned `Uid` type is now called `UidBuf`
|
||||||
|
- Replace `ring` with RustCrypto crates to get rid of the `flakebi-ring` crate
|
||||||
|
|
||||||
|
### ❌ Removed
|
||||||
|
- The `ConnectionManager` in `tsproto` was removed
|
||||||
|
|
||||||
|
### 🐛 Fixed
|
||||||
|
- Hashcash implementation counts leading zeroes from lsb instead of msb
|
||||||
|
- Use `3.?.?` version by default to allow connecting to newer TeamSpeak servers
|
||||||
|
- Fix channel order handling
|
||||||
|
- Use `git-testament` instead of `built`, this removes building libgit
|
||||||
|
- Fix encoding newlines in commands
|
||||||
|
- The last `Ack` packet is sent reliably now, previously it was lost sometimes
|
||||||
|
- Fix connecting to servers behind certain protections by restart sending init packets
|
||||||
|
- Try to reconnect infinitely after a timeout
|
||||||
|
- Keep channel and muted state when reconnecting
|
||||||
|
- Automatically subscribe to new channels when the server is subscribed
|
||||||
|
|
||||||
|
## [0.1.0] - 2019-04-14
|
||||||
|
### Added
|
||||||
|
- First release on crates.io for
|
||||||
|
- tsclientlib
|
||||||
|
- tsproto
|
||||||
|
- tsproto-commands
|
||||||
|
- tsproto-structs
|
||||||
Vendored
+10
@@ -0,0 +1,10 @@
|
|||||||
|
[workspace]
|
||||||
|
resolver = "2"
|
||||||
|
members = [
|
||||||
|
"tsclientlib",
|
||||||
|
"tsproto",
|
||||||
|
"utils/ts-bookkeeping",
|
||||||
|
"utils/tsproto-packets",
|
||||||
|
"utils/tsproto-structs",
|
||||||
|
"utils/tsproto-types",
|
||||||
|
]
|
||||||
+201
@@ -0,0 +1,201 @@
|
|||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
The MIT License (MIT)
|
||||||
|
|
||||||
|
Copyright (c) 2017-2020 tsclientlib contributors
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
Vendored
+115
@@ -0,0 +1,115 @@
|
|||||||
|
# TsClientlib [](https://ci.appveyor.com/project/Flakebi/tsclientlib/branch/master)
|
||||||
|
TsClientlib is a library that enables you to write voip clients and bots using
|
||||||
|
the TeamSpeak protocol.
|
||||||
|
|
||||||
|
> TeamSpeak is a proprietary voice-over-Internet Protocol (VoIP) application for
|
||||||
|
> audio communication between users on a chat channel, much like a telephone
|
||||||
|
> conference call. Users typically use headphones with a microphone. The client
|
||||||
|
> software connects to a TeamSpeak server of the user's choice, from which the
|
||||||
|
> user may join chat channels. – [Wikipedia](https://en.wikipedia.org/wiki/Teamspeak)
|
||||||
|
|
||||||
|
The various libraries in this repository are currently a work in progress so
|
||||||
|
don‘t expect everything to work. Many things you would expect from a
|
||||||
|
library are working, like connecting, getting events, writing and receiving
|
||||||
|
messages, etc. Some features like automatic reconnects are not yet there.
|
||||||
|
|
||||||
|
If you are searching for a usable client instead of a library,
|
||||||
|
[Qint](https://github.com/ReSpeak/Qint) will be a cross-platform TeamSpeak
|
||||||
|
client, which is based on this library (but it is not ready yet).
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- [Rust](https://rust-lang.org) (preferred installation method is [rustup](https://rustup.rs))
|
||||||
|
- [OpenSSL](https://www.openssl.org) 1.1 (linux only)
|
||||||
|
|
||||||
|
## Getting Started
|
||||||
|
An example of a simple chat bot can be found [here](https://github.com/ReSpeak/SimpleBot).
|
||||||
|
|
||||||
|
## Clone
|
||||||
|
This repository embeds the [declarations](https://github.com/ReSpeak/tsdeclarations) as submodule. You can clone with
|
||||||
|
```
|
||||||
|
git clone https://github.com/ReSpeak/tsclientlib.git --recurse-submodules
|
||||||
|
```
|
||||||
|
or download the submodule afterwards with
|
||||||
|
```
|
||||||
|
git clone https://github.com/ReSpeak/tsclientlib.git
|
||||||
|
cd tsclientlib
|
||||||
|
git submodule update --init --recursive
|
||||||
|
```
|
||||||
|
|
||||||
|
## Build and run the example client
|
||||||
|
The code can be found [here](tsclientlib/examples/simple.rs).
|
||||||
|
```
|
||||||
|
cd tsclientlib
|
||||||
|
cargo run --example simple
|
||||||
|
```
|
||||||
|
|
||||||
|
## Build and run the example audio client
|
||||||
|
The code can be found [here](tsclientlib/examples/audio.rs).
|
||||||
|
```
|
||||||
|
cd tsclientlib
|
||||||
|
cargo run --example audio
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## Projects
|
||||||
|
You probably want to use tsclientlib, it builds upon all other projects. This
|
||||||
|
list shows what each library does and it may be useful if you want to help
|
||||||
|
developing.
|
||||||
|
|
||||||
|
- `tsclientlib`: This is the main product of this repository, a simple to use TeamSpeak library
|
||||||
|
- `tsproto`: The low level library that does the network part. You probably don't want to use that, but a higher level library like tsclientlib.
|
||||||
|
|
||||||
|
### Utils
|
||||||
|
The utils folder contains smaller building blocks for the library.
|
||||||
|
|
||||||
|
- `ts-bookkeeping`: This crates keeps book of the currently connected clients and channels of a server.
|
||||||
|
- `tsproto-packets`: Parse packets and commands.
|
||||||
|
- `tsproto-structs`: Contains parsed versions of the [tsdeclarations](https://github.com/ReSpeak/tsdeclarations).
|
||||||
|
- `tsproto-types`: Contains basic types for TeamSpeak, e.g. versions and error codes.
|
||||||
|
|
||||||
|
## How this works
|
||||||
|
`tsproto` implements the basic TeamSpeak protocol stuff (uh, who would have
|
||||||
|
expected that), which comes down to creating a connection, make sure that udp
|
||||||
|
packets are delivered, encrypt and compress the communication and give access to
|
||||||
|
all these low-level things.
|
||||||
|
|
||||||
|
The convenient client library on top is `tsclientlib`. It uses all the versions,
|
||||||
|
messages, structures and errors which are written down in a
|
||||||
|
[machine readable format](https://github.com/ReSpeak/tsdeclarations) and
|
||||||
|
provides a nice and safe api.
|
||||||
|
|
||||||
|
## Performance
|
||||||
|
For benchmarks, a TeamSpeak server has to run at localhost. Run
|
||||||
|
```
|
||||||
|
cd tsproto
|
||||||
|
cargo bench -- <name>
|
||||||
|
```
|
||||||
|
where `<name>` is `connect` or `message`.
|
||||||
|
|
||||||
|
On a i7-5280K with 6 cores/12 threads @3.6 GHz, which uses more or less only one
|
||||||
|
thread because we only test a single connection, we get:
|
||||||
|
|
||||||
|
- 199 ms for creating one connection, which means 6.5 connections per second. This comes down to solving the RSA puzzle at the beginning of a connection, not much else plays a role. Be sure to run the benchmark with `--features rug` to get an efficient big integer implementation, otherwise it will fall back to a slower implementation.
|
||||||
|
- 189 µs for sending a message, which means 5300 messages per second. The benchmark is not perfectly accurate as it does not wait for all packets to be sent.
|
||||||
|
|
||||||
|
## Miscellaneous
|
||||||
|
This project is not an official TeamSpeak project. We started to write an own
|
||||||
|
client for fun and because we want some features (and bugfixes) which are not
|
||||||
|
available in the official client.
|
||||||
|
|
||||||
|
That said, we do not want to harm the company behind TeamSpeak because we like
|
||||||
|
their product. Otherwise we would just use something else and not write our own
|
||||||
|
client 😉. As TeamSpeak earns its money with selling servers and thus their
|
||||||
|
existence depends on it, we will not publish any server related code and we
|
||||||
|
encourage you to do the same (this may change with the new licensing system,
|
||||||
|
introduced in the 3.1 server).
|
||||||
|
|
||||||
|
Thanks TeamSpeak for your software!
|
||||||
|
|
||||||
|
## License
|
||||||
|
Licensed under either of
|
||||||
|
|
||||||
|
* [Apache License, Version 2.0](LICENSE-APACHE)
|
||||||
|
* [MIT license](LICENSE-MIT)
|
||||||
|
|
||||||
|
at your option.
|
||||||
+1
@@ -0,0 +1 @@
|
|||||||
|
doc-valid-idents = ["MiB", "GiB", "TiB", "PiB", "EiB", "TeamSpeak", "TeamSpeak3", "PRIME256v1"]
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -e
|
||||||
|
# Measure the latency of recording (a microphone) with the ts client, sending it
|
||||||
|
# to the server and to another client again and playing it.
|
||||||
|
|
||||||
|
if [[ -f ~/.TsLatencyPulseaudioLoop ]]; then
|
||||||
|
echo Removing modules
|
||||||
|
# Try to unload first
|
||||||
|
while read -r line; do
|
||||||
|
pactl unload-module $line || true
|
||||||
|
done < ~/.TsLatencyPulseaudioLoop
|
||||||
|
|
||||||
|
rm -f ~/.TsLatencyPulseaudioLoop
|
||||||
|
fi
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
if [[ -n $1 ]]; then
|
||||||
|
exit
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Either TeamSpeak3 or voice-client
|
||||||
|
from='"audio-latency"'
|
||||||
|
to='"audio-latency"'
|
||||||
|
|
||||||
|
# The sink for the music
|
||||||
|
pactl load-module module-null-sink sink_name=latency_nullsink object.linger=1 media.class=Audio/Sink sink_properties=device.description=LatencySink >> ~/.TsLatencyPulseaudioLoop
|
||||||
|
# The sink for TeamSpeak
|
||||||
|
pactl load-module module-null-sink sink_name=latency_tssink object.linger=1 media.class=Audio/Sink sink_properties=device.description=LatencyTsSink >> ~/.TsLatencyPulseaudioLoop
|
||||||
|
echo Created modules
|
||||||
|
|
||||||
|
# Find source-output id of teamspeak
|
||||||
|
id=`pactl list source-outputs | grep "$from" -B20 | grep "Source Output" | cut -d# -f2`
|
||||||
|
echo Found output "$from": "$id"
|
||||||
|
# Connect nullsink to teamspeak3
|
||||||
|
pactl move-source-output $id latency_nullsink.monitor
|
||||||
|
|
||||||
|
# Find source-output id of teamspeak
|
||||||
|
id=`pactl list sink-inputs | grep "$to" -B20 | grep "Sink Input" | cut -d# -f2`
|
||||||
|
echo Found input "$to": "$id"
|
||||||
|
# Connect teamspeak3 to nullsink
|
||||||
|
pactl move-sink-input $id latency_tssink
|
||||||
|
|
||||||
|
|
||||||
|
# Now measure latency
|
||||||
|
echo Starting measurement
|
||||||
|
gst-launch-1.0 -v pulsesrc device=latency_tssink.monitor ! audiolatency print-latency=true ! pulsesink device=latency_nullsink
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
[package]
|
||||||
|
name = "tsclientlib"
|
||||||
|
version = "0.2.0"
|
||||||
|
authors = ["Flakebi <flakebi@t-online.de>"]
|
||||||
|
description = "A library to create TeamSpeak clients and bots."
|
||||||
|
repository = "https://github.com/ReSpeak/tsclientlib"
|
||||||
|
readme = "README.md"
|
||||||
|
keywords = ["teamspeak3", "ts3", "voip"]
|
||||||
|
categories = ["multimedia"]
|
||||||
|
license = "MIT OR Apache-2.0"
|
||||||
|
edition = "2018"
|
||||||
|
include = [
|
||||||
|
"/Cargo.toml",
|
||||||
|
"/README.md",
|
||||||
|
"**/*.rs",
|
||||||
|
]
|
||||||
|
|
||||||
|
[package.metadata.docs.rs]
|
||||||
|
features = ["unstable"]
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = ["audio", "default-tls"]
|
||||||
|
# Enable the unstable api
|
||||||
|
unstable = []
|
||||||
|
audio = ["audiopus"]
|
||||||
|
# Forward encoded packets without linking a native audio codec.
|
||||||
|
raw-audio = []
|
||||||
|
# Enable default reqwest features.
|
||||||
|
# Use default-features=false on tsclientlib to configure reqwest differently.
|
||||||
|
default-tls = ["reqwest/charset", "reqwest/default-tls", "reqwest/http2"]
|
||||||
|
# Use API of audiopus fork at https://github.com/Flakebi/audiopus for more features
|
||||||
|
audiopus-unstable = []
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
audiopus = { version = "0.3.0-rc.0", optional = true }
|
||||||
|
base64 = "0.22"
|
||||||
|
futures = "0.3"
|
||||||
|
git-testament = "0.2"
|
||||||
|
itertools = "0.14"
|
||||||
|
num-traits = "0.2"
|
||||||
|
pin-utils = "0.1"
|
||||||
|
rand = "0.10"
|
||||||
|
reqwest = { version = "0.13", default-features = false }
|
||||||
|
thiserror = "2"
|
||||||
|
time = "0.3"
|
||||||
|
tokio = { version = "1", features = ["time"] }
|
||||||
|
tokio-stream = "0.1"
|
||||||
|
tracing = "0.1"
|
||||||
|
hickory-net = "0.26"
|
||||||
|
hickory-resolver = "0.26"
|
||||||
|
ts-bookkeeping = { path = "../utils/ts-bookkeeping", version = "0.1" }
|
||||||
|
tsproto = { path = "../tsproto", version = "0.2" }
|
||||||
|
tsproto-packets = { path = "../utils/tsproto-packets", version = "0.1" }
|
||||||
|
tsproto-types = { path = "../utils/tsproto-types", version = "0.1" }
|
||||||
|
url = "2"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
anyhow = "1"
|
||||||
|
audiopus = "0.3.0-rc.0"
|
||||||
|
cpal = "0.18"
|
||||||
|
once_cell = "1"
|
||||||
|
quickcheck = "1"
|
||||||
|
quickcheck_macros = "1"
|
||||||
|
clap = { version = "4", features = ["derive"] }
|
||||||
|
tokio = { version = "1", features = ["io-util", "net", "rt-multi-thread", "rt", "signal"] }
|
||||||
|
tracing-subscriber = "0.3"
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
# TsClientlib [](https://docs.rs/tsclientlib)
|
||||||
|
tsclientlib is a library which makes it simple to create TeamSpeak clients
|
||||||
|
and bots.
|
||||||
|
|
||||||
|
For a full client application, you might want to have a look at [Qint].
|
||||||
|
|
||||||
|
If more power over the internals of a connection is needed, the `unstable` feature can be
|
||||||
|
enabled. Beware that functionality behind this feature may change on any minor release.
|
||||||
|
|
||||||
|
The base class of this library is the [`Connection`]. One instance of this
|
||||||
|
struct manages a single connection to a server.
|
||||||
|
|
||||||
|
[Qint]: https://github.com/ReSpeak/Qint
|
||||||
|
|
||||||
|
## License
|
||||||
|
Licensed under either of
|
||||||
|
|
||||||
|
* [Apache License, Version 2.0](../LICENSE-APACHE)
|
||||||
|
* [MIT license](../LICENSE-MIT)
|
||||||
|
|
||||||
|
at your option.
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# TsClientlib [](https://docs.rs/tsclientlib)
|
||||||
|
{{readme}}
|
||||||
|
|
||||||
|
## License
|
||||||
|
Licensed under either of
|
||||||
|
|
||||||
|
* [Apache License, Version 2.0](../LICENSE-APACHE)
|
||||||
|
* [MIT license](../LICENSE-MIT)
|
||||||
|
|
||||||
|
at your option.
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
use anyhow::Result;
|
||||||
|
use clap::Parser;
|
||||||
|
use tokio::sync::mpsc;
|
||||||
|
use tokio::task::LocalSet;
|
||||||
|
use tracing::{debug, info};
|
||||||
|
|
||||||
|
use tsclientlib::ClientId;
|
||||||
|
use tsproto_packets::packets::{Direction, InAudioBuf};
|
||||||
|
|
||||||
|
mod audio_utils;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||||
|
struct ConnectionId(u64);
|
||||||
|
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
#[command(author, about)]
|
||||||
|
struct Args {
|
||||||
|
/// The volume for the capturing
|
||||||
|
#[arg(default_value_t = 1.0)]
|
||||||
|
volume: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<()> { real_main().await }
|
||||||
|
|
||||||
|
async fn real_main() -> Result<()> {
|
||||||
|
tracing_subscriber::fmt::init();
|
||||||
|
|
||||||
|
// Parse command line options
|
||||||
|
let args = Args::parse();
|
||||||
|
|
||||||
|
let con_id = ConnectionId(0);
|
||||||
|
let local_set = LocalSet::new();
|
||||||
|
let audiodata = audio_utils::start(&local_set)?;
|
||||||
|
|
||||||
|
let (send, mut recv) = mpsc::channel(1);
|
||||||
|
{
|
||||||
|
let mut a2t = audiodata.a2ts.lock().unwrap();
|
||||||
|
a2t.set_listener(send);
|
||||||
|
a2t.set_volume(args.volume);
|
||||||
|
a2t.set_playing(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
let t2a = audiodata.ts2a.clone();
|
||||||
|
loop {
|
||||||
|
// Wait for ctrl + c
|
||||||
|
tokio::select! {
|
||||||
|
send_audio = recv.recv() => {
|
||||||
|
if let Some(packet) = send_audio {
|
||||||
|
let from = ClientId(0);
|
||||||
|
let mut t2a = t2a.lock().unwrap();
|
||||||
|
let in_audio = InAudioBuf::try_new(Direction::C2S, packet.into_vec()).unwrap();
|
||||||
|
if let Err(error) = t2a.play_packet((con_id, from), in_audio) {
|
||||||
|
debug!(%error, "Failed to play packet");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
info!("Audio sending stream was canceled");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = tokio::signal::ctrl_c() => { break; }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
//! This example connects to a teamspeak instance and joins a channel.
|
||||||
|
//! The connected bot-identity will listen on your microphone and send everything to the current
|
||||||
|
//! channel. In parallel, the program will play back all other clients in the channel via its own
|
||||||
|
//! audio output.
|
||||||
|
//! Microphone -> Channel
|
||||||
|
//! Channel -> PC Speakers
|
||||||
|
|
||||||
|
use anyhow::{bail, Result};
|
||||||
|
use clap::Parser;
|
||||||
|
use futures::prelude::*;
|
||||||
|
use tokio::sync::mpsc;
|
||||||
|
use tokio::task::LocalSet;
|
||||||
|
use tracing::{debug, info};
|
||||||
|
|
||||||
|
use tsclientlib::{ClientId, Connection, DisconnectOptions, Identity, StreamItem};
|
||||||
|
use tsproto_packets::packets::AudioData;
|
||||||
|
|
||||||
|
mod audio_utils;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||||
|
struct ConnectionId(u64);
|
||||||
|
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
#[command(author, about)]
|
||||||
|
struct Args {
|
||||||
|
/// The address of the server to connect to
|
||||||
|
#[arg(short, long, default_value = "localhost")]
|
||||||
|
address: String,
|
||||||
|
/// The volume for the capturing
|
||||||
|
#[arg(default_value_t = 1.0)]
|
||||||
|
volume: f32,
|
||||||
|
/// Print the content of all packets
|
||||||
|
///
|
||||||
|
/// 0. Print nothing
|
||||||
|
/// 1. Print command string
|
||||||
|
/// 2. Print packets
|
||||||
|
/// 3. Print udp packets
|
||||||
|
#[arg(short, long, action = clap::ArgAction::Count)]
|
||||||
|
verbose: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<()> { real_main().await }
|
||||||
|
|
||||||
|
async fn real_main() -> Result<()> {
|
||||||
|
tracing_subscriber::fmt::init();
|
||||||
|
|
||||||
|
// Parse command line options
|
||||||
|
let args = Args::parse();
|
||||||
|
|
||||||
|
let con_id = ConnectionId(0);
|
||||||
|
let local_set = LocalSet::new();
|
||||||
|
let audiodata = audio_utils::start(&local_set)?;
|
||||||
|
|
||||||
|
let con_config = Connection::build(args.address)
|
||||||
|
.log_commands(args.verbose >= 1)
|
||||||
|
.log_packets(args.verbose >= 2)
|
||||||
|
.log_udp_packets(args.verbose >= 3);
|
||||||
|
|
||||||
|
// Optionally set the key of this client, otherwise a new key is generated.
|
||||||
|
let id = Identity::new_from_str(
|
||||||
|
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
|
||||||
|
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITs\
|
||||||
|
C/50CIA8M5nmDBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
|
||||||
|
let con_config = con_config.identity(id);
|
||||||
|
|
||||||
|
// Connect
|
||||||
|
let mut con = con_config.connect()?;
|
||||||
|
|
||||||
|
let r = con
|
||||||
|
.events()
|
||||||
|
.try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_))))
|
||||||
|
.next()
|
||||||
|
.await;
|
||||||
|
if let Some(r) = r {
|
||||||
|
r?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let (send, mut recv) = mpsc::channel(5);
|
||||||
|
{
|
||||||
|
let mut a2t = audiodata.a2ts.lock().unwrap();
|
||||||
|
a2t.set_listener(send);
|
||||||
|
a2t.set_volume(args.volume);
|
||||||
|
a2t.set_playing(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let t2a = audiodata.ts2a.clone();
|
||||||
|
let events = con.events().try_for_each(|e| async {
|
||||||
|
if let StreamItem::Audio(packet) = e {
|
||||||
|
let from = ClientId(match packet.data().data() {
|
||||||
|
AudioData::S2C { from, .. } => *from,
|
||||||
|
AudioData::S2CWhisper { from, .. } => *from,
|
||||||
|
_ => panic!("Can only handle S2C packets but got a C2S packet"),
|
||||||
|
});
|
||||||
|
let mut t2a = t2a.lock().unwrap();
|
||||||
|
if let Err(error) = t2a.play_packet((con_id, from), packet) {
|
||||||
|
debug!(%error, "Failed to play packet");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
});
|
||||||
|
|
||||||
|
// Wait for ctrl + c
|
||||||
|
tokio::select! {
|
||||||
|
send_audio = recv.recv() => {
|
||||||
|
if let Some(packet) = send_audio {
|
||||||
|
con.send_audio(packet)?;
|
||||||
|
} else {
|
||||||
|
info!("Audio sending stream was canceled");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = tokio::signal::ctrl_c() => { break; }
|
||||||
|
r = events => {
|
||||||
|
r?;
|
||||||
|
bail!("Disconnected");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Disconnect
|
||||||
|
con.disconnect(DisconnectOptions::new())?;
|
||||||
|
con.events().for_each(|_| future::ready(())).await;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
use std::sync::atomic::{AtomicU32, Ordering};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use anyhow::{Result, format_err};
|
||||||
|
use audiopus::coder::Encoder;
|
||||||
|
use cpal::traits::{DeviceTrait, StreamTrait};
|
||||||
|
use cpal::{Device, Stream, StreamConfig};
|
||||||
|
use futures::prelude::*;
|
||||||
|
use tokio::sync::mpsc;
|
||||||
|
use tokio::task::LocalSet;
|
||||||
|
use tokio::time::{self, Duration};
|
||||||
|
use tokio_stream::wrappers::IntervalStream;
|
||||||
|
use tracing::{debug, error, instrument, warn};
|
||||||
|
use tsproto_packets::packets::{AudioData, CodecType, OutAudio, OutPacket};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
pub struct AudioToTs {
|
||||||
|
device: Device,
|
||||||
|
listener: Arc<Mutex<Option<mpsc::Sender<OutPacket>>>>,
|
||||||
|
stream: Option<Stream>,
|
||||||
|
|
||||||
|
is_playing: bool,
|
||||||
|
/// Storing an f32
|
||||||
|
volume: Arc<AtomicU32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Callback {
|
||||||
|
listener: Arc<Mutex<Option<mpsc::Sender<OutPacket>>>>,
|
||||||
|
encoder: Encoder,
|
||||||
|
/// Storing an f32
|
||||||
|
volume: Arc<AtomicU32>,
|
||||||
|
|
||||||
|
tmp_buffer: [f32; USUAL_FRAME_SIZE * 2],
|
||||||
|
opus_output: [u8; MAX_OPUS_FRAME_SIZE],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AudioToTs {
|
||||||
|
pub fn new(device: Device, local_set: &LocalSet) -> Result<Arc<Mutex<Self>>> {
|
||||||
|
let listener = Arc::new(Mutex::new(Default::default()));
|
||||||
|
let volume = Arc::new(AtomicU32::new(1.0_f32.to_bits()));
|
||||||
|
|
||||||
|
let res = Arc::new(Mutex::new(Self {
|
||||||
|
device,
|
||||||
|
listener,
|
||||||
|
stream: None,
|
||||||
|
|
||||||
|
is_playing: false,
|
||||||
|
volume,
|
||||||
|
}));
|
||||||
|
|
||||||
|
Self::start(res.clone(), local_set);
|
||||||
|
|
||||||
|
Ok(res)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(self))]
|
||||||
|
fn open_capture(&self) -> Result<Stream> {
|
||||||
|
let config = StreamConfig {
|
||||||
|
channels: 1,
|
||||||
|
sample_rate: 48000,
|
||||||
|
buffer_size: cpal::BufferSize::Fixed(USUAL_FRAME_SIZE as u32),
|
||||||
|
};
|
||||||
|
|
||||||
|
let encoder = Encoder::new(
|
||||||
|
audiopus::SampleRate::Hz48000,
|
||||||
|
audiopus::Channels::Mono,
|
||||||
|
audiopus::Application::Voip,
|
||||||
|
)
|
||||||
|
.expect("Could not create encoder");
|
||||||
|
let mut callback = Callback {
|
||||||
|
listener: self.listener.clone(),
|
||||||
|
encoder,
|
||||||
|
volume: self.volume.clone(),
|
||||||
|
|
||||||
|
tmp_buffer: [0.0; _],
|
||||||
|
opus_output: [0; _],
|
||||||
|
};
|
||||||
|
|
||||||
|
self.device
|
||||||
|
.build_input_stream(
|
||||||
|
config,
|
||||||
|
move |audio_data, _| callback.callback(audio_data),
|
||||||
|
|error| error!(%error, "Error during audio capture"),
|
||||||
|
Some(Duration::from_secs(5)),
|
||||||
|
)
|
||||||
|
.map_err(|e| format_err!("cpal error: {}", e))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_listener(&self, sender: mpsc::Sender<OutPacket>) {
|
||||||
|
let mut listener = self.listener.lock().unwrap();
|
||||||
|
*listener = Some(sender);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_volume(&mut self, volume: f32) {
|
||||||
|
self.volume.store(volume.to_bits(), Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_playing(&mut self, playing: bool) {
|
||||||
|
if let Some(stream) = &self.stream {
|
||||||
|
if playing {
|
||||||
|
if let Err(error) = stream.play() {
|
||||||
|
error!(%error, "Failed to start stream");
|
||||||
|
self.stream = None;
|
||||||
|
} else {
|
||||||
|
self.is_playing = true;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if let Err(error) = stream.pause() {
|
||||||
|
error!(%error, "Failed to pause stream");
|
||||||
|
self.stream = None;
|
||||||
|
}
|
||||||
|
self.is_playing = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(a2t, local_set))]
|
||||||
|
fn start(a2t: Arc<Mutex<Self>>, local_set: &LocalSet) {
|
||||||
|
local_set.spawn_local(
|
||||||
|
IntervalStream::new(time::interval(Duration::from_secs(1))).for_each(move |_| {
|
||||||
|
let mut a2t = a2t.lock().unwrap();
|
||||||
|
|
||||||
|
if a2t.stream.is_none() {
|
||||||
|
// Try to reconnect to audio
|
||||||
|
match a2t.open_capture() {
|
||||||
|
Ok(s) => {
|
||||||
|
a2t.stream = Some(s);
|
||||||
|
debug!("Reconnected to capture device");
|
||||||
|
if a2t.is_playing {
|
||||||
|
a2t.set_playing(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
error!(%error, "Failed to open capture device");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
future::ready(())
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Callback {
|
||||||
|
#[instrument(skip(self, buffer))]
|
||||||
|
fn callback<'a>(&'a mut self, mut buffer: &'a [f32]) {
|
||||||
|
// Handle volume
|
||||||
|
let volume = f32::from_bits(self.volume.load(Ordering::Relaxed));
|
||||||
|
if volume != 1.0 {
|
||||||
|
if self.tmp_buffer.len() < buffer.len() {
|
||||||
|
warn!("tmp buffer len smaller than received capture buffer, dropping data");
|
||||||
|
}
|
||||||
|
for (dst, src) in self.tmp_buffer.iter_mut().zip(buffer.iter()) {
|
||||||
|
*dst = *src * volume;
|
||||||
|
}
|
||||||
|
buffer = &self.tmp_buffer[..buffer.len()];
|
||||||
|
}
|
||||||
|
|
||||||
|
match self.encoder.encode_float(buffer, &mut self.opus_output[..]) {
|
||||||
|
Err(error) => {
|
||||||
|
error!(%error, "Failed to encode opus");
|
||||||
|
}
|
||||||
|
Ok(len) => {
|
||||||
|
// Create packet
|
||||||
|
let packet = OutAudio::new(&AudioData::C2S {
|
||||||
|
id: 0,
|
||||||
|
codec: CodecType::OpusVoice,
|
||||||
|
data: &self.opus_output[..len],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Write into packet sink
|
||||||
|
let mut listener = self.listener.lock().unwrap();
|
||||||
|
if let Some(lis) = &mut *listener {
|
||||||
|
match lis.try_send(packet) {
|
||||||
|
Err(mpsc::error::TrySendError::Closed(_)) => *listener = None,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use anyhow::Result;
|
||||||
|
use cpal::traits::HostTrait;
|
||||||
|
use tokio::task::LocalSet;
|
||||||
|
|
||||||
|
use audio_to_ts::AudioToTs;
|
||||||
|
use ts_to_audio::TsToAudio;
|
||||||
|
|
||||||
|
pub mod audio_to_ts;
|
||||||
|
pub mod ts_to_audio;
|
||||||
|
|
||||||
|
/// The usual frame size.
|
||||||
|
///
|
||||||
|
/// 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;
|
||||||
|
|
||||||
|
/// The maximum size of an opus frame is 1275 as from RFC6716.
|
||||||
|
const MAX_OPUS_FRAME_SIZE: usize = 1275;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct AudioData {
|
||||||
|
pub a2ts: Arc<Mutex<AudioToTs>>,
|
||||||
|
pub ts2a: Arc<Mutex<TsToAudio>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn start(local_set: &LocalSet) -> Result<AudioData> {
|
||||||
|
let host = cpal::default_host();
|
||||||
|
let output_device = host.default_output_device().unwrap();
|
||||||
|
let input_device = host.default_input_device().unwrap();
|
||||||
|
|
||||||
|
let ts2a = TsToAudio::new(output_device, local_set)?;
|
||||||
|
let a2ts = AudioToTs::new(input_device, local_set)?;
|
||||||
|
|
||||||
|
Ok(AudioData { a2ts, ts2a })
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use anyhow::{Result, format_err};
|
||||||
|
use cpal::traits::{DeviceTrait, StreamTrait};
|
||||||
|
use cpal::{Device, Stream, StreamConfig};
|
||||||
|
use futures::prelude::*;
|
||||||
|
use tokio::task::LocalSet;
|
||||||
|
use tokio::time::{self, Duration};
|
||||||
|
use tokio_stream::wrappers::IntervalStream;
|
||||||
|
use tracing::{debug, error, instrument};
|
||||||
|
use tsclientlib::ClientId;
|
||||||
|
use tsproto_packets::packets::InAudioBuf;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use crate::ConnectionId;
|
||||||
|
|
||||||
|
type Id = (ConnectionId, ClientId);
|
||||||
|
type AudioHandler = tsclientlib::audio::AudioHandler<Id>;
|
||||||
|
|
||||||
|
pub struct TsToAudio {
|
||||||
|
device: Device,
|
||||||
|
stream: Option<Stream>,
|
||||||
|
is_playing: bool,
|
||||||
|
data: Arc<Mutex<AudioHandler>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Callback {
|
||||||
|
data: Arc<Mutex<AudioHandler>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TsToAudio {
|
||||||
|
pub fn new(device: Device, local_set: &LocalSet) -> Result<Arc<Mutex<Self>>> {
|
||||||
|
let data = Arc::new(Mutex::new(AudioHandler::new()));
|
||||||
|
|
||||||
|
let res = Arc::new(Mutex::new(Self { device, stream: None, is_playing: false, data }));
|
||||||
|
|
||||||
|
Self::start(res.clone(), local_set);
|
||||||
|
|
||||||
|
Ok(res)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(self))]
|
||||||
|
fn open_playback(&self) -> Result<Stream> {
|
||||||
|
let config = StreamConfig {
|
||||||
|
channels: 2,
|
||||||
|
sample_rate: 48000,
|
||||||
|
buffer_size: cpal::BufferSize::Fixed(USUAL_FRAME_SIZE as u32),
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut callback = Callback { data: self.data.clone() };
|
||||||
|
|
||||||
|
self.device
|
||||||
|
.build_output_stream(
|
||||||
|
config,
|
||||||
|
move |audio_data, _| callback.callback(audio_data),
|
||||||
|
|error| error!(%error, "Error during audio playback"),
|
||||||
|
Some(Duration::from_secs(5)),
|
||||||
|
)
|
||||||
|
.map_err(|e| format_err!("cpal error: {}", e))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(t2a, local_set))]
|
||||||
|
fn start(t2a: Arc<Mutex<Self>>, local_set: &LocalSet) {
|
||||||
|
local_set.spawn_local(
|
||||||
|
IntervalStream::new(time::interval(Duration::from_secs(1))).for_each(move |_| {
|
||||||
|
let mut t2a = t2a.lock().unwrap();
|
||||||
|
|
||||||
|
if t2a.stream.is_none() {
|
||||||
|
// Try to reconnect to audio
|
||||||
|
match t2a.open_playback() {
|
||||||
|
Ok(s) => {
|
||||||
|
t2a.stream = Some(s);
|
||||||
|
t2a.is_playing = false;
|
||||||
|
debug!("Reconnected to playback device");
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
error!(%error, "Failed to open playback device");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(stream) = &t2a.stream {
|
||||||
|
let data_empty = t2a.data.lock().unwrap().get_queues().is_empty();
|
||||||
|
if !t2a.is_playing && !data_empty {
|
||||||
|
debug!("Resuming playback");
|
||||||
|
if let Err(error) = stream.play() {
|
||||||
|
error!(%error, "Failed to start stream");
|
||||||
|
t2a.stream = None;
|
||||||
|
} else {
|
||||||
|
t2a.is_playing = true;
|
||||||
|
}
|
||||||
|
} else if t2a.is_playing && data_empty {
|
||||||
|
debug!("Pausing playback");
|
||||||
|
if let Err(error) = stream.pause() {
|
||||||
|
error!(%error, "Failed to pause stream");
|
||||||
|
t2a.stream = None;
|
||||||
|
}
|
||||||
|
t2a.is_playing = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
future::ready(())
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(self, id, packet))]
|
||||||
|
pub(crate) fn play_packet(&mut self, id: Id, packet: InAudioBuf) -> Result<()> {
|
||||||
|
{
|
||||||
|
let mut data = self.data.lock().unwrap();
|
||||||
|
data.handle_packet(id, packet)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
if !self.is_playing {
|
||||||
|
if let Some(stream) = &self.stream {
|
||||||
|
debug!("Resuming playback");
|
||||||
|
if let Err(error) = stream.play() {
|
||||||
|
error!(%error, "Failed to start stream");
|
||||||
|
self.stream = None;
|
||||||
|
} else {
|
||||||
|
self.is_playing = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Callback {
|
||||||
|
fn callback(&mut self, buffer: &mut [f32]) {
|
||||||
|
// Clear buffer
|
||||||
|
for d in &mut *buffer {
|
||||||
|
*d = 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut data = self.data.lock().unwrap();
|
||||||
|
data.fill_buffer(buffer);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
use anyhow::{bail, Result};
|
||||||
|
use clap::Parser;
|
||||||
|
use futures::prelude::*;
|
||||||
|
use tokio::time::{self, Duration};
|
||||||
|
|
||||||
|
use tsclientlib::data::{self, Channel, Client};
|
||||||
|
use tsclientlib::prelude::*;
|
||||||
|
use tsclientlib::{ChannelId, Connection, DisconnectOptions, Identity, StreamItem};
|
||||||
|
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
#[command(author, about)]
|
||||||
|
struct Args {
|
||||||
|
/// The address of the server to connect to
|
||||||
|
#[arg(short, long, default_value = "localhost")]
|
||||||
|
address: String,
|
||||||
|
/// Print the content of all packets
|
||||||
|
///
|
||||||
|
/// 0. Print nothing
|
||||||
|
/// 1. Print command string
|
||||||
|
/// 2. Print packets
|
||||||
|
/// 3. Print udp packets
|
||||||
|
#[arg(short, long, action = clap::ArgAction::Count)]
|
||||||
|
verbose: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `channels` have to be ordered.
|
||||||
|
fn print_channels(clients: &[&Client], channels: &[&Channel], parent: ChannelId, depth: usize) {
|
||||||
|
let indention = " ".repeat(depth);
|
||||||
|
for channel in channels {
|
||||||
|
if channel.parent == parent {
|
||||||
|
println!("{}- {}", indention, channel.name);
|
||||||
|
// Print all clients in this channel
|
||||||
|
for client in clients {
|
||||||
|
if client.channel == channel.id {
|
||||||
|
println!("{} {}", indention, client.name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
print_channels(clients, channels, channel.id, depth + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn print_channel_tree(con: &data::Connection) {
|
||||||
|
let mut channels: Vec<_> = con.channels.values().collect();
|
||||||
|
let mut clients: Vec<_> = con.clients.values().collect();
|
||||||
|
// This is not the real sorting order, the order is the ChannelId of the
|
||||||
|
// channel on top of this one, but we don't care for this example.
|
||||||
|
channels.sort_by_key(|ch| ch.order.0);
|
||||||
|
clients.sort_by_key(|c| c.talk_power);
|
||||||
|
println!("{}", con.server.name);
|
||||||
|
print_channels(&clients, &channels, ChannelId(0), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<()> { real_main().await }
|
||||||
|
|
||||||
|
async fn real_main() -> Result<()> {
|
||||||
|
tracing_subscriber::fmt::init();
|
||||||
|
|
||||||
|
// Parse command line options
|
||||||
|
let args = Args::parse();
|
||||||
|
|
||||||
|
let con_config = Connection::build(args.address)
|
||||||
|
.log_commands(args.verbose >= 1)
|
||||||
|
.log_packets(args.verbose >= 2)
|
||||||
|
.log_udp_packets(args.verbose >= 3);
|
||||||
|
|
||||||
|
// Optionally set the key of this client, otherwise a new key is generated.
|
||||||
|
let id = Identity::new_from_str(
|
||||||
|
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
|
||||||
|
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITs\
|
||||||
|
C/50CIA8M5nmDBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
|
||||||
|
let con_config = con_config.identity(id);
|
||||||
|
|
||||||
|
// Connect
|
||||||
|
let mut con = con_config.connect()?;
|
||||||
|
|
||||||
|
let r = con
|
||||||
|
.events()
|
||||||
|
.try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_))))
|
||||||
|
.next()
|
||||||
|
.await;
|
||||||
|
if let Some(r) = r {
|
||||||
|
r?;
|
||||||
|
}
|
||||||
|
|
||||||
|
con.get_state().unwrap().server.set_subscribed(true).send(&mut con)?;
|
||||||
|
|
||||||
|
// Wait some time
|
||||||
|
let mut events = con.events().try_filter(|_| future::ready(false));
|
||||||
|
tokio::select! {
|
||||||
|
_ = time::sleep(Duration::from_secs(1)) => {}
|
||||||
|
_ = events.next() => {
|
||||||
|
bail!("Disconnected");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
drop(events);
|
||||||
|
|
||||||
|
// Print channel tree
|
||||||
|
print_channel_tree(con.get_state().unwrap());
|
||||||
|
|
||||||
|
// Change name
|
||||||
|
{
|
||||||
|
let state = con.get_state().unwrap();
|
||||||
|
let name = state.clients[&state.own_client].name.clone();
|
||||||
|
state
|
||||||
|
.client_update()
|
||||||
|
.set_input_muted(true)
|
||||||
|
.set_name(&format!("{}1", name))
|
||||||
|
.send(&mut con)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait some time
|
||||||
|
let mut events = con.events().try_filter(|_| future::ready(false));
|
||||||
|
tokio::select! {
|
||||||
|
_ = time::sleep(Duration::from_secs(3)) => {}
|
||||||
|
_ = events.next() => {
|
||||||
|
bail!("Disconnected");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
drop(events);
|
||||||
|
|
||||||
|
// Disconnect
|
||||||
|
con.disconnect(DisconnectOptions::new())?;
|
||||||
|
con.events().for_each(|_| future::ready(())).await;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
use anyhow::Result;
|
||||||
|
use clap::Parser;
|
||||||
|
use futures::prelude::*;
|
||||||
|
use tokio::time::{self, Duration};
|
||||||
|
use tracing::error;
|
||||||
|
|
||||||
|
use tsclientlib::{Connection, DisconnectOptions, Identity, StreamItem};
|
||||||
|
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
#[command(author, about)]
|
||||||
|
struct Args {
|
||||||
|
/// The address of the server to connect to
|
||||||
|
#[arg(short, long, default_value = "localhost")]
|
||||||
|
address: String,
|
||||||
|
/// Print the content of all packets
|
||||||
|
///
|
||||||
|
/// 0. Print nothing
|
||||||
|
/// 1. Print command string
|
||||||
|
/// 2. Print packets
|
||||||
|
/// 3. Print udp packets
|
||||||
|
#[arg(short, long, action = clap::ArgAction::Count)]
|
||||||
|
verbose: u8,
|
||||||
|
/// How many connections
|
||||||
|
#[arg()]
|
||||||
|
count: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<()> { real_main().await }
|
||||||
|
|
||||||
|
async fn real_main() -> Result<()> {
|
||||||
|
tracing_subscriber::fmt::init();
|
||||||
|
|
||||||
|
// Parse command line options
|
||||||
|
let args = Args::parse();
|
||||||
|
|
||||||
|
let con_config = Connection::build(args.address.as_str())
|
||||||
|
.log_commands(args.verbose >= 1)
|
||||||
|
.log_packets(args.verbose >= 2)
|
||||||
|
.log_udp_packets(args.verbose >= 3);
|
||||||
|
|
||||||
|
// Optionally set the key of this client, otherwise a new key is generated.
|
||||||
|
let id = Identity::new_from_str(
|
||||||
|
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
|
||||||
|
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITs\
|
||||||
|
C/50CIA8M5nmDBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
|
||||||
|
let con_config = con_config.identity(id);
|
||||||
|
|
||||||
|
stream::iter(0..args.count)
|
||||||
|
.for_each_concurrent(None, |_| {
|
||||||
|
let con_config = con_config.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
// Connect
|
||||||
|
let mut con = con_config.connect().unwrap();
|
||||||
|
|
||||||
|
let r = con
|
||||||
|
.events()
|
||||||
|
.try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_))))
|
||||||
|
.next()
|
||||||
|
.await;
|
||||||
|
if let Some(Err(error)) = r {
|
||||||
|
error!(%error, "Connection failed");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait some time
|
||||||
|
let mut events = con.events().try_filter(|_| future::ready(false));
|
||||||
|
tokio::select! {
|
||||||
|
_ = time::sleep(Duration::from_secs(15)) => {}
|
||||||
|
_ = events.next() => {
|
||||||
|
error!("Disconnected unexpectedly");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
drop(events);
|
||||||
|
|
||||||
|
// Disconnect
|
||||||
|
let _ = con.disconnect(DisconnectOptions::new());
|
||||||
|
con.events().for_each(|_| future::ready(())).await;
|
||||||
|
})
|
||||||
|
.map(|_| ())
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
use anyhow::Result;
|
||||||
|
use clap::Parser;
|
||||||
|
use futures::prelude::*;
|
||||||
|
use tokio::time::{self, Duration};
|
||||||
|
|
||||||
|
use tsclientlib::sync::SyncConnection;
|
||||||
|
use tsclientlib::{Connection, DisconnectOptions, Identity};
|
||||||
|
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
#[command(author, about)]
|
||||||
|
struct Args {
|
||||||
|
/// The address of the server to connect to
|
||||||
|
#[arg(short, long, default_value = "localhost")]
|
||||||
|
address: String,
|
||||||
|
/// Print the content of all packets
|
||||||
|
///
|
||||||
|
/// 0. Print nothing
|
||||||
|
/// 1. Print command string
|
||||||
|
/// 2. Print packets
|
||||||
|
/// 3. Print udp packets
|
||||||
|
#[arg(short, long, action = clap::ArgAction::Count)]
|
||||||
|
verbose: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<()> { real_main().await }
|
||||||
|
|
||||||
|
async fn real_main() -> Result<()> {
|
||||||
|
tracing_subscriber::fmt::init();
|
||||||
|
|
||||||
|
// Parse command line options
|
||||||
|
let args = Args::parse();
|
||||||
|
|
||||||
|
let con_config = Connection::build(args.address)
|
||||||
|
.log_commands(args.verbose >= 1)
|
||||||
|
.log_packets(args.verbose >= 2)
|
||||||
|
.log_udp_packets(args.verbose >= 3);
|
||||||
|
|
||||||
|
// Optionally set the key of this client, otherwise a new key is generated.
|
||||||
|
let id = Identity::new_from_str(
|
||||||
|
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
|
||||||
|
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITs\
|
||||||
|
C/50CIA8M5nmDBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
|
||||||
|
let con_config = con_config.identity(id);
|
||||||
|
|
||||||
|
// Connect
|
||||||
|
let con: SyncConnection = con_config.connect()?.into();
|
||||||
|
let mut handle = con.get_handle();
|
||||||
|
|
||||||
|
// Do event handling in another thread
|
||||||
|
tokio::spawn(con.for_each(|_| future::ready(())));
|
||||||
|
|
||||||
|
handle.wait_until_connected().await?;
|
||||||
|
|
||||||
|
let welcome_message = handle
|
||||||
|
.with_connection(|con| Result::<_>::Ok(con.get_state()?.server.welcome_message.clone()))
|
||||||
|
.await??;
|
||||||
|
println!("Server welcome message: {}", sanitize(&welcome_message));
|
||||||
|
|
||||||
|
// Wait some time
|
||||||
|
time::sleep(Duration::from_secs(1)).await;
|
||||||
|
|
||||||
|
// Disconnect
|
||||||
|
handle.disconnect(DisconnectOptions::new()).await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Only retain a certain set of characters.
|
||||||
|
fn sanitize(s: &str) -> String {
|
||||||
|
s.chars()
|
||||||
|
.filter(|c| {
|
||||||
|
c.is_alphanumeric()
|
||||||
|
|| [' ', '\t', '.', ':', '-', '_', '"', '\'', '/', '(', ')', '[', ']', '{', '}']
|
||||||
|
.contains(c)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
use anyhow::{bail, Result};
|
||||||
|
use clap::Parser;
|
||||||
|
use futures::prelude::*;
|
||||||
|
use tokio::time::{self, Duration};
|
||||||
|
|
||||||
|
use tsclientlib::{Connection, DisconnectOptions, Identity, StreamItem};
|
||||||
|
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
#[command(author, about)]
|
||||||
|
struct Args {
|
||||||
|
/// The address of the server to connect to
|
||||||
|
#[arg(short, long, default_value = "localhost")]
|
||||||
|
address: String,
|
||||||
|
/// Print the content of all packets
|
||||||
|
///
|
||||||
|
/// 0. Print nothing
|
||||||
|
/// 1. Print command string
|
||||||
|
/// 2. Print packets
|
||||||
|
/// 3. Print udp packets
|
||||||
|
#[arg(short, long, action = clap::ArgAction::Count)]
|
||||||
|
verbose: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<()> { real_main().await }
|
||||||
|
|
||||||
|
async fn real_main() -> Result<()> {
|
||||||
|
tracing_subscriber::fmt::init();
|
||||||
|
|
||||||
|
// Parse command line options
|
||||||
|
let args = Args::parse();
|
||||||
|
|
||||||
|
let con_config = Connection::build(args.address)
|
||||||
|
.log_commands(args.verbose >= 1)
|
||||||
|
.log_packets(args.verbose >= 2)
|
||||||
|
.log_udp_packets(args.verbose >= 3);
|
||||||
|
|
||||||
|
// Optionally set the key of this client, otherwise a new key is generated.
|
||||||
|
let id = Identity::new_from_str(
|
||||||
|
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
|
||||||
|
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITs\
|
||||||
|
C/50CIA8M5nmDBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
|
||||||
|
let con_config = con_config.identity(id);
|
||||||
|
|
||||||
|
// Connect
|
||||||
|
let mut con = con_config.connect()?;
|
||||||
|
|
||||||
|
let r = con
|
||||||
|
.events()
|
||||||
|
.try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_))))
|
||||||
|
.next()
|
||||||
|
.await;
|
||||||
|
if let Some(r) = r {
|
||||||
|
r?;
|
||||||
|
}
|
||||||
|
|
||||||
|
println!("Server welcome message: {}", sanitize(&con.get_state()?.server.welcome_message));
|
||||||
|
|
||||||
|
// Wait some time
|
||||||
|
let mut events = con.events().try_filter(|_| future::ready(false));
|
||||||
|
tokio::select! {
|
||||||
|
_ = time::sleep(Duration::from_secs(1)) => {}
|
||||||
|
_ = events.next() => {
|
||||||
|
bail!("Disconnected");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
drop(events);
|
||||||
|
|
||||||
|
// Disconnect
|
||||||
|
con.disconnect(DisconnectOptions::new())?;
|
||||||
|
con.events().for_each(|_| future::ready(())).await;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Only retain a certain set of characters.
|
||||||
|
fn sanitize(s: &str) -> String {
|
||||||
|
s.chars()
|
||||||
|
.filter(|c| {
|
||||||
|
c.is_alphanumeric()
|
||||||
|
|| [' ', '\t', '.', ':', '-', '_', '"', '\'', '/', '(', ')', '[', ']', '{', '}']
|
||||||
|
.contains(c)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
use anyhow::Result;
|
||||||
|
use clap::Parser;
|
||||||
|
use futures::prelude::*;
|
||||||
|
use tokio::time::{self, Duration};
|
||||||
|
|
||||||
|
use tsclientlib::prelude::*;
|
||||||
|
use tsclientlib::sync::SyncConnection;
|
||||||
|
use tsclientlib::{Connection, DisconnectOptions, Identity, StreamItem};
|
||||||
|
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
#[command(author, about)]
|
||||||
|
struct Args {
|
||||||
|
/// The address of the server to connect to
|
||||||
|
#[arg(short, long, default_value = "localhost")]
|
||||||
|
address: String,
|
||||||
|
/// Print the content of all packets
|
||||||
|
///
|
||||||
|
/// 0. Print nothing
|
||||||
|
/// 1. Print command string
|
||||||
|
/// 2. Print packets
|
||||||
|
/// 3. Print udp packets
|
||||||
|
#[arg(short, long, action = clap::ArgAction::Count)]
|
||||||
|
verbose: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<()> { real_main().await }
|
||||||
|
|
||||||
|
async fn real_main() -> Result<()> {
|
||||||
|
tracing_subscriber::fmt::init();
|
||||||
|
|
||||||
|
// Parse command line options
|
||||||
|
let args = Args::parse();
|
||||||
|
|
||||||
|
let con_config = Connection::build(args.address)
|
||||||
|
.log_commands(args.verbose >= 1)
|
||||||
|
.log_packets(args.verbose >= 2)
|
||||||
|
.log_udp_packets(args.verbose >= 3);
|
||||||
|
|
||||||
|
// Optionally set the key of this client, otherwise a new key is generated.
|
||||||
|
let id = Identity::new_from_str(
|
||||||
|
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
|
||||||
|
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITs\
|
||||||
|
C/50CIA8M5nmDBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
|
||||||
|
let con_config = con_config.identity(id);
|
||||||
|
|
||||||
|
// Connect
|
||||||
|
let mut con = con_config.connect()?;
|
||||||
|
let r = con
|
||||||
|
.events()
|
||||||
|
.try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_))))
|
||||||
|
.next()
|
||||||
|
.await;
|
||||||
|
if let Some(r) = r {
|
||||||
|
r?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let sync_con: SyncConnection = con.into();
|
||||||
|
let mut con = sync_con.get_handle();
|
||||||
|
|
||||||
|
tokio::spawn(sync_con.for_each(|_| future::ready(())));
|
||||||
|
|
||||||
|
con.with_connection(move |mut con| {
|
||||||
|
let state = con.get_state()?;
|
||||||
|
state.server.send_textmessage("Hello there").send(&mut con)?;
|
||||||
|
Result::<_>::Ok(())
|
||||||
|
})
|
||||||
|
.await??;
|
||||||
|
|
||||||
|
// Wait some time
|
||||||
|
time::sleep(Duration::from_secs(1)).await;
|
||||||
|
|
||||||
|
// Disconnect
|
||||||
|
con.disconnect(DisconnectOptions::new()).await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
+876
@@ -0,0 +1,876 @@
|
|||||||
|
//! Handle receiving audio.
|
||||||
|
//!
|
||||||
|
//! The [`AudioHandler`] collects all incoming audio packets and queues them per
|
||||||
|
//! client. 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 std::fmt::Debug;
|
||||||
|
use std::hash::Hash;
|
||||||
|
|
||||||
|
use audiopus::coder::Decoder;
|
||||||
|
#[cfg(feature = "audiopus-unstable")]
|
||||||
|
use audiopus::coder::GenericCtl;
|
||||||
|
use audiopus::{Channels, SampleRate, packet};
|
||||||
|
use thiserror::Error;
|
||||||
|
use tracing::{Span, debug, info_span, trace, warn};
|
||||||
|
use tsproto_packets::packets::{AudioData, CodecType, InAudioBuf};
|
||||||
|
|
||||||
|
use crate::ClientId;
|
||||||
|
|
||||||
|
const SAMPLE_RATE: SampleRate = SampleRate::Hz48000;
|
||||||
|
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] audiopus::Error),
|
||||||
|
#[error("Opus decode failed: {error} (packet: {packet:?})")]
|
||||||
|
Decode {
|
||||||
|
#[source]
|
||||||
|
error: audiopus::Error,
|
||||||
|
packet: Option<Vec<u8>>,
|
||||||
|
},
|
||||||
|
#[error("Get duplicate packet id {0}")]
|
||||||
|
Duplicate(u16),
|
||||||
|
#[error("Failed to get packet samples: {0}")]
|
||||||
|
GetPacketSample(#[source] audiopus::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,
|
||||||
|
#[error("Only opus audio is supported, ignoring {0:?}")]
|
||||||
|
UnsupportedCodec(CodecType),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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: InAudioBuf,
|
||||||
|
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 sending client.
|
||||||
|
pub struct AudioHandler<Id: Clone + Debug + Eq + Hash + PartialEq = ClientId> {
|
||||||
|
queues: HashMap<Id, 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: InAudioBuf) -> Result<Self> {
|
||||||
|
let data = packet.data().data();
|
||||||
|
let opus_packet = data.data().try_into().map_err(Error::GetPacketSample)?;
|
||||||
|
let last_packet_samples =
|
||||||
|
packet::nb_samples(opus_packet, 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 = matches!(data, AudioData::S2CWhisper { .. });
|
||||||
|
let decoder = Decoder::new(SAMPLE_RATE, CHANNELS).map_err(Error::CreateDecoder)?;
|
||||||
|
|
||||||
|
// Enable DRED and NoLACE, ignore errors e.g. if unsupported
|
||||||
|
#[cfg(feature = "audiopus-unstable")]
|
||||||
|
let decoder = {
|
||||||
|
let mut decoder = decoder;
|
||||||
|
if let Err(error) = decoder.set_complexity(7) {
|
||||||
|
debug!(%error, "Failed setting opus decoder complexity, ignoring");
|
||||||
|
}
|
||||||
|
decoder
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut res = Self {
|
||||||
|
span: Span::current(),
|
||||||
|
decoder,
|
||||||
|
volume: 1.0,
|
||||||
|
next_id: data.id(),
|
||||||
|
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: InAudioBuf) -> Result<()> {
|
||||||
|
let _span = self.span.enter();
|
||||||
|
if self.packet_buffer.len() >= MAX_BUFFER_PACKETS {
|
||||||
|
return Err(Error::QueueFull);
|
||||||
|
}
|
||||||
|
let samples;
|
||||||
|
if packet.data().data().data().len() <= 1 {
|
||||||
|
// End of stream
|
||||||
|
samples = 0;
|
||||||
|
} else {
|
||||||
|
let opus_packet =
|
||||||
|
packet.data().data().data().try_into().map_err(Error::GetPacketSample)?;
|
||||||
|
samples =
|
||||||
|
packet::nb_samples(opus_packet, SAMPLE_RATE).map_err(Error::GetPacketSample)?;
|
||||||
|
if samples > MAX_BUFFER_SIZE {
|
||||||
|
return Err(Error::TooManySamples);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let id = packet.data().data().id();
|
||||||
|
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) {
|
||||||
|
if 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 =
|
||||||
|
Some(p.packet.data().data().data().try_into().map_err(Error::GetPacketSample)?);
|
||||||
|
len = p.samples;
|
||||||
|
self.whispering = matches!(p.packet.data().data(), AudioData::S2CWhisper { .. });
|
||||||
|
} else {
|
||||||
|
packet_data = None;
|
||||||
|
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..])
|
||||||
|
.try_into()
|
||||||
|
.map_err(Error::GetPacketSample)?,
|
||||||
|
fec,
|
||||||
|
)
|
||||||
|
.map_err(|e| Error::Decode {
|
||||||
|
error: e,
|
||||||
|
packet: packet.map(|p| p.packet.raw_data().to_vec()),
|
||||||
|
})?;
|
||||||
|
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.data().data().data().len() <= 1 {
|
||||||
|
// 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<Id: Clone + Debug + Eq + Hash + PartialEq> Default for AudioHandler<Id> {
|
||||||
|
fn default() -> Self { Self { queues: Default::default(), avg_buffer_samples: 0 } }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<Id: Clone + Debug + Eq + Hash + PartialEq> AudioHandler<Id> {
|
||||||
|
pub fn new() -> Self { Default::default() }
|
||||||
|
|
||||||
|
/// Delete all queues
|
||||||
|
pub fn reset(&mut self) { self.queues.clear(); }
|
||||||
|
|
||||||
|
pub fn get_queues(&self) -> &HashMap<Id, AudioQueue> { &self.queues }
|
||||||
|
pub fn get_mut_queues(&mut self) -> &mut HashMap<Id, 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<Id> {
|
||||||
|
self.fill_buffer_with_proc(buf, |_, _| {})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `buf` is not cleared before filling it.
|
||||||
|
///
|
||||||
|
/// Same as [`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(&Id, &[f32])>(
|
||||||
|
&mut self, buf: &mut [f32], mut handle: F,
|
||||||
|
) -> Vec<Id> {
|
||||||
|
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.clone());
|
||||||
|
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.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for id in &to_remove {
|
||||||
|
self.queues.remove(id);
|
||||||
|
}
|
||||||
|
to_remove
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add a packet to the audio queue.
|
||||||
|
///
|
||||||
|
/// If a new client started talking, returns the id of this client.
|
||||||
|
pub fn handle_packet(&mut self, id: Id, packet: InAudioBuf) -> Result<Option<Id>> {
|
||||||
|
let empty = packet.data().data().data().len() <= 1;
|
||||||
|
let codec = packet.data().data().codec();
|
||||||
|
if codec != CodecType::OpusMusic && codec != CodecType::OpusVoice {
|
||||||
|
return Err(Error::UnsupportedCodec(codec));
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
self.avg_buffer_samples = USUAL_FRAME_SIZE
|
||||||
|
+ self
|
||||||
|
.queues
|
||||||
|
.values()
|
||||||
|
.map(|q| usize::from(q.last_buffer_size_min.get_min()))
|
||||||
|
.sum::<usize>() / self.queues.len();
|
||||||
|
}
|
||||||
|
queue.buffering_samples = self.avg_buffer_samples;
|
||||||
|
self.queues.insert(id.clone(), queue);
|
||||||
|
Ok(Some(id))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use anyhow::{Result, bail};
|
||||||
|
use audiopus::coder::Encoder;
|
||||||
|
use tsproto_packets::packets::{Direction, OutAudio};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use crate::tests::create_logger;
|
||||||
|
|
||||||
|
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<ClientId>)>),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Helper function to check an audio packet.
|
||||||
|
#[allow(dead_code)]
|
||||||
|
fn check_packet(data: &[u8]) -> Result<()> {
|
||||||
|
create_logger();
|
||||||
|
let mut handler = AudioHandler::<ClientId>::new();
|
||||||
|
let id = ClientId(0);
|
||||||
|
let mut buf = vec![0.0; 48_000 / 100 * 2];
|
||||||
|
|
||||||
|
// Sometimes, TS sends short, non-opus packets
|
||||||
|
let packet =
|
||||||
|
OutAudio::new(&AudioData::S2C { id: 30, codec: CodecType::OpusMusic, from: 0, data });
|
||||||
|
let input = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
|
||||||
|
handler.handle_packet(id, input)?;
|
||||||
|
|
||||||
|
handler.fill_buffer(&mut buf);
|
||||||
|
handler.fill_buffer(&mut buf);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn simulate(actions: Vec<SimulateAction>) -> Result<()> {
|
||||||
|
let mut encoder = None;
|
||||||
|
let mut opus_output = [0; 1275]; // Max size for an opus packet
|
||||||
|
let id = ClientId(0);
|
||||||
|
create_logger();
|
||||||
|
let mut handler = AudioHandler::<ClientId>::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(
|
||||||
|
audiopus::SampleRate::Hz48000,
|
||||||
|
audiopus::Channels::Mono,
|
||||||
|
audiopus::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[..])?;
|
||||||
|
let packet = OutAudio::new(&AudioData::S2C {
|
||||||
|
id: i,
|
||||||
|
codec: CodecType::OpusMusic,
|
||||||
|
from: 0,
|
||||||
|
data: &opus_output[..len],
|
||||||
|
});
|
||||||
|
let input = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
|
||||||
|
if handler.handle_packet(id, input).is_ok() != success {
|
||||||
|
bail!("handle_packet returned {:?} but expected {:?}", !success, success);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SimulateAction::ReceiveRaw(i, data) => {
|
||||||
|
let packet = OutAudio::new(&AudioData::S2C {
|
||||||
|
id: i,
|
||||||
|
codec: CodecType::OpusMusic,
|
||||||
|
from: 0,
|
||||||
|
data: &data,
|
||||||
|
});
|
||||||
|
let input = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
|
||||||
|
let _ = handler.handle_packet(id, input);
|
||||||
|
}
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*if let Some(e) = expect {
|
||||||
|
let e = *e as f32;
|
||||||
|
for b in &buf {
|
||||||
|
if (*b - e).abs() > 0.01 {
|
||||||
|
bail!("Buffer contains wrong value, \
|
||||||
|
expected {}: {:?}", e, buf);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}*/
|
||||||
|
}
|
||||||
|
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() {
|
||||||
|
create_logger();
|
||||||
|
let mut handler = AudioHandler::<ClientId>::new();
|
||||||
|
let id = ClientId(0);
|
||||||
|
let mut buf = vec![0.0; 48_000 / 100 * 2];
|
||||||
|
|
||||||
|
for i in 0..100 {
|
||||||
|
let packet = OutAudio::new(&AudioData::S2C {
|
||||||
|
id: 65_500u16.wrapping_add(i),
|
||||||
|
codec: CodecType::OpusMusic,
|
||||||
|
from: 0,
|
||||||
|
data: &[0, 0, 0, 0, 0, 0, 0],
|
||||||
|
});
|
||||||
|
let input = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
|
||||||
|
handler.handle_packet(id, input).unwrap();
|
||||||
|
|
||||||
|
if i > 5 {
|
||||||
|
handler.fill_buffer(&mut buf);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[quickcheck_macros::quickcheck]
|
||||||
|
fn short_packet_quickcheck(data: Vec<Vec<u8>>) {
|
||||||
|
create_logger();
|
||||||
|
let mut handler = AudioHandler::<ClientId>::new();
|
||||||
|
let id = ClientId(0);
|
||||||
|
let mut buf = vec![0.0; 48_000 / 100 * 2];
|
||||||
|
|
||||||
|
for p in data {
|
||||||
|
// Sometimes, TS sends short, non-opus packets
|
||||||
|
let packet = OutAudio::new(&AudioData::S2C {
|
||||||
|
id: 30,
|
||||||
|
codec: CodecType::OpusMusic,
|
||||||
|
from: 0,
|
||||||
|
data: &p,
|
||||||
|
});
|
||||||
|
let input = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
|
||||||
|
let _ = handler.handle_packet(id, input);
|
||||||
|
|
||||||
|
handler.fill_buffer(&mut buf);
|
||||||
|
handler.fill_buffer(&mut buf);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn packets_wrapping2() -> Result<()> {
|
||||||
|
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() -> Result<()> {
|
||||||
|
let mut a = vec![SimulateAction::CreateEncoder];
|
||||||
|
for _ in 0..100 {
|
||||||
|
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
|
||||||
|
}
|
||||||
|
simulate(a)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reversed() -> Result<()> {
|
||||||
|
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() -> Result<()> {
|
||||||
|
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() -> Result<()> {
|
||||||
|
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() -> Result<()> {
|
||||||
|
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() -> Result<()> {
|
||||||
|
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() -> Result<()> {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
+2042
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,4 @@
|
|||||||
|
pub use ts_bookkeeping::data::exts::*;
|
||||||
|
pub use ts_bookkeeping::messages::OutMessageTrait;
|
||||||
|
|
||||||
|
pub use crate::OutCommandExt as _;
|
||||||
@@ -0,0 +1,514 @@
|
|||||||
|
//! Resolve TeamSpeak server addresses of any kind.
|
||||||
|
// Changes with TeamSpeak client 3.1:
|
||||||
|
// https://support.teamspeakusa.com/index.php?/Knowledgebase/Article/View/332
|
||||||
|
|
||||||
|
use std::net::{IpAddr, Ipv6Addr, SocketAddr};
|
||||||
|
use std::str;
|
||||||
|
|
||||||
|
use futures::prelude::*;
|
||||||
|
use hickory_net::proto::rr::RData;
|
||||||
|
use hickory_resolver::TokioResolver;
|
||||||
|
use hickory_resolver::config::{CLOUDFLARE, ResolverConfig, ResolverOpts};
|
||||||
|
use hickory_resolver::net::runtime::TokioRuntimeProvider;
|
||||||
|
use itertools::Itertools;
|
||||||
|
use rand::RngExt;
|
||||||
|
use thiserror::Error;
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
use tokio::net::{self, TcpStream};
|
||||||
|
use tokio::time::Duration;
|
||||||
|
use tracing::{debug, instrument, warn};
|
||||||
|
|
||||||
|
const DEFAULT_PORT: u16 = 9987;
|
||||||
|
const DNS_PREFIX_TCP: &str = "_tsdns._tcp.";
|
||||||
|
const DNS_PREFIX_UDP: &str = "_ts3._udp.";
|
||||||
|
const NICKNAME_LOOKUP_ADDRESS: &str = "https://named.myteamspeak.com/lookup";
|
||||||
|
/// Wait this amount of seconds before giving up.
|
||||||
|
const TIMEOUT_SECONDS: u64 = 10;
|
||||||
|
|
||||||
|
type Result<T> = std::result::Result<T, Error>;
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub enum Error {
|
||||||
|
#[error("Failed to create resolver: {0}")]
|
||||||
|
CreateResolver(#[source] hickory_net::NetError),
|
||||||
|
#[error("Invalid IPv4 address")]
|
||||||
|
InvalidIp4Address,
|
||||||
|
#[error("Invalid IPv6 address")]
|
||||||
|
InvalidIp6Address,
|
||||||
|
#[error("Invalid IP address")]
|
||||||
|
InvalidIpAddress,
|
||||||
|
#[error("Not a valid nickname")]
|
||||||
|
InvalidNickname,
|
||||||
|
#[error("Failed to parse port: {0}")]
|
||||||
|
InvalidPort(#[source] std::num::ParseIntError),
|
||||||
|
#[error("Failed to contact {0} server: {1}")]
|
||||||
|
Io(&'static str, #[source] std::io::Error),
|
||||||
|
#[error("Failed to parse url: {0}")]
|
||||||
|
NicknameParseUrl(#[source] url::ParseError),
|
||||||
|
#[error("Failed to resolve nickname: {0}")]
|
||||||
|
NicknameResolve(#[source] reqwest::Error),
|
||||||
|
#[error("Failed to resolve hostname: {0}")]
|
||||||
|
ResolveHost(#[source] tokio::io::Error),
|
||||||
|
#[error("Failed to get SRV record")]
|
||||||
|
SrvLookup(#[source] hickory_net::NetError),
|
||||||
|
#[error("tsdns did not return an ip address but {0:?}")]
|
||||||
|
TsdnsAddressInvalidResponse(String),
|
||||||
|
#[error("tsdns server does not know the address")]
|
||||||
|
TsdnsAddressNotFound,
|
||||||
|
#[error("Failed to parse tsdns response: {0}")]
|
||||||
|
TsdnsParseResponse(#[source] std::str::Utf8Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
|
enum ParseIpResult<'a> {
|
||||||
|
Addr(SocketAddr),
|
||||||
|
Other(&'a str, Option<u16>),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Beware that this may be slow because it tries all available methods.
|
||||||
|
///
|
||||||
|
/// The following methods are tried:
|
||||||
|
/// 1. If the address is an ip, the ip is returned
|
||||||
|
/// 1. Server nicknames are resolved by a http request to TeamSpeak
|
||||||
|
/// 1. The SRV record at `_ts3._udp.<address>`
|
||||||
|
/// 1. The SRV record at `_tsdns._tcp.address.tld` to get the address of a tsdns
|
||||||
|
/// server, e.g. when the address is `ts3.subdomain.from.com`, the SRV record
|
||||||
|
/// at `_tsdns._tcp.from.com` is requested
|
||||||
|
/// 1. Directly resolve the address to an ip address
|
||||||
|
///
|
||||||
|
/// If a port is given with `:port`, it overwrites the automatically determined
|
||||||
|
/// port. IPv6 addresses are put in square brackets when a port is present:
|
||||||
|
/// `[::1]:9987`
|
||||||
|
#[instrument]
|
||||||
|
pub fn resolve(address: String) -> impl Stream<Item = Result<SocketAddr>> {
|
||||||
|
debug!("Starting resolve");
|
||||||
|
let addr;
|
||||||
|
let port;
|
||||||
|
match parse_ip(&address) {
|
||||||
|
Ok(ParseIpResult::Addr(res)) => {
|
||||||
|
return stream::once(future::ok(res)).left_stream();
|
||||||
|
}
|
||||||
|
Ok(ParseIpResult::Other(a, p)) => {
|
||||||
|
addr = a.to_string();
|
||||||
|
port = p;
|
||||||
|
if let Some(port) = port {
|
||||||
|
debug!(port, "Found port");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(res) => return stream::once(future::err(res)).left_stream(),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve as nickname
|
||||||
|
let res = if !address.contains('.') && addr != "localhost" {
|
||||||
|
debug!("Resolving nickname");
|
||||||
|
// Could be a server nickname
|
||||||
|
resolve_nickname(address.clone())
|
||||||
|
.map_ok(move |mut addr| {
|
||||||
|
if let Some(port) = port {
|
||||||
|
addr.set_port(port);
|
||||||
|
}
|
||||||
|
addr
|
||||||
|
})
|
||||||
|
.left_stream()
|
||||||
|
} else {
|
||||||
|
stream::once(future::err(Error::InvalidNickname)).right_stream()
|
||||||
|
};
|
||||||
|
|
||||||
|
// The system config does not yet work on android:
|
||||||
|
// https://github.com/bluejekyll/trust-dns/issues/652
|
||||||
|
let addr2 = addr.clone();
|
||||||
|
// TODO Move current span into stream
|
||||||
|
let res = res.chain(
|
||||||
|
stream::once(async move {
|
||||||
|
let resolver = create_resolver()?;
|
||||||
|
|
||||||
|
// Try to get the address by an SRV record
|
||||||
|
Result::<_>::Ok(resolve_srv(resolver, format!("{DNS_PREFIX_UDP}{addr2}.")))
|
||||||
|
})
|
||||||
|
.try_flatten(),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Try to get the address of a tsdns server by an SRV record
|
||||||
|
let addr2 = addr.clone();
|
||||||
|
// TODO Move current span into stream
|
||||||
|
let res = res.chain(
|
||||||
|
stream::once(async move {
|
||||||
|
let resolver = create_resolver()?;
|
||||||
|
// Trim address to two components
|
||||||
|
let name = if let Some(i) = addr2.rfind('.').and_then(|i| addr2[..i].rfind('.')) {
|
||||||
|
&addr2[i + 1..]
|
||||||
|
} else {
|
||||||
|
&addr2
|
||||||
|
};
|
||||||
|
// Pick the first srv record of the first server that answers
|
||||||
|
Result::<_>::Ok(resolve_srv(resolver, format!("{DNS_PREFIX_TCP}{name}.")).and_then(
|
||||||
|
move |srv| {
|
||||||
|
let address = address.clone();
|
||||||
|
async move {
|
||||||
|
// Got tsdns server
|
||||||
|
let mut addr = resolve_tsdns(srv, &address).await?;
|
||||||
|
if let Some(port) = port {
|
||||||
|
// Overwrite port if it was specified
|
||||||
|
addr.set_port(port);
|
||||||
|
}
|
||||||
|
Ok(addr)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
))
|
||||||
|
})
|
||||||
|
.try_flatten(),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Interpret as normal address and resolve with system resolver
|
||||||
|
let res = res.chain(
|
||||||
|
stream::once(async move {
|
||||||
|
let res = net::lookup_host((addr.as_str(), port.unwrap_or(DEFAULT_PORT)))
|
||||||
|
.await
|
||||||
|
.map_err(Error::ResolveHost)?
|
||||||
|
.map(Ok)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
Result::<_>::Ok(stream::iter(res))
|
||||||
|
})
|
||||||
|
.try_flatten(),
|
||||||
|
);
|
||||||
|
|
||||||
|
// TODO Move current span into stream
|
||||||
|
tokio_stream::StreamExt::timeout(res, Duration::from_secs(TIMEOUT_SECONDS))
|
||||||
|
.filter_map(move |r: std::result::Result<Result<SocketAddr>, _>| {
|
||||||
|
future::ready(match r {
|
||||||
|
// Timeout
|
||||||
|
Err(_) => None,
|
||||||
|
// Error
|
||||||
|
Ok(Err(error)) => {
|
||||||
|
debug!(%error, "Resolver failed in one step");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
// Success
|
||||||
|
Ok(Ok(r)) => Some(Ok(r)),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.right_stream()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Windows for some reason automatically adds a link-local address to the dns
|
||||||
|
// resolver. These addresses are usually not reachable and should be filtered out.
|
||||||
|
// See: https://superuser.com/questions/638566/strange-value-in-dns-shown-in-ipconfig
|
||||||
|
const FILTERED_IPS: &[IpAddr] = &[
|
||||||
|
IpAddr::V6(Ipv6Addr::new(0xfec0, 0, 0, 0xffff, 0, 0, 0, 1)),
|
||||||
|
IpAddr::V6(Ipv6Addr::new(0xfec0, 0, 0, 0xffff, 0, 0, 0, 2)),
|
||||||
|
IpAddr::V6(Ipv6Addr::new(0xfec0, 0, 0, 0xffff, 0, 0, 0, 3)),
|
||||||
|
];
|
||||||
|
|
||||||
|
fn create_resolver() -> Result<TokioResolver> {
|
||||||
|
let (config, options) = match hickory_resolver::system_conf::read_system_conf() {
|
||||||
|
Ok((mut config, options)) => {
|
||||||
|
config.name_servers.retain(|ns| !FILTERED_IPS.contains(&ns.ip));
|
||||||
|
(config, options)
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
warn!(%error, "Failed to use system dns resolver config");
|
||||||
|
// Fallback
|
||||||
|
(ResolverConfig::udp_and_tcp(&CLOUDFLARE), ResolverOpts::default())
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut builder = TokioResolver::builder_with_config(config, TokioRuntimeProvider::default());
|
||||||
|
*builder.options_mut() = options;
|
||||||
|
builder.build().map_err(Error::CreateResolver)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_ip(address: &str) -> Result<ParseIpResult<'_>> {
|
||||||
|
let mut addr = address;
|
||||||
|
let mut port = None;
|
||||||
|
if let Some(pos) = address.rfind(':') {
|
||||||
|
// Either with port or IPv6 address
|
||||||
|
if address.find(':').unwrap() == pos {
|
||||||
|
// Port is appended
|
||||||
|
addr = &address[..pos];
|
||||||
|
port = Some(&address[pos + 1..]);
|
||||||
|
if addr.chars().all(|c| c.is_ascii_digit() || c == '.') {
|
||||||
|
// IPv4 address
|
||||||
|
return Ok(ParseIpResult::Addr(
|
||||||
|
std::net::ToSocketAddrs::to_socket_addrs(address)
|
||||||
|
.map_err(|_| Error::InvalidIp4Address)?
|
||||||
|
.next()
|
||||||
|
.ok_or(Error::InvalidIp4Address)?,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} else if let Some(pos_bracket) = address.rfind(']') {
|
||||||
|
if pos_bracket < pos {
|
||||||
|
// IPv6 address and port
|
||||||
|
return Ok(ParseIpResult::Addr(
|
||||||
|
std::net::ToSocketAddrs::to_socket_addrs(address)
|
||||||
|
.map_err(|_| Error::InvalidIp6Address)?
|
||||||
|
.next()
|
||||||
|
.ok_or(Error::InvalidIp6Address)?,
|
||||||
|
));
|
||||||
|
} else if pos_bracket == address.len() - 1 && address.starts_with('[') {
|
||||||
|
// IPv6 address
|
||||||
|
return Ok(ParseIpResult::Addr(
|
||||||
|
std::net::ToSocketAddrs::to_socket_addrs(&(
|
||||||
|
&address[1..pos_bracket],
|
||||||
|
DEFAULT_PORT,
|
||||||
|
))
|
||||||
|
.map_err(|_| Error::InvalidIp6Address)?
|
||||||
|
.next()
|
||||||
|
.ok_or(Error::InvalidIp6Address)?,
|
||||||
|
));
|
||||||
|
} else {
|
||||||
|
return Err(Error::InvalidIpAddress);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// IPv6 address
|
||||||
|
return Ok(ParseIpResult::Addr(
|
||||||
|
std::net::ToSocketAddrs::to_socket_addrs(&(address, DEFAULT_PORT))
|
||||||
|
.map_err(|_| Error::InvalidIp6Address)?
|
||||||
|
.next()
|
||||||
|
.ok_or(Error::InvalidIp6Address)?,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} else if address.chars().all(|c| c.is_ascii_digit() || c == '.') {
|
||||||
|
// IPv4 address
|
||||||
|
return Ok(ParseIpResult::Addr(
|
||||||
|
std::net::ToSocketAddrs::to_socket_addrs(&(address, DEFAULT_PORT))
|
||||||
|
.map_err(|_| Error::InvalidIp4Address)?
|
||||||
|
.next()
|
||||||
|
.ok_or(Error::InvalidIp4Address)?,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let port = if let Some(port) = port.map(|p| p.parse().map_err(Error::InvalidPort)) {
|
||||||
|
Some(port?)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
Ok(ParseIpResult::Other(addr, port))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resolve_nickname(nickname: String) -> impl Stream<Item = Result<SocketAddr>> {
|
||||||
|
stream::once(async {
|
||||||
|
let nickname = nickname;
|
||||||
|
let url =
|
||||||
|
reqwest::Url::parse_with_params(NICKNAME_LOOKUP_ADDRESS, Some(("name", &nickname)))
|
||||||
|
.map_err(Error::NicknameParseUrl)?;
|
||||||
|
let body = reqwest::get(url)
|
||||||
|
.await
|
||||||
|
.map_err(Error::NicknameResolve)?
|
||||||
|
.error_for_status()
|
||||||
|
.map_err(Error::NicknameResolve)?
|
||||||
|
.text()
|
||||||
|
.await
|
||||||
|
.map_err(Error::NicknameResolve)?;
|
||||||
|
let addrs = body
|
||||||
|
.split(&['\r', '\n'][..])
|
||||||
|
.filter(|s| !s.is_empty())
|
||||||
|
.map(|s| Result::<_>::Ok(s.to_string()))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
Result::<_>::Ok(
|
||||||
|
stream::iter(addrs)
|
||||||
|
.and_then(|addr| async move {
|
||||||
|
match parse_ip(&addr)? {
|
||||||
|
ParseIpResult::Addr(a) => Ok(stream::once(future::ok(a)).left_stream()),
|
||||||
|
ParseIpResult::Other(a, p) => {
|
||||||
|
let addrs = net::lookup_host((a, p.unwrap_or(DEFAULT_PORT)))
|
||||||
|
.await
|
||||||
|
.map_err(Error::ResolveHost)?
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
Ok(stream::iter(addrs).map(Result::<_>::Ok).right_stream())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.try_flatten(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.try_flatten()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn resolve_tsdns<A: net::ToSocketAddrs>(server: A, addr: &str) -> Result<SocketAddr> {
|
||||||
|
let mut stream = TcpStream::connect(server).await.map_err(|e| Error::Io("tsdns", e))?;
|
||||||
|
stream.write_all(addr.as_bytes()).await.map_err(|e| Error::Io("tsdns", e))?;
|
||||||
|
let mut data = Vec::new();
|
||||||
|
stream.read_to_end(&mut data).await.map_err(|e| Error::Io("tsdns", e))?;
|
||||||
|
|
||||||
|
let addr = str::from_utf8(&data).map_err(Error::TsdnsParseResponse)?;
|
||||||
|
if addr.starts_with("404") {
|
||||||
|
return Err(Error::TsdnsAddressNotFound);
|
||||||
|
}
|
||||||
|
match parse_ip(addr)? {
|
||||||
|
ParseIpResult::Addr(a) => Ok(a),
|
||||||
|
_ => Err(Error::TsdnsAddressInvalidResponse(addr.to_string())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolve_srv(resolver: TokioResolver, addr: String) -> impl Stream<Item = Result<SocketAddr>> {
|
||||||
|
stream::once(async {
|
||||||
|
let lookup = resolver.srv_lookup(addr).await.map_err(Error::SrvLookup)?;
|
||||||
|
let srvs = lookup
|
||||||
|
.answers()
|
||||||
|
.iter()
|
||||||
|
.map(|r| {
|
||||||
|
let RData::SRV(srv) = &r.data else { panic!("Unexpected answer") };
|
||||||
|
srv.clone()
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
let prios = srvs.iter().chunk_by(|srv| srv.priority);
|
||||||
|
let entries = prios.into_iter().sorted_by_key(|(p, _)| *p);
|
||||||
|
|
||||||
|
// Select by weight
|
||||||
|
let mut sorted_entries = Vec::new();
|
||||||
|
for (_, es) in entries {
|
||||||
|
let mut zero_entries = Vec::new();
|
||||||
|
|
||||||
|
// All non-zero entries
|
||||||
|
let mut entries = es
|
||||||
|
.filter_map(|e| {
|
||||||
|
if e.weight == 0 {
|
||||||
|
zero_entries.push(e);
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(e)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
while !entries.is_empty() {
|
||||||
|
let weight: u32 = entries.iter().map(|e| e.weight as u32).sum();
|
||||||
|
let mut w = rand::rng().random_range(0..=weight);
|
||||||
|
if w == 0 {
|
||||||
|
// Pick the first entry with weight 0
|
||||||
|
if let Some(i) = entries.iter().position(|e| e.weight == 0) {
|
||||||
|
sorted_entries.push(entries.remove(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i in 0..entries.len() {
|
||||||
|
let weight = entries[i].weight as u32;
|
||||||
|
if w <= weight {
|
||||||
|
sorted_entries.push(entries.remove(i));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
w -= weight;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let res = sorted_entries
|
||||||
|
.into_iter()
|
||||||
|
.map(|e| Ok((e.target.to_ascii(), e.port)))
|
||||||
|
.collect::<Vec<Result<(String, u16)>>>();
|
||||||
|
drop(resolver);
|
||||||
|
Ok(stream::iter(res)
|
||||||
|
.and_then(|(e, port)| async move {
|
||||||
|
let res = net::lookup_host((e.as_str(), port))
|
||||||
|
.await
|
||||||
|
.map_err(Error::ResolveHost)?
|
||||||
|
.map(Ok)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
Ok(stream::iter(res))
|
||||||
|
})
|
||||||
|
.try_flatten())
|
||||||
|
})
|
||||||
|
.try_flatten()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use super::*;
|
||||||
|
use crate::tests::create_logger;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_ip_without_port() {
|
||||||
|
let res = parse_ip("127.0.0.1");
|
||||||
|
assert_eq!(
|
||||||
|
res.unwrap(),
|
||||||
|
ParseIpResult::Addr(format!("127.0.0.1:{}", DEFAULT_PORT).parse().unwrap())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_ip_with_port() {
|
||||||
|
let res = parse_ip("127.0.0.1:1");
|
||||||
|
assert_eq!(res.unwrap(), ParseIpResult::Addr("127.0.0.1:1".parse().unwrap()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_ip6_without_port() {
|
||||||
|
let res = parse_ip("::");
|
||||||
|
assert_eq!(
|
||||||
|
res.unwrap(),
|
||||||
|
ParseIpResult::Addr(format!("[::]:{}", DEFAULT_PORT).parse().unwrap())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_ip6_without_port2() {
|
||||||
|
let res = parse_ip("[::]");
|
||||||
|
assert_eq!(
|
||||||
|
res.unwrap(),
|
||||||
|
ParseIpResult::Addr(format!("[::]:{}", DEFAULT_PORT).parse().unwrap())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_ip6_with_port() {
|
||||||
|
let res = parse_ip("[::]:1");
|
||||||
|
assert_eq!(res.unwrap(), ParseIpResult::Addr("[::]:1".parse().unwrap()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_ip_address_without_port() {
|
||||||
|
assert_eq!(parse_ip("localhost").unwrap(), ParseIpResult::Other("localhost", None));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_ip_address_with_port() {
|
||||||
|
assert_eq!(parse_ip("localhost:1").unwrap(), ParseIpResult::Other("localhost", Some(1)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_ip_with_large_port() {
|
||||||
|
assert!(parse_ip("127.0.0.1:65536").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn resolve_localhost() {
|
||||||
|
create_logger();
|
||||||
|
let res: Vec<_> = resolve("127.0.0.1".into()).map(|r| r.unwrap()).collect().await;
|
||||||
|
let addr = format!("127.0.0.1:{}", DEFAULT_PORT).parse::<SocketAddr>().unwrap();
|
||||||
|
assert_eq!(res.as_slice(), &[addr]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn resolve_localhost2() {
|
||||||
|
create_logger();
|
||||||
|
let res: Vec<_> = resolve("localhost".into()).map(|r| r.unwrap()).collect().await;
|
||||||
|
assert!(res.contains(&format!("127.0.0.1:{}", DEFAULT_PORT).parse().unwrap()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn resolve_example() {
|
||||||
|
create_logger();
|
||||||
|
let res: Vec<_> = resolve("example.com".into()).map(|r| r.unwrap()).collect().await;
|
||||||
|
assert!(!res.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn resolve_splamy_de() {
|
||||||
|
create_logger();
|
||||||
|
|
||||||
|
let res: Vec<_> = tokio::time::timeout(
|
||||||
|
Duration::from_secs(5),
|
||||||
|
resolve("splamy.de".into()).map(|r| r.unwrap()).collect(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("Resolve takes unacceptable long");
|
||||||
|
assert!(res.contains(&format!("37.120.179.68:{}", DEFAULT_PORT).parse().unwrap()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn resolve_loc() {
|
||||||
|
create_logger();
|
||||||
|
let res: Vec<_> = resolve("loc".into()).map(|r| r.unwrap()).collect().await;
|
||||||
|
assert!(res.contains(&format!("127.0.0.1:{}", DEFAULT_PORT).parse().unwrap()));
|
||||||
|
}
|
||||||
|
}
|
||||||
+470
@@ -0,0 +1,470 @@
|
|||||||
|
//! The `sync` module contains an easier to use interface for a connection.
|
||||||
|
//!
|
||||||
|
//! It makes it easier to use a connection from multiple threads and use
|
||||||
|
//! `async`/`await` syntax for the cost of a little bit performance.
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::ops::{Deref, DerefMut};
|
||||||
|
use std::pin::Pin;
|
||||||
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
|
use futures::prelude::*;
|
||||||
|
use tokio::sync::{mpsc, oneshot};
|
||||||
|
use tracing::{error, info};
|
||||||
|
use ts_bookkeeping::ChannelId;
|
||||||
|
#[cfg(any(feature = "audio", feature = "raw-audio"))]
|
||||||
|
use tsproto_packets::packets::InAudioBuf;
|
||||||
|
#[cfg(feature = "unstable")]
|
||||||
|
use tsproto_packets::packets::OutCommand;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
events, AudioEvent, DisconnectOptions, Error, InMessage, Result, StreamItem,
|
||||||
|
TemporaryDisconnectReason,
|
||||||
|
};
|
||||||
|
|
||||||
|
enum SyncConMessage {
|
||||||
|
RunFn(Box<dyn FnOnce(&mut SyncConnection) + Send>),
|
||||||
|
#[cfg(feature = "unstable")]
|
||||||
|
SendCommand(OutCommand, oneshot::Sender<Result<()>>),
|
||||||
|
WaitConnected(oneshot::Sender<Result<()>>),
|
||||||
|
Disconnect(DisconnectOptions, oneshot::Sender<Result<()>>),
|
||||||
|
DownloadFile {
|
||||||
|
channel_id: ChannelId,
|
||||||
|
path: String,
|
||||||
|
channel_password: Option<String>,
|
||||||
|
seek_position: Option<u64>,
|
||||||
|
send: oneshot::Sender<Result<super::FileDownloadResult>>,
|
||||||
|
},
|
||||||
|
UploadFile {
|
||||||
|
channel_id: ChannelId,
|
||||||
|
path: String,
|
||||||
|
channel_password: Option<String>,
|
||||||
|
size: u64,
|
||||||
|
overwrite: bool,
|
||||||
|
resume: bool,
|
||||||
|
send: oneshot::Sender<Result<super::FileUploadResult>>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This is a subset of [`StreamItem`](crate::StreamItem).
|
||||||
|
pub enum SyncStreamItem {
|
||||||
|
/// All the incoming book events.
|
||||||
|
///
|
||||||
|
/// If a connection to the server was established this will contain an added event of a server.
|
||||||
|
BookEvents(Vec<events::Event>),
|
||||||
|
/// All incoming messages that are not related to the book.
|
||||||
|
///
|
||||||
|
/// This contains messages like `ChannelListFinished` or `ClientChatComposing`.
|
||||||
|
/// All events related to channels or clients are returned as events in the `BookEvents`
|
||||||
|
/// variant. Other messages handled by tsclientlib, e.g. for filetransfer are also not included
|
||||||
|
/// in these events.
|
||||||
|
MessageEvent(InMessage),
|
||||||
|
/// Received an audio packet.
|
||||||
|
///
|
||||||
|
/// Audio packets can be handled by the [`AudioHandler`](crate::audio::AudioHandler), which
|
||||||
|
/// builds a queue per client and handles packet loss and jitter.
|
||||||
|
#[cfg(any(feature = "audio", feature = "raw-audio"))]
|
||||||
|
Audio(InAudioBuf),
|
||||||
|
/// The needed level.
|
||||||
|
IdentityLevelIncreasing(u8),
|
||||||
|
/// This event may occur without an `IdentityLevelIncreasing` event before
|
||||||
|
/// if a new identity is created because no identity was supplied.
|
||||||
|
IdentityLevelIncreased,
|
||||||
|
/// The connection timed out or the server shut down. The connection will be
|
||||||
|
/// rebuilt automatically.
|
||||||
|
DisconnectedTemporarily(TemporaryDisconnectReason),
|
||||||
|
/// The network statistics were updated.
|
||||||
|
///
|
||||||
|
/// This means e.g. the packet loss got a new value. Clients with audio probably want to update
|
||||||
|
/// the packet loss option of opus.
|
||||||
|
NetworkStatsUpdated,
|
||||||
|
/// A change related to audio.
|
||||||
|
AudioChange(AudioEvent),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A handle for a [`SyncConnection`] which can be sent across threads.
|
||||||
|
///
|
||||||
|
/// All actions like sending messages, downloading and uploading happens through
|
||||||
|
/// a handle.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct SyncConnectionHandle {
|
||||||
|
send: mpsc::Sender<SyncConMessage>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct SyncConnection {
|
||||||
|
con: super::Connection,
|
||||||
|
recv: mpsc::Receiver<SyncConMessage>,
|
||||||
|
send: mpsc::Sender<SyncConMessage>,
|
||||||
|
|
||||||
|
commands: HashMap<super::MessageHandle, oneshot::Sender<Result<()>>>,
|
||||||
|
connects: Vec<oneshot::Sender<Result<()>>>,
|
||||||
|
disconnects: Vec<oneshot::Sender<Result<()>>>,
|
||||||
|
downloads:
|
||||||
|
HashMap<super::FiletransferHandle, oneshot::Sender<Result<super::FileDownloadResult>>>,
|
||||||
|
uploads: HashMap<super::FiletransferHandle, oneshot::Sender<Result<super::FileUploadResult>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<super::Connection> for SyncConnection {
|
||||||
|
fn from(con: super::Connection) -> Self {
|
||||||
|
let (send, recv) = mpsc::channel(1);
|
||||||
|
Self {
|
||||||
|
con,
|
||||||
|
recv,
|
||||||
|
send,
|
||||||
|
|
||||||
|
commands: Default::default(),
|
||||||
|
connects: Default::default(),
|
||||||
|
disconnects: Default::default(),
|
||||||
|
downloads: Default::default(),
|
||||||
|
uploads: Default::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Deref for SyncConnection {
|
||||||
|
type Target = super::Connection;
|
||||||
|
#[inline]
|
||||||
|
fn deref(&self) -> &Self::Target { &self.con }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DerefMut for SyncConnection {
|
||||||
|
#[inline]
|
||||||
|
fn deref_mut(&mut self) -> &mut <Self as Deref>::Target { &mut self.con }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Stream for SyncConnection {
|
||||||
|
type Item = Result<SyncStreamItem>;
|
||||||
|
fn poll_next(mut self: Pin<&mut Self>, ctx: &mut Context) -> Poll<Option<Self::Item>> {
|
||||||
|
let _span = self.con.span.clone().entered();
|
||||||
|
loop {
|
||||||
|
if let Poll::Ready(msg) = self.recv.poll_recv(ctx) {
|
||||||
|
if let Some(msg) = msg {
|
||||||
|
match msg {
|
||||||
|
SyncConMessage::RunFn(f) => f(&mut self),
|
||||||
|
#[cfg(feature = "unstable")]
|
||||||
|
SyncConMessage::SendCommand(arg, send) => {
|
||||||
|
let handle = match self.con.send_command_with_result(arg) {
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(e) => {
|
||||||
|
let _ = send.send(Err(e));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
self.commands.insert(handle, send);
|
||||||
|
}
|
||||||
|
SyncConMessage::WaitConnected(send) => {
|
||||||
|
if self.con.get_state().is_ok() {
|
||||||
|
let _ = send.send(Ok(()));
|
||||||
|
} else {
|
||||||
|
self.connects.push(send);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SyncConMessage::Disconnect(arg, send) => {
|
||||||
|
match self.con.disconnect(arg) {
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(e) => {
|
||||||
|
let _ = send.send(Err(e));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.disconnects.push(send);
|
||||||
|
}
|
||||||
|
SyncConMessage::DownloadFile {
|
||||||
|
channel_id,
|
||||||
|
path,
|
||||||
|
channel_password,
|
||||||
|
seek_position,
|
||||||
|
send,
|
||||||
|
} => {
|
||||||
|
let handle = match self.con.download_file(
|
||||||
|
channel_id,
|
||||||
|
&path,
|
||||||
|
channel_password.as_deref(),
|
||||||
|
seek_position,
|
||||||
|
) {
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(e) => {
|
||||||
|
let _ = send.send(Err(e));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
self.downloads.insert(handle, send);
|
||||||
|
}
|
||||||
|
SyncConMessage::UploadFile {
|
||||||
|
channel_id,
|
||||||
|
path,
|
||||||
|
channel_password,
|
||||||
|
size,
|
||||||
|
overwrite,
|
||||||
|
resume,
|
||||||
|
send,
|
||||||
|
} => {
|
||||||
|
let handle = match self.con.upload_file(
|
||||||
|
channel_id,
|
||||||
|
&path,
|
||||||
|
channel_password.as_deref(),
|
||||||
|
size,
|
||||||
|
overwrite,
|
||||||
|
resume,
|
||||||
|
) {
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(e) => {
|
||||||
|
let _ = send.send(Err(e));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
self.uploads.insert(handle, send);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
} else {
|
||||||
|
error!("Message stream ended unexpectedly");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
loop {
|
||||||
|
break if let Poll::Ready(item) = self.con.poll_next(ctx) {
|
||||||
|
Poll::Ready(match item {
|
||||||
|
Some(Ok(item)) => Some(Ok(match item {
|
||||||
|
StreamItem::BookEvents(i) => {
|
||||||
|
self.connects.drain(..).for_each(|send| {
|
||||||
|
let _ = send.send(Ok(()));
|
||||||
|
});
|
||||||
|
SyncStreamItem::BookEvents(i)
|
||||||
|
}
|
||||||
|
StreamItem::MessageEvent(i) => SyncStreamItem::MessageEvent(i),
|
||||||
|
#[cfg(any(feature = "audio", feature = "raw-audio"))]
|
||||||
|
StreamItem::Audio(i) => SyncStreamItem::Audio(i),
|
||||||
|
StreamItem::IdentityLevelIncreasing(i) => {
|
||||||
|
SyncStreamItem::IdentityLevelIncreasing(i)
|
||||||
|
}
|
||||||
|
StreamItem::IdentityLevelIncreased => {
|
||||||
|
SyncStreamItem::IdentityLevelIncreased
|
||||||
|
}
|
||||||
|
StreamItem::DisconnectedTemporarily(reason) => {
|
||||||
|
SyncStreamItem::DisconnectedTemporarily(reason)
|
||||||
|
}
|
||||||
|
StreamItem::MessageResult(handle, res) => {
|
||||||
|
if let Some(send) = self.commands.remove(&handle) {
|
||||||
|
let _ = send.send(res.map_err(|e| e.into()));
|
||||||
|
} else {
|
||||||
|
info!("Got untracked message result");
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
StreamItem::FileDownload(handle, res) => {
|
||||||
|
if let Some(send) = self.downloads.remove(&handle) {
|
||||||
|
let _ = send.send(Ok(res));
|
||||||
|
} else {
|
||||||
|
info!("Got untracked download");
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
StreamItem::FileUpload(handle, res) => {
|
||||||
|
if let Some(send) = self.uploads.remove(&handle) {
|
||||||
|
let _ = send.send(Ok(res));
|
||||||
|
} else {
|
||||||
|
info!("Got untracked upload");
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
StreamItem::FiletransferFailed(handle, res) => {
|
||||||
|
if let Some(send) = self.downloads.remove(&handle) {
|
||||||
|
let _ = send.send(Err(res));
|
||||||
|
} else if let Some(send) = self.uploads.remove(&handle) {
|
||||||
|
let _ = send.send(Err(res));
|
||||||
|
} else {
|
||||||
|
info!("Got untracked file transfer");
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
StreamItem::NetworkStatsUpdated => SyncStreamItem::NetworkStatsUpdated,
|
||||||
|
StreamItem::AudioChange(change) => SyncStreamItem::AudioChange(change),
|
||||||
|
})),
|
||||||
|
Some(Err(e)) => Some(Err(e)),
|
||||||
|
None => {
|
||||||
|
self.disconnects.drain(..).for_each(|send| {
|
||||||
|
let _ = send.send(Ok(()));
|
||||||
|
});
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
Poll::Pending
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SyncConnection {
|
||||||
|
/// Get a handle to the connection that can be sent across threads.
|
||||||
|
#[inline]
|
||||||
|
pub fn get_handle(&self) -> SyncConnectionHandle {
|
||||||
|
SyncConnectionHandle { send: self.send.clone() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SyncConnectionHandle {
|
||||||
|
/// Run a function on the connection.
|
||||||
|
pub async fn with_connection<
|
||||||
|
T: Send + 'static,
|
||||||
|
F: FnOnce(&mut SyncConnection) -> T + Send + 'static,
|
||||||
|
>(
|
||||||
|
&mut self, f: F,
|
||||||
|
) -> Result<T> {
|
||||||
|
let (send, recv) = oneshot::channel();
|
||||||
|
self.send
|
||||||
|
.send(SyncConMessage::RunFn(Box::new(move |con| {
|
||||||
|
let _ = send.send(f(con));
|
||||||
|
})))
|
||||||
|
.await
|
||||||
|
.map_err(|_| Error::ConnectionGone)?;
|
||||||
|
recv.await.map_err(|_| Error::ConnectionGone)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds a `return_code` to the command and returns if the corresponding
|
||||||
|
/// answer is received. If an error occurs, the future will return an error.
|
||||||
|
#[cfg(feature = "unstable")]
|
||||||
|
pub async fn send_command(&mut self, arg: OutCommand) -> Result<()> {
|
||||||
|
let (send, recv) = oneshot::channel();
|
||||||
|
self.send
|
||||||
|
.send(SyncConMessage::SendCommand(arg, send))
|
||||||
|
.await
|
||||||
|
.map_err(|_| Error::ConnectionGone)?;
|
||||||
|
recv.await.map_err(|_| Error::ConnectionGone)?
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This future resolves once the connection is connected to the server.
|
||||||
|
pub async fn wait_until_connected(&mut self) -> Result<()> {
|
||||||
|
let (send, recv) = oneshot::channel();
|
||||||
|
self.send
|
||||||
|
.send(SyncConMessage::WaitConnected(send))
|
||||||
|
.await
|
||||||
|
.map_err(|_| Error::ConnectionGone)?;
|
||||||
|
recv.await.map_err(|_| Error::ConnectionGone)?
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Disconnect from the server.
|
||||||
|
///
|
||||||
|
/// # Arguments
|
||||||
|
/// - `options`: Either `None` or `DisconnectOptions`.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// Use default options:
|
||||||
|
///
|
||||||
|
/// ```no_run
|
||||||
|
/// # use futures::prelude::*;
|
||||||
|
/// # use tsclientlib::{Connection, ConnectOptions, DisconnectOptions, StreamItem};
|
||||||
|
/// # use tsclientlib::sync::SyncConnection;
|
||||||
|
///
|
||||||
|
/// # #[tokio::main]
|
||||||
|
/// # async fn main() {
|
||||||
|
/// let con: SyncConnection = Connection::build("localhost").connect().unwrap().into();
|
||||||
|
/// let mut handle = con.get_handle();
|
||||||
|
/// tokio::spawn(con.for_each(|_| future::ready(())));
|
||||||
|
/// // Wait until connected
|
||||||
|
/// handle.wait_until_connected().await.unwrap();
|
||||||
|
///
|
||||||
|
/// // Disconnect
|
||||||
|
/// handle.disconnect(DisconnectOptions::new()).await.unwrap();
|
||||||
|
/// # }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// Specify a reason and a quit message:
|
||||||
|
///
|
||||||
|
/// ```no_run
|
||||||
|
/// # use futures::prelude::*;
|
||||||
|
/// # use tsclientlib::{Connection, ConnectOptions, DisconnectOptions, Reason, StreamItem};
|
||||||
|
/// # use tsclientlib::sync::SyncConnection;
|
||||||
|
///
|
||||||
|
/// # #[tokio::main]
|
||||||
|
/// # async fn main() {
|
||||||
|
/// let con: SyncConnection = Connection::build("localhost").connect().unwrap().into();
|
||||||
|
/// let mut handle = con.get_handle();
|
||||||
|
/// tokio::spawn(con.for_each(|_| future::ready(())));
|
||||||
|
/// // Wait until connected
|
||||||
|
/// handle.wait_until_connected().await.unwrap();
|
||||||
|
///
|
||||||
|
/// // Disconnect
|
||||||
|
/// let options = DisconnectOptions::new()
|
||||||
|
/// .reason(Reason::Clientdisconnect)
|
||||||
|
/// .message("Away for a while");
|
||||||
|
/// handle.disconnect(DisconnectOptions::new()).await.unwrap();
|
||||||
|
/// # }
|
||||||
|
/// ```
|
||||||
|
pub async fn disconnect(&mut self, arg: DisconnectOptions) -> Result<()> {
|
||||||
|
let (send, recv) = oneshot::channel();
|
||||||
|
self.send
|
||||||
|
.send(SyncConMessage::Disconnect(arg, send))
|
||||||
|
.await
|
||||||
|
.map_err(|_| Error::ConnectionGone)?;
|
||||||
|
recv.await.map_err(|_| Error::ConnectionGone)?
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Download a file from a channel of the connected TeamSpeak server.
|
||||||
|
///
|
||||||
|
/// Returns the size of the file and a tcp stream of the requested file.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
/// Download an icon.
|
||||||
|
///
|
||||||
|
/// ```no_run
|
||||||
|
/// # use tsclientlib::ChannelId;
|
||||||
|
/// # let handle: tsclientlib::sync::SyncConnectionHandle = panic!();
|
||||||
|
/// # let id = 0;
|
||||||
|
/// let download = handle.download_file(ChannelId(0), format!("/icon_{}", id), None, None);
|
||||||
|
/// ```
|
||||||
|
pub async fn download_file(
|
||||||
|
&mut self, channel_id: ChannelId, path: String, channel_password: Option<String>,
|
||||||
|
seek_position: Option<u64>,
|
||||||
|
) -> Result<super::FileDownloadResult> {
|
||||||
|
let (send, recv) = oneshot::channel();
|
||||||
|
self.send
|
||||||
|
.send(SyncConMessage::DownloadFile {
|
||||||
|
channel_id,
|
||||||
|
path,
|
||||||
|
channel_password,
|
||||||
|
seek_position,
|
||||||
|
send,
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|_| Error::ConnectionGone)?;
|
||||||
|
recv.await.map_err(|_| Error::ConnectionGone)?
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Upload a file to a channel of the connected TeamSpeak server.
|
||||||
|
///
|
||||||
|
/// Returns the size of the part which is already uploaded (when resume is
|
||||||
|
/// specified) and a tcp stream where the requested file should be uploaded.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
/// Upload an avatar.
|
||||||
|
///
|
||||||
|
/// ```no_run
|
||||||
|
/// # use tsclientlib::ChannelId;
|
||||||
|
/// # let handle: tsclientlib::sync::SyncConnectionHandle = panic!();
|
||||||
|
/// # let size = 0;
|
||||||
|
/// let upload = handle.upload_file(ChannelId(0), "/avatar".to_string(), None, size, true, false);
|
||||||
|
/// ```
|
||||||
|
pub async fn upload_file(
|
||||||
|
&mut self, channel_id: ChannelId, path: String, channel_password: Option<String>,
|
||||||
|
size: u64, overwrite: bool, resume: bool,
|
||||||
|
) -> Result<super::FileUploadResult> {
|
||||||
|
let (send, recv) = oneshot::channel();
|
||||||
|
self.send
|
||||||
|
.send(SyncConMessage::UploadFile {
|
||||||
|
channel_id,
|
||||||
|
path,
|
||||||
|
channel_password,
|
||||||
|
size,
|
||||||
|
overwrite,
|
||||||
|
resume,
|
||||||
|
send,
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|_| Error::ConnectionGone)?;
|
||||||
|
recv.await.map_err(|_| Error::ConnectionGone)?
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
use once_cell::sync::Lazy;
|
||||||
|
use ts_bookkeeping::messages::s2c::InMessage;
|
||||||
|
use tsproto_packets::packets::{Direction, Flags, OutPacket, PacketType};
|
||||||
|
|
||||||
|
static TRACING: Lazy<()> = Lazy::new(|| tracing_subscriber::fmt().with_test_writer().init());
|
||||||
|
|
||||||
|
pub(crate) fn create_logger() { Lazy::force(&TRACING); }
|
||||||
|
|
||||||
|
fn parse_msg(msg: &str) -> InMessage {
|
||||||
|
let header = OutPacket::new_with_dir(Direction::S2C, Flags::empty(), PacketType::Command);
|
||||||
|
|
||||||
|
InMessage::new(&header.header(), msg.as_bytes()).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn test_iconid(input: &str, expected: u32) {
|
||||||
|
create_logger();
|
||||||
|
|
||||||
|
let msg = parse_msg(&format!(
|
||||||
|
r#"initserver virtualserver_name=TeamSpeak\s]I[\sServer virtualserver_welcomemessage=Welcome\sto\sTeamSpeak,\scheck\s[URL]www.teamspeak.com[\/URL]\sfor\slatest\sinformation virtualserver_platform=Linux virtualserver_version=3.11.0\s[Build:\s1578903157] virtualserver_maxclients=32 virtualserver_created=1571572631 virtualserver_codec_encryption_mode=2 virtualserver_hostmessage virtualserver_hostmessage_mode=0 virtualserver_default_server_group=8 virtualserver_default_channel_group=8 virtualserver_hostbanner_url virtualserver_hostbanner_gfx_url virtualserver_hostbanner_gfx_interval=0 virtualserver_priority_speaker_dimm_modificator=-18.0000 virtualserver_id=1 virtualserver_hostbutton_tooltip virtualserver_hostbutton_url virtualserver_hostbutton_gfx_url virtualserver_name_phonetic virtualserver_ip=0.0.0.0,\s:: virtualserver_ask_for_privilegekey=0 virtualserver_hostbanner_mode=0 virtualserver_channel_temp_delete_delay_default=0 virtualserver_nickname client_nickname=TeamSpeakUser client_version=3.?.?\s[Build:\s5680278000] client_platform=Windows client_input_muted=0 client_output_muted=0 client_outputonly_muted=0 client_input_hardware=1 client_output_hardware=1 client_default_channel client_default_channel_password client_server_password client_meta_data client_version_sign=DX5NIYLvfJEUjuIbCidnoeozxIDRRkpq3I9vVMBmE9L2qnekOoBzSenkzsg2lC9CMv8K5hkEzhr2TYUYSwUXCg== client_security_hash client_key_offset=354 client_away=0 client_away_message client_nickname_phonetic client_default_token client_badges client_myteamspeak_id client_integrations client_active_integrations_info client_myteamspeak_avatar client_signed_badges acn=TeamSpeakUser aclid=2 pv=7 client_talk_power=75 client_needed_serverquery_view_power=75 virtualserver_icon_id={}"#,
|
||||||
|
input
|
||||||
|
));
|
||||||
|
if let InMessage::InitServer(list) = msg {
|
||||||
|
let cmd = list.iter().next().unwrap();
|
||||||
|
assert_eq!(cmd.icon, ts_bookkeeping::IconId(expected));
|
||||||
|
} else {
|
||||||
|
panic!("Failed to parse as initserver");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn normal_iconid() { test_iconid("96136942", 96136942); }
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn negative_iconid() { test_iconid("-96136942", 4198830354); }
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn big_iconid() { test_iconid("18446744073225738240", 3811153920); }
|
||||||
+67
@@ -0,0 +1,67 @@
|
|||||||
|
[package]
|
||||||
|
name = "tsproto"
|
||||||
|
version = "0.2.0"
|
||||||
|
authors = ["Flakebi <flakebi@t-online.de>"]
|
||||||
|
description = "An implementation of the TeamSpeak3 protocol as a library for use in clients and bots."
|
||||||
|
repository = "https://github.com/ReSpeak/tsclientlib"
|
||||||
|
readme = "README.md"
|
||||||
|
keywords = ["teamspeak3", "ts3", "voip"]
|
||||||
|
categories = ["multimedia"]
|
||||||
|
license = "MIT OR Apache-2.0"
|
||||||
|
edition = "2018"
|
||||||
|
autobenches = false
|
||||||
|
include = [
|
||||||
|
"/Cargo.toml",
|
||||||
|
"/README.md",
|
||||||
|
"**/*.rs",
|
||||||
|
]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
aes = "0.8"
|
||||||
|
base64 = "0.22"
|
||||||
|
omnom = "3"
|
||||||
|
curve25519-dalek-ng = "4"
|
||||||
|
eax = "0.5"
|
||||||
|
futures = "0.3"
|
||||||
|
generic-array = "0.14"
|
||||||
|
git-testament = "0.2"
|
||||||
|
num-bigint = "0.4"
|
||||||
|
num-derive = "0.4"
|
||||||
|
num-traits = "0.2"
|
||||||
|
pin-project-lite = "0.2"
|
||||||
|
rand = "0.10"
|
||||||
|
rug = { version = "1", optional = true, default-features = false, features = ["integer"] }
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
sha-1 = "0.10"
|
||||||
|
sha2 = "0.10"
|
||||||
|
thiserror = "2"
|
||||||
|
time = { version = "0.3", features = ["formatting"] }
|
||||||
|
tokio = { version = "1", features = ["macros", "net", "sync", "time"] }
|
||||||
|
tracing = "0.1"
|
||||||
|
tsproto-packets = { path = "../utils/tsproto-packets", version = "0.1" }
|
||||||
|
tsproto-types = { path = "../utils/tsproto-types", version = "0.1" }
|
||||||
|
quicklz = "0.3"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
anyhow = "1"
|
||||||
|
criterion = "0.8"
|
||||||
|
once_cell = "1"
|
||||||
|
clap = { version = "4", features = ["derive"] }
|
||||||
|
tokio = { version = "1", features = ["rt-multi-thread", "signal"] }
|
||||||
|
tracing-subscriber = "0.3"
|
||||||
|
|
||||||
|
[[bench]]
|
||||||
|
name = "modpow"
|
||||||
|
harness = false
|
||||||
|
|
||||||
|
[[bench]]
|
||||||
|
name = "connect"
|
||||||
|
harness = false
|
||||||
|
|
||||||
|
[[bench]]
|
||||||
|
name = "license"
|
||||||
|
harness = false
|
||||||
|
|
||||||
|
[[bench]]
|
||||||
|
name = "message"
|
||||||
|
harness = false
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
# TsProto   [](https://docs.rs/tsproto)
|
||||||
|
This library implements the TeamSpeak3 protocol.
|
||||||
|
|
||||||
|
For a usable library to build clients and bots, you should take a look at
|
||||||
|
[`tsclientlib`](https://github.com/ReSpeak/tsclientlib), which provides a
|
||||||
|
convenient interface to this library.
|
||||||
|
|
||||||
|
If you are searching for a usable client, [Qint](https://github.com/ReSpeak/Qint)
|
||||||
|
is a cross-platform TeamSpeak client, which is using this library (more
|
||||||
|
correctly, it is using `tsclientlib`).
|
||||||
|
|
||||||
|
For more info on this project, take a look at the
|
||||||
|
[tsclientlib README](https://github.com/ReSpeak/tsclientlib).
|
||||||
|
|
||||||
|
## License
|
||||||
|
Licensed under either of
|
||||||
|
|
||||||
|
* [Apache License, Version 2.0](../LICENSE-APACHE)
|
||||||
|
* [MIT license](../LICENSE-MIT)
|
||||||
|
|
||||||
|
at your option.
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
# TsProto   [](https://docs.rs/tsproto)
|
||||||
|
{{readme}}
|
||||||
|
|
||||||
|
## License
|
||||||
|
Licensed under either of
|
||||||
|
|
||||||
|
* [Apache License, Version 2.0](../LICENSE-APACHE)
|
||||||
|
* [MIT license](../LICENSE-MIT)
|
||||||
|
|
||||||
|
at your option.
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
use anyhow::{Error, Result};
|
||||||
|
use criterion::{criterion_group, criterion_main, Bencher, Criterion};
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
|
use tracing::{info, warn};
|
||||||
|
use tsproto::client::Client;
|
||||||
|
use tsproto::connection::StreamItem;
|
||||||
|
use tsproto_packets::commands::CommandParser;
|
||||||
|
|
||||||
|
mod utils;
|
||||||
|
use crate::utils::*;
|
||||||
|
|
||||||
|
static TRACING: Lazy<()> = Lazy::new(|| tracing_subscriber::fmt().with_test_writer().init());
|
||||||
|
|
||||||
|
async fn wait_channellistfinished(con: &mut Client) -> Result<()> {
|
||||||
|
con.filter_items(|con, i| {
|
||||||
|
Ok(match i {
|
||||||
|
StreamItem::S2CInit(packet) => {
|
||||||
|
con.hand_back_buffer(packet.into_buffer());
|
||||||
|
None
|
||||||
|
}
|
||||||
|
StreamItem::C2SInit(packet) => {
|
||||||
|
con.hand_back_buffer(packet.into_buffer());
|
||||||
|
None
|
||||||
|
}
|
||||||
|
StreamItem::Command(packet) => {
|
||||||
|
let (name, _) = CommandParser::new(packet.data().packet().content());
|
||||||
|
if name == b"channellistfinished" { Some(()) } else { None }
|
||||||
|
}
|
||||||
|
StreamItem::Error(error) => {
|
||||||
|
warn!(%error, "Got connection error");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
i => {
|
||||||
|
warn!(got = ?i, "Unexpected packet, waiting for channellistfinished");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn one_connect(b: &mut Bencher) {
|
||||||
|
Lazy::force(&TRACING);
|
||||||
|
|
||||||
|
let local_address = "127.0.0.1:0".parse().unwrap();
|
||||||
|
let address = "127.0.0.1:9987".parse().unwrap();
|
||||||
|
|
||||||
|
let rt = tokio::runtime::Runtime::new().unwrap();
|
||||||
|
|
||||||
|
b.iter(|| {
|
||||||
|
rt.block_on(async move {
|
||||||
|
// The TS server does not accept the 3rd reconnect from the same port
|
||||||
|
// so we create a new client for every connection.
|
||||||
|
let mut con = create_client(local_address, address, 0).await?;
|
||||||
|
|
||||||
|
connect(&mut con).await?;
|
||||||
|
info!("Connected");
|
||||||
|
// Wait until channellistfinished
|
||||||
|
wait_channellistfinished(&mut con).await?;
|
||||||
|
|
||||||
|
info!("Disconnecting");
|
||||||
|
disconnect(&mut con).await?;
|
||||||
|
Ok::<_, Error>(())
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bench_connect(c: &mut Criterion) { c.bench_function("connect", one_connect); }
|
||||||
|
|
||||||
|
criterion_group! {
|
||||||
|
name = benches;
|
||||||
|
config = Criterion::default().sample_size(20);
|
||||||
|
targets = bench_connect
|
||||||
|
}
|
||||||
|
criterion_main!(benches);
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
use base64::prelude::*;
|
||||||
|
use criterion::{criterion_group, criterion_main, Bencher, Criterion};
|
||||||
|
use tsproto::license::Licenses;
|
||||||
|
use tsproto_types::crypto::EccKeyPubEd25519;
|
||||||
|
|
||||||
|
fn license_parse(b: &mut Bencher, license: Vec<u8>) {
|
||||||
|
b.iter(|| {
|
||||||
|
Licenses::parse_ignore_expired(license.clone()).unwrap();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn license_derive_key(b: &mut Bencher, license: Vec<u8>) {
|
||||||
|
let licenses = Licenses::parse_ignore_expired(license).unwrap();
|
||||||
|
|
||||||
|
b.iter(|| {
|
||||||
|
let derived_key =
|
||||||
|
licenses.derive_public_key(EccKeyPubEd25519::from_bytes(tsproto::ROOT_KEY)).unwrap();
|
||||||
|
derived_key.compress().0
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const STANDARD_LICENSE: &str = "AQA1hUFJiiSs0wFXkYuPUJVcDa6XCrZTcsvkB0\
|
||||||
|
Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAACiIBip9hQaK6P3QhwOJs/BkPn0i\
|
||||||
|
oyIDPaNgzJ6M8x0kiAJf4hxCYAxMQ==";
|
||||||
|
|
||||||
|
const AAL_LICENSE: &str = "AQCvbHFTQDY/terPeilrp/ECU9xCH5U3xC92lY\
|
||||||
|
TNaY/0KQAJFueAazbsgAAAACVUZWFtU3BlYWsgU3lzdGVtcyBHbWJIAABhl9gwla/UJ\
|
||||||
|
p2Eszst9TRVXO/PeE6a6d+CTI6Pg7OEVgAJc5CrL4Nh8gAAACRUZWFtU3BlYWsgc3lz\
|
||||||
|
dGVtcyBHbWJIAACvTQIgpv6zmLZq3znh7ygmOSokGFkFjz4bTigrOnetrgIJdIIACdS\
|
||||||
|
/gAYAAAAAU29zc2VuU3lzdGVtcy5iaWQAADY7+uV1CQ1niOvYSdGzsu83kPTNWijovr\
|
||||||
|
3B78eHGeePIAm98vQJvpu0";
|
||||||
|
|
||||||
|
fn standard_license_parse(b: &mut Bencher) {
|
||||||
|
license_parse(b, BASE64_STANDARD.decode(STANDARD_LICENSE).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn aal_license_parse(b: &mut Bencher) {
|
||||||
|
license_parse(b, BASE64_STANDARD.decode(AAL_LICENSE).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn standard_license_derive_key(b: &mut Bencher) {
|
||||||
|
license_derive_key(b, BASE64_STANDARD.decode(STANDARD_LICENSE).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn aal_license_derive_key(b: &mut Bencher) {
|
||||||
|
license_derive_key(b, BASE64_STANDARD.decode(AAL_LICENSE).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bench_license(c: &mut Criterion) {
|
||||||
|
c.bench_function("parse standard license", standard_license_parse);
|
||||||
|
c.bench_function("parse aal license", aal_license_parse);
|
||||||
|
|
||||||
|
c.bench_function("derive key standard license", standard_license_derive_key);
|
||||||
|
c.bench_function("derive key aal license", aal_license_derive_key);
|
||||||
|
}
|
||||||
|
|
||||||
|
criterion_group!(benches, bench_license);
|
||||||
|
criterion_main!(benches);
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
use anyhow::Error;
|
||||||
|
use criterion::{criterion_group, criterion_main, Bencher, Criterion};
|
||||||
|
use tracing::info;
|
||||||
|
use tsproto_packets::packets::*;
|
||||||
|
|
||||||
|
mod utils;
|
||||||
|
use crate::utils::*;
|
||||||
|
|
||||||
|
fn send_messages(b: &mut Bencher) {
|
||||||
|
create_logger(false);
|
||||||
|
|
||||||
|
let local_address = "127.0.0.1:0".parse().unwrap();
|
||||||
|
let address = "127.0.0.1:9987".parse().unwrap();
|
||||||
|
|
||||||
|
let rt = tokio::runtime::Runtime::new().unwrap();
|
||||||
|
let mut con = rt
|
||||||
|
.block_on(async move {
|
||||||
|
let mut con = create_client(local_address, address, 0).await?;
|
||||||
|
|
||||||
|
info!("Connecting");
|
||||||
|
connect(&mut con).await?;
|
||||||
|
Ok::<_, Error>(con)
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let mut i = 0;
|
||||||
|
|
||||||
|
let mut last_id = None;
|
||||||
|
b.iter(|| {
|
||||||
|
let text = format!("Hello {}", i);
|
||||||
|
let mut packet =
|
||||||
|
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "sendtextmessage");
|
||||||
|
packet.write_arg("targetmode", &"3");
|
||||||
|
packet.write_arg("msg", &text);
|
||||||
|
i += 1;
|
||||||
|
|
||||||
|
rt.block_on(async {
|
||||||
|
con.wait_until_can_send().await.unwrap();
|
||||||
|
last_id = Some(con.send_packet(packet.into_packet()).unwrap());
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
rt.block_on(async move {
|
||||||
|
if let Some(id) = last_id {
|
||||||
|
info!("Waiting for {:?}", id);
|
||||||
|
con.wait_for_ack(id).await?;
|
||||||
|
}
|
||||||
|
tokio::select! {
|
||||||
|
_ = tokio::time::sleep(tokio::time::Duration::from_millis(50)) => {
|
||||||
|
}
|
||||||
|
_ = con.wait_disconnect() => {
|
||||||
|
anyhow::bail!("Disconnected");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
info!("Disconnecting");
|
||||||
|
disconnect(&mut con).await
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bench_message(c: &mut Criterion) { c.bench_function("message", send_messages); }
|
||||||
|
|
||||||
|
criterion_group! {
|
||||||
|
name = benches;
|
||||||
|
config = Criterion::default().sample_size(200);
|
||||||
|
targets = bench_message
|
||||||
|
}
|
||||||
|
criterion_main!(benches);
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
use criterion::{criterion_group, criterion_main, Bencher, Criterion};
|
||||||
|
use num_bigint::BigUint;
|
||||||
|
use num_traits::One;
|
||||||
|
#[cfg(feature = "rug")]
|
||||||
|
use rug::Integer;
|
||||||
|
|
||||||
|
fn num_modpow(b: &mut Bencher) {
|
||||||
|
let n = "9387019355706217197639129234358945126657617361248696932841794255538327365072557602175160199263073329488914880215590036563068284078359088114486271428098753";
|
||||||
|
let x = "2148617454765635492758175407769288127281667975788420713054995716016550287184632946544163990319181591625774561067011999700977775946073267145316355582522577";
|
||||||
|
let level = 10_000;
|
||||||
|
let n = n.parse().unwrap();
|
||||||
|
let x: BigUint = x.parse().unwrap();
|
||||||
|
let mut e = BigUint::one();
|
||||||
|
e <<= level as usize;
|
||||||
|
|
||||||
|
b.iter(|| x.modpow(&e, &n));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rug")]
|
||||||
|
fn gmp_modpow(b: &mut Bencher) {
|
||||||
|
let n = "9387019355706217197639129234358945126657617361248696932841794255538327365072557602175160199263073329488914880215590036563068284078359088114486271428098753";
|
||||||
|
let x = "2148617454765635492758175407769288127281667975788420713054995716016550287184632946544163990319181591625774561067011999700977775946073267145316355582522577";
|
||||||
|
let level = 10_000;
|
||||||
|
let n: Integer = n.parse().unwrap();
|
||||||
|
let x: Integer = x.parse().unwrap();
|
||||||
|
let mut e = Integer::new();
|
||||||
|
e.set_bit(level, true);
|
||||||
|
|
||||||
|
b.iter(|| x.pow_mod_ref(&e, &n).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bench_modpow(c: &mut Criterion) {
|
||||||
|
c.bench_function("num bigint", num_modpow);
|
||||||
|
|
||||||
|
#[cfg(feature = "rug")]
|
||||||
|
{
|
||||||
|
c.bench_function("gmp", gmp_modpow);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
criterion_group!(benches, bench_modpow);
|
||||||
|
criterion_main!(benches);
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
use std::net::SocketAddr;
|
||||||
|
|
||||||
|
use anyhow::Result;
|
||||||
|
use tokio::net::UdpSocket;
|
||||||
|
use tsproto::algorithms as algs;
|
||||||
|
use tsproto::client::Client;
|
||||||
|
use tsproto_packets::packets::*;
|
||||||
|
use tsproto_types::crypto::EccKeyPrivP256;
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn create_logger(to_file: bool) {
|
||||||
|
if to_file {
|
||||||
|
tracing_subscriber::fmt()
|
||||||
|
.with_writer(|| std::fs::OpenOptions::new().append(true).open("bench.log").unwrap())
|
||||||
|
.init();
|
||||||
|
} else {
|
||||||
|
tracing_subscriber::fmt::init();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_client(
|
||||||
|
local_address: SocketAddr, remote_address: SocketAddr, verbose: u8,
|
||||||
|
) -> Result<Client> {
|
||||||
|
// Get P-256 ECDH key
|
||||||
|
let private_key = EccKeyPrivP256::import_str(
|
||||||
|
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
|
||||||
|
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITsC/50CIA8M5nm\
|
||||||
|
DBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
|
||||||
|
|
||||||
|
let udp_socket = UdpSocket::bind(local_address).await?;
|
||||||
|
let mut con = Client::new(remote_address, Box::new(udp_socket), private_key);
|
||||||
|
|
||||||
|
if verbose >= 1 {
|
||||||
|
tsproto::log::add_logger(true, verbose > 1, verbose > 2, &mut con)
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(con)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the `initserver` command.
|
||||||
|
pub async fn connect(con: &mut Client) -> Result<InCommandBuf> {
|
||||||
|
con.connect().await?;
|
||||||
|
|
||||||
|
// Send clientinit
|
||||||
|
let private_key = EccKeyPrivP256::import_str(
|
||||||
|
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
|
||||||
|
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITsC/50CIA8M5nm\
|
||||||
|
DBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
|
||||||
|
|
||||||
|
let private_key_as_pub = private_key.to_pub();
|
||||||
|
let offset = algs::hash_cash(&private_key_as_pub, 8);
|
||||||
|
|
||||||
|
// Create clientinit packet
|
||||||
|
let offset = offset.to_string();
|
||||||
|
let mut packet =
|
||||||
|
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "clientinit");
|
||||||
|
|
||||||
|
for (arg, val) in [
|
||||||
|
("client_nickname", "Bot"),
|
||||||
|
("client_version", "3.?.? [Build: 5680278000]"),
|
||||||
|
("client_platform", "Linux"),
|
||||||
|
("client_input_hardware", "1"),
|
||||||
|
("client_output_hardware", "1"),
|
||||||
|
("client_default_channel", ""),
|
||||||
|
("client_default_channel_password", ""),
|
||||||
|
("client_server_password", ""),
|
||||||
|
("client_meta_data", ""),
|
||||||
|
(
|
||||||
|
"client_version_sign",
|
||||||
|
"Hjd+N58Gv3ENhoKmGYy2bNRBsNNgm5kpiaQWxOj5HN2DXttG6REjymSwJtpJ8muC2gSwRuZi0R+8Laan5ts5CQ==",
|
||||||
|
),
|
||||||
|
("client_nickname_phonetic", ""),
|
||||||
|
("client_key_offset", &offset),
|
||||||
|
("client_default_token", ""),
|
||||||
|
("client_badges", "Overwolf=0"),
|
||||||
|
(
|
||||||
|
"hwid",
|
||||||
|
"923f136fb1e22ae6ce95e60255529c00,\
|
||||||
|
d13231b1bc33edfecfb9169cc7a63bcc",
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
packet.write_arg(arg, &val);
|
||||||
|
}
|
||||||
|
|
||||||
|
con.send_packet(packet.into_packet())?;
|
||||||
|
Ok(con
|
||||||
|
.filter_commands(|con, cmd| {
|
||||||
|
Ok(if cmd.data().packet().content().starts_with(b"initserver ") {
|
||||||
|
Some(cmd)
|
||||||
|
} else {
|
||||||
|
con.hand_back_buffer(cmd.into_buffer());
|
||||||
|
None
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn disconnect(con: &mut Client) -> Result<()> {
|
||||||
|
let mut packet =
|
||||||
|
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "clientdisconnect");
|
||||||
|
for (arg, val) in [
|
||||||
|
// Reason: Disconnect
|
||||||
|
("reasonid", "8"),
|
||||||
|
("reasonmsg", "Bye"),
|
||||||
|
] {
|
||||||
|
packet.write_arg(arg, &val);
|
||||||
|
}
|
||||||
|
|
||||||
|
con.send_packet(packet.into_packet())?;
|
||||||
|
con.wait_disconnect().await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
use std::net::SocketAddr;
|
||||||
|
|
||||||
|
use anyhow::{bail, Result};
|
||||||
|
use clap::Parser;
|
||||||
|
use tokio::time::{self, Duration};
|
||||||
|
use tracing::info;
|
||||||
|
use tsproto_packets::packets::*;
|
||||||
|
|
||||||
|
mod utils;
|
||||||
|
use crate::utils::*;
|
||||||
|
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
#[command(author, about)]
|
||||||
|
struct Args {
|
||||||
|
/// The address of the server to connect to
|
||||||
|
#[arg(short, long, default_value = "127.0.0.1:9987")]
|
||||||
|
address: SocketAddr,
|
||||||
|
/// The listening address of the client
|
||||||
|
#[arg(long, default_value = "0.0.0.0:0")]
|
||||||
|
local_address: SocketAddr,
|
||||||
|
/// Print the content of all packets
|
||||||
|
///
|
||||||
|
/// 0. Print nothing
|
||||||
|
/// 1. Print command string
|
||||||
|
/// 2. Print packets
|
||||||
|
/// 3. Print udp packets
|
||||||
|
#[arg(short, long, action = clap::ArgAction::Count)]
|
||||||
|
verbose: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<()> { real_main().await }
|
||||||
|
|
||||||
|
async fn real_main() -> Result<()> {
|
||||||
|
// Parse command line options
|
||||||
|
let args = Args::parse();
|
||||||
|
create_logger();
|
||||||
|
|
||||||
|
let mut con = create_client(args.local_address, args.address, args.verbose).await?;
|
||||||
|
|
||||||
|
// Connect
|
||||||
|
connect(&mut con).await?;
|
||||||
|
info!("Connected");
|
||||||
|
|
||||||
|
// Wait some time
|
||||||
|
tokio::select! {
|
||||||
|
_ = time::sleep(Duration::from_secs(2)) => {}
|
||||||
|
_ = con.wait_disconnect() => {
|
||||||
|
bail!("Disconnected");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
info!("Waited");
|
||||||
|
|
||||||
|
// Send packet
|
||||||
|
let mut cmd =
|
||||||
|
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "sendtextmessage");
|
||||||
|
cmd.write_arg("targetmode", &3);
|
||||||
|
cmd.write_arg("msg", &"Hello");
|
||||||
|
let id = con.send_packet(cmd.into_packet())?;
|
||||||
|
con.wait_for_ack(id).await?;
|
||||||
|
|
||||||
|
// Disconnect
|
||||||
|
disconnect(&mut con).await?;
|
||||||
|
info!("Disconnected");
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
use std::io::{Cursor, Write};
|
||||||
|
|
||||||
|
use clap::Parser;
|
||||||
|
use tsproto::utils;
|
||||||
|
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
#[command(author, about)]
|
||||||
|
struct Args {
|
||||||
|
/// Data (hex)
|
||||||
|
#[arg()]
|
||||||
|
data: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
// Parse command line options
|
||||||
|
let args = Args::parse();
|
||||||
|
|
||||||
|
let data = utils::read_hex(&args.data).unwrap();
|
||||||
|
let data = quicklz::decompress(&mut Cursor::new(data), std::u32::MAX).unwrap();
|
||||||
|
std::io::stdout().write_all(&data).unwrap();
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
use std::net::SocketAddr;
|
||||||
|
|
||||||
|
use anyhow::Result;
|
||||||
|
use clap::Parser;
|
||||||
|
use futures::prelude::*;
|
||||||
|
use tokio::time::{self, Duration};
|
||||||
|
use tracing::info;
|
||||||
|
|
||||||
|
mod utils;
|
||||||
|
use crate::utils::*;
|
||||||
|
|
||||||
|
#[derive(Parser, Clone, Debug)]
|
||||||
|
#[command(author, about)]
|
||||||
|
struct Args {
|
||||||
|
/// The address of the server to connect to
|
||||||
|
#[arg(short, long, default_value = "127.0.0.1:9987")]
|
||||||
|
address: SocketAddr,
|
||||||
|
/// The listening address of the client
|
||||||
|
#[arg(long, default_value = "0.0.0.0:0")]
|
||||||
|
local_address: SocketAddr,
|
||||||
|
/// Print the content of all packets
|
||||||
|
///
|
||||||
|
/// 0. Print nothing
|
||||||
|
/// 1. Print command string
|
||||||
|
/// 2. Print packets
|
||||||
|
/// 3. Print udp packets
|
||||||
|
#[arg(short, long, action = clap::ArgAction::Count)]
|
||||||
|
verbose: u8,
|
||||||
|
/// How many connections
|
||||||
|
#[arg()]
|
||||||
|
count: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<()> { real_main().await }
|
||||||
|
|
||||||
|
async fn real_main() -> Result<()> {
|
||||||
|
// Parse command line options
|
||||||
|
let args = Args::parse();
|
||||||
|
create_logger();
|
||||||
|
|
||||||
|
stream::iter(0..args.count)
|
||||||
|
.for_each_concurrent(None, |_| {
|
||||||
|
let args = args.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let mut con =
|
||||||
|
create_client(args.local_address, args.address, args.verbose).await.unwrap();
|
||||||
|
|
||||||
|
// Connect
|
||||||
|
connect(&mut con).await.unwrap();
|
||||||
|
info!("Connected");
|
||||||
|
|
||||||
|
// Wait some time
|
||||||
|
tokio::select! {
|
||||||
|
_ = time::sleep(Duration::from_secs(2)) => {}
|
||||||
|
_ = con.wait_disconnect() => {
|
||||||
|
panic!("Disconnected");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
info!("Waited");
|
||||||
|
|
||||||
|
// Disconnect
|
||||||
|
let _ = disconnect(&mut con).await;
|
||||||
|
info!("Disconnected");
|
||||||
|
})
|
||||||
|
.map(|_| ())
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
use base64::prelude::*;
|
||||||
|
use clap::Parser;
|
||||||
|
use tsproto::license::*;
|
||||||
|
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
#[command(author, about)]
|
||||||
|
struct Args {
|
||||||
|
/// The license data (base64)
|
||||||
|
#[arg()]
|
||||||
|
license: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
// Parse command line options
|
||||||
|
let args = Args::parse();
|
||||||
|
|
||||||
|
let l = Licenses::parse(BASE64_STANDARD.decode(&args.license).unwrap()).unwrap();
|
||||||
|
println!("{:#?}", l);
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
use std::io::Write;
|
||||||
|
|
||||||
|
use clap::Parser;
|
||||||
|
use tsproto::algorithms as algs;
|
||||||
|
use tsproto::utils;
|
||||||
|
use tsproto_packets::packets::*;
|
||||||
|
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
#[command(author, about)]
|
||||||
|
struct Args {
|
||||||
|
/// Print backtrace
|
||||||
|
#[arg(short, long = "debug")]
|
||||||
|
debug: bool,
|
||||||
|
/// Server to client
|
||||||
|
#[arg(short, long = "client")]
|
||||||
|
c2s: bool,
|
||||||
|
/// Data (hex)
|
||||||
|
#[arg()]
|
||||||
|
data: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
// Parse command line options
|
||||||
|
let args = Args::parse();
|
||||||
|
|
||||||
|
let dir = if args.c2s { Direction::C2S } else { Direction::S2C };
|
||||||
|
|
||||||
|
let data = utils::read_hex(&args.data).unwrap();
|
||||||
|
let packet = match InPacket::try_new(dir, &data) {
|
||||||
|
Ok(p) => p,
|
||||||
|
Err(e) => {
|
||||||
|
if args.debug {
|
||||||
|
println!("Failed to decode: {:?}", e);
|
||||||
|
} else {
|
||||||
|
println!("Failed to decode: {}", e);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let decrypted = match algs::decrypt_fake(&packet) {
|
||||||
|
Ok(d) => d,
|
||||||
|
Err(e) => {
|
||||||
|
if args.debug {
|
||||||
|
println!("Failed to decrypt: {:?}", e);
|
||||||
|
} else {
|
||||||
|
println!("Failed to decrypt: {}", e);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
std::io::stdout().write_all(&decrypted).unwrap();
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
use base64::prelude::*;
|
||||||
|
use clap::Parser;
|
||||||
|
use curve25519_dalek_ng::edwards::CompressedEdwardsY;
|
||||||
|
use curve25519_dalek_ng::scalar::Scalar;
|
||||||
|
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
#[command(author, about)]
|
||||||
|
struct Args {
|
||||||
|
/// Public key
|
||||||
|
#[arg(short, long = "pub")]
|
||||||
|
pub_key: String,
|
||||||
|
/// Private key
|
||||||
|
#[arg(short, long = "priv")]
|
||||||
|
priv_key: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
// Parse command line options
|
||||||
|
let args = Args::parse();
|
||||||
|
|
||||||
|
let pub_key = BASE64_STANDARD.decode(&args.pub_key).unwrap();
|
||||||
|
let priv_key = BASE64_STANDARD.decode(&args.priv_key).unwrap();
|
||||||
|
let mut pubk = [0; 32];
|
||||||
|
pubk.copy_from_slice(&pub_key);
|
||||||
|
let mut privk = [0; 32];
|
||||||
|
privk.copy_from_slice(&priv_key);
|
||||||
|
/*privk[0] &= 248;
|
||||||
|
privk[31] &= 63;
|
||||||
|
privk[31] |= 64;*/
|
||||||
|
|
||||||
|
let priv_scal = Scalar::from_bytes_mod_order(privk);
|
||||||
|
//let priv_scal = Scalar::from_bytes_mod_order(privk);
|
||||||
|
let pub_point_compr = CompressedEdwardsY(pubk);
|
||||||
|
let pub_point = -pub_point_compr.decompress().unwrap();
|
||||||
|
//let pub_point = curve25519_dalek::constants::ED25519_BASEPOINT_POINT;
|
||||||
|
|
||||||
|
let res = (pub_point * priv_scal).compress();
|
||||||
|
println!("Result: {}", BASE64_STANDARD.encode(&res.0));
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
use base64::prelude::*;
|
||||||
|
use clap::Parser;
|
||||||
|
use tsproto_types::crypto::EccKeyPubP256;
|
||||||
|
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
#[command(author, about)]
|
||||||
|
struct Args {
|
||||||
|
/// Public key
|
||||||
|
#[arg(short, long)]
|
||||||
|
key: String,
|
||||||
|
/// Data (base64)
|
||||||
|
#[arg(short, long)]
|
||||||
|
data: String,
|
||||||
|
/// Signature (base64)
|
||||||
|
#[arg(short, long)]
|
||||||
|
signature: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
// Parse command line options
|
||||||
|
let args = Args::parse();
|
||||||
|
|
||||||
|
// l → proof
|
||||||
|
// ek || beta → proof
|
||||||
|
|
||||||
|
let data = BASE64_STANDARD.decode(&args.data).unwrap();
|
||||||
|
let signature = BASE64_STANDARD.decode(&args.signature).unwrap();
|
||||||
|
let key = EccKeyPubP256::from_ts(&args.key).unwrap();
|
||||||
|
/*let keyts = tomcrypt::P256EccKey::import(&BASE64_STANDARD.decode(&args.key).unwrap())
|
||||||
|
.unwrap();
|
||||||
|
let res = keyts.verify_hash(&data, &signature).unwrap();
|
||||||
|
println!("Res: {:?}", res);*/
|
||||||
|
|
||||||
|
key.verify(&data, &signature).unwrap();
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
use std::net::SocketAddr;
|
||||||
|
|
||||||
|
use anyhow::Result;
|
||||||
|
use tokio::net::UdpSocket;
|
||||||
|
use tracing::{info, info_span};
|
||||||
|
use tsproto::algorithms as algs;
|
||||||
|
use tsproto::client::Client;
|
||||||
|
use tsproto_packets::packets::*;
|
||||||
|
use tsproto_types::crypto::EccKeyPrivP256;
|
||||||
|
|
||||||
|
pub fn create_logger() { tracing_subscriber::fmt::init(); }
|
||||||
|
|
||||||
|
pub async fn create_client(
|
||||||
|
local_address: SocketAddr, remote_address: SocketAddr, verbose: u8,
|
||||||
|
) -> Result<Client> {
|
||||||
|
// Get P-256 ECDH key
|
||||||
|
let private_key = EccKeyPrivP256::import_str(
|
||||||
|
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
|
||||||
|
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITsC/50CIA8M5nm\
|
||||||
|
DBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
|
||||||
|
|
||||||
|
let udp_socket = UdpSocket::bind(local_address).await?;
|
||||||
|
let mut con = Client::new(remote_address, Box::new(udp_socket), private_key);
|
||||||
|
|
||||||
|
if verbose >= 1 {
|
||||||
|
tsproto::log::add_logger_with_verbosity(verbose, &mut con)
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(con)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the `initserver` command.
|
||||||
|
pub async fn connect(con: &mut Client) -> Result<InCommandBuf> {
|
||||||
|
con.connect().await?;
|
||||||
|
|
||||||
|
// Send clientinit
|
||||||
|
let private_key = EccKeyPrivP256::import_str(
|
||||||
|
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
|
||||||
|
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITsC/50CIA8M5nm\
|
||||||
|
DBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
|
||||||
|
|
||||||
|
// Compute hash cash
|
||||||
|
let offset;
|
||||||
|
{
|
||||||
|
let _span = info_span!("Compute public key hash cash level").entered();
|
||||||
|
let private_key_as_pub = private_key.to_pub();
|
||||||
|
offset = algs::hash_cash(&private_key_as_pub, 8);
|
||||||
|
let omega = private_key_as_pub.to_ts();
|
||||||
|
info!(
|
||||||
|
level = algs::get_hash_cash_level(&omega, offset),
|
||||||
|
offset, "Computed hash cash level"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create clientinit packet
|
||||||
|
let offset = offset.to_string();
|
||||||
|
let mut cmd =
|
||||||
|
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "clientinit");
|
||||||
|
cmd.write_arg("client_nickname", &"Bot");
|
||||||
|
cmd.write_arg("client_version", &"3.?.? [Build: 5680278000]");
|
||||||
|
cmd.write_arg("client_platform", &"Linux");
|
||||||
|
|
||||||
|
cmd.write_arg("client_input_hardware", &"1");
|
||||||
|
cmd.write_arg("client_output_hardware", &"1");
|
||||||
|
cmd.write_arg("client_default_channel", &"");
|
||||||
|
cmd.write_arg("client_default_channel_password", &"");
|
||||||
|
cmd.write_arg("client_server_password", &"");
|
||||||
|
cmd.write_arg("client_meta_data", &"");
|
||||||
|
cmd.write_arg(
|
||||||
|
"client_version_sign",
|
||||||
|
&"Hjd+N58Gv3ENhoKmGYy2bNRBsNNgm5kpiaQWxOj5HN2DXttG6REjymSwJtpJ8muC2gSwRuZi0R+8Laan5ts5CQ==",
|
||||||
|
);
|
||||||
|
cmd.write_arg("client_nickname_phonetic", &"");
|
||||||
|
cmd.write_arg("client_key_offset", &offset);
|
||||||
|
cmd.write_arg("client_default_token", &"");
|
||||||
|
cmd.write_arg("client_badges", &"Overwolf=0");
|
||||||
|
cmd.write_arg("hwid", &"923f136fb1e22ae6ce95e60255529c00,d13231b1bc33edfecfb9169cc7a63bcc");
|
||||||
|
|
||||||
|
con.send_packet(cmd.into_packet())?;
|
||||||
|
Ok(con
|
||||||
|
.filter_commands(|con, cmd| {
|
||||||
|
Ok(if cmd.data().packet().content().starts_with(b"initserver ") {
|
||||||
|
Some(cmd)
|
||||||
|
} else {
|
||||||
|
con.hand_back_buffer(cmd.into_buffer());
|
||||||
|
None
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn disconnect(con: &mut Client) -> Result<()> {
|
||||||
|
let mut cmd =
|
||||||
|
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "clientdisconnect");
|
||||||
|
cmd.write_arg("reasonid", &8);
|
||||||
|
cmd.write_arg("reasonmsg", &"Bye");
|
||||||
|
|
||||||
|
con.send_packet(cmd.into_packet())?;
|
||||||
|
con.wait_disconnect().await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
+452
@@ -0,0 +1,452 @@
|
|||||||
|
//! Handle packet splitting and cryptography
|
||||||
|
use curve25519_dalek_ng::edwards::EdwardsPoint;
|
||||||
|
use eax::aead::consts::{U16, U8};
|
||||||
|
use eax::{AeadInPlace, Eax, KeyInit};
|
||||||
|
use generic_array::GenericArray;
|
||||||
|
use num_bigint::BigUint;
|
||||||
|
use num_traits::ToPrimitive;
|
||||||
|
use omnom::WriteExt;
|
||||||
|
use quicklz::CompressionLevel;
|
||||||
|
use sha1::Sha1;
|
||||||
|
use sha2::{Digest, Sha256, Sha512};
|
||||||
|
use tsproto_types::crypto::{EccKeyPrivEd25519, EccKeyPubP256};
|
||||||
|
|
||||||
|
use crate::connection::CachedKey;
|
||||||
|
use crate::{Error, Result};
|
||||||
|
use tsproto_packets::packets::*;
|
||||||
|
|
||||||
|
pub fn must_encrypt(t: PacketType) -> bool {
|
||||||
|
match t {
|
||||||
|
PacketType::Command | PacketType::CommandLow => true,
|
||||||
|
PacketType::Voice
|
||||||
|
| PacketType::Ack
|
||||||
|
| PacketType::AckLow
|
||||||
|
| PacketType::VoiceWhisper
|
||||||
|
| PacketType::Ping
|
||||||
|
| PacketType::Pong
|
||||||
|
| PacketType::Init => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn should_encrypt(t: PacketType, voice_encryption: bool) -> bool {
|
||||||
|
must_encrypt(t)
|
||||||
|
|| t == PacketType::Ack
|
||||||
|
|| t == PacketType::AckLow
|
||||||
|
|| (voice_encryption && t.is_voice())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compresses and splits the packet data of a `Command` or `CommandLow` packet.
|
||||||
|
///
|
||||||
|
/// Returns the splitted packet data and their headers.
|
||||||
|
/// The headers have their type and the compressed and fragmented flag set
|
||||||
|
/// to the right value.
|
||||||
|
///
|
||||||
|
/// Returns an error if the packet is too large but cannot be splitted.
|
||||||
|
/// Only `Command` and `CommandLow` packets can be compressed and splitted.
|
||||||
|
pub fn compress_and_split(is_client: bool, packet: OutPacket) -> Vec<OutPacket> {
|
||||||
|
// Everything except whisper packets has to be less than 500 bytes
|
||||||
|
let header_size =
|
||||||
|
if is_client { tsproto_packets::C2S_HEADER_LEN } else { tsproto_packets::S2C_HEADER_LEN };
|
||||||
|
let data = packet.content();
|
||||||
|
// The maximum packet size (including header) is 500 bytes.
|
||||||
|
let max_size = 500 - header_size;
|
||||||
|
// Split the data if it is necessary.
|
||||||
|
let compressed;
|
||||||
|
let datas = if data.len() > max_size {
|
||||||
|
// Compress with QuickLZ
|
||||||
|
let cdata = ::quicklz::compress(data, CompressionLevel::Lvl1);
|
||||||
|
// Use only if it is efficient
|
||||||
|
let mut data = if cdata.len() > data.len() {
|
||||||
|
compressed = false;
|
||||||
|
data
|
||||||
|
} else {
|
||||||
|
compressed = true;
|
||||||
|
&cdata
|
||||||
|
};
|
||||||
|
|
||||||
|
// Ignore size limit for whisper packets
|
||||||
|
if data.len() <= max_size || packet.header().packet_type() == PacketType::VoiceWhisper {
|
||||||
|
let mut v = vec![0; header_size + data.len()];
|
||||||
|
v[header_size..].copy_from_slice(data);
|
||||||
|
vec![v]
|
||||||
|
} else {
|
||||||
|
// Split
|
||||||
|
let count = (data.len() + max_size - 1) / max_size;
|
||||||
|
let mut splitted = Vec::with_capacity(count);
|
||||||
|
while data.len() > max_size {
|
||||||
|
let (first, last) = data.split_at(max_size);
|
||||||
|
let mut v = vec![0; header_size + max_size];
|
||||||
|
v[header_size..].copy_from_slice(first);
|
||||||
|
splitted.push(v);
|
||||||
|
data = last;
|
||||||
|
}
|
||||||
|
// Rest
|
||||||
|
let mut v = vec![0; header_size + data.len()];
|
||||||
|
v[header_size..].copy_from_slice(data);
|
||||||
|
splitted.push(v);
|
||||||
|
splitted
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return vec![packet];
|
||||||
|
};
|
||||||
|
|
||||||
|
let len = datas.len();
|
||||||
|
let fragmented = len > 1;
|
||||||
|
let orig_header = packet.header_bytes();
|
||||||
|
let dir = packet.direction();
|
||||||
|
let mut packets = Vec::with_capacity(datas.len());
|
||||||
|
for (i, mut d) in datas.into_iter().enumerate() {
|
||||||
|
d[..header_size].copy_from_slice(orig_header);
|
||||||
|
let mut packet = OutPacket::new_from_data(dir, d);
|
||||||
|
// Only set flags on first fragment
|
||||||
|
if i == 0 && compressed {
|
||||||
|
packet.flags(packet.header().flags() | Flags::COMPRESSED);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set fragmented flag on first and last part
|
||||||
|
if fragmented && (i == 0 || i == len - 1) {
|
||||||
|
packet.flags(packet.header().flags() | Flags::FRAGMENTED);
|
||||||
|
}
|
||||||
|
packets.push(packet);
|
||||||
|
}
|
||||||
|
packets
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_key_nonce(
|
||||||
|
p_type: PacketType, c_id: Option<u16>, p_id: u16, generation_id: u32, iv: &[u8; 64],
|
||||||
|
cache: &mut [[CachedKey; 2]; 8],
|
||||||
|
) -> (GenericArray<u8, U16>, GenericArray<u8, U16>) {
|
||||||
|
// Check if this generation is cached
|
||||||
|
let cache = &mut cache[p_type.to_usize().unwrap()][if c_id.is_some() { 1 } else { 0 }];
|
||||||
|
if cache.generation_id != generation_id {
|
||||||
|
// Update the cache
|
||||||
|
let mut temp = [0; 70];
|
||||||
|
if c_id.is_some() {
|
||||||
|
temp[0] = 0x31;
|
||||||
|
} else {
|
||||||
|
temp[0] = 0x30;
|
||||||
|
}
|
||||||
|
temp[1] = p_type.to_u8().unwrap();
|
||||||
|
(&mut temp[2..6]).write_be(generation_id).unwrap();
|
||||||
|
temp[6..].copy_from_slice(iv);
|
||||||
|
|
||||||
|
let keynonce = Sha256::digest(&temp[..]);
|
||||||
|
let keynonce = keynonce.as_slice();
|
||||||
|
cache.generation_id = generation_id;
|
||||||
|
cache.key.copy_from_slice(&keynonce[..16]);
|
||||||
|
cache.nonce.copy_from_slice(&keynonce[16..]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use the cached version
|
||||||
|
let mut key = cache.key;
|
||||||
|
let nonce = cache.nonce;
|
||||||
|
key[0] ^= (p_id >> 8) as u8;
|
||||||
|
key[1] ^= (p_id & 0xff) as u8;
|
||||||
|
(key, nonce)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn encrypt_key_nonce(
|
||||||
|
packet: &mut OutPacket, key: &GenericArray<u8, U16>, nonce: &GenericArray<u8, U16>,
|
||||||
|
) -> Result<()> {
|
||||||
|
let meta = packet.header().get_meta().to_vec();
|
||||||
|
let cipher = Eax::<aes::Aes128, U8>::new(key);
|
||||||
|
let mac = cipher
|
||||||
|
.encrypt_in_place_detached(nonce, &meta, packet.content_mut())
|
||||||
|
.map_err(|_| Error::MaxLengthExceeded("encryption data"))?;
|
||||||
|
packet.mac().copy_from_slice(mac.as_slice());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn encrypt_fake(packet: &mut OutPacket) -> Result<()> {
|
||||||
|
encrypt_key_nonce(packet, &crate::FAKE_KEY.into(), &crate::FAKE_NONCE.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn encrypt(
|
||||||
|
packet: &mut OutPacket, generation_id: u32, iv: &[u8; 64], cache: &mut [[CachedKey; 2]; 8],
|
||||||
|
) -> Result<()> {
|
||||||
|
let header = packet.header();
|
||||||
|
let (key, nonce) = create_key_nonce(
|
||||||
|
header.packet_type(),
|
||||||
|
header.client_id(),
|
||||||
|
header.packet_id(),
|
||||||
|
generation_id,
|
||||||
|
iv,
|
||||||
|
cache,
|
||||||
|
);
|
||||||
|
encrypt_key_nonce(packet, &key, &nonce)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decrypt_key_nonce(
|
||||||
|
packet: &InPacket, key: &GenericArray<u8, U16>, nonce: &GenericArray<u8, U16>,
|
||||||
|
) -> Result<Vec<u8>> {
|
||||||
|
let header = packet.header();
|
||||||
|
let meta = header.get_meta();
|
||||||
|
// TODO decrypt in-place in packet
|
||||||
|
let mut content = packet.content().to_vec();
|
||||||
|
let cipher = Eax::<aes::Aes128, U8>::new(key);
|
||||||
|
cipher
|
||||||
|
.decrypt_in_place_detached(nonce, meta, &mut content, header.mac().into())
|
||||||
|
.map(|()| content)
|
||||||
|
.map_err(|_| Error::WrongMac {
|
||||||
|
p_type: header.packet_type(),
|
||||||
|
generation_id: 0,
|
||||||
|
packet_id: header.packet_id(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decrypt_fake(packet: &InPacket) -> Result<Vec<u8>> {
|
||||||
|
decrypt_key_nonce(packet, &crate::FAKE_KEY.into(), &crate::FAKE_NONCE.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decrypt(
|
||||||
|
packet: &InPacket, generation_id: u32, iv: &[u8; 64], cache: &mut [[CachedKey; 2]; 8],
|
||||||
|
) -> Result<Vec<u8>> {
|
||||||
|
let header = packet.header();
|
||||||
|
let (key, nonce) = create_key_nonce(
|
||||||
|
header.packet_type(),
|
||||||
|
header.client_id(),
|
||||||
|
header.packet_id(),
|
||||||
|
generation_id,
|
||||||
|
iv,
|
||||||
|
cache,
|
||||||
|
);
|
||||||
|
decrypt_key_nonce(packet, &key, &nonce).map_err(|e| {
|
||||||
|
if let Error::WrongMac { p_type, packet_id, .. } = e {
|
||||||
|
Error::WrongMac { p_type, generation_id, packet_id }
|
||||||
|
} else {
|
||||||
|
e
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compute shared iv and shared mac.
|
||||||
|
pub fn compute_iv_mac(
|
||||||
|
alpha: &[u8; 10], beta: &[u8; 54], our_key: &EccKeyPrivEd25519, other_key: &EdwardsPoint,
|
||||||
|
) -> ([u8; 64], [u8; 8]) {
|
||||||
|
let shared_secret = our_key.create_shared_secret(other_key);
|
||||||
|
let mut shared_iv = [0; 64];
|
||||||
|
shared_iv.copy_from_slice(Sha512::digest(shared_secret).as_slice());
|
||||||
|
for i in 0..10 {
|
||||||
|
shared_iv[i] ^= alpha[i];
|
||||||
|
}
|
||||||
|
for i in 0..54 {
|
||||||
|
shared_iv[i + 10] ^= beta[i];
|
||||||
|
}
|
||||||
|
let mut shared_mac = [0; 8];
|
||||||
|
shared_mac.copy_from_slice(&Sha1::digest(shared_iv).as_slice()[..8]);
|
||||||
|
(shared_iv, shared_mac)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn hash_cash(key: &EccKeyPubP256, level: u8) -> u64 {
|
||||||
|
let omega = key.to_ts();
|
||||||
|
let mut offset = 0;
|
||||||
|
while offset < u64::MAX && get_hash_cash_level(&omega, offset) < level {
|
||||||
|
offset += 1;
|
||||||
|
}
|
||||||
|
offset
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn get_hash_cash_level(omega: &str, offset: u64) -> u8 {
|
||||||
|
let data = Sha1::digest(format!("{}{}", omega, offset).as_bytes());
|
||||||
|
let mut res = 0;
|
||||||
|
for &d in data.as_slice() {
|
||||||
|
if d == 0 {
|
||||||
|
res += 8;
|
||||||
|
} else {
|
||||||
|
res += d.trailing_zeros() as u8;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn biguint_to_array(i: &BigUint) -> [u8; 64] {
|
||||||
|
let mut v = i.to_bytes_le();
|
||||||
|
|
||||||
|
// Extend with zeroes until 64 bytes
|
||||||
|
let len = v.len();
|
||||||
|
v.append(&mut vec![0; 64 - len]);
|
||||||
|
v.reverse();
|
||||||
|
|
||||||
|
let mut a = [0; 64];
|
||||||
|
a.copy_from_slice(&v);
|
||||||
|
a
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn array_to_biguint(i: &[u8; 64]) -> BigUint { BigUint::from_bytes_be(i) }
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use base64::prelude::*;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use crate::license::Licenses;
|
||||||
|
use crate::packets::PacketType;
|
||||||
|
use crate::utils;
|
||||||
|
use tsproto_types::crypto::EccKeyPubEd25519;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_fake_crypt() {
|
||||||
|
let data = (0..100).into_iter().collect::<Vec<_>>();
|
||||||
|
let mut packet = OutPacket::new_with_dir(Direction::C2S, Flags::empty(), PacketType::Ack);
|
||||||
|
packet.data_mut().extend_from_slice(&data);
|
||||||
|
encrypt_fake(&mut packet).unwrap();
|
||||||
|
let packet =
|
||||||
|
InPacket::try_new(Direction::C2S, packet.data_mut().as_slice().into()).unwrap();
|
||||||
|
let dec_data = decrypt_fake(&packet).unwrap();
|
||||||
|
assert_eq!(&data, &dec_data);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_fake_encrypt() {
|
||||||
|
let mut packet = OutAck::new(Direction::C2S, PacketType::Command, 0);
|
||||||
|
encrypt_fake(&mut packet).unwrap();
|
||||||
|
|
||||||
|
let real_res: &[u8] =
|
||||||
|
&[0xa4, 0x7b, 0x47, 0x94, 0xdb, 0xa9, 0x6a, 0xc5, 0, 0, 0, 0, 0x6, 0xfe, 0x18];
|
||||||
|
assert_eq!(real_res, packet.data_mut().as_slice());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn shared_iv31() {
|
||||||
|
let licenses = Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQA1hUFJiiSs\
|
||||||
|
0wFXkYuPUJVcDa6XCrZTcsvkB0Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAAC\
|
||||||
|
4R+5mos+UQ/KCbkpQLMI5WRp4wkQu8e5PZY4zU+/FlyAJwaE8CcJJ/A==")
|
||||||
|
.unwrap()).unwrap();
|
||||||
|
let derived_key =
|
||||||
|
licenses.derive_public_key(EccKeyPubEd25519::from_bytes(crate::ROOT_KEY)).unwrap();
|
||||||
|
|
||||||
|
let client_ek = [
|
||||||
|
0xb0, 0x4e, 0xa1, 0xd9, 0x5c, 0x72, 0x64, 0xdf, 0x0d, 0xe8, 0xb3, 0x6b, 0xaa, 0x7c,
|
||||||
|
0xa1, 0x5f, 0x75, 0x71, 0xf5, 0x1f, 0xa0, 0x54, 0xb5, 0x51, 0x27, 0x08, 0x8e, 0xdd,
|
||||||
|
0x96, 0x3d, 0x6e, 0x79,
|
||||||
|
];
|
||||||
|
|
||||||
|
let priv_key = EccKeyPrivEd25519::from_bytes(client_ek);
|
||||||
|
|
||||||
|
let alpha_b64 = BASE64_STANDARD.decode("Jkxq1wIvvhzaCA==").unwrap();
|
||||||
|
let mut alpha = [0; 10];
|
||||||
|
alpha.copy_from_slice(&alpha_b64);
|
||||||
|
let beta_b64 = BASE64_STANDARD
|
||||||
|
.decode("wU5T/MM6toW6Wge9th7VlTlzVZ9JDWypw2P9migfc25pjGP2Tj7Hm6rJpmKeHRr08Ch7BEAR")
|
||||||
|
.unwrap();
|
||||||
|
let mut beta = [0; 54];
|
||||||
|
beta.copy_from_slice(&beta_b64);
|
||||||
|
|
||||||
|
let expected_shared_shared_iv: [u8; 64] = [
|
||||||
|
0x58, 0x78, 0xae, 0x08, 0x08, 0x72, 0x05, 0xb0, 0x13, 0x27, 0x10, 0xe9, 0x81, 0xb4,
|
||||||
|
0xaf, 0x14, 0x14, 0x71, 0xad, 0xcd, 0x82, 0x98, 0xf3, 0xd1, 0x1d, 0x07, 0x20, 0x72,
|
||||||
|
0x7e, 0xb2, 0x1b, 0x89, 0x47, 0x82, 0x1e, 0xfb, 0x02, 0x53, 0x5a, 0x8a, 0x52, 0x4d,
|
||||||
|
0x9a, 0x7a, 0x09, 0x2c, 0x1b, 0xe7, 0x1f, 0xd1, 0x9d, 0x2a, 0x9d, 0x4f, 0xbd, 0xe3,
|
||||||
|
0x22, 0x09, 0xe4, 0x86, 0x7d, 0x63, 0x49, 0x07,
|
||||||
|
];
|
||||||
|
|
||||||
|
let expected_xored_shared_shared_iv: [u8; 64] = [
|
||||||
|
0x7e, 0x34, 0xc4, 0xdf, 0x0a, 0x5d, 0xbb, 0xac, 0xc9, 0x2f, 0xd1, 0xa7, 0xd2, 0x48,
|
||||||
|
0x6c, 0x2e, 0xa2, 0xf4, 0x17, 0x97, 0x85, 0x25, 0x45, 0xcf, 0xc8, 0x92, 0x19, 0x01,
|
||||||
|
0x2b, 0x2d, 0x52, 0x84, 0x2b, 0x2b, 0xdd, 0x98, 0xff, 0xc9, 0x72, 0x95, 0x21, 0x23,
|
||||||
|
0xf3, 0xf6, 0x6a, 0xda, 0x55, 0xd9, 0xd8, 0x4a, 0x37, 0xe3, 0x3b, 0x2d, 0x23, 0xfe,
|
||||||
|
0x38, 0xfd, 0x14, 0xae, 0x06, 0x67, 0x09, 0x16,
|
||||||
|
];
|
||||||
|
|
||||||
|
let (mut shared_iv, _shared_mac) = compute_iv_mac(&alpha, &beta, &priv_key, &derived_key);
|
||||||
|
|
||||||
|
assert_eq!(&shared_iv as &[u8], &expected_xored_shared_shared_iv as &[u8]);
|
||||||
|
|
||||||
|
for i in 0..10 {
|
||||||
|
shared_iv[i] ^= alpha[i];
|
||||||
|
}
|
||||||
|
for i in 0..54 {
|
||||||
|
shared_iv[i + 10] ^= beta[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
assert_eq!(&shared_iv as &[u8], &expected_shared_shared_iv as &[u8]);
|
||||||
|
|
||||||
|
let mut temp = [0; 70];
|
||||||
|
temp[0] = 0x31;
|
||||||
|
temp[1] = 0x2 & 0xf;
|
||||||
|
temp[6..].copy_from_slice(&expected_xored_shared_shared_iv);
|
||||||
|
|
||||||
|
let temporary: [u8; 70] = [
|
||||||
|
0x31, 0x02, 0x00, 0x00, 0x00, 0x00, 0x7e, 0x34, 0xc4, 0xdf, 0x0a, 0x5d, 0xbb, 0xac,
|
||||||
|
0xc9, 0x2f, 0xd1, 0xa7, 0xd2, 0x48, 0x6c, 0x2e, 0xa2, 0xf4, 0x17, 0x97, 0x85, 0x25,
|
||||||
|
0x45, 0xcf, 0xc8, 0x92, 0x19, 0x01, 0x2b, 0x2d, 0x52, 0x84, 0x2b, 0x2b, 0xdd, 0x98,
|
||||||
|
0xff, 0xc9, 0x72, 0x95, 0x21, 0x23, 0xf3, 0xf6, 0x6a, 0xda, 0x55, 0xd9, 0xd8, 0x4a,
|
||||||
|
0x37, 0xe3, 0x3b, 0x2d, 0x23, 0xfe, 0x38, 0xfd, 0x14, 0xae, 0x06, 0x67, 0x09, 0x16,
|
||||||
|
];
|
||||||
|
assert!(&temp as &[u8] == &temporary as &[u8]);
|
||||||
|
|
||||||
|
let keynonce = Sha256::digest(&temp);
|
||||||
|
|
||||||
|
let expected_keynonce: [u8; 32] = [
|
||||||
|
0xf3, 0x70, 0xd3, 0x43, 0xe7, 0x78, 0x15, 0x70, 0x7a, 0xff, 0x60, 0x48, 0xfb, 0xd9,
|
||||||
|
0xac, 0x6b, 0xb6, 0x33, 0x35, 0x79, 0x31, 0x9b, 0x88, 0x0e, 0x2d, 0x25, 0xef, 0x9c,
|
||||||
|
0xe9, 0x9e, 0x77, 0x5c,
|
||||||
|
];
|
||||||
|
|
||||||
|
assert!(keynonce.as_slice() == &expected_keynonce as &[u8]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_new_decrypt() {
|
||||||
|
let shared_iv = utils::read_hex(
|
||||||
|
"C2 45 6F CB FC 22 08 AE 44 2B 7D E7 3A 67 1B DA 93 09 B2 00 F2 CD 10 49 08 CD 3A B0 \
|
||||||
|
7B DD 58 AD",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let mut shared_iv = Sha512::digest(&shared_iv).as_slice().to_vec();
|
||||||
|
assert_eq!(
|
||||||
|
utils::read_hex(
|
||||||
|
"4D 3F DA B7 D8 B0 2C 82 70 6A 39 3E 97 17 61 09 FA 03 AB 30 5C BB 78 7A 9A 82 D5 \
|
||||||
|
39 9A 60 FD A9 F6 7A D9 04 52 F2 AE 00 3E 35 E8 19 10 89 40 43 80 58 27 1F 0A E0 \
|
||||||
|
E0 3D E0 9C F0 A3 4D 15 6B F0"
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
.as_slice(),
|
||||||
|
shared_iv.as_slice()
|
||||||
|
);
|
||||||
|
|
||||||
|
let alpha = [0; 10];
|
||||||
|
let beta = BASE64_STANDARD
|
||||||
|
.decode("I4onb0zMyAD6bd24QANDls40eOES7qmjonBFtt5wRWzAfIIQWTSxjEas6TGTZIJ8QSJNX+Pl")
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
for i in 0..10 {
|
||||||
|
shared_iv[i] ^= alpha[i];
|
||||||
|
}
|
||||||
|
for i in 0..54 {
|
||||||
|
shared_iv[i + 10] ^= beta[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut temp = [0; 70];
|
||||||
|
temp[0] = 0x31;
|
||||||
|
temp[1] = 0x2 & 0xf;
|
||||||
|
temp[6..].copy_from_slice(&shared_iv);
|
||||||
|
|
||||||
|
let keynonce = Sha256::digest(&temp);
|
||||||
|
let keynonce = keynonce.as_slice();
|
||||||
|
|
||||||
|
let all = utils::read_hex("2b982443ab38be6b00020000329abf64d4572e1349897b5e1e96fbc4a763a4c4ce1f64f0c1e3febd0a5f04a82ab1f2bc2344bb374fd16181beb8233b5b06944280470e9b6893290a1da0776ffcd89f3beec2ce23b9694930c09efaaea0d88a6895a08ede4d5cbfea61291fc553ac651f1e2bc1d2bd277a8bd9ab5386415579a9e56fac46d8b6b119f454bebd99179cd317dec60af205341d11f274d02bbacdd7e9773f72a426358ca1d39016dd95bde2409cd81bf99b340887e997ea982370c6790cf4d23150460820224766838ea4ec4d71dd102ede701ea0001f392623aa410dd9ab0e45874da82e29e6e370515ec30a37dd73f5a364c233ff014384beab5f1708c9f48dfba33a520f8fcdcef055789c54693c3fe72c5bfaca7cb4ca1fed77b8624660b8abc882f4b95b1284cb6dc55019c6082dd6dd146fa50383662d7298bef04ababaf1af80e15cd4c1f81326f085788e2918e00324147dce39b23db71326abc3de4b94df10f1531e9cce202bba71fa3ebeefd77b21fa3260a62e92eeee2183421d384a8c48777e2f9efbc58d4f442c5f0529c7c0e27e81b2b6b1b05eb8fa19256886248d553582dfd24c7cfab3c3f7317a5cebc6504b53fa0e86fc8c1100fc1d506fcf96caa76a7c0b6a27e577f2efdecd4070e847a559bf37d75bfdbe9e814c702426ce696d8645bc300b5f28f9e7f1ce").unwrap();
|
||||||
|
|
||||||
|
let packet = InPacket::try_new(Direction::C2S, &all).unwrap();
|
||||||
|
println!("Packet: {:?}", packet);
|
||||||
|
let mut key = [0; 16];
|
||||||
|
let mut nonce = [0; 16];
|
||||||
|
key.copy_from_slice(&keynonce[..16]);
|
||||||
|
nonce.copy_from_slice(&keynonce[16..]);
|
||||||
|
|
||||||
|
let expected_key =
|
||||||
|
utils::read_hex("D2 42 75 71 9C EE 83 35 EF 8A CE E0 B7 28 40 B8").unwrap();
|
||||||
|
let expected_nonce =
|
||||||
|
utils::read_hex("9C D9 30 B7 58 FE 50 23 64 66 11 C5 36 0E A2 5F").unwrap();
|
||||||
|
|
||||||
|
assert_eq!(&expected_nonce, &nonce);
|
||||||
|
assert_eq!(&expected_key, &key);
|
||||||
|
|
||||||
|
key[1] ^= 2; // packet id
|
||||||
|
let dec = decrypt_key_nonce(&packet, &key.into(), &nonce.into()).unwrap();
|
||||||
|
|
||||||
|
println!("Decrypted: {:?}", String::from_utf8_lossy(&dec));
|
||||||
|
}
|
||||||
|
}
|
||||||
+1213
File diff suppressed because it is too large.
Load diff
+449
@@ -0,0 +1,449 @@
|
|||||||
|
use std::collections::VecDeque;
|
||||||
|
use std::io;
|
||||||
|
use std::mem;
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::pin::Pin;
|
||||||
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
|
use futures::prelude::*;
|
||||||
|
use generic_array::GenericArray;
|
||||||
|
use generic_array::typenum::consts::U16;
|
||||||
|
use num_traits::ToPrimitive;
|
||||||
|
use tokio::io::ReadBuf;
|
||||||
|
use tokio::net::UdpSocket;
|
||||||
|
use tracing::{Span, info_span};
|
||||||
|
use tsproto_packets::packets::*;
|
||||||
|
use tsproto_types::crypto::EccKeyPubP256;
|
||||||
|
|
||||||
|
use crate::packet_codec::PacketCodec;
|
||||||
|
use crate::resend::{PacketId, PartialPacketId, Resender, ResenderState};
|
||||||
|
use crate::{Error, MAX_UDP_PACKET_LENGTH, Result, UDP_SINK_CAPACITY};
|
||||||
|
|
||||||
|
/// The needed functions, this can be used to abstract from the underlying
|
||||||
|
/// transport and allows simulation.
|
||||||
|
pub trait Socket {
|
||||||
|
fn poll_recv_from(&self, cx: &mut Context, buf: &mut ReadBuf) -> Poll<io::Result<SocketAddr>>;
|
||||||
|
fn poll_send_to(
|
||||||
|
&self, cx: &mut Context, buf: &[u8], target: SocketAddr,
|
||||||
|
) -> Poll<io::Result<usize>>;
|
||||||
|
fn local_addr(&self) -> io::Result<SocketAddr>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A cache for the key and nonce for a generation id.
|
||||||
|
/// This has to be stored for each packet type.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct CachedKey {
|
||||||
|
pub generation_id: u32,
|
||||||
|
pub key: GenericArray<u8, U16>,
|
||||||
|
pub nonce: GenericArray<u8, U16>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Data that has to be stored for a connection when it is connected.
|
||||||
|
pub struct ConnectedParams {
|
||||||
|
/// The client id of this connection.
|
||||||
|
pub c_id: u16,
|
||||||
|
/// If voice packets should be encrypted
|
||||||
|
pub voice_encryption: bool,
|
||||||
|
|
||||||
|
/// The public key of the other side.
|
||||||
|
pub public_key: EccKeyPubP256,
|
||||||
|
/// The iv used to encrypt and decrypt packets.
|
||||||
|
pub shared_iv: [u8; 64],
|
||||||
|
/// The mac used for unencrypted packets.
|
||||||
|
pub shared_mac: [u8; 8],
|
||||||
|
/// Cached key and nonce per packet type and for server to client (without
|
||||||
|
/// client id inside the packet) and client to server communication.
|
||||||
|
pub key_cache: [[CachedKey; 2]; 8],
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An event that originates from a tsproto raw connection.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum Event<'a> {
|
||||||
|
ReceiveUdpPacket(&'a InUdpPacket<'a>),
|
||||||
|
ReceivePacket(&'a InPacket<'a>),
|
||||||
|
SendUdpPacket(&'a OutUdpPacket),
|
||||||
|
SendPacket(&'a OutPacket),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An item that originates from a tsproto raw event stream.
|
||||||
|
///
|
||||||
|
/// The disconnected event is signaled by returning `None` from the stream.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum StreamItem {
|
||||||
|
Command(InCommandBuf),
|
||||||
|
Audio(InAudioBuf),
|
||||||
|
C2SInit(InC2SInitBuf),
|
||||||
|
S2CInit(InS2CInitBuf),
|
||||||
|
/// All packets with an id less or equal to this id were acknowledged.
|
||||||
|
AckPacket(PacketId),
|
||||||
|
/// The network statistics were updated.
|
||||||
|
NetworkStatsUpdated,
|
||||||
|
Error(Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
type EventListener = Box<dyn for<'a> Fn(&'a Event<'a>) + Send>;
|
||||||
|
|
||||||
|
/// Represents a currently alive connection.
|
||||||
|
pub struct Connection {
|
||||||
|
pub is_client: bool,
|
||||||
|
pub span: Span,
|
||||||
|
/// The parameters of this connection, if it is already established.
|
||||||
|
pub params: Option<ConnectedParams>,
|
||||||
|
/// The address of the other side, where packets are coming from and going
|
||||||
|
/// to.
|
||||||
|
pub address: SocketAddr,
|
||||||
|
|
||||||
|
pub resender: Resender,
|
||||||
|
pub codec: PacketCodec,
|
||||||
|
pub udp_socket: Box<dyn Socket + Send>,
|
||||||
|
udp_buffer: Vec<u8>,
|
||||||
|
|
||||||
|
/// A buffer of packets that should be returned from the stream.
|
||||||
|
///
|
||||||
|
/// If a new udp packet is received and we already received the following
|
||||||
|
/// ids, we can get multiple packets back at once. As we can only return one
|
||||||
|
/// from the stream, the rest is stored here.
|
||||||
|
pub(crate) stream_items: VecDeque<StreamItem>,
|
||||||
|
|
||||||
|
/// The queue of non-command packets that should be sent.
|
||||||
|
///
|
||||||
|
/// These packets are not influenced by congestion control.
|
||||||
|
/// If it gets too long, we don't poll from the `udp_socket` anymore.
|
||||||
|
acks_to_send: VecDeque<OutUdpPacket>,
|
||||||
|
|
||||||
|
pub event_listeners: Vec<EventListener>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Socket for UdpSocket {
|
||||||
|
fn poll_recv_from(&self, cx: &mut Context, buf: &mut ReadBuf) -> Poll<io::Result<SocketAddr>> {
|
||||||
|
self.poll_recv_from(cx, buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_send_to(
|
||||||
|
&self, cx: &mut Context, buf: &[u8], target: SocketAddr,
|
||||||
|
) -> Poll<io::Result<usize>> {
|
||||||
|
self.poll_send_to(cx, buf, target)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn local_addr(&self) -> io::Result<SocketAddr> { self.local_addr() }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for CachedKey {
|
||||||
|
fn default() -> Self {
|
||||||
|
CachedKey { generation_id: u32::MAX, key: [0; 16].into(), nonce: [0; 16].into() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ConnectedParams {
|
||||||
|
/// Fills the parameters for a connection with their default state.
|
||||||
|
pub fn new(public_key: EccKeyPubP256, shared_iv: [u8; 64], shared_mac: [u8; 8]) -> Self {
|
||||||
|
Self {
|
||||||
|
c_id: 0,
|
||||||
|
voice_encryption: true,
|
||||||
|
public_key,
|
||||||
|
shared_iv,
|
||||||
|
shared_mac,
|
||||||
|
key_cache: Default::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Connection {
|
||||||
|
pub fn new(is_client: bool, address: SocketAddr, udp_socket: Box<dyn Socket + Send>) -> Self {
|
||||||
|
let span = info_span!("connection", local_addr = %udp_socket.local_addr().unwrap(),
|
||||||
|
remote_addr = %address);
|
||||||
|
|
||||||
|
let mut res = Self {
|
||||||
|
is_client,
|
||||||
|
span,
|
||||||
|
params: None,
|
||||||
|
address,
|
||||||
|
resender: Default::default(),
|
||||||
|
codec: Default::default(),
|
||||||
|
udp_socket,
|
||||||
|
udp_buffer: Default::default(),
|
||||||
|
|
||||||
|
stream_items: Default::default(),
|
||||||
|
acks_to_send: Default::default(),
|
||||||
|
event_listeners: Default::default(),
|
||||||
|
};
|
||||||
|
if is_client {
|
||||||
|
// The first command is sent as part of the C2SInit::Init4 packet
|
||||||
|
// so it does not get registered automatically.
|
||||||
|
res.codec.outgoing_p_ids[PacketType::Command.to_usize().unwrap()] =
|
||||||
|
PartialPacketId { generation_id: 0, packet_id: 1 };
|
||||||
|
} else {
|
||||||
|
res.codec.incoming_p_ids[PacketType::Command.to_usize().unwrap()] =
|
||||||
|
PartialPacketId { generation_id: 0, packet_id: 1 };
|
||||||
|
}
|
||||||
|
res
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if a given id is in the receive window.
|
||||||
|
///
|
||||||
|
/// Returns
|
||||||
|
/// 1. If the packet id is inside the receive window
|
||||||
|
/// 1. The generation of the packet
|
||||||
|
/// 1. The minimum accepted packet id
|
||||||
|
/// 1. The maximum accepted packet id
|
||||||
|
pub(crate) fn in_receive_window(&self, p_type: PacketType, p_id: u16) -> (bool, u32, u16, u16) {
|
||||||
|
if p_type == PacketType::Init {
|
||||||
|
return (true, 0, 0, 0);
|
||||||
|
}
|
||||||
|
let type_i = p_type.to_usize().unwrap();
|
||||||
|
// Receive window is the next half of ids
|
||||||
|
let cur_next = self.codec.incoming_p_ids[type_i].packet_id;
|
||||||
|
let (limit, next_gen) = cur_next.overflowing_add(u16::MAX / 2);
|
||||||
|
let gen = self.codec.incoming_p_ids[type_i].generation_id;
|
||||||
|
let in_recv_win = (!next_gen && p_id >= cur_next && p_id < limit)
|
||||||
|
|| (next_gen && (p_id >= cur_next || p_id < limit));
|
||||||
|
let gen_id = if in_recv_win {
|
||||||
|
if next_gen && p_id < limit { gen + 1 } else { gen }
|
||||||
|
} else if p_id < cur_next {
|
||||||
|
gen
|
||||||
|
} else {
|
||||||
|
gen - 1
|
||||||
|
};
|
||||||
|
|
||||||
|
(in_recv_win, gen_id, cur_next, limit)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn send_event(&self, event: &Event) {
|
||||||
|
for l in &self.event_listeners {
|
||||||
|
l(event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn hand_back_buffer(&mut self, buffer: Vec<u8>) {
|
||||||
|
if self.udp_buffer.capacity() < MAX_UDP_PACKET_LENGTH
|
||||||
|
&& buffer.capacity() >= MAX_UDP_PACKET_LENGTH
|
||||||
|
{
|
||||||
|
self.udp_buffer = buffer;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_send_acks(&mut self, cx: &mut Context) -> Result<()> {
|
||||||
|
// Poll acks_to_send
|
||||||
|
while let Some(packet) = self.acks_to_send.front() {
|
||||||
|
match self.poll_send_udp_packet(cx, packet) {
|
||||||
|
Poll::Ready(Ok(())) => {
|
||||||
|
self.resender.handle_loss_outgoing(packet);
|
||||||
|
}
|
||||||
|
Poll::Ready(Err(e)) => return Err(e),
|
||||||
|
Poll::Pending => break,
|
||||||
|
}
|
||||||
|
self.acks_to_send.pop_front();
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_incoming_udp_packet(&mut self, cx: &mut Context) -> Poll<Result<StreamItem>> {
|
||||||
|
if self.acks_to_send.len() >= UDP_SINK_CAPACITY {
|
||||||
|
return Poll::Pending;
|
||||||
|
}
|
||||||
|
|
||||||
|
loop {
|
||||||
|
// Poll udp_socket
|
||||||
|
if self.udp_buffer.len() != MAX_UDP_PACKET_LENGTH {
|
||||||
|
self.udp_buffer.resize(MAX_UDP_PACKET_LENGTH, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut read_buf = ReadBuf::new(&mut self.udp_buffer);
|
||||||
|
match self.udp_socket.poll_recv_from(cx, &mut read_buf) {
|
||||||
|
Poll::Ready(Ok(addr)) => {
|
||||||
|
let size = read_buf.filled().len();
|
||||||
|
let mut udp_buffer = mem::take(&mut self.udp_buffer);
|
||||||
|
udp_buffer.truncate(size);
|
||||||
|
match self.handle_udp_packet(cx, udp_buffer, addr) {
|
||||||
|
Ok(()) => {
|
||||||
|
if let Some(item) = self.stream_items.pop_front() {
|
||||||
|
return Poll::Ready(Ok(item));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
return Poll::Ready(Err(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Udp socket closed
|
||||||
|
Poll::Ready(Err(e)) => return Poll::Ready(Err(Error::Network(e))),
|
||||||
|
Poll::Pending => return Poll::Pending,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_udp_packet(
|
||||||
|
&mut self, cx: &mut Context, udp_buffer: Vec<u8>, addr: SocketAddr,
|
||||||
|
) -> Result<()> {
|
||||||
|
let _span = self.span.clone().entered();
|
||||||
|
if addr != self.address {
|
||||||
|
self.stream_items.push_back(StreamItem::Error(Error::WrongAddress));
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let dir = if self.is_client { Direction::S2C } else { Direction::C2S };
|
||||||
|
let packet = InUdpPacket(match InPacket::try_new(dir, &udp_buffer) {
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(e) => {
|
||||||
|
self.stream_items.push_back(StreamItem::Error(Error::PacketParse("udp", e)));
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let event = Event::ReceiveUdpPacket(&packet);
|
||||||
|
self.send_event(&event);
|
||||||
|
|
||||||
|
self.resender.received_packet();
|
||||||
|
PacketCodec::handle_udp_packet(self, cx, udp_buffer)?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Try to send an ack packet.
|
||||||
|
///
|
||||||
|
/// If it does not work, add it to the ack queue.
|
||||||
|
pub(crate) fn send_ack_packet(&mut self, cx: &mut Context, packet: OutPacket) -> Result<()> {
|
||||||
|
self.send_event(&Event::SendPacket(&packet));
|
||||||
|
let mut udp_packets = PacketCodec::encode_packet(self, packet)?;
|
||||||
|
assert_eq!(
|
||||||
|
udp_packets.len(),
|
||||||
|
1,
|
||||||
|
"Encoding an ack packet should only yield a single packet"
|
||||||
|
);
|
||||||
|
let packet = udp_packets.pop().unwrap();
|
||||||
|
|
||||||
|
match self.poll_send_udp_packet(cx, &packet) {
|
||||||
|
Poll::Ready(r) => {
|
||||||
|
if r.is_ok() {
|
||||||
|
self.resender.handle_loss_outgoing(&packet);
|
||||||
|
}
|
||||||
|
r
|
||||||
|
}
|
||||||
|
Poll::Pending => {
|
||||||
|
self.acks_to_send.push_back(packet);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add a packet to the send queue.
|
||||||
|
///
|
||||||
|
/// This function buffers indefinitely, to prevent using a large amount of
|
||||||
|
/// memory, check `is_send_queue_full` first and only send a packet if this
|
||||||
|
/// function returns `false`.
|
||||||
|
///
|
||||||
|
/// When the `PacketId` which is returned by this function is acknowledged,
|
||||||
|
/// the packet was successfully received by the other side of the
|
||||||
|
/// connection.
|
||||||
|
pub fn send_packet(&mut self, packet: OutPacket) -> Result<PacketId> {
|
||||||
|
self.send_event(&Event::SendPacket(&packet));
|
||||||
|
let udp_packets = PacketCodec::encode_packet(self, packet)?;
|
||||||
|
|
||||||
|
let id = udp_packets.last().unwrap().into();
|
||||||
|
for p in udp_packets {
|
||||||
|
self.send_udp_packet(p);
|
||||||
|
}
|
||||||
|
Ok(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add an udp packet to the send queue.
|
||||||
|
pub fn send_udp_packet(&mut self, packet: OutUdpPacket) {
|
||||||
|
let _span = self.span.clone().entered();
|
||||||
|
match packet.packet_type() {
|
||||||
|
PacketType::Init | PacketType::Command | PacketType::CommandLow => {
|
||||||
|
Resender::send_packet(self, packet);
|
||||||
|
}
|
||||||
|
_ => self.acks_to_send.push_back(packet),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn poll_send_udp_packet(
|
||||||
|
&self, cx: &mut Context, packet: &OutUdpPacket,
|
||||||
|
) -> Poll<Result<()>> {
|
||||||
|
Self::static_poll_send_udp_packet(
|
||||||
|
&*self.udp_socket,
|
||||||
|
self.address,
|
||||||
|
&self.event_listeners,
|
||||||
|
cx,
|
||||||
|
packet,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remember to add the size of the sent packet to the stats in the resender.
|
||||||
|
pub fn static_poll_send_udp_packet(
|
||||||
|
udp_socket: &dyn Socket, address: SocketAddr, event_listeners: &[EventListener],
|
||||||
|
cx: &mut Context, packet: &OutUdpPacket,
|
||||||
|
) -> Poll<Result<()>> {
|
||||||
|
let data = packet.data().data();
|
||||||
|
match udp_socket.poll_send_to(cx, data, address).map_err(Error::Network)? {
|
||||||
|
Poll::Pending => Poll::Pending,
|
||||||
|
Poll::Ready(size) => {
|
||||||
|
let event = Event::SendUdpPacket(packet);
|
||||||
|
for l in event_listeners {
|
||||||
|
l(&event)
|
||||||
|
}
|
||||||
|
|
||||||
|
if size != data.len() {
|
||||||
|
Poll::Ready(Err(Error::Network(std::io::Error::new(
|
||||||
|
std::io::ErrorKind::Other,
|
||||||
|
"Failed to send whole udp packet",
|
||||||
|
))))
|
||||||
|
} else {
|
||||||
|
Poll::Ready(Ok(()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_send_queue_full(&self) -> bool { self.resender.is_full() }
|
||||||
|
pub fn is_send_queue_empty(&self) -> bool { self.resender.is_empty() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pull for events.
|
||||||
|
///
|
||||||
|
/// `Ok(StreamItem::Error)` is recoverable, `Err()` is not.
|
||||||
|
///
|
||||||
|
/// Polling does a few things in round robin fashion:
|
||||||
|
/// 1. Check for new udp packets
|
||||||
|
/// 2. Use the resender to resend packets if necessary
|
||||||
|
/// 3. Use the resender to send ping packets if necessary
|
||||||
|
impl Stream for Connection {
|
||||||
|
type Item = Result<StreamItem>;
|
||||||
|
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
|
||||||
|
let _span = self.span.clone().entered();
|
||||||
|
if let Err(e) = self.poll_send_acks(cx) {
|
||||||
|
return Poll::Ready(Some(Err(e)));
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.resender.get_state() == ResenderState::Disconnected {
|
||||||
|
// Send all ack packets and return `None` afterwards
|
||||||
|
if self.acks_to_send.is_empty() {
|
||||||
|
return Poll::Ready(None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use the resender to resend packets
|
||||||
|
match Resender::poll_resend(&mut self, cx) {
|
||||||
|
Ok(()) => {}
|
||||||
|
Err(e) => return Poll::Ready(Some(Err(e))),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use the resender to send pings
|
||||||
|
match Resender::poll_ping(&mut self, cx) {
|
||||||
|
Ok(()) => {}
|
||||||
|
Err(e) => return Poll::Ready(Some(Err(e))),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return existing stream_items
|
||||||
|
if let Some(item) = self.stream_items.pop_front() {
|
||||||
|
return Poll::Ready(Some(Ok(item)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for new udp packets
|
||||||
|
match self.poll_incoming_udp_packet(cx) {
|
||||||
|
Poll::Ready(r) => return Poll::Ready(Some(r)),
|
||||||
|
Poll::Pending => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
Poll::Pending
|
||||||
|
}
|
||||||
|
}
|
||||||
+255
@@ -0,0 +1,255 @@
|
|||||||
|
//! This library implements the TeamSpeak3 protocol.
|
||||||
|
//!
|
||||||
|
//! For a usable library to build clients and bots, you should take a look at
|
||||||
|
//! [`tsclientlib`](https://github.com/ReSpeak/tsclientlib), which provides a
|
||||||
|
//! convenient interface to this library.
|
||||||
|
//!
|
||||||
|
//! If you are searching for a usable client, [Qint](https://github.com/ReSpeak/Qint)
|
||||||
|
//! is a cross-platform TeamSpeak client, which is using this library (more
|
||||||
|
//! correctly, it is using `tsclientlib`).
|
||||||
|
//!
|
||||||
|
//! For more info on this project, take a look at the
|
||||||
|
//! [tsclientlib README](https://github.com/ReSpeak/tsclientlib).
|
||||||
|
|
||||||
|
use std::fmt;
|
||||||
|
use std::num::ParseIntError;
|
||||||
|
|
||||||
|
use base64::prelude::*;
|
||||||
|
use serde::de::{Unexpected, Visitor};
|
||||||
|
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||||
|
use thiserror::Error;
|
||||||
|
use tsproto_packets::packets;
|
||||||
|
use tsproto_types::crypto::EccKeyPrivP256;
|
||||||
|
|
||||||
|
pub mod algorithms;
|
||||||
|
pub mod client;
|
||||||
|
pub mod connection;
|
||||||
|
pub mod license;
|
||||||
|
pub mod log;
|
||||||
|
pub mod packet_codec;
|
||||||
|
pub mod resend;
|
||||||
|
pub mod utils;
|
||||||
|
|
||||||
|
use algorithms as algs;
|
||||||
|
|
||||||
|
// The build environment of tsproto.
|
||||||
|
git_testament::git_testament!(TESTAMENT);
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub fn get_testament() -> &'static git_testament::GitTestament<'static> { &TESTAMENT }
|
||||||
|
|
||||||
|
type Result<T> = std::result::Result<T, Error>;
|
||||||
|
|
||||||
|
/// The maximum number of bytes for a fragmented packet.
|
||||||
|
///
|
||||||
|
/// The maximum packet size is 500 bytes, as used by
|
||||||
|
/// `algorithms::compress_and_split`.
|
||||||
|
/// We pick the ethernet MTU for possible future compatibility, it is unlikely
|
||||||
|
/// that a packet will get bigger.
|
||||||
|
pub const MAX_UDP_PACKET_LENGTH: usize = 1500;
|
||||||
|
|
||||||
|
/// The maximum number of bytes for a fragmented packet.
|
||||||
|
#[allow(clippy::unreadable_literal)]
|
||||||
|
const MAX_FRAGMENTS_LENGTH: usize = 40960;
|
||||||
|
|
||||||
|
/// The maximum number of packets which are stored, if they are received
|
||||||
|
/// out-of-order.
|
||||||
|
// A high-latency initial channel burst can span more than 200 packet IDs
|
||||||
|
// before a missing command is retransmitted. Keep a bounded reorder window.
|
||||||
|
const MAX_QUEUE_LEN: u16 = 2048;
|
||||||
|
|
||||||
|
/// The maximum decompressed size of a packet.
|
||||||
|
#[allow(clippy::unreadable_literal)]
|
||||||
|
|
||||||
|
/// On large servers with more than 2000 channels, the notifychannelsubscribed packet can be
|
||||||
|
/// 50 kB large (uncompressed). A maximum size to 2 MiB should allow for even larger servers.
|
||||||
|
const MAX_DECOMPRESSED_SIZE: u32 = 2 * 1024 * 1024;
|
||||||
|
const FAKE_KEY: [u8; 16] = *b"c:\\windows\\syste";
|
||||||
|
const FAKE_NONCE: [u8; 16] = *b"m\\firewall32.cpl";
|
||||||
|
|
||||||
|
/// The root key in the TeamSpeak license system.
|
||||||
|
pub const ROOT_KEY: [u8; 32] = [
|
||||||
|
0xcd, 0x0d, 0xe2, 0xae, 0xd4, 0x63, 0x45, 0x50, 0x9a, 0x7e, 0x3c, 0xfd, 0x8f, 0x68, 0xb3, 0xdc,
|
||||||
|
0x75, 0x55, 0xb2, 0x9d, 0xcc, 0xec, 0x73, 0xcd, 0x18, 0x75, 0x0f, 0x99, 0x38, 0x12, 0x40, 0x8a,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// The maximum amount of ack pachets that a connection intermediately stores.
|
||||||
|
///
|
||||||
|
/// When this amount is stored, no new packets will be polled from the UDP
|
||||||
|
/// connection.
|
||||||
|
const UDP_SINK_CAPACITY: usize = 50;
|
||||||
|
|
||||||
|
#[derive(Error, Debug)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub enum Error {
|
||||||
|
#[error("Failed to create ack packet: {0}")]
|
||||||
|
CreateAck(#[source] tsproto_packets::Error),
|
||||||
|
#[error("Failed to decompress packet: {0}")]
|
||||||
|
DecompressPacket(#[source] quicklz::Error),
|
||||||
|
#[error(transparent)]
|
||||||
|
IdentityCrypto(tsproto_types::crypto::Error),
|
||||||
|
#[error("Failed to parse int: {0}")]
|
||||||
|
InvalidHex(#[source] ParseIntError),
|
||||||
|
#[error("Maximum length exceeded for {0}")]
|
||||||
|
MaxLengthExceeded(&'static str),
|
||||||
|
#[error("Network error: {0}")]
|
||||||
|
Network(#[source] std::io::Error),
|
||||||
|
#[error("Packet {id} not in receive window [{next};{limit}) for type {p_type:?}")]
|
||||||
|
NotInReceiveWindow { id: u16, next: u16, limit: u16, p_type: packets::PacketType },
|
||||||
|
#[error("Failed to parse {0} packet: {1}")]
|
||||||
|
PacketParse(&'static str, #[source] tsproto_packets::Error),
|
||||||
|
#[error("Connection timed out: {0}")]
|
||||||
|
Timeout(&'static str),
|
||||||
|
#[error("Got unallowed unencrypted packet")]
|
||||||
|
UnallowedUnencryptedPacket,
|
||||||
|
#[error("Got unexpected init packet")]
|
||||||
|
UnexpectedInitPacket,
|
||||||
|
#[error("Packet has wrong client id {0}")]
|
||||||
|
WrongClientId(u16),
|
||||||
|
#[error("Received udp packet from wrong address")]
|
||||||
|
WrongAddress,
|
||||||
|
#[error("{p_type:?} Packet {generation_id}:{packet_id} has a wrong mac")]
|
||||||
|
WrongMac { p_type: packets::PacketType, generation_id: u32, packet_id: u16 },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||||
|
pub struct Identity {
|
||||||
|
#[serde(serialize_with = "serialize_id_key", deserialize_with = "deserialize_id_key")]
|
||||||
|
key: EccKeyPrivP256,
|
||||||
|
/// The `client_key_offset`/counter for hash cash.
|
||||||
|
counter: u64,
|
||||||
|
/// The maximum counter that was tried, this is greater or equal to
|
||||||
|
/// `counter` but may yield a lower level.
|
||||||
|
max_counter: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct IdKeyVisitor;
|
||||||
|
impl<'de> Visitor<'de> for IdKeyVisitor {
|
||||||
|
type Value = EccKeyPrivP256;
|
||||||
|
|
||||||
|
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
write!(f, "a P256 private ecc key")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_str<E: serde::de::Error>(self, s: &str) -> std::result::Result<Self::Value, E> {
|
||||||
|
EccKeyPrivP256::import_str(s)
|
||||||
|
.map_err(|_| serde::de::Error::invalid_value(Unexpected::Str(s), &self))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_id_key<S: Serializer>(
|
||||||
|
key: &EccKeyPrivP256, s: S,
|
||||||
|
) -> std::result::Result<S::Ok, S::Error> {
|
||||||
|
s.serialize_str(&BASE64_STANDARD.encode(key.to_short()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deserialize_id_key<'de, D: Deserializer<'de>>(
|
||||||
|
d: D,
|
||||||
|
) -> std::result::Result<EccKeyPrivP256, D::Error> {
|
||||||
|
d.deserialize_str(IdKeyVisitor)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Identity {
|
||||||
|
#[inline]
|
||||||
|
pub fn create() -> Self {
|
||||||
|
let mut res = Self::new(EccKeyPrivP256::create(), 0);
|
||||||
|
res.upgrade_level(8);
|
||||||
|
res
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn new(key: EccKeyPrivP256, counter: u64) -> Self {
|
||||||
|
Self::new_with_max_counter(key, counter, counter)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn new_with_max_counter(key: EccKeyPrivP256, counter: u64, max_counter: u64) -> Self {
|
||||||
|
Self { key, counter, max_counter }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn new_from_str(key: &str) -> Result<Self> {
|
||||||
|
if let Ok(identity) = Identity::new_from_ts_str(key) {
|
||||||
|
return Ok(identity);
|
||||||
|
}
|
||||||
|
let mut res = Self::new(EccKeyPrivP256::import_str(key).map_err(Error::IdentityCrypto)?, 0);
|
||||||
|
res.upgrade_level(8);
|
||||||
|
Ok(res)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new_from_ts_str(key: &str) -> Result<Self> {
|
||||||
|
let counter_separator = key
|
||||||
|
.find('V')
|
||||||
|
.ok_or(Error::IdentityCrypto(tsproto_types::crypto::Error::NoCounterBlock))?;
|
||||||
|
let counter = key[..counter_separator]
|
||||||
|
.parse::<u64>()
|
||||||
|
.map_err(|_| Error::IdentityCrypto(tsproto_types::crypto::Error::NoCounterBlock))?;
|
||||||
|
let ecc_key = EccKeyPrivP256::import_str(&key[(counter_separator + 1)..])
|
||||||
|
.map_err(Error::IdentityCrypto)?;
|
||||||
|
Ok(Self::new(ecc_key, counter))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn new_from_bytes(key: &[u8]) -> Result<Self> {
|
||||||
|
let mut res = Self::new(EccKeyPrivP256::import(key).map_err(Error::IdentityCrypto)?, 0);
|
||||||
|
res.upgrade_level(8);
|
||||||
|
Ok(res)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn key(&self) -> &EccKeyPrivP256 { &self.key }
|
||||||
|
#[inline]
|
||||||
|
pub fn counter(&self) -> u64 { self.counter }
|
||||||
|
#[inline]
|
||||||
|
pub fn max_counter(&self) -> u64 { self.max_counter }
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn set_key(&mut self, key: EccKeyPrivP256) { self.key = key }
|
||||||
|
#[inline]
|
||||||
|
pub fn set_counter(&mut self, counter: u64) { self.counter = counter; }
|
||||||
|
#[inline]
|
||||||
|
pub fn set_max_counter(&mut self, max_counter: u64) { self.max_counter = max_counter; }
|
||||||
|
|
||||||
|
/// Compute the current hash cash level.
|
||||||
|
#[inline]
|
||||||
|
pub fn level(&self) -> u8 {
|
||||||
|
let omega = self.key.to_pub().to_ts();
|
||||||
|
algs::get_hash_cash_level(&omega, self.counter)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compute a better hash cash level.
|
||||||
|
pub fn upgrade_level(&mut self, target: u8) {
|
||||||
|
let omega = self.key.to_pub().to_ts();
|
||||||
|
let mut offset = self.max_counter;
|
||||||
|
while offset < u64::MAX && algs::get_hash_cash_level(&omega, offset) < target {
|
||||||
|
offset += 1;
|
||||||
|
}
|
||||||
|
self.counter = offset;
|
||||||
|
self.max_counter = offset;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod identity_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
const TEST_PRIV_KEY: &str =
|
||||||
|
"MG8DAgeAAgEgAiEA6rtKxDn/o/Bo50rNtAE5Ph3h2RKLHQ0gbFkvm2yA79kCIQCrfzAZts/\
|
||||||
|
vHP+3MOetKLjNnpZXt4c6U3UB4gWLKR4H9AIgYTyJofmztcTBjq3KZcDdxu+G4RPVwE5vg8VaN2jbQao=";
|
||||||
|
const TEST_UID: &str = "test/9PZ9vww/Bpf5vJxtJhpz80=";
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_ts_base64() {
|
||||||
|
let identity = Identity::new_from_str(TEST_PRIV_KEY).unwrap();
|
||||||
|
let uid = identity.key().to_pub().get_uid();
|
||||||
|
assert_eq!(TEST_UID, &uid);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_ts_base64_with_offset() {
|
||||||
|
let ident_str = String::from("2792354V") + TEST_PRIV_KEY;
|
||||||
|
let identity = Identity::new_from_str(&ident_str).unwrap();
|
||||||
|
let uid = identity.key().to_pub().get_uid();
|
||||||
|
assert_eq!(TEST_UID, &uid);
|
||||||
|
assert_eq!(identity.level(), 21u8);
|
||||||
|
}
|
||||||
|
}
|
||||||
+932
@@ -0,0 +1,932 @@
|
|||||||
|
use std::convert::{TryFrom, TryInto};
|
||||||
|
use std::fmt;
|
||||||
|
use std::io::Cursor;
|
||||||
|
use std::str;
|
||||||
|
|
||||||
|
use curve25519_dalek_ng::edwards::EdwardsPoint;
|
||||||
|
use curve25519_dalek_ng::scalar::Scalar;
|
||||||
|
use num_derive::{FromPrimitive, ToPrimitive};
|
||||||
|
use num_traits::{FromPrimitive as _, ToPrimitive as _};
|
||||||
|
use omnom::{ReadExt, WriteExt};
|
||||||
|
use sha2::{Digest, Sha512};
|
||||||
|
use thiserror::Error;
|
||||||
|
use time::OffsetDateTime;
|
||||||
|
use time::format_description::well_known::Rfc3339;
|
||||||
|
use tracing::trace;
|
||||||
|
use tsproto_packets::HexSlice;
|
||||||
|
use tsproto_types::{
|
||||||
|
LicenseType,
|
||||||
|
crypto::{EccKeyPrivEd25519, EccKeyPubEd25519},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const TIMESTAMP_OFFSET: i64 = 0x50e2_2700;
|
||||||
|
|
||||||
|
const BLOCK_MIN_LEN: usize = 42;
|
||||||
|
const BLOCK_TYPE_OFFSET: usize = 33;
|
||||||
|
const BLOCK_NOT_VALID_BEFORE_OFFSET: usize = 34;
|
||||||
|
const BLOCK_NOT_VALID_AFTER_OFFSET: usize = 38;
|
||||||
|
|
||||||
|
type Result<T> = std::result::Result<T, Error>;
|
||||||
|
|
||||||
|
#[derive(Error, Debug)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub enum Error {
|
||||||
|
#[error(
|
||||||
|
"License must not exceed bounds {outer_start} - {outer_end} but has {inner_start} - \
|
||||||
|
{inner_end}"
|
||||||
|
)]
|
||||||
|
Bounds {
|
||||||
|
outer_start: OffsetDateTime,
|
||||||
|
outer_end: OffsetDateTime,
|
||||||
|
inner_start: OffsetDateTime,
|
||||||
|
inner_end: OffsetDateTime,
|
||||||
|
},
|
||||||
|
#[error("Failed to deserialize license: {0}")]
|
||||||
|
Deserialize(#[source] std::io::Error),
|
||||||
|
#[error("Failed to deserialize license: {0}")]
|
||||||
|
DeserializeString(#[source] std::str::Utf8Error),
|
||||||
|
#[error("Failed to deserialize date: {0}")]
|
||||||
|
DeserializeDate(#[source] time::error::ComponentRange),
|
||||||
|
#[error("License is only valid between {start} and {end}")]
|
||||||
|
Expired { start: OffsetDateTime, end: OffsetDateTime },
|
||||||
|
#[error("Cannot uncompress license public key")]
|
||||||
|
InvalidPublicKey,
|
||||||
|
#[error("Invalid data {0:#x} in intermediate license")]
|
||||||
|
IntermediateInvalidData(u32),
|
||||||
|
#[error("Invalid public root key for license")]
|
||||||
|
InvalidRootKey,
|
||||||
|
#[error("Non-null-terminated string")]
|
||||||
|
NonterminatedString,
|
||||||
|
#[error("License contains no private key")]
|
||||||
|
NoPrivateKey,
|
||||||
|
#[error("Too many license blocks: {0}")]
|
||||||
|
TooManyBlocks(usize),
|
||||||
|
#[error("License too short ({0}): {1}")]
|
||||||
|
TooShort(usize, &'static str),
|
||||||
|
#[error("Unknown license block type {0}")]
|
||||||
|
UnknownBlockType(u8),
|
||||||
|
#[error("Unknown license type {0}")]
|
||||||
|
UnknownLicenseType(u8),
|
||||||
|
#[error("Unsupported license version {0}")]
|
||||||
|
UnsupportedVersion(u8),
|
||||||
|
#[error("Wrong key kind {0} in license")]
|
||||||
|
WrongKeyKind(u8),
|
||||||
|
#[error("There is no {0} in this block")]
|
||||||
|
NoSuchProperty(&'static str),
|
||||||
|
#[error("Wrong property type for id {id}: Expected type {expected} but got type {actual}")]
|
||||||
|
WrongPropertyType { id: u8, expected: u8, actual: u8 },
|
||||||
|
#[error(
|
||||||
|
"Property with id {id} and type {typ} has wrong length: Expected length {expected} but \
|
||||||
|
got length {actual}"
|
||||||
|
)]
|
||||||
|
WrongPropertyLength { id: u8, typ: u8, expected: u8, actual: u8 },
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A single block of a license
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct License {
|
||||||
|
/// Length of the block
|
||||||
|
pub len: usize,
|
||||||
|
/// A private key for the block to derive a private key
|
||||||
|
pub private_key: Option<EccKeyPrivEd25519>,
|
||||||
|
pub inner: InnerLicense,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Helper struct to debug print a license block.
|
||||||
|
pub struct DebugLicense<'a>(&'a License, &'a [u8]);
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq, FromPrimitive, ToPrimitive)]
|
||||||
|
pub enum LicenseBlockType {
|
||||||
|
Intermediate,
|
||||||
|
Website,
|
||||||
|
/// Ts3_Server
|
||||||
|
Server,
|
||||||
|
Code,
|
||||||
|
// Not existing in the license parameter:
|
||||||
|
// 4: Token, 5: License_Sign, 6: MyTsId_Sign, 7: Updater
|
||||||
|
/// Ts_Server_License
|
||||||
|
Ts5Server = 8,
|
||||||
|
/// 32, Ephemeral_Key
|
||||||
|
Ephemeral = 32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub enum InnerLicense {
|
||||||
|
Ts5Server {
|
||||||
|
/// Properties from the license, offset from the start of properties for every field
|
||||||
|
properties: Vec<usize>,
|
||||||
|
},
|
||||||
|
Other,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A list of blocks, forming a complete license
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Licenses {
|
||||||
|
pub data: Vec<u8>,
|
||||||
|
pub blocks: Vec<License>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub enum LicenseProperty<'a> {
|
||||||
|
/// Unknown property with id 1 and type 1
|
||||||
|
Unknown1(u32),
|
||||||
|
Issuer(&'a str),
|
||||||
|
MaxClients(u32),
|
||||||
|
Unknown {
|
||||||
|
id: u8,
|
||||||
|
typ: u8,
|
||||||
|
data: &'a [u8],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct LicenseBuilder<'a> {
|
||||||
|
licenses: &'a mut Licenses,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct LicenseBlockBuilder<'a, 'b> {
|
||||||
|
builder: &'b mut LicenseBuilder<'a>,
|
||||||
|
/// The start offset for the new block
|
||||||
|
offset: usize,
|
||||||
|
typ: LicenseBlockType,
|
||||||
|
}
|
||||||
|
|
||||||
|
type LicenseTimeBounds = (OffsetDateTime, OffsetDateTime);
|
||||||
|
|
||||||
|
impl Licenses {
|
||||||
|
pub fn new() -> Self { Self::default() }
|
||||||
|
|
||||||
|
/// Parse a license but ignore expired licenses.
|
||||||
|
///
|
||||||
|
/// This is useful for tests but should not be used otherwise.
|
||||||
|
pub fn parse_ignore_expired(data: Vec<u8>) -> Result<Self> { Self::parse_internal(data, false) }
|
||||||
|
|
||||||
|
pub fn parse(data: Vec<u8>) -> Result<Self> { Self::parse_internal(data, true) }
|
||||||
|
|
||||||
|
pub fn parse_internal(data: Vec<u8>, check_expired: bool) -> Result<Self> {
|
||||||
|
let version = data[0];
|
||||||
|
if version != 0 && version != 1 {
|
||||||
|
return Err(Error::UnsupportedVersion(version));
|
||||||
|
}
|
||||||
|
// Read licenses
|
||||||
|
let mut blocks = Vec::new();
|
||||||
|
|
||||||
|
let now = OffsetDateTime::now_utc();
|
||||||
|
let mut offset = 1;
|
||||||
|
let mut bounds = None;
|
||||||
|
while data.len() > offset {
|
||||||
|
if blocks.len() >= 8 {
|
||||||
|
// Accept only 8 blocks
|
||||||
|
return Err(Error::TooManyBlocks(blocks.len()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read next license
|
||||||
|
let (license, b) = Self::parse_block(&data[offset..], check_expired, now, bounds)?;
|
||||||
|
offset += license.len;
|
||||||
|
bounds = Some(b);
|
||||||
|
|
||||||
|
blocks.push(license);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Licenses { data, blocks })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_block(
|
||||||
|
data: &[u8], check_expired: bool, now: OffsetDateTime, bounds: Option<LicenseTimeBounds>,
|
||||||
|
) -> Result<(License, LicenseTimeBounds)> {
|
||||||
|
let license = License::parse(data)?;
|
||||||
|
let license_data = &data[..license.len];
|
||||||
|
|
||||||
|
// Check if the certificate is valid
|
||||||
|
let new_bounds = (
|
||||||
|
license.get_not_valid_before(license_data)?,
|
||||||
|
license.get_not_valid_after(license_data)?,
|
||||||
|
);
|
||||||
|
if new_bounds.0 > now && check_expired {
|
||||||
|
return Err(Error::Expired { start: new_bounds.0, end: new_bounds.1 });
|
||||||
|
}
|
||||||
|
if new_bounds.1 < now && check_expired {
|
||||||
|
return Err(Error::Expired { start: new_bounds.0, end: new_bounds.1 });
|
||||||
|
}
|
||||||
|
if let Some((start, end)) = bounds {
|
||||||
|
// The inner license must not have wider bounds
|
||||||
|
if new_bounds.0 < start || new_bounds.1 > end {
|
||||||
|
return Err(Error::Bounds {
|
||||||
|
outer_start: start,
|
||||||
|
outer_end: end,
|
||||||
|
inner_start: new_bounds.0,
|
||||||
|
inner_end: new_bounds.1,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok((license, new_bounds))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn derive_public_key(&self, root: EccKeyPubEd25519) -> Result<EdwardsPoint> {
|
||||||
|
let mut last_round = root.0.decompress().ok_or(Error::InvalidRootKey)?;
|
||||||
|
let mut offset = 1;
|
||||||
|
trace!("Deriving public key for license");
|
||||||
|
for l in &self.blocks {
|
||||||
|
trace!(current_key = %HexSlice((&last_round.compress().0) as &[u8]));
|
||||||
|
last_round = l.derive_public_key(&self.data[offset..offset + l.len], &last_round)?;
|
||||||
|
offset += l.len;
|
||||||
|
}
|
||||||
|
trace!(
|
||||||
|
final_key = %HexSlice((&last_round.compress().0) as &[u8]),
|
||||||
|
"Finished deriving public key"
|
||||||
|
);
|
||||||
|
Ok(last_round)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Derive the private key of this license, starting with a specific block.
|
||||||
|
///
|
||||||
|
/// The keys which are stored inside the licenses from the starting block on
|
||||||
|
/// have to be private keys.
|
||||||
|
///
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// `starting_block`: The index of the first block for the key computation.
|
||||||
|
/// `first_key`: The starting private key (the key of a parent block or the
|
||||||
|
/// root private key).
|
||||||
|
///
|
||||||
|
/// # Panics
|
||||||
|
///
|
||||||
|
/// Panics if `starting_block` is not a valid license block index.
|
||||||
|
pub fn derive_private_key(
|
||||||
|
&self, starting_block: usize, first_key: EccKeyPrivEd25519,
|
||||||
|
) -> Result<EccKeyPrivEd25519> {
|
||||||
|
let mut res = first_key;
|
||||||
|
let mut offset = 1;
|
||||||
|
for (i, l) in self.blocks.iter().enumerate() {
|
||||||
|
if i >= starting_block {
|
||||||
|
res = l.derive_private_key(&self.data[offset..offset + l.len], &res)?;
|
||||||
|
}
|
||||||
|
offset += l.len;
|
||||||
|
}
|
||||||
|
Ok(res)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn build<F: FnOnce(LicenseBuilder)>(mut self, f: F) -> Result<Self> {
|
||||||
|
let len = self.data.len();
|
||||||
|
|
||||||
|
f(LicenseBuilder { licenses: &mut self });
|
||||||
|
|
||||||
|
// Parse new blocks
|
||||||
|
let now = OffsetDateTime::now_utc();
|
||||||
|
let mut offset = len;
|
||||||
|
let mut bounds = self
|
||||||
|
.blocks
|
||||||
|
.last()
|
||||||
|
.map(|b| {
|
||||||
|
let b_offset = len - b.len;
|
||||||
|
let b_data = &self.data[b_offset..len];
|
||||||
|
Ok((b.get_not_valid_before(b_data)?, b.get_not_valid_after(b_data)?))
|
||||||
|
})
|
||||||
|
.transpose()?;
|
||||||
|
|
||||||
|
while self.data.len() > offset {
|
||||||
|
if self.blocks.len() >= 8 {
|
||||||
|
// Accept only 8 blocks
|
||||||
|
return Err(Error::TooManyBlocks(self.blocks.len()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read next license
|
||||||
|
let (license, b) = Self::parse_block(&self.data[offset..], false, now, bounds)?;
|
||||||
|
offset += license.len;
|
||||||
|
bounds = Some(b);
|
||||||
|
|
||||||
|
self.blocks.push(license);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_valid(&self) -> Result<()> {
|
||||||
|
let mut offset = 1;
|
||||||
|
for b in &self.blocks {
|
||||||
|
b.is_valid(&self.data[offset..offset + b.len])?;
|
||||||
|
offset += b.len;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Licenses {
|
||||||
|
fn default() -> Self { Self { data: vec![1], blocks: Default::default() } }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for Licenses {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
write!(f, "Licenses ")?;
|
||||||
|
let mut offset = 1;
|
||||||
|
f.debug_list()
|
||||||
|
.entries(self.blocks.iter().map(|b| {
|
||||||
|
let o = offset;
|
||||||
|
offset += b.len;
|
||||||
|
DebugLicense(b, &self.data[o..o + b.len])
|
||||||
|
}))
|
||||||
|
.finish()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl License {
|
||||||
|
/// Parse license and return read length.
|
||||||
|
pub fn parse(data: &[u8]) -> Result<Self> {
|
||||||
|
let len = data.len();
|
||||||
|
if data.len() < BLOCK_MIN_LEN {
|
||||||
|
return Err(Error::TooShort(len, "less than minimum block length"));
|
||||||
|
}
|
||||||
|
if data[0] != 0 {
|
||||||
|
return Err(Error::WrongKeyKind(data[0]));
|
||||||
|
}
|
||||||
|
|
||||||
|
let typ_i = data[BLOCK_TYPE_OFFSET];
|
||||||
|
let typ = LicenseBlockType::from_u8(typ_i).ok_or(Error::UnknownBlockType(typ_i))?;
|
||||||
|
let data = &data[BLOCK_MIN_LEN..];
|
||||||
|
let (inner, extra_len) = match typ {
|
||||||
|
LicenseBlockType::Intermediate => {
|
||||||
|
if data.len() < 5 {
|
||||||
|
return Err(Error::TooShort(
|
||||||
|
len,
|
||||||
|
"less than minimum length of intermediate license",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
// 4 byte unknown
|
||||||
|
// Issuer string
|
||||||
|
|
||||||
|
let len = if let Some(len) = data[4..].iter().position(|&b| b == 0) {
|
||||||
|
len
|
||||||
|
} else {
|
||||||
|
return Err(Error::NonterminatedString);
|
||||||
|
};
|
||||||
|
(InnerLicense::Other, 5 + len)
|
||||||
|
}
|
||||||
|
LicenseBlockType::Server => {
|
||||||
|
if data.len() < 6 {
|
||||||
|
return Err(Error::TooShort(
|
||||||
|
len,
|
||||||
|
"less than minimum length of TS3 server license",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
// 1 byte server license type
|
||||||
|
// 4 byte max clients
|
||||||
|
// Issuer string
|
||||||
|
let len = if let Some(len) = data[5..].iter().position(|&b| b == 0) {
|
||||||
|
len
|
||||||
|
} else {
|
||||||
|
return Err(Error::NonterminatedString);
|
||||||
|
};
|
||||||
|
|
||||||
|
(InnerLicense::Other, 6 + len)
|
||||||
|
}
|
||||||
|
LicenseBlockType::Ts5Server => {
|
||||||
|
if data.len() < 2 {
|
||||||
|
return Err(Error::TooShort(
|
||||||
|
len,
|
||||||
|
"less than minimum length of TS5 server license",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
// 1 byte server license type
|
||||||
|
// Property count and properties
|
||||||
|
let property_count = data[1];
|
||||||
|
let mut pos = 2;
|
||||||
|
|
||||||
|
let properties = (0..property_count)
|
||||||
|
.map(|_| {
|
||||||
|
let p = pos - 2;
|
||||||
|
if pos >= data.len() {
|
||||||
|
return Err(Error::TooShort(len, "missing TS5 license property"));
|
||||||
|
}
|
||||||
|
let len = usize::from(data[pos]);
|
||||||
|
pos += 1;
|
||||||
|
if pos + len >= data.len() {
|
||||||
|
return Err(Error::TooShort(len, "cut off TS5 license property"));
|
||||||
|
}
|
||||||
|
pos += len;
|
||||||
|
Ok(p)
|
||||||
|
})
|
||||||
|
.collect::<Result<_>>()?;
|
||||||
|
|
||||||
|
(InnerLicense::Ts5Server { properties }, pos)
|
||||||
|
}
|
||||||
|
LicenseBlockType::Ephemeral => (InnerLicense::Other, 0),
|
||||||
|
_ => {
|
||||||
|
return Err(Error::UnknownBlockType(typ_i));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(License { len: BLOCK_MIN_LEN + extra_len, private_key: None, inner })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_type(&self, data: &[u8]) -> Result<LicenseBlockType> {
|
||||||
|
let typ_i = data[BLOCK_TYPE_OFFSET];
|
||||||
|
LicenseBlockType::from_u8(typ_i).ok_or(Error::UnknownBlockType(typ_i))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_public_key(&self, data: &[u8]) -> Result<EdwardsPoint> {
|
||||||
|
let k = EccKeyPubEd25519::from_bytes(data[1..33].try_into().unwrap());
|
||||||
|
k.0.decompress().ok_or(Error::InvalidPublicKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_timestamp(&self, data: &[u8], block_offset: usize) -> Result<OffsetDateTime> {
|
||||||
|
let num: u32 = (&data[block_offset..]).read_be().map_err(Error::Deserialize)?;
|
||||||
|
OffsetDateTime::from_unix_timestamp(i64::from(num) + TIMESTAMP_OFFSET)
|
||||||
|
.map_err(Error::DeserializeDate)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_not_valid_before(&self, data: &[u8]) -> Result<OffsetDateTime> {
|
||||||
|
self.get_timestamp(data, BLOCK_NOT_VALID_BEFORE_OFFSET)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_not_valid_after(&self, data: &[u8]) -> Result<OffsetDateTime> {
|
||||||
|
self.get_timestamp(data, BLOCK_NOT_VALID_AFTER_OFFSET)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_license_type(&self, data: &[u8]) -> Result<LicenseType> {
|
||||||
|
if ![LicenseBlockType::Server, LicenseBlockType::Ts5Server].contains(&self.get_type(data)?)
|
||||||
|
{
|
||||||
|
return Err(Error::NoSuchProperty("license type"));
|
||||||
|
}
|
||||||
|
LicenseType::from_u8(data[BLOCK_MIN_LEN])
|
||||||
|
.ok_or(Error::UnknownLicenseType(data[BLOCK_MIN_LEN]))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_issuer<'a>(&self, data: &'a [u8]) -> Result<&'a str> {
|
||||||
|
let typ = self.get_type(data)?;
|
||||||
|
|
||||||
|
if typ == LicenseBlockType::Ts5Server {
|
||||||
|
// Search in properties
|
||||||
|
let res = self
|
||||||
|
.get_properties(data)?
|
||||||
|
.find_map(|p| if let Ok(LicenseProperty::Issuer(i)) = p { Some(i) } else { None })
|
||||||
|
.ok_or(Error::NoSuchProperty("issuer"));
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
let offset = BLOCK_MIN_LEN
|
||||||
|
+ match typ {
|
||||||
|
LicenseBlockType::Intermediate => 4,
|
||||||
|
LicenseBlockType::Website | LicenseBlockType::Code => 0,
|
||||||
|
LicenseBlockType::Server => 5,
|
||||||
|
_ => return Err(Error::NoSuchProperty("issuer")),
|
||||||
|
};
|
||||||
|
let len = match typ {
|
||||||
|
LicenseBlockType::Intermediate
|
||||||
|
| LicenseBlockType::Website
|
||||||
|
| LicenseBlockType::Code
|
||||||
|
| LicenseBlockType::Server => self.len - offset - 1,
|
||||||
|
_ => return Err(Error::NoSuchProperty("issuer")),
|
||||||
|
};
|
||||||
|
str::from_utf8(&data[offset..offset + len]).map_err(Error::DeserializeString)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_max_clients(&self, data: &[u8]) -> Result<u32> {
|
||||||
|
let typ = self.get_type(data)?;
|
||||||
|
|
||||||
|
if typ == LicenseBlockType::Ts5Server {
|
||||||
|
// Search in properties
|
||||||
|
let res = self
|
||||||
|
.get_properties(data)?
|
||||||
|
.find_map(
|
||||||
|
|p| if let Ok(LicenseProperty::MaxClients(i)) = p { Some(i) } else { None },
|
||||||
|
)
|
||||||
|
.ok_or(Error::NoSuchProperty("max clients"));
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
let offset = BLOCK_MIN_LEN
|
||||||
|
+ match typ {
|
||||||
|
LicenseBlockType::Intermediate => 0,
|
||||||
|
LicenseBlockType::Server => 1,
|
||||||
|
_ => return Err(Error::NoSuchProperty("max clients")),
|
||||||
|
};
|
||||||
|
(&data[offset..offset + 4]).read_be().map_err(Error::Deserialize)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_properties<'a: 'b, 'b>(
|
||||||
|
&'b self, data: &'a [u8],
|
||||||
|
) -> Result<impl Iterator<Item = Result<LicenseProperty<'a>>> + 'b> {
|
||||||
|
if let InnerLicense::Ts5Server { properties } = &self.inner {
|
||||||
|
Ok(properties.iter().map(move |p| {
|
||||||
|
let o = BLOCK_MIN_LEN + 2 + p;
|
||||||
|
let len = data[o];
|
||||||
|
let len_usize = len as usize;
|
||||||
|
let id = data[o + 1];
|
||||||
|
let typ = data[o + 2];
|
||||||
|
|
||||||
|
// Check length
|
||||||
|
if let Some(expected) = match typ {
|
||||||
|
// String, check that it is null-terminated
|
||||||
|
0 => {
|
||||||
|
if data[o + len_usize] != 0 {
|
||||||
|
return Err(Error::NonterminatedString);
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
1 | 3 => Some(4),
|
||||||
|
2 | 4 => Some(8),
|
||||||
|
_ => None,
|
||||||
|
} {
|
||||||
|
if len != expected {
|
||||||
|
return Err(Error::WrongPropertyLength { id, typ, expected, actual: len });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match id {
|
||||||
|
1 => {
|
||||||
|
if typ != 1 {
|
||||||
|
return Err(Error::WrongPropertyType { id, expected: 1, actual: typ });
|
||||||
|
}
|
||||||
|
Ok(LicenseProperty::Unknown1(
|
||||||
|
(&data[o + 3..o + 3 + 4]).read_be().map_err(Error::Deserialize)?,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
2 => {
|
||||||
|
if typ != 0 {
|
||||||
|
return Err(Error::WrongPropertyType { id, expected: 0, actual: typ });
|
||||||
|
}
|
||||||
|
let s = str::from_utf8(&data[o + 3..o + len_usize])
|
||||||
|
.map_err(Error::DeserializeString)?;
|
||||||
|
Ok(LicenseProperty::Issuer(s))
|
||||||
|
}
|
||||||
|
3 => {
|
||||||
|
if typ != 1 {
|
||||||
|
return Err(Error::WrongPropertyType { id, expected: 1, actual: typ });
|
||||||
|
}
|
||||||
|
Ok(LicenseProperty::MaxClients(
|
||||||
|
(&data[o + 3..o + 3 + 4]).read_be().map_err(Error::Deserialize)?,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
Ok(LicenseProperty::Unknown { id, typ, data: &data[o + 3..o + len_usize] })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
} else {
|
||||||
|
Err(Error::NoSuchProperty("properties"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the private key from the hash of this license block.
|
||||||
|
pub fn get_hash_key(&self, data: &[u8]) -> Scalar {
|
||||||
|
// Make a valid private key from the hash
|
||||||
|
let mut hash_key = Sha512::digest(&data[1..]);
|
||||||
|
hash_key[0] &= 248;
|
||||||
|
hash_key[31] &= 63;
|
||||||
|
hash_key[31] |= 64;
|
||||||
|
Scalar::from_bytes_mod_order(hash_key.as_slice()[..32].try_into().unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn derive_public_key(
|
||||||
|
&self, data: &[u8], parent_key: &EdwardsPoint,
|
||||||
|
) -> Result<EdwardsPoint> {
|
||||||
|
let pub_key = self.get_public_key(data)?;
|
||||||
|
let hash_key = self.get_hash_key(data);
|
||||||
|
Ok(pub_key * hash_key + parent_key)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Derive the private key of this license block.
|
||||||
|
///
|
||||||
|
/// The key which is stored inside this license has to be a private key.
|
||||||
|
///
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// `parent_key`: The resulting private key of the previous block.
|
||||||
|
pub fn derive_private_key(
|
||||||
|
&self, data: &[u8], parent_key: &EccKeyPrivEd25519,
|
||||||
|
) -> Result<EccKeyPrivEd25519> {
|
||||||
|
let priv_key = if let Some(k) = &self.private_key {
|
||||||
|
&k.0
|
||||||
|
} else {
|
||||||
|
return Err(Error::NoPrivateKey);
|
||||||
|
};
|
||||||
|
let hash_key = self.get_hash_key(data);
|
||||||
|
Ok(EccKeyPrivEd25519(priv_key * hash_key + parent_key.0))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if this is a valid license.
|
||||||
|
///
|
||||||
|
/// Does some sanity checking on fields. Does not need to be called for correctness.
|
||||||
|
pub fn is_valid(&self, data: &[u8]) -> Result<()> {
|
||||||
|
self.get_public_key(data)?;
|
||||||
|
self.get_not_valid_before(data)?;
|
||||||
|
self.get_not_valid_after(data)?;
|
||||||
|
|
||||||
|
if let Err(e) = self.get_license_type(data) {
|
||||||
|
if !matches!(e, Error::NoSuchProperty(_)) {
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Err(e) = self.get_issuer(data) {
|
||||||
|
if !matches!(e, Error::NoSuchProperty(_)) {
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match self.get_properties(data) {
|
||||||
|
Ok(ps) => {
|
||||||
|
for p in ps {
|
||||||
|
p?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
if !matches!(e, Error::NoSuchProperty(_)) {
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for DebugLicense<'_> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
let from = self
|
||||||
|
.0
|
||||||
|
.get_not_valid_before(self.1)
|
||||||
|
.ok()
|
||||||
|
.and_then(|d| d.format(&Rfc3339).ok())
|
||||||
|
.unwrap_or_else(|| "error".to_string());
|
||||||
|
let to = self
|
||||||
|
.0
|
||||||
|
.get_not_valid_after(self.1)
|
||||||
|
.ok()
|
||||||
|
.and_then(|d| d.format(&Rfc3339).ok())
|
||||||
|
.unwrap_or_else(|| "error".to_string());
|
||||||
|
|
||||||
|
let mut d = f.debug_struct("License");
|
||||||
|
let typ = self.0.get_type(self.1).unwrap();
|
||||||
|
d.field("type", &typ);
|
||||||
|
if let Some(key) = &self.0.private_key {
|
||||||
|
d.field("private_key", key);
|
||||||
|
}
|
||||||
|
d.field("not_valid_before", &from).field("not_valid_after", &to);
|
||||||
|
|
||||||
|
match typ {
|
||||||
|
LicenseBlockType::Intermediate => {
|
||||||
|
if let Ok(num) = self.0.get_max_clients(self.1) {
|
||||||
|
d.field("data", &num);
|
||||||
|
} else {
|
||||||
|
d.field("data", &"error");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LicenseBlockType::Website | LicenseBlockType::Code => {
|
||||||
|
if let Ok(issuer) = self.0.get_issuer(self.1) {
|
||||||
|
d.field("issuer", &issuer);
|
||||||
|
} else {
|
||||||
|
d.field("issuer", &"error");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LicenseBlockType::Server => {
|
||||||
|
if let Ok(license_type) = self.0.get_license_type(self.1) {
|
||||||
|
d.field("license_type", &license_type);
|
||||||
|
} else {
|
||||||
|
d.field("license_type", &"error");
|
||||||
|
}
|
||||||
|
if let Ok(issuer) = self.0.get_issuer(self.1) {
|
||||||
|
d.field("issuer", &issuer);
|
||||||
|
} else {
|
||||||
|
d.field("issuer", &"error");
|
||||||
|
}
|
||||||
|
if let Ok(max_clients) = self.0.get_max_clients(self.1) {
|
||||||
|
d.field("max_clients", &max_clients);
|
||||||
|
} else {
|
||||||
|
d.field("max_clients", &"error");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LicenseBlockType::Ts5Server => {
|
||||||
|
if let Ok(props) =
|
||||||
|
self.0.get_properties(self.1).and_then(|ps| ps.collect::<Result<Vec<_>>>())
|
||||||
|
{
|
||||||
|
d.field("properties", &props);
|
||||||
|
} else {
|
||||||
|
d.field("properties", &"error");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LicenseBlockType::Ephemeral => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
d.finish()?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LicenseBlockType {
|
||||||
|
fn min_len(&self) -> usize {
|
||||||
|
BLOCK_MIN_LEN
|
||||||
|
+ match self {
|
||||||
|
Self::Intermediate => 5,
|
||||||
|
Self::Website | Self::Code => 1,
|
||||||
|
Self::Server => 6,
|
||||||
|
Self::Ts5Server => 2,
|
||||||
|
Self::Ephemeral => 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> LicenseBuilder<'a> {
|
||||||
|
pub fn add_block<'b>(&'b mut self, typ: LicenseBlockType) -> LicenseBlockBuilder<'a, 'b> {
|
||||||
|
let len = self.licenses.data.len();
|
||||||
|
self.licenses.data.resize(len + typ.min_len(), 0);
|
||||||
|
self.licenses.data[len + BLOCK_TYPE_OFFSET] = typ.to_u8().unwrap();
|
||||||
|
LicenseBlockBuilder { builder: self, offset: len, typ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LicenseBlockBuilder<'_, '_> {
|
||||||
|
pub fn public_key(&mut self, key: &EccKeyPubEd25519) -> &mut Self {
|
||||||
|
let o = self.offset + 1;
|
||||||
|
self.builder.licenses.data[o..o + 32].copy_from_slice(&key.0.0);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_timestamp(&mut self, offset: usize, time: OffsetDateTime) -> &mut Self {
|
||||||
|
let o = self.offset + offset;
|
||||||
|
Cursor::new(&mut self.builder.licenses.data[o..o + 4])
|
||||||
|
.write_be((time.unix_timestamp() - TIMESTAMP_OFFSET) as u32)
|
||||||
|
.unwrap();
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn not_valid_before(&mut self, time: OffsetDateTime) -> &mut Self {
|
||||||
|
self.write_timestamp(BLOCK_NOT_VALID_BEFORE_OFFSET, time)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn not_valid_after(&mut self, time: OffsetDateTime) -> &mut Self {
|
||||||
|
self.write_timestamp(BLOCK_NOT_VALID_AFTER_OFFSET, time)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Only valid for Server and Ts5Server license types
|
||||||
|
pub fn server_license_type(&mut self, typ: LicenseType) -> &mut Self {
|
||||||
|
if ![LicenseBlockType::Server, LicenseBlockType::Ts5Server].contains(&self.typ) {
|
||||||
|
panic!(
|
||||||
|
"Setting the license type is only allowed for Server and Ts5Server license types, \
|
||||||
|
but this is a {:?}",
|
||||||
|
self.typ
|
||||||
|
);
|
||||||
|
}
|
||||||
|
self.builder.licenses.data[self.offset + BLOCK_MIN_LEN] = typ.to_u8().unwrap();
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add a property in a TS5 license block.
|
||||||
|
///
|
||||||
|
/// `len` is the length of the content, excluding id, type and length field.
|
||||||
|
/// Return the byte offset to where the contents of the property starts.
|
||||||
|
fn ts5_add_property(&mut self, id: u8, typ: u8, len: usize) -> usize {
|
||||||
|
let o = self.builder.licenses.data.len();
|
||||||
|
self.builder.licenses.data.resize(o + len + 3, 0);
|
||||||
|
// Increment property count
|
||||||
|
self.builder.licenses.data[self.offset + BLOCK_MIN_LEN + 1] += 1;
|
||||||
|
self.builder.licenses.data[o] = u8::try_from(len).unwrap() + 2;
|
||||||
|
self.builder.licenses.data[o + 1] = id;
|
||||||
|
self.builder.licenses.data[o + 2] = typ;
|
||||||
|
o + 3
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Only valid for Intermediate, Server and Ts5Server license types
|
||||||
|
pub fn max_clients(&mut self, max_clients: u32) -> &mut Self {
|
||||||
|
let o = if self.typ == LicenseBlockType::Ts5Server {
|
||||||
|
self.ts5_add_property(3, 1, 4)
|
||||||
|
} else {
|
||||||
|
self.offset
|
||||||
|
+ BLOCK_MIN_LEN
|
||||||
|
+ match self.typ {
|
||||||
|
LicenseBlockType::Intermediate => 0,
|
||||||
|
LicenseBlockType::Server => 1,
|
||||||
|
_ => panic!(
|
||||||
|
"Setting max clients is only allowed for Intermediate, Server and \
|
||||||
|
Ts5Server license types, but this is a {:?}",
|
||||||
|
self.typ
|
||||||
|
),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Cursor::new(&mut self.builder.licenses.data[o..o + 4]).write_be(max_clients).unwrap();
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Only valid for Intermediate, Server and Ts5Server license types
|
||||||
|
pub fn issuer(&mut self, issuer: &str) -> &mut Self {
|
||||||
|
// Check that the issuer does not contain null bytes
|
||||||
|
assert!(
|
||||||
|
!issuer.contains('\0'),
|
||||||
|
"The issuer is written as a null-terminated string so it cannot contain null bytes"
|
||||||
|
);
|
||||||
|
|
||||||
|
let o = if self.typ == LicenseBlockType::Ts5Server {
|
||||||
|
self.ts5_add_property(2, 0, issuer.len() + 1)
|
||||||
|
} else {
|
||||||
|
if ![LicenseBlockType::Intermediate, LicenseBlockType::Server].contains(&self.typ) {
|
||||||
|
panic!(
|
||||||
|
"Setting the issuer is only allowed for Intermediate, Server and Ts5Server \
|
||||||
|
license types, but this is a {:?}",
|
||||||
|
self.typ
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Check that no issuer was written so far
|
||||||
|
assert!(
|
||||||
|
self.builder.licenses.data.len() - self.offset == self.typ.min_len(),
|
||||||
|
"Only a single issuer can be written into a license block"
|
||||||
|
);
|
||||||
|
let o = self.builder.licenses.data.len();
|
||||||
|
self.builder.licenses.data.resize(o + issuer.len(), 0);
|
||||||
|
o - 1
|
||||||
|
};
|
||||||
|
self.builder.licenses.data[o..o + issuer.len()].copy_from_slice(issuer.as_bytes());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use base64::prelude::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_standard_license() {
|
||||||
|
Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQA1hUFJiiSs0wFXkYuPUJVcDa6XCrZTcsvkB0\
|
||||||
|
Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAACiIBip9hQaK6P3QhwOJs/BkPn0i\
|
||||||
|
oyIDPaNgzJ6M8x0kiAJf4hxCYAxMQ==").unwrap()).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_standard_license_expired() {
|
||||||
|
assert!(Licenses::parse(BASE64_STANDARD.decode("AQA1hUFJiiSs0wFXkYuPUJVcDa6XCrZTcsvkB0\
|
||||||
|
Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAACiIBip9hQaK6P3QhwOJs/BkPn0i\
|
||||||
|
oyIDPaNgzJ6M8x0kiAJf4hxCYAxMQ==").unwrap()).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_aal_license() {
|
||||||
|
Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQCvbHFTQDY/terPeilrp/ECU9xCH5U3xC92lY\
|
||||||
|
TNaY/0KQAJFueAazbsgAAAACVUZWFtU3BlYWsgU3lzdGVtcyBHbWJIAABhl9gwla/UJ\
|
||||||
|
p2Eszst9TRVXO/PeE6a6d+CTI6Pg7OEVgAJc5CrL4Nh8gAAACRUZWFtU3BlYWsgc3lz\
|
||||||
|
dGVtcyBHbWJIAACvTQIgpv6zmLZq3znh7ygmOSokGFkFjz4bTigrOnetrgIJdIIACdS\
|
||||||
|
/gAYAAAAAU29zc2VuU3lzdGVtcy5iaWQAADY7+uV1CQ1niOvYSdGzsu83kPTNWijovr\
|
||||||
|
3B78eHGeePIAm98vQJvpu0").unwrap()).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_ts5_server_license_long() {
|
||||||
|
// Slightly older format having a block with a Ts5 license block in it
|
||||||
|
Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQDVsMGbcrMmGif1vSXPWWXNW2CB5\
|
||||||
|
Fe9oZ/2uxP29j1EXQAQSfiAazbsgAAAASVUZWFtU3BlYWsgU3lzdGVtcyBHbWJIAAALB6Qfbe\
|
||||||
|
JyN+9foJhe+/KPFwyU+i++4MAA0q1/WCnizwARRuEPN1aeBQAAASBUZWFtU3BlYWsgc3lzdGV\
|
||||||
|
tcyBHbWJIAADrhbI5gUR3thsS7FqKV5P5h7djnwMSJfF2vi58lm1VcwgRUFMAE0P7gAUCGQIA\
|
||||||
|
VGVhbVNwZWFrIFN5c3RlbXMgR21iSAAGAwEAAAAFAAf2KhQ7WLjOvwwY0Bi7LxAcWmQeT+LQt\
|
||||||
|
uaOzjhYoA+YIBGNq1kRjlQZ").unwrap()).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_ts5_server_license_long2() {
|
||||||
|
// Also slightly older, has 3 properties
|
||||||
|
Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQDVsMGbcrMmGif1vSXPWWXNW2CB5\
|
||||||
|
Fe9oZ/2uxP29j1EXQAQSfiAazbsgAAAASVUZWFtU3BlYWsgU3lzdGVtcyBHbWJIAAAtXG5p2n\
|
||||||
|
iXlDfpVAGuD88w8hetKYL4vqHRkB5xB8ASRwAR2t/MN+ttjAAAASBUZWFtU3BlYWsgc3lzdGV\
|
||||||
|
tcyBHbWJIAAAdZYGtwkeZFhzqnoV1uk+Tcphe8GgcqiPVtELF9y4wOAgR4qmAF4jnAAkDGQIA\
|
||||||
|
VGVhbVNwZWFrIFN5c3RlbXMgR21iSAAGAwEAAAAFBgEBAAGGoADzyFvD+9G6uhIxmh0jK+Uo8\
|
||||||
|
z8fYGJVH81vWFULDS0l8yATKe4cEyqW3A==").unwrap()).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_ts5_server_license_single_block_with_issuer() {
|
||||||
|
Licenses::parse_ignore_expired(
|
||||||
|
BASE64_STANDARD
|
||||||
|
.decode(
|
||||||
|
"AQBgjAAqtcBUrw5futTtkl3+EM3OW4Lal6OTPlwuv4xV/\
|
||||||
|
gIRFlEAG0NlAAcAAAAgQW5vbnltb3VzAACKNY+/\
|
||||||
|
9qCbonCSxG18vBb7y7zPIgDdjTmcZoAHHclnJSATPa69Ez5XfQ==",
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_ts5_server_license_single_block() {
|
||||||
|
// Only a single server block and the ephemeral block
|
||||||
|
Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQAuio9ZxThXKE+hmzQyzBRedysp9\
|
||||||
|
79JBTv2xP3s2oCkiAgQI70AE+YkAAcBBgMBAAAABQBoazM313063zaipPTH06zrXc91ch3huB\
|
||||||
|
YrUET9sEbz1CATKgK8EyqrfA==").unwrap()).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn derive_public_key() {
|
||||||
|
let licenses = Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQA1hUFJiiSs0wFXkYuPUJVcDa6XCrZTcsvkB0Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAAC4R+5mos+UQ/KCbkpQLMI5WRp4wkQu8e5PZY4zU+/FlyAJwaE8CcJJ/A==").unwrap()).unwrap();
|
||||||
|
let derived_key =
|
||||||
|
licenses.derive_public_key(EccKeyPubEd25519::from_bytes(crate::ROOT_KEY)).unwrap();
|
||||||
|
|
||||||
|
let expected_key = [
|
||||||
|
0x40, 0xe9, 0x50, 0xc4, 0x61, 0xba, 0x18, 0x3a, 0x1e, 0xb7, 0xcb, 0xb1, 0x9a, 0xc3,
|
||||||
|
0xd8, 0xd9, 0xc4, 0xd5, 0x24, 0xdb, 0x38, 0xf7, 0x2d, 0x3d, 0x66, 0x75, 0x77, 0x2a,
|
||||||
|
0xc5, 0x9c, 0xc5, 0xc6,
|
||||||
|
];
|
||||||
|
let derived_key = derived_key.compress().0;
|
||||||
|
assert_eq!(derived_key, expected_key);
|
||||||
|
}
|
||||||
|
}
|
||||||
+111
@@ -0,0 +1,111 @@
|
|||||||
|
use std::fmt::Debug;
|
||||||
|
use std::str;
|
||||||
|
|
||||||
|
use tracing::{debug, debug_span, Span};
|
||||||
|
use tsproto_packets::packets::{InUdpPacket, OutUdpPacket, PacketType};
|
||||||
|
use tsproto_packets::HexSlice;
|
||||||
|
|
||||||
|
use crate::connection::{Connection, Event};
|
||||||
|
|
||||||
|
fn prepare_span(is_client: bool, incoming: bool) -> Span {
|
||||||
|
let dir = if incoming {
|
||||||
|
if !cfg!(windows) { "\x1b[1;32mIN\x1b[0m" } else { "IN" }
|
||||||
|
} else if !cfg!(windows) {
|
||||||
|
"\x1b[1;31mOUT\x1b[0m"
|
||||||
|
} else {
|
||||||
|
"OUT"
|
||||||
|
};
|
||||||
|
let to = if is_client { "S" } else { "C" };
|
||||||
|
debug_span!("packet", to, %dir)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn log_udp_packet(is_client: bool, incoming: bool, packet: &InUdpPacket) {
|
||||||
|
let _span = prepare_span(is_client, incoming).entered();
|
||||||
|
debug!(header = ?packet.0.header(), content = %HexSlice(packet.0.content()), "UdpPacket");
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn log_out_udp_packet(is_client: bool, incoming: bool, packet: &OutUdpPacket) {
|
||||||
|
let _span = prepare_span(is_client, incoming).entered();
|
||||||
|
debug!(
|
||||||
|
generation = packet.generation_id(),
|
||||||
|
header = ?packet.data().header(),
|
||||||
|
content = %HexSlice(packet.data().content()),
|
||||||
|
"UdpPacket"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn log_packet<P: Debug>(is_client: bool, incoming: bool, packet: &P) {
|
||||||
|
// packet.header.c_id is not set for newly created packets so we cannot
|
||||||
|
// detect if a packet is incoming or not.
|
||||||
|
let _span = prepare_span(is_client, incoming).entered();
|
||||||
|
debug!(content = ?packet, "Packet");
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn log_command(is_client: bool, incoming: bool, p_type: PacketType, cmd: &str) {
|
||||||
|
// packet.header.c_id is not set for newly created packets so we cannot
|
||||||
|
// detect if a packet is incoming or not.
|
||||||
|
let _span = prepare_span(is_client, incoming).entered();
|
||||||
|
if p_type == PacketType::Command {
|
||||||
|
debug!(content = cmd, "Command");
|
||||||
|
} else {
|
||||||
|
debug!(content = cmd, "CommandLow");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Print the content of all packets
|
||||||
|
///
|
||||||
|
/// 0 - Print commands
|
||||||
|
/// 1 - Print packets
|
||||||
|
/// 2 - Print udp packets
|
||||||
|
pub fn add_logger_with_verbosity(verbosity: u8, con: &mut Connection) {
|
||||||
|
let log_commands = verbosity > 0;
|
||||||
|
let log_packets = verbosity > 1;
|
||||||
|
let log_udp_packets = verbosity > 2;
|
||||||
|
add_logger(log_commands, log_packets, log_udp_packets, con);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_logger(
|
||||||
|
log_commands: bool, log_packets: bool, log_udp_packets: bool, con: &mut Connection,
|
||||||
|
) {
|
||||||
|
if log_commands || log_packets || log_udp_packets {
|
||||||
|
let is_client = con.is_client;
|
||||||
|
let listener = Box::new(move |event: &Event| match event {
|
||||||
|
Event::ReceiveUdpPacket(packet) => {
|
||||||
|
if log_udp_packets {
|
||||||
|
log_udp_packet(is_client, true, packet);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Event::ReceivePacket(packet) => {
|
||||||
|
if log_packets {
|
||||||
|
log_packet(is_client, true, packet);
|
||||||
|
} else if log_commands {
|
||||||
|
let p_type = packet.header().packet_type();
|
||||||
|
if p_type.is_command() {
|
||||||
|
if let Ok(s) = str::from_utf8(packet.content()) {
|
||||||
|
log_command(is_client, true, p_type, s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Event::SendUdpPacket(packet) => {
|
||||||
|
if log_udp_packets {
|
||||||
|
log_out_udp_packet(is_client, false, packet);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Event::SendPacket(packet) => {
|
||||||
|
if log_packets {
|
||||||
|
log_packet(is_client, false, &packet.packet());
|
||||||
|
} else if log_commands {
|
||||||
|
let p_type = packet.header().packet_type();
|
||||||
|
if p_type.is_command() {
|
||||||
|
if let Ok(s) = str::from_utf8(packet.content()) {
|
||||||
|
log_command(is_client, false, p_type, s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
con.event_listeners.push(listener);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,518 @@
|
|||||||
|
use std::io::Cursor;
|
||||||
|
use std::task::Context;
|
||||||
|
|
||||||
|
use num_traits::ToPrimitive;
|
||||||
|
use omnom::WriteExt;
|
||||||
|
use tracing::warn;
|
||||||
|
use tsproto_packets::packets::*;
|
||||||
|
|
||||||
|
use crate::algorithms as algs;
|
||||||
|
use crate::connection::{Connection, Event, StreamItem};
|
||||||
|
use crate::resend::{PartialPacketId, Resender};
|
||||||
|
use crate::{Error, Result, MAX_FRAGMENTS_LENGTH, MAX_QUEUE_LEN};
|
||||||
|
|
||||||
|
/// Encodes outgoing packets.
|
||||||
|
///
|
||||||
|
/// This part does the compression, encryption and fragmentation.
|
||||||
|
#[derive(Clone, Debug, Default)]
|
||||||
|
pub struct PacketCodec {
|
||||||
|
/// The next packet id that should be sent.
|
||||||
|
///
|
||||||
|
/// This list is indexed by the `PacketType`, `PacketType::Init` is an
|
||||||
|
/// invalid index.
|
||||||
|
pub outgoing_p_ids: [PartialPacketId; 8],
|
||||||
|
/// Used for incoming out-of-order packets.
|
||||||
|
///
|
||||||
|
/// Only used for `Command` and `CommandLow` packets.
|
||||||
|
pub receive_queue: [Vec<Vec<u8>>; 2],
|
||||||
|
/// Used for incoming fragmented packets.
|
||||||
|
///
|
||||||
|
/// Contains the accumulated data from fragmented packets, the header of the
|
||||||
|
/// first packet is at the beginning, all other headers are stripped away.
|
||||||
|
/// Only used for `Command` and `CommandLow` packets.
|
||||||
|
pub fragmented_queue: [Option<Vec<u8>>; 2],
|
||||||
|
/// The next packet id that is expected.
|
||||||
|
///
|
||||||
|
/// Works like the `outgoing_p_ids`.
|
||||||
|
pub incoming_p_ids: [PartialPacketId; 8],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PacketCodec {
|
||||||
|
/// Handle a packet for a specific connection.
|
||||||
|
///
|
||||||
|
/// This part does the defragmentation, decryption and decompression.
|
||||||
|
pub fn handle_udp_packet(
|
||||||
|
con: &mut Connection, cx: &mut Context, mut packet_data: Vec<u8>,
|
||||||
|
) -> Result<()> {
|
||||||
|
let mut ack = false;
|
||||||
|
|
||||||
|
let dir = if con.is_client { Direction::S2C } else { Direction::C2S };
|
||||||
|
let packet = InPacket::new(dir, &packet_data);
|
||||||
|
let p_type = packet.header().packet_type();
|
||||||
|
let type_i = p_type.to_usize().unwrap();
|
||||||
|
let id = packet.header().packet_id();
|
||||||
|
let (in_recv_win, gen_id, cur_next, limit) = con.in_receive_window(p_type, id);
|
||||||
|
|
||||||
|
con.resender.handle_loss_incoming(&packet, in_recv_win, cur_next);
|
||||||
|
|
||||||
|
if let Some(params) = &con.params {
|
||||||
|
if p_type == PacketType::Init {
|
||||||
|
con.stream_items.push_back(StreamItem::Error(Error::UnexpectedInitPacket));
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if !con.is_client {
|
||||||
|
let c_id = packet.header().client_id().unwrap();
|
||||||
|
// Accept any client id for the first few acks
|
||||||
|
let is_first_ack = gen_id == 0 && id <= 3 && p_type == PacketType::Ack;
|
||||||
|
if c_id != params.c_id && !is_first_ack {
|
||||||
|
con.stream_items.push_back(StreamItem::Error(Error::WrongClientId(c_id)));
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ignore range for acks and audio packets
|
||||||
|
if [PacketType::Ack, PacketType::AckLow, PacketType::Voice, PacketType::VoiceWhisper]
|
||||||
|
.contains(&p_type)
|
||||||
|
|| in_recv_win
|
||||||
|
{
|
||||||
|
if !packet.header().flags().contains(Flags::UNENCRYPTED) {
|
||||||
|
if p_type == PacketType::Ack && id == 1 && con.is_client {
|
||||||
|
// This is the ack packet for the clientinit, we take the
|
||||||
|
// initserver as ack instead.
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
// If it is the first ack packet of a client, try to fake
|
||||||
|
// decrypt it.
|
||||||
|
let new_content = if (p_type == PacketType::Ack && id <= 1 && con.is_client)
|
||||||
|
|| con.params.is_none()
|
||||||
|
{
|
||||||
|
match algs::decrypt_fake(&packet).or_else(|_| {
|
||||||
|
if let Some(params) = &mut con.params {
|
||||||
|
// Decrypt the packet
|
||||||
|
algs::decrypt(&packet, gen_id, ¶ms.shared_iv, &mut params.key_cache)
|
||||||
|
} else {
|
||||||
|
// Failed to fake decrypt the packet
|
||||||
|
Err(Error::WrongMac { p_type, generation_id: gen_id, packet_id: id })
|
||||||
|
}
|
||||||
|
}) {
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(e) => {
|
||||||
|
con.stream_items.push_back(StreamItem::Error(e));
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if let Some(params) = &mut con.params {
|
||||||
|
// Decrypt the packet
|
||||||
|
match algs::decrypt(&packet, gen_id, ¶ms.shared_iv, &mut params.key_cache) {
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(e) => {
|
||||||
|
con.stream_items.push_back(StreamItem::Error(e));
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Failed to fake decrypt the packet
|
||||||
|
con.stream_items.push_back(StreamItem::Error(Error::WrongMac {
|
||||||
|
p_type,
|
||||||
|
generation_id: gen_id,
|
||||||
|
packet_id: id,
|
||||||
|
}));
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
|
||||||
|
let start = packet.header().data().len();
|
||||||
|
packet_data[start..].copy_from_slice(&new_content);
|
||||||
|
} else if algs::must_encrypt(p_type) {
|
||||||
|
// Check if it is ok for the packet to be unencrypted
|
||||||
|
con.stream_items.push_back(StreamItem::Error(Error::UnallowedUnencryptedPacket));
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let packet = InPacket::new(dir, &packet_data);
|
||||||
|
match p_type {
|
||||||
|
PacketType::Command | PacketType::CommandLow => {
|
||||||
|
ack = true;
|
||||||
|
|
||||||
|
let commands = Self::handle_command_packet(con, packet_data)?;
|
||||||
|
|
||||||
|
// Be careful with command packets, they are guaranteed to
|
||||||
|
// be in the right order now.
|
||||||
|
for c in commands {
|
||||||
|
// Send again
|
||||||
|
let packet = InPacket::new(dir, &c);
|
||||||
|
let event = Event::ReceivePacket(&packet);
|
||||||
|
con.send_event(&event);
|
||||||
|
|
||||||
|
let item = match InCommandBuf::try_new(dir, c) {
|
||||||
|
Ok(c) => {
|
||||||
|
// initivexpand2 is the ack for the last init packet
|
||||||
|
if con.is_client
|
||||||
|
&& c.data().packet().content().starts_with(b"initivexpand2 ")
|
||||||
|
{
|
||||||
|
Resender::ack_packet(con, cx, PacketType::Init, 4);
|
||||||
|
} else if con.is_client
|
||||||
|
&& c.data().packet().content().starts_with(b"initserver ")
|
||||||
|
{
|
||||||
|
// initserver acks clientinit
|
||||||
|
Resender::ack_packet(con, cx, PacketType::Command, 2);
|
||||||
|
} else if !con.is_client
|
||||||
|
&& c.data().packet().content().starts_with(b"clientek ")
|
||||||
|
{
|
||||||
|
// clientek acks initivexpand2
|
||||||
|
Resender::ack_packet(con, cx, PacketType::Command, 0);
|
||||||
|
}
|
||||||
|
StreamItem::Command(c)
|
||||||
|
}
|
||||||
|
Err(e) => return Err(Error::PacketParse("command", e)),
|
||||||
|
};
|
||||||
|
con.stream_items.push_back(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
if p_type == PacketType::Ping {
|
||||||
|
ack = true;
|
||||||
|
}
|
||||||
|
// Update packet ids
|
||||||
|
let in_ids = &mut con.codec.incoming_p_ids;
|
||||||
|
if p_type != PacketType::Init {
|
||||||
|
let (id, next_gen) = id.overflowing_add(1);
|
||||||
|
let generation_id = if next_gen { gen_id + 1 } else { gen_id };
|
||||||
|
in_ids[type_i] = PartialPacketId { generation_id, packet_id: id };
|
||||||
|
}
|
||||||
|
|
||||||
|
match packet.ack_packet() {
|
||||||
|
Ok(Some(ack_id)) => {
|
||||||
|
// Remove command packet from send queue if the fitting ack is received.
|
||||||
|
let p_type = if p_type == PacketType::Ack {
|
||||||
|
PacketType::Command
|
||||||
|
} else if p_type == PacketType::AckLow {
|
||||||
|
PacketType::CommandLow
|
||||||
|
} else if p_type == PacketType::Pong {
|
||||||
|
PacketType::Ping
|
||||||
|
} else {
|
||||||
|
p_type
|
||||||
|
};
|
||||||
|
Resender::ack_packet(con, cx, p_type, ack_id);
|
||||||
|
}
|
||||||
|
Ok(None) => {}
|
||||||
|
Err(e) => {
|
||||||
|
con.stream_items.push_back(StreamItem::Error(Error::CreateAck(e)));
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send event after handling acks
|
||||||
|
let event = Event::ReceivePacket(&packet);
|
||||||
|
con.send_event(&event);
|
||||||
|
|
||||||
|
if p_type.is_voice() {
|
||||||
|
con.stream_items.push_back(match InAudioBuf::try_new(dir, packet_data) {
|
||||||
|
Ok(r) => StreamItem::Audio(r),
|
||||||
|
Err(e) => StreamItem::Error(Error::PacketParse("audio", e)),
|
||||||
|
});
|
||||||
|
} else if p_type == PacketType::Init {
|
||||||
|
con.stream_items.push_back(if con.is_client {
|
||||||
|
match InS2CInitBuf::try_new(dir, packet_data) {
|
||||||
|
Ok(r) => StreamItem::S2CInit(r),
|
||||||
|
Err(e) => StreamItem::Error(Error::PacketParse("s2cinit", e)),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
match InC2SInitBuf::try_new(dir, packet_data) {
|
||||||
|
Ok(r) => StreamItem::C2SInit(r),
|
||||||
|
Err(e) => StreamItem::Error(Error::PacketParse("c2sinit", e)),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Send an ack for the case when it was lost
|
||||||
|
if p_type == PacketType::Command || p_type == PacketType::CommandLow {
|
||||||
|
ack = true;
|
||||||
|
con.resender.handle_loss_resend_ack();
|
||||||
|
}
|
||||||
|
con.stream_items.push_back(StreamItem::Error(Error::NotInReceiveWindow {
|
||||||
|
id,
|
||||||
|
next: cur_next,
|
||||||
|
limit,
|
||||||
|
p_type,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send ack
|
||||||
|
if ack {
|
||||||
|
con.send_ack_packet(cx, OutAck::new(dir.reverse(), p_type, id))?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handle `Command` and `CommandLow` packets.
|
||||||
|
///
|
||||||
|
/// They have to be handled in the right order.
|
||||||
|
fn handle_command_packet(
|
||||||
|
con: &mut Connection, mut packet_data: Vec<u8>,
|
||||||
|
) -> Result<Vec<Vec<u8>>> {
|
||||||
|
let dir = if con.is_client { Direction::S2C } else { Direction::C2S };
|
||||||
|
let mut packet = InPacket::new(dir, &packet_data);
|
||||||
|
let header = packet.header();
|
||||||
|
let p_type = header.packet_type();
|
||||||
|
let mut id = header.packet_id();
|
||||||
|
let type_i = p_type.to_usize().unwrap();
|
||||||
|
let cmd_i = if p_type == PacketType::Command { 0 } else { 1 };
|
||||||
|
let r_queue = &mut con.codec.receive_queue[cmd_i];
|
||||||
|
let frag_queue = &mut con.codec.fragmented_queue[cmd_i];
|
||||||
|
let in_ids = &mut con.codec.incoming_p_ids[type_i];
|
||||||
|
let cur_next = in_ids.packet_id;
|
||||||
|
if cur_next == id {
|
||||||
|
// In order
|
||||||
|
let mut packets = Vec::new();
|
||||||
|
loop {
|
||||||
|
// Update next packet id
|
||||||
|
*in_ids = *in_ids + 1;
|
||||||
|
|
||||||
|
let flags = packet.header().flags();
|
||||||
|
let res_packet = if flags.contains(Flags::FRAGMENTED) {
|
||||||
|
if let Some(mut frag_queue) = frag_queue.take() {
|
||||||
|
// Last fragmented packet
|
||||||
|
frag_queue.extend_from_slice(packet.content());
|
||||||
|
let header = InPacket::new(dir, &frag_queue);
|
||||||
|
// Decompress
|
||||||
|
if header.header().flags().contains(Flags::COMPRESSED) {
|
||||||
|
let decompressed = quicklz::decompress(
|
||||||
|
&mut Cursor::new(header.content()),
|
||||||
|
crate::MAX_DECOMPRESSED_SIZE,
|
||||||
|
)
|
||||||
|
.map_err(Error::DecompressPacket)?;
|
||||||
|
let start = header.header().data().len();
|
||||||
|
frag_queue.truncate(start);
|
||||||
|
frag_queue.extend_from_slice(&decompressed);
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(frag_queue)
|
||||||
|
} else {
|
||||||
|
// Enqueue
|
||||||
|
*frag_queue = Some(packet_data);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
} else if let Some(frag_queue) = frag_queue {
|
||||||
|
// The packet is fragmented
|
||||||
|
if frag_queue.len() < MAX_FRAGMENTS_LENGTH {
|
||||||
|
frag_queue.extend_from_slice(packet.content());
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
return Err(Error::MaxLengthExceeded("fragment queue"));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Decompress
|
||||||
|
if flags.contains(Flags::COMPRESSED) {
|
||||||
|
let decompressed = quicklz::decompress(
|
||||||
|
&mut Cursor::new(packet.content()),
|
||||||
|
crate::MAX_DECOMPRESSED_SIZE,
|
||||||
|
)
|
||||||
|
.map_err(Error::DecompressPacket)?;
|
||||||
|
let start = packet.header().data().len();
|
||||||
|
packet_data.truncate(start);
|
||||||
|
packet_data.extend_from_slice(&decompressed);
|
||||||
|
};
|
||||||
|
Some(packet_data)
|
||||||
|
};
|
||||||
|
if let Some(p) = res_packet {
|
||||||
|
packets.push(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if there are following packets in the receive queue.
|
||||||
|
id = id.wrapping_add(1);
|
||||||
|
if let Some(pos) =
|
||||||
|
r_queue.iter().position(|p| InHeader::new(dir, p).packet_id() == id)
|
||||||
|
{
|
||||||
|
packet_data = r_queue.remove(pos);
|
||||||
|
packet = InPacket::new(dir, &packet_data);
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(packets)
|
||||||
|
} else {
|
||||||
|
// Out of order
|
||||||
|
warn!(got = id, expected = cur_next, "Out of order command packet");
|
||||||
|
let (limit, next_gen) = cur_next.overflowing_add(MAX_QUEUE_LEN);
|
||||||
|
if (!next_gen && id >= cur_next && id < limit)
|
||||||
|
|| (next_gen && (id >= cur_next || id < limit))
|
||||||
|
{
|
||||||
|
// Retransmissions must not grow the queue or survive as stale duplicates.
|
||||||
|
if !r_queue.iter().any(|p| InHeader::new(dir, p).packet_id() == id) {
|
||||||
|
if r_queue.len() >= usize::from(MAX_QUEUE_LEN) {
|
||||||
|
return Err(Error::MaxLengthExceeded("command queue"));
|
||||||
|
}
|
||||||
|
r_queue.push(packet_data);
|
||||||
|
}
|
||||||
|
Ok(vec![])
|
||||||
|
} else {
|
||||||
|
Err(Error::MaxLengthExceeded("command queue"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn encode_packet(con: &mut Connection, mut packet: OutPacket) -> Result<Vec<OutUdpPacket>> {
|
||||||
|
let p_type = packet.header().packet_type();
|
||||||
|
let type_i = p_type.to_usize().unwrap();
|
||||||
|
|
||||||
|
// TODO Needed, commands should set their own flag?
|
||||||
|
if (p_type == PacketType::Command || p_type == PacketType::CommandLow) && con.is_client {
|
||||||
|
// Set newprotocol flag
|
||||||
|
packet.flags(packet.header().flags() | Flags::NEWPROTOCOL);
|
||||||
|
}
|
||||||
|
|
||||||
|
let p_id = if p_type == PacketType::Init {
|
||||||
|
PartialPacketId { generation_id: 0, packet_id: 0 }
|
||||||
|
} else {
|
||||||
|
con.codec.outgoing_p_ids[type_i]
|
||||||
|
};
|
||||||
|
// We fake encrypt the first command packet of the server (id 0) and the
|
||||||
|
// first command packet of the client (id 1, clientek).
|
||||||
|
let mut fake_encrypt = p_type == PacketType::Command
|
||||||
|
&& p_id.generation_id == 0
|
||||||
|
&& ((!con.is_client && p_id.packet_id == 0)
|
||||||
|
|| (con.is_client && p_id.packet_id == 1 && {
|
||||||
|
// Test if it is a clientek packet
|
||||||
|
packet.content().starts_with(b"clientek")
|
||||||
|
}));
|
||||||
|
// Also fake encrypt the first ack of the client, which is the response
|
||||||
|
// for the initivexpand2 packet.
|
||||||
|
fake_encrypt |= con.is_client
|
||||||
|
&& p_type == PacketType::Ack
|
||||||
|
&& p_id.generation_id == 0
|
||||||
|
&& p_id.packet_id == 0;
|
||||||
|
|
||||||
|
// Get values from parameters
|
||||||
|
let should_encrypt;
|
||||||
|
let c_id;
|
||||||
|
if let Some(params) = con.params.as_mut() {
|
||||||
|
should_encrypt = algs::should_encrypt(p_type, params.voice_encryption);
|
||||||
|
c_id = params.c_id;
|
||||||
|
} else {
|
||||||
|
should_encrypt = algs::should_encrypt(p_type, false);
|
||||||
|
if should_encrypt {
|
||||||
|
fake_encrypt = true;
|
||||||
|
}
|
||||||
|
c_id = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Client id for clients
|
||||||
|
if con.is_client {
|
||||||
|
packet.client_id(c_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
if !should_encrypt && !fake_encrypt {
|
||||||
|
packet.flags(packet.header().flags() | Flags::UNENCRYPTED);
|
||||||
|
if let Some(params) = con.params.as_mut() {
|
||||||
|
packet.mac().copy_from_slice(¶ms.shared_mac);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compress and split packet
|
||||||
|
let packets = if p_type == PacketType::Command || p_type == PacketType::CommandLow {
|
||||||
|
algs::compress_and_split(con.is_client, packet)
|
||||||
|
} else {
|
||||||
|
// Set the inner packet id for voice packets
|
||||||
|
if con.is_client && (p_type == PacketType::Voice || p_type == PacketType::VoiceWhisper)
|
||||||
|
{
|
||||||
|
(&mut packet.content_mut()[..2])
|
||||||
|
.write_be(con.codec.outgoing_p_ids[type_i].packet_id)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
vec![packet]
|
||||||
|
};
|
||||||
|
|
||||||
|
let packets = packets
|
||||||
|
.into_iter()
|
||||||
|
.map(|mut packet| -> Result<_> {
|
||||||
|
// Get packet id
|
||||||
|
let p_id = if p_type == PacketType::Init {
|
||||||
|
PartialPacketId { generation_id: 0, packet_id: 0 }
|
||||||
|
} else {
|
||||||
|
packet.packet_id(con.codec.outgoing_p_ids[type_i].packet_id);
|
||||||
|
con.codec.outgoing_p_ids[type_i]
|
||||||
|
};
|
||||||
|
|
||||||
|
// Encrypt if necessary
|
||||||
|
if fake_encrypt {
|
||||||
|
algs::encrypt_fake(&mut packet)?;
|
||||||
|
} else if should_encrypt {
|
||||||
|
// The params are set
|
||||||
|
let params = con.params.as_mut().unwrap();
|
||||||
|
algs::encrypt(
|
||||||
|
&mut packet,
|
||||||
|
p_id.generation_id,
|
||||||
|
¶ms.shared_iv,
|
||||||
|
&mut params.key_cache,
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Increment outgoing_p_ids
|
||||||
|
let p_id = p_id + 1;
|
||||||
|
if p_type != PacketType::Init {
|
||||||
|
con.codec.outgoing_p_ids[type_i] = p_id;
|
||||||
|
}
|
||||||
|
Ok(OutUdpPacket::new(p_id.generation_id, packet))
|
||||||
|
})
|
||||||
|
.collect::<Result<Vec<_>>>()?;
|
||||||
|
Ok(packets)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod reorder_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn packet(id: u16, kind: PacketType) -> Vec<u8> {
|
||||||
|
OutPacket::new([0; 8], id, None, Flags::empty(), kind).into_vec()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn connection() -> Connection {
|
||||||
|
let socket = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
Connection::new(true, "127.0.0.1:9987".parse().unwrap(), Box::new(socket))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn burst_waits_for_missing_command_and_drains_in_order() {
|
||||||
|
let mut con = connection().await;
|
||||||
|
for id in (1..MAX_QUEUE_LEN).rev() {
|
||||||
|
assert!(PacketCodec::handle_command_packet(&mut con, packet(id, PacketType::Command)).unwrap().is_empty());
|
||||||
|
}
|
||||||
|
for _ in 0..100 {
|
||||||
|
PacketCodec::handle_command_packet(&mut con, packet(300, PacketType::Command)).unwrap();
|
||||||
|
}
|
||||||
|
assert_eq!(con.codec.receive_queue[0].len(), usize::from(MAX_QUEUE_LEN - 1));
|
||||||
|
assert!(matches!(PacketCodec::handle_command_packet(&mut con, packet(MAX_QUEUE_LEN, PacketType::Command)), Err(Error::MaxLengthExceeded("command queue"))));
|
||||||
|
let packets = PacketCodec::handle_command_packet(&mut con, packet(0, PacketType::Command)).unwrap();
|
||||||
|
assert_eq!(packets.len(), usize::from(MAX_QUEUE_LEN));
|
||||||
|
for (id, bytes) in packets.iter().enumerate() {
|
||||||
|
assert_eq!(InHeader::new(Direction::S2C, bytes).packet_id(), id as u16);
|
||||||
|
}
|
||||||
|
assert!(con.codec.receive_queue[0].is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn reorder_window_wraps_and_command_priorities_remain_independent() {
|
||||||
|
let mut con = connection().await;
|
||||||
|
let start = u16::MAX - 100;
|
||||||
|
con.codec.incoming_p_ids[PacketType::Command as usize].packet_id = start;
|
||||||
|
for offset in (1..350u16).rev() {
|
||||||
|
PacketCodec::handle_command_packet(&mut con, packet(start.wrapping_add(offset), PacketType::Command)).unwrap();
|
||||||
|
}
|
||||||
|
PacketCodec::handle_command_packet(&mut con, packet(1, PacketType::CommandLow)).unwrap();
|
||||||
|
let packets = PacketCodec::handle_command_packet(&mut con, packet(start, PacketType::Command)).unwrap();
|
||||||
|
assert_eq!(packets.len(), 350);
|
||||||
|
for (offset, bytes) in packets.iter().enumerate() {
|
||||||
|
assert_eq!(InHeader::new(Direction::S2C, bytes).packet_id(), start.wrapping_add(offset as u16));
|
||||||
|
}
|
||||||
|
assert_eq!(con.codec.receive_queue[1].len(), 1);
|
||||||
|
assert_eq!(PacketCodec::handle_command_packet(&mut con, packet(0, PacketType::CommandLow)).unwrap().len(), 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
+1067
File diff suppressed because it is too large.
Load diff
+47
@@ -0,0 +1,47 @@
|
|||||||
|
use std::net::IpAddr;
|
||||||
|
|
||||||
|
use crate::{Error, Result};
|
||||||
|
|
||||||
|
/// Try to approximate the not stabilized ip.is_global().
|
||||||
|
pub fn is_global_ip(ip: &IpAddr) -> bool {
|
||||||
|
if !ip.is_unspecified() && !ip.is_loopback() && !ip.is_multicast() {
|
||||||
|
match *ip {
|
||||||
|
IpAddr::V4(ref ip) => !ip.is_broadcast() && !ip.is_link_local() && !ip.is_private(),
|
||||||
|
IpAddr::V6(_) => true,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn read_hex(s: &str) -> Result<Vec<u8>> {
|
||||||
|
// Detect hex format
|
||||||
|
if s.chars().nth(2) == Some(':') {
|
||||||
|
// Wireshark
|
||||||
|
Ok(s.split(':')
|
||||||
|
.map(|s| u8::from_str_radix(s, 16))
|
||||||
|
.collect::<::std::result::Result<Vec<_>, _>>()
|
||||||
|
.map_err(Error::InvalidHex)?)
|
||||||
|
} else if s.chars().nth(2) == Some(' ') {
|
||||||
|
// Wireshark
|
||||||
|
Ok(s.split(' ')
|
||||||
|
.map(|s| u8::from_str_radix(s, 16))
|
||||||
|
.collect::<::std::result::Result<Vec<_>, _>>()
|
||||||
|
.map_err(Error::InvalidHex)?)
|
||||||
|
} else if s.starts_with("0x") {
|
||||||
|
let s: String = s.chars().filter(|c| !c.is_whitespace()).collect();
|
||||||
|
// Own dumps
|
||||||
|
Ok(s[2..]
|
||||||
|
.split(',')
|
||||||
|
.map(|s| u8::from_str_radix(s.trim_start_matches("0x"), 16))
|
||||||
|
.collect::<::std::result::Result<Vec<_>, _>>()
|
||||||
|
.map_err(Error::InvalidHex)?)
|
||||||
|
} else {
|
||||||
|
let s: String = s.chars().filter(|c| !c.is_whitespace()).collect();
|
||||||
|
Ok(s.as_bytes()
|
||||||
|
.chunks(2)
|
||||||
|
.map(|s| u8::from_str_radix(::std::str::from_utf8(s).unwrap(), 16))
|
||||||
|
.collect::<::std::result::Result<Vec<_>, _>>()
|
||||||
|
.map_err(Error::InvalidHex)?)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
[package]
|
||||||
|
name = "ts-bookkeeping"
|
||||||
|
version = "0.1.0"
|
||||||
|
authors = ["Flakebi <flakebi@t-online.de>"]
|
||||||
|
description = "Structs to store the state of a TeamSpeak server, with its clients and channels."
|
||||||
|
repository = "https://github.com/ReSpeak/tsclientlib/tree/master/utils/ts-bookkeeping"
|
||||||
|
readme = "README.md"
|
||||||
|
keywords = ["teamspeak3", "ts3"]
|
||||||
|
license = "MIT OR Apache-2.0"
|
||||||
|
build = "build/build.rs"
|
||||||
|
edition = "2018"
|
||||||
|
autobenches = false
|
||||||
|
include = [
|
||||||
|
"/Cargo.toml",
|
||||||
|
"/README.md",
|
||||||
|
"**/*.rs",
|
||||||
|
"**/*.tt",
|
||||||
|
]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
base64 = "0.22"
|
||||||
|
num-traits = "0.2"
|
||||||
|
num-derive = "0.4"
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
thiserror = "2"
|
||||||
|
time = { version = "0.3", features = ["serde"] }
|
||||||
|
tracing = "0.1"
|
||||||
|
tsproto-packets = { path = "../tsproto-packets", version = "0.1" }
|
||||||
|
tsproto-types = { path = "../tsproto-types", version = "0.1" }
|
||||||
|
|
||||||
|
[build-dependencies]
|
||||||
|
heck = "0.5"
|
||||||
|
itertools = "0.14"
|
||||||
|
t4rust-derive = "0.3"
|
||||||
|
tsproto-structs = { path = "../tsproto-structs", version = "0.2" }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
criterion = "0.8"
|
||||||
|
once_cell = "1"
|
||||||
|
tracing-subscriber = "0.3"
|
||||||
|
|
||||||
|
[[bench]]
|
||||||
|
name = "command"
|
||||||
|
harness = false
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# ts-bookkeeping [](https://docs.rs/ts-bookkeeping)
|
||||||
|
`ts-bookkeeping` contains structs to store the state of a TeamSpeak server, with its clients and
|
||||||
|
channels.
|
||||||
|
|
||||||
|
The crate can be used to keep track of the state on a server by processing all incoming
|
||||||
|
commands, which is why it is called “bookkeeping”. It also contains generated structs for all
|
||||||
|
TeamSpeak commands.
|
||||||
|
|
||||||
|
Incoming commands can be applied to the state and generate [`events`]. The main struct is
|
||||||
|
[`data::Connection`].
|
||||||
|
|
||||||
|
The structs have methods to create packets for various actions. The generated packets can be
|
||||||
|
sent to a server.
|
||||||
|
|
||||||
|
## License
|
||||||
|
Licensed under either of
|
||||||
|
|
||||||
|
* [Apache License, Version 2.0](../../LICENSE-APACHE)
|
||||||
|
* [MIT license](../../LICENSE-MIT)
|
||||||
|
|
||||||
|
at your option.
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# ts-bookkeeping [](https://docs.rs/ts-bookkeeping)
|
||||||
|
{{readme}}
|
||||||
|
|
||||||
|
## License
|
||||||
|
Licensed under either of
|
||||||
|
|
||||||
|
* [Apache License, Version 2.0](../../LICENSE-APACHE)
|
||||||
|
* [MIT license](../../LICENSE-MIT)
|
||||||
|
|
||||||
|
at your option.
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
use std::iter;
|
||||||
|
|
||||||
|
use criterion::{criterion_group, criterion_main, Bencher, Criterion};
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
|
use ts_bookkeeping::messages::s2c::{self, InMessage};
|
||||||
|
use tsproto_packets::packets::{Direction, Flags, OutPacket, PacketType};
|
||||||
|
|
||||||
|
const SHORT_CMD: &[u8] = b"notifyclientleftview cfid=1 ctid=0 clid=61";
|
||||||
|
const LONG_CMD: &[u8] = b"channellist cid=2 cpid=0 channel_name=Trusted\\sChannel channel_topic channel_codec=0 channel_codec_quality=0 channel_maxclients=0 channel_maxfamilyclients=-1 channel_order=1 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=0 channel_flag_maxfamilyclients_unlimited=0 channel_flag_maxfamilyclients_inherited=1 channel_needed_talk_power=0 channel_forced_silence=0 channel_name_phonetic channel_icon_id=0 channel_flag_private=0|cid=4 cpid=2 channel_name=Ding\\s\xe2\x80\xa2\\s1\\s\\p\\sSplamy\xc2\xb4s\\sBett channel_topic channel_codec=4 channel_codec_quality=7 channel_maxclients=-1 channel_maxfamilyclients=-1 channel_order=0 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=0 channel_flag_maxfamilyclients_inherited=1 channel_needed_talk_power=0 channel_forced_silence=0 channel_name_phonetic=Neo\\sSeebi\\sEvangelion channel_icon_id=0 channel_flag_private=0|cid=6 cpid=2 channel_name=Ding\\s\xe2\x80\xa2\\s2\\s\\p\\sThe\\sBook\\sof\\sHeavy\\sMetal channel_topic channel_codec=2 channel_codec_quality=7 channel_maxclients=-1 channel_maxfamilyclients=-1 channel_order=4 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=0 channel_flag_maxfamilyclients_inherited=1 channel_needed_talk_power=0 channel_forced_silence=0 channel_name_phonetic=Not\\senought\\sChannels channel_icon_id=0 channel_flag_private=0|cid=30 cpid=2 channel_name=Ding\\s\xe2\x80\xa2\\s3\\s\\p\\sSenpai\\sGef\xc3\xa4hrlich channel_topic channel_codec=2 channel_codec_quality=7 channel_maxclients=-1 channel_maxfamilyclients=-1 channel_order=6 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=0 channel_flag_maxfamilyclients_inherited=1 channel_needed_talk_power=0 channel_forced_silence=0 channel_name_phonetic=The\\strashcan\\shas\\sthe\\strash channel_icon_id=0 channel_flag_private=0";
|
||||||
|
|
||||||
|
static TRACING: Lazy<()> = Lazy::new(|| tracing_subscriber::fmt().with_test_writer().init());
|
||||||
|
|
||||||
|
fn parse(b: &mut Bencher, cmd: &[u8]) {
|
||||||
|
Lazy::force(&TRACING);
|
||||||
|
let header = OutPacket::new_with_dir(Direction::S2C, Flags::empty(), PacketType::Command);
|
||||||
|
|
||||||
|
b.iter(|| InMessage::new(&header.header(), cmd).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write(b: &mut Bencher, cmd: &[u8]) {
|
||||||
|
Lazy::force(&TRACING);
|
||||||
|
let header = OutPacket::new_with_dir(Direction::S2C, Flags::empty(), PacketType::Command);
|
||||||
|
let msg = InMessage::new(&header.header(), cmd).unwrap();
|
||||||
|
match msg {
|
||||||
|
InMessage::ClientLeftView(msg) => {
|
||||||
|
let out_part = msg.iter().next().unwrap().as_out();
|
||||||
|
b.iter(|| s2c::OutClientLeftViewMessage::new(&mut iter::once(out_part.clone())));
|
||||||
|
}
|
||||||
|
InMessage::ChannelList(msg) => {
|
||||||
|
let out_part = msg.iter().next().unwrap().as_out();
|
||||||
|
b.iter(|| s2c::OutChannelListMessage::new(&mut iter::once(out_part.clone())));
|
||||||
|
}
|
||||||
|
_ => unreachable!("This command type is not supported in this test"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_short(c: &mut Criterion) { c.bench_function("parse short", |b| parse(b, SHORT_CMD)); }
|
||||||
|
fn parse_long(c: &mut Criterion) { c.bench_function("parse long", |b| parse(b, LONG_CMD)); }
|
||||||
|
|
||||||
|
fn write_short(c: &mut Criterion) { c.bench_function("write short", |b| write(b, SHORT_CMD)); }
|
||||||
|
fn write_long(c: &mut Criterion) { c.bench_function("write long", |b| write(b, LONG_CMD)); }
|
||||||
|
|
||||||
|
criterion_group!(benches, parse_short, parse_long, write_short, write_long);
|
||||||
|
criterion_main!(benches);
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<#@ template cleanws="true" #>
|
||||||
|
<# for struc in &self.0.structs { #>
|
||||||
|
<#= doc_comment(&struc.doc) #>
|
||||||
|
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||||
|
pub struct <#= struc.name #> {
|
||||||
|
<# for p in struc.get_all_properties() {
|
||||||
|
if let Some(ref doc) = p.get_doc() { #>
|
||||||
|
<#= indent(doc_comment(doc), 1) #>
|
||||||
|
<# } #>
|
||||||
|
pub <#= p.get_attr_name(&struc) #>: <#= p.get_type(&self.0.structs)? #>,
|
||||||
|
<# } #>
|
||||||
|
}
|
||||||
|
|
||||||
|
<# } #>
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
<#@ template cleanws="true" #>
|
||||||
|
<#
|
||||||
|
use std::{fmt, iter};
|
||||||
|
|
||||||
|
use tsproto_structs::messages::{MessageDeclarations, MessageGroup};
|
||||||
|
|
||||||
|
fn get_all_arguments<'a>(e: &'a Event<'a>, r: Option<&'a RuleKind<'a>>) -> String {
|
||||||
|
let mut args = String::new();
|
||||||
|
for r in e.ids.iter().chain(r.iter().cloned()) {
|
||||||
|
match r {
|
||||||
|
RuleKind::ArgumentMap { .. } |
|
||||||
|
RuleKind::ArgumentFunction { .. } => {
|
||||||
|
let arg = r.get_argument();
|
||||||
|
if !arg.is_empty() {
|
||||||
|
args.push_str(", ");
|
||||||
|
args.push_str(&arg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
args
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_all_id_arguments<'a>(e: &'a Event<'a>) -> String {
|
||||||
|
let mut args = String::new();
|
||||||
|
for r in &e.ids {
|
||||||
|
match r {
|
||||||
|
RuleKind::ArgumentMap { .. } |
|
||||||
|
RuleKind::ArgumentFunction { .. } => {
|
||||||
|
let arg = r.get_argument();
|
||||||
|
if !arg.is_empty() {
|
||||||
|
args.push_str(&arg);
|
||||||
|
args.push_str(", ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
args
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_message(
|
||||||
|
_fmt: &mut fmt::Formatter, e: &Event, rule: Option<&RuleKind>,
|
||||||
|
msg_group: &MessageGroup, messages: &MessageDeclarations,
|
||||||
|
) -> fmt::Result {
|
||||||
|
for r in e.ids.iter().chain(rule.iter().cloned()) {
|
||||||
|
call_func(_fmt, r)?;
|
||||||
|
}
|
||||||
|
#>
|
||||||
|
c2s::Out<#= e.msg.name #>Part {
|
||||||
|
<#
|
||||||
|
for a in &e.msg.attributes {
|
||||||
|
let field = messages.get_field(a);
|
||||||
|
|
||||||
|
let (from_rule, found) = find_rule(e, rule, field);
|
||||||
|
let from = match found {
|
||||||
|
Some(RuleKind::Map { from, .. }) => {
|
||||||
|
let from_self = if from_rule { "" } else { "self." };
|
||||||
|
Some(format!("{}{}", from_self, from.name.to_snake_case()))
|
||||||
|
}
|
||||||
|
Some(found@RuleKind::ArgumentMap { .. }) => Some(found.from_name().to_snake_case()),
|
||||||
|
Some(RuleKind::Function { .. })
|
||||||
|
| Some(RuleKind::ArgumentFunction { .. }) => Some(field.get_rust_name()),
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(from) = from {
|
||||||
|
if field.is_opt(&e.msg) { #>
|
||||||
|
<#= field.get_rust_name() #>: Some(<#= from #>.into()),
|
||||||
|
<# } else { #>
|
||||||
|
<#= field.get_rust_name() #>: <#= from #>.into(),
|
||||||
|
<# }
|
||||||
|
} else { #>
|
||||||
|
<#= field.get_rust_name() #>: None,
|
||||||
|
<# }
|
||||||
|
} #>
|
||||||
|
}
|
||||||
|
<#
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Calls function if it is one, otherwise does nothing.
|
||||||
|
fn call_func(_fmt: &mut fmt::Formatter, r: &RuleKind) -> fmt::Result {
|
||||||
|
match r {
|
||||||
|
RuleKind::Function { name, to, .. } => { #>
|
||||||
|
let <#= get_to_list(to.as_slice()) #> = self.<#= name.to_snake_case() #>();
|
||||||
|
<# }
|
||||||
|
RuleKind::ArgumentFunction { from, to, name, .. } => { #>
|
||||||
|
let <#= get_to_list(to.as_slice())
|
||||||
|
#> = self.<#= name.to_snake_case() #>(<#= from.to_snake_case() #>);
|
||||||
|
<# }
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Calls function if it is one, otherwise does nothing.
|
||||||
|
fn call_func2(_fmt: &mut fmt::Formatter, struct_name: &str, r: &RuleKind) -> fmt::Result {
|
||||||
|
match r {
|
||||||
|
RuleKind::Function { name, to, .. } => { #>
|
||||||
|
let <#= get_to_list(to.as_slice()) #> = <#= struct_name #>::<#= name.to_snake_case() #>();
|
||||||
|
<# }
|
||||||
|
RuleKind::ArgumentFunction { from, to, name, .. } => { #>
|
||||||
|
let <#= get_to_list(to.as_slice())
|
||||||
|
#> = <#= struct_name #>::<#= name.to_snake_case() #>(<#= from.to_snake_case() #>);
|
||||||
|
<# }
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
for e in &self.decls {
|
||||||
|
let msg_group = self.messages.get_message_group(&e.msg);
|
||||||
|
let uses_lifetime = self.messages.uses_lifetime(&e.msg);
|
||||||
|
// Update
|
||||||
|
if e.op == RuleOp::Update {
|
||||||
|
let small_change_name = e.get_small_name();
|
||||||
|
let change_name = e.get_change_name();
|
||||||
|
#>
|
||||||
|
|
||||||
|
impl <#= e.book_struct.name #> {
|
||||||
|
pub fn <#= change_name.to_snake_case() #><# if uses_lifetime { #><'a><# } #>(&self, <#=
|
||||||
|
get_all_id_arguments(e).replace('&', "&'a ") #>
|
||||||
|
<# if e.msg.attributes.is_empty() { #>
|
||||||
|
) -> OutCommand
|
||||||
|
<# } else { #>
|
||||||
|
) -> c2s::Out<#= e.msg.name #>Part<# if uses_lifetime { #><'a><# } #>
|
||||||
|
<# } #>
|
||||||
|
{
|
||||||
|
<# if e.msg.attributes.is_empty() { #>
|
||||||
|
c2s::Out<#= e.msg.name #>Message::new()
|
||||||
|
<# } else { #>
|
||||||
|
<# create_message(_fmt, e, None, msg_group, &self.messages)?; #>
|
||||||
|
<# } #>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
<# if !e.rules.is_empty() { #>
|
||||||
|
pub trait M2B<#= e.msg.name #>Ext<# if uses_lifetime { #><'a><# } #> {
|
||||||
|
<# for r in &e.rules {
|
||||||
|
let name = r.from_name();
|
||||||
|
#>
|
||||||
|
fn set_<#= name.to_snake_case() #>(self, <#= r.get_argument_no_option()
|
||||||
|
.replace('&', "&'a ") #>) -> Self;
|
||||||
|
<# } #>
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<# if uses_lifetime { #><'a><# } #> M2B<#= e.msg.name #>Ext<# if uses_lifetime { #><'a><# } #> for c2s::Out<#= e.msg.name #>Part<# if uses_lifetime { #><'a><# } #> {
|
||||||
|
<# for r in &e.rules {
|
||||||
|
let name = r.from_name();
|
||||||
|
let from_name;
|
||||||
|
match r {
|
||||||
|
RuleKind::Map { from, .. } => {
|
||||||
|
from_name = format!("self.{}", from.name.to_snake_case());
|
||||||
|
}
|
||||||
|
RuleKind::ArgumentMap { .. } => from_name = r.from_name().to_snake_case(),
|
||||||
|
RuleKind::Function { .. }
|
||||||
|
| RuleKind::ArgumentFunction { .. } => from_name = r.from_name().to_snake_case(),
|
||||||
|
}
|
||||||
|
#>
|
||||||
|
fn set_<#= name.to_snake_case() #>(mut self, <#= r.get_argument_no_option()
|
||||||
|
.replace('&', "&'a ") #>) -> Self {
|
||||||
|
<# call_func2(_fmt, &e.book_struct.name, r)?; #>
|
||||||
|
<# match r {
|
||||||
|
RuleKind::Map { to, .. }
|
||||||
|
| RuleKind::ArgumentMap { to, .. } => { #>
|
||||||
|
self.<#= to.get_rust_name() #> = Some(<#= r.from_name().to_snake_case() #>.into());
|
||||||
|
<# }
|
||||||
|
RuleKind::Function { to, .. }
|
||||||
|
| RuleKind::ArgumentFunction { to, .. } => {
|
||||||
|
for t in to { #>
|
||||||
|
self.<#= t.get_rust_name() #> = Some(<#= t.get_rust_name() #>.into());
|
||||||
|
<# }
|
||||||
|
}
|
||||||
|
} #>
|
||||||
|
self
|
||||||
|
}
|
||||||
|
<# } #>
|
||||||
|
}
|
||||||
|
<# } #>
|
||||||
|
<#
|
||||||
|
} else if e.op == RuleOp::Remove {
|
||||||
|
if e.rules.is_empty() {
|
||||||
|
let args = get_all_arguments(e, None);
|
||||||
|
let name_add = if !args.is_empty() {
|
||||||
|
format!("_{}", &args[2..args.find(':').unwrap()])
|
||||||
|
} else {
|
||||||
|
"".into()
|
||||||
|
}; #>
|
||||||
|
|
||||||
|
impl <#= e.book_struct.name #> {
|
||||||
|
pub fn remove<#= name_add #>(&self<#= args #>) -> OutCommand {
|
||||||
|
c2s::Out<#= e.msg.name #>Message::new(&mut std::iter::once({
|
||||||
|
<# create_message(_fmt, e, None, msg_group, &self.messages)?; #>
|
||||||
|
})<# if msg_group.default.response { #>, None<# } #>)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
<# } else {
|
||||||
|
// Remove the property
|
||||||
|
for r in &e.rules {
|
||||||
|
let args = get_all_arguments(e, Some(r));
|
||||||
|
let name_add = if !args.is_empty() {
|
||||||
|
format!("_{}", &args[2..args.find(':').unwrap()])
|
||||||
|
} else {
|
||||||
|
"".into()
|
||||||
|
}; #>
|
||||||
|
|
||||||
|
impl <#= e.book_struct.name #> {
|
||||||
|
pub fn remove<#= name_add #>(&self<#= args #>) -> OutCommand {
|
||||||
|
c2s::Out<#= e.msg.name #>Message::new(&mut std::iter::once({
|
||||||
|
<# create_message(_fmt, e, Some(r), msg_group, &self.messages)?; #>
|
||||||
|
})<# if msg_group.default.response { #>, None<# } #>)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
<# }
|
||||||
|
}
|
||||||
|
} else if e.op == RuleOp::Add {
|
||||||
|
for r in &e.rules {
|
||||||
|
let name = r.from_name_singular();
|
||||||
|
#>
|
||||||
|
|
||||||
|
impl <#= e.book_struct.name #> {
|
||||||
|
pub fn add_<#= name.to_snake_case() #>(&self<#= get_all_arguments(e, Some(r)) #>) -> OutCommand {
|
||||||
|
c2s::Out<#= e.msg.name #>Message::new(&mut std::iter::once({
|
||||||
|
<# create_message(_fmt, e, Some(r), msg_group, &self.messages)?; #>
|
||||||
|
})<# if msg_group.default.response { #>, None<# } #>)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
<# }
|
||||||
|
}
|
||||||
|
} #>
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
<#@ template cleanws="true" #>
|
||||||
|
/// A `PropertyId` identifies a single attribute in the data structure of a
|
||||||
|
/// connection.
|
||||||
|
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub enum PropertyId {
|
||||||
|
<# for struc in &self.structs { #>
|
||||||
|
<#= struc.name #><#= struc.get_ids(&self.structs) #>,
|
||||||
|
<# } #>
|
||||||
|
|
||||||
|
<# for struc in self.structs.iter().filter(|s| !s.opt) {
|
||||||
|
for p in struc.get_properties(&self.structs) { #>
|
||||||
|
<#= struc.name #><#= p.get_name() #><#= p.get_ids(&self.structs, struc) #>,
|
||||||
|
<# }
|
||||||
|
} #>
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A `PropertyValue` contains the value of an attribute in the data structures.
|
||||||
|
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub enum PropertyValue {
|
||||||
|
<# for struc in &self.structs { #>
|
||||||
|
<#= struc.name #>(<#= struc.get_type()? #>),
|
||||||
|
<# } #>
|
||||||
|
|
||||||
|
<#
|
||||||
|
let mut done = HashSet::new();
|
||||||
|
for struc in self.structs.iter().filter(|s| !s.opt) {
|
||||||
|
for p in struc.get_properties(&self.structs) {
|
||||||
|
let type_s = p.get_inner_type()?;
|
||||||
|
if !done.insert(type_s.to_string()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
#>
|
||||||
|
<#= p.get_inner_type_as_name()? #>(<#= type_s #>),
|
||||||
|
<# }
|
||||||
|
} #>
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A `PropertyValueRef` contains a reference to the value of an attribute in
|
||||||
|
/// the data structures.
|
||||||
|
///
|
||||||
|
/// See [`PropertyValue`] for the owned variant.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub enum PropertyValueRef<'a> {
|
||||||
|
<# for struc in &self.structs { #>
|
||||||
|
<#= struc.name #>(<#= struc.get_type()?.lifetime(true).to_ref(true) #>),
|
||||||
|
<# } #>
|
||||||
|
|
||||||
|
<#
|
||||||
|
let mut done = HashSet::new();
|
||||||
|
for struc in self.structs.iter().filter(|s| !s.opt) {
|
||||||
|
for p in struc.get_properties(&self.structs) {
|
||||||
|
let type_s = p.get_inner_type()?;
|
||||||
|
if !done.insert(type_s.to_string()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
#>
|
||||||
|
<#= p.get_inner_type_as_name()? #>(<#= p.get_inner_type()?.lifetime(true).to_ref(true) #>),
|
||||||
|
<# }
|
||||||
|
} #>
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PropertyValue {
|
||||||
|
pub fn as_ref(&self) -> PropertyValueRef<'_> {
|
||||||
|
match self {
|
||||||
|
<# for struc in &self.structs { #>
|
||||||
|
PropertyValue::<#= struc.name #>(s) => PropertyValueRef::<#= struc.name #>(<#= struc.get_type()?.code_as_ref("s").trim_start_matches('&') #>),
|
||||||
|
<# } #>
|
||||||
|
|
||||||
|
<#
|
||||||
|
let mut done = HashSet::new();
|
||||||
|
for struc in self.structs.iter().filter(|s| !s.opt) {
|
||||||
|
for p in struc.get_properties(&self.structs) {
|
||||||
|
let inner_type = p.get_inner_type()?;
|
||||||
|
if !done.insert(inner_type.to_string()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let name = inner_type.to_name();
|
||||||
|
let has_ref = inner_type.lifetime(true).to_ref(true).uses_lifetime();
|
||||||
|
#>
|
||||||
|
PropertyValue::<#= name #>(s) => PropertyValueRef::<#= name #>(<#= inner_type.wrap_ref().code_as_ref("s").trim_start_matches('&') #>),
|
||||||
|
<# }
|
||||||
|
} #>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,340 @@
|
|||||||
|
<#@ template cleanws="true" #>
|
||||||
|
use std::borrow::Cow;
|
||||||
|
// Needed for vector serialization
|
||||||
|
#[allow(unused_imports)]
|
||||||
|
use std::fmt::Write as _;
|
||||||
|
use std::str;
|
||||||
|
|
||||||
|
use base64::prelude::*;
|
||||||
|
use num_traits::{FromPrimitive, ToPrimitive};
|
||||||
|
use tracing::{instrument, warn};
|
||||||
|
use tsproto_packets::commands::{CommandItem, CommandParser};
|
||||||
|
use tsproto_packets::packets::*;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub enum InMessage {
|
||||||
|
<# for msg_group in &self.0.msg_group {
|
||||||
|
for msg in &msg_group.msg { #>
|
||||||
|
<#= msg.name #>(In<#= msg.name #>),
|
||||||
|
<# }
|
||||||
|
} #>
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InMessage {
|
||||||
|
/// Parse a message into a struct.
|
||||||
|
pub fn new(header: &InHeader, cmd: &[u8]) -> Result<Self> {
|
||||||
|
let (name, args) = CommandParser::new(cmd);
|
||||||
|
match name {
|
||||||
|
<#
|
||||||
|
let mut msgs: Vec<_> = self.0.msg_group.iter()
|
||||||
|
.flat_map(|g| g.msg.iter())
|
||||||
|
.filter(|m| m.notify.is_some())
|
||||||
|
.collect();
|
||||||
|
msgs.sort_unstable_by_key(|m| m.notify.as_ref().map(|s| s.as_str()).unwrap());
|
||||||
|
for (notify, group) in &msgs.iter().group_by(|m| m.notify.as_ref().map(|s| s.as_str()).unwrap()) {
|
||||||
|
let group: Vec<_> = group.collect();
|
||||||
|
let (msg, group) = group.split_last().unwrap();
|
||||||
|
#>
|
||||||
|
b"<#= notify #>" => <# for msg in group {
|
||||||
|
#>if let Ok(r) = In<#= msg.name #>::new(header, args.clone()) {
|
||||||
|
Ok(InMessage::<#= msg.name #>(r))
|
||||||
|
} else <#
|
||||||
|
} #>{
|
||||||
|
Ok(InMessage::<#= msg.name #>(In<#= msg.name #>::new(header, args)?))
|
||||||
|
}
|
||||||
|
<# } #>
|
||||||
|
s => Err(ParseError::UnknownCommand(str::from_utf8(s)?.to_string())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_command_name(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
<# for msg_group in &self.0.msg_group {
|
||||||
|
for msg in &msg_group.msg { #>
|
||||||
|
InMessage::<#= msg.name #>(_) => "<#= if let Some(s) = &msg.notify { s } else { &msg.name } #>",
|
||||||
|
<# }
|
||||||
|
} #>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
<# for msg_group in &self.0.msg_group {
|
||||||
|
for msg in &msg_group.msg {
|
||||||
|
let has_attributes = !msg.attributes.is_empty(); #>
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct In<#= msg.name #> {
|
||||||
|
<# if msg_group.default.response { #>
|
||||||
|
pub return_code: Option<String>,
|
||||||
|
<# }
|
||||||
|
if has_attributes { #>
|
||||||
|
list: Vec<In<#= msg.name #>Part>,
|
||||||
|
<# } #>
|
||||||
|
}
|
||||||
|
<# if has_attributes { #>
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct In<#= msg.name #>Part {
|
||||||
|
<# for a in &msg.attributes {
|
||||||
|
let field = self.0.get_field(a);
|
||||||
|
if field.get_rust_name() != field.ts { #>
|
||||||
|
/// `<#= field.ts #>` in TeamSpeak
|
||||||
|
<# } #>
|
||||||
|
pub <#= field.get_rust_name() #>: <#= field.get_type(a)? #>,
|
||||||
|
<# } #>
|
||||||
|
}
|
||||||
|
<# } #>
|
||||||
|
|
||||||
|
impl InMessageTrait for In<#= msg.name #> {
|
||||||
|
#[instrument(name = "parse_message", skip(header, <# if !has_attributes { #>_<# } #>args))]
|
||||||
|
fn new(header: &InHeader, <# if !has_attributes { #>_<# } #>args: CommandParser) -> Result<Self> {
|
||||||
|
// TODO newprotocol
|
||||||
|
//if <#= if msg_group.default.np { "!" } else { "" } #>header.flags().contains(Flags::NEWPROTOCOL) { return Err(ParseError::WrongNewprotocol(<#= if msg_group.default.np { "false" } else { "true" } #>)); }
|
||||||
|
if header.packet_type() != PacketType::Command<#= if msg_group.default.low { "Low" } else { "" } #> { return Err(ParseError::WrongPacketType(header.packet_type())); }
|
||||||
|
<# if !msg_group.default.s2c { #>
|
||||||
|
if header.direction() == Direction::S2C { return Err(ParseError::WrongDirection(header.direction())); }
|
||||||
|
<# } #>
|
||||||
|
<# if !msg_group.default.c2s { #>
|
||||||
|
if header.direction() == Direction::C2S { return Err(ParseError::WrongDirection(header.direction())); }
|
||||||
|
<# } #>
|
||||||
|
|
||||||
|
<# if msg_group.default.response { #>
|
||||||
|
let mut return_code = None;
|
||||||
|
<# } #>
|
||||||
|
<# for a in &msg.attributes { #>
|
||||||
|
let mut <#= self.0.get_field(a).get_rust_name() #> = None;
|
||||||
|
<# } #>
|
||||||
|
|
||||||
|
<# if !has_attributes { #>
|
||||||
|
Ok(In<#= msg.name #> {<# if msg_group.default.response { #> return_code <# } #>})
|
||||||
|
<# } else { #>
|
||||||
|
let mut list = Vec::<In<#= msg.name #>Part>::new();
|
||||||
|
for item in args.chain(std::iter::once(CommandItem::NextCommand)) {
|
||||||
|
match item {
|
||||||
|
CommandItem::NextCommand => {
|
||||||
|
// Build command
|
||||||
|
let new = In<#= msg.name #>Part {
|
||||||
|
<# for a in &msg.attributes {
|
||||||
|
let field = self.0.get_field(a);
|
||||||
|
let transform_func = if !field.get_type(a)?.is_primitive() {
|
||||||
|
".clone()"
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
}; #>
|
||||||
|
<#= field.get_rust_name() #>: <#= field.get_rust_name() #>
|
||||||
|
<# if !a.ends_with('?') { /* is not optional */ #>
|
||||||
|
.take()
|
||||||
|
.or_else(|| list.first().map(|p| p.<#= field.get_rust_name() #><#= transform_func #>))
|
||||||
|
.ok_or(ParseError::ParameterNotFound { arg: "<#= field.pretty #>", name: "<#= msg.name #>", })?,
|
||||||
|
<# } else { #>
|
||||||
|
.take()
|
||||||
|
.or_else(|| list.first().and_then(|p| p.<#= field.get_rust_name() #><#= transform_func #>)),
|
||||||
|
<# } #>
|
||||||
|
<# } #>
|
||||||
|
};
|
||||||
|
list.push(new);
|
||||||
|
}
|
||||||
|
CommandItem::Argument(arg) => {
|
||||||
|
match arg.name() {
|
||||||
|
<# for a in &msg.attributes {
|
||||||
|
let field = self.0.get_field(a); #>
|
||||||
|
b"<#= field.ts #>" => {
|
||||||
|
let val = arg.value().get_str()?;
|
||||||
|
let val = val.as_ref();
|
||||||
|
<#= field.get_rust_name() #> = Some({
|
||||||
|
<# #><#= generate_deserializer(field) #>
|
||||||
|
});
|
||||||
|
}
|
||||||
|
<# } #>
|
||||||
|
<# if msg_group.default.response { #>
|
||||||
|
b"return_code" => {
|
||||||
|
if return_code.is_some() {
|
||||||
|
warn!(command = "<#= msg.name #>", "Got multiple return codes");
|
||||||
|
}
|
||||||
|
return_code = Some(arg.value().get_str()?.into_owned());
|
||||||
|
}
|
||||||
|
<# } #>
|
||||||
|
s => warn!(command = "<#= msg.name #>", argument = ?str::from_utf8(s),
|
||||||
|
"Unknown argument"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(In<#= msg.name #> {<# if msg_group.default.response { #> return_code,<# } #> list })
|
||||||
|
<# } #>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
<# if has_attributes { #>
|
||||||
|
impl In<#= msg.name #> {
|
||||||
|
#[inline]
|
||||||
|
pub fn iter(&self) -> InMessageIterator<In<#= msg.name #>Part> { self.into_iter() }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> IntoIterator for &'a In<#= msg.name #> {
|
||||||
|
type Item = &'a In<#= msg.name #>Part;
|
||||||
|
type IntoIter = InMessageIterator<'a, In<#= msg.name #>Part>;
|
||||||
|
#[inline]
|
||||||
|
fn into_iter(self) -> Self::IntoIter { InMessageIterator(&self.list, 0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl In<#= msg.name #>Part {
|
||||||
|
pub fn get_invoker(&self) -> Option<Invoker> {
|
||||||
|
<#
|
||||||
|
let mut has_invoker_id = false;
|
||||||
|
let mut has_invoker_name = false;
|
||||||
|
let mut has_invoker_uid = false;
|
||||||
|
let mut invoker_optional = true;
|
||||||
|
|
||||||
|
for a in &msg.attributes {
|
||||||
|
let field = self.0.get_field(a);
|
||||||
|
match field.ts.as_str() {
|
||||||
|
"invokerid" => {
|
||||||
|
has_invoker_id = true;
|
||||||
|
invoker_optional = a.ends_with('?');
|
||||||
|
}
|
||||||
|
"invokername" => has_invoker_name = true,
|
||||||
|
"invokeruid" => has_invoker_uid = true,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if has_invoker_id && has_invoker_name && has_invoker_uid { #>
|
||||||
|
<# if invoker_optional { #>
|
||||||
|
let id = self.invoker_id?;
|
||||||
|
let name = self.invoker_name.clone()?;
|
||||||
|
let uid = self.invoker_uid.clone();
|
||||||
|
<# } else { #>
|
||||||
|
let id = self.invoker_id;
|
||||||
|
let name = self.invoker_name.clone();
|
||||||
|
let uid = self.invoker_uid.clone();
|
||||||
|
<# } #>
|
||||||
|
Some(Invoker {
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
uid,
|
||||||
|
})
|
||||||
|
<# } else { #>
|
||||||
|
None
|
||||||
|
<# } #>
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_out(&self) -> Out<#= msg.name #>Part {
|
||||||
|
Out<#= msg.name #>Part {
|
||||||
|
<#
|
||||||
|
let mut uses_lifetime = false;
|
||||||
|
for a in &msg.attributes {
|
||||||
|
let field = self.0.get_field(a);
|
||||||
|
let ty = field.get_type(a)?;
|
||||||
|
let mut from = ty
|
||||||
|
.code_as_ref("field")
|
||||||
|
.replacen("field", &format!("self.{}", field.get_rust_name()), 1);
|
||||||
|
if ty.to_cow().is_cow() {
|
||||||
|
if ty.is_opt() {
|
||||||
|
from.push_str(".map(Cow::Borrowed)");
|
||||||
|
} else {
|
||||||
|
from = format!("Cow::Borrowed({})", from);
|
||||||
|
}
|
||||||
|
} #>
|
||||||
|
<#= field.get_rust_name() #>: <#= from #>,
|
||||||
|
<# } #>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
<# } #>
|
||||||
|
|
||||||
|
<# }
|
||||||
|
} #>
|
||||||
|
|
||||||
|
/// The iterator is guaranteed to output at least one part.
|
||||||
|
pub struct InMessageIterator<'a, T>(&'a [T], usize);
|
||||||
|
impl<'a, T> Iterator for InMessageIterator<'a, T> {
|
||||||
|
type Item = &'a T;
|
||||||
|
fn next(&mut self) -> Option<Self::Item> {
|
||||||
|
let i = self.1;
|
||||||
|
self.1 += 1;
|
||||||
|
self.0.get(i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
<# for msg_group in &self.0.msg_group {
|
||||||
|
let defs = &msg_group.default;
|
||||||
|
for msg in &msg_group.msg {
|
||||||
|
let uses_lifetime = self.0.uses_lifetime(msg);
|
||||||
|
let has_attributes = msg_group.default.response || !msg.attributes.is_empty(); #>
|
||||||
|
|
||||||
|
<# if has_attributes { #>
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Out<#= msg.name #>Part<# if uses_lifetime { #><'a><# } #> {
|
||||||
|
<# for a in &msg.attributes {
|
||||||
|
let field = self.0.get_field(a);
|
||||||
|
if field.get_rust_name() != field.ts { #>
|
||||||
|
/// `<#= field.ts #>` in TeamSpeak
|
||||||
|
<# } #>
|
||||||
|
pub <#= field.get_rust_name() #>: <#= field.get_type(a)?.to_cow().lifetime(true) #>,
|
||||||
|
<# } #>
|
||||||
|
}
|
||||||
|
|
||||||
|
<#
|
||||||
|
let part_name = format!("Out{}Part{}", msg.name, if uses_lifetime { "<'a>" } else { "" });
|
||||||
|
#>
|
||||||
|
impl<<# if uses_lifetime { #>'a, <# } #>> OutMessage<# if msg_group.default.response { #>WithReturn<# } #>Trait for &mut dyn Iterator<Item=<#= part_name #>> {
|
||||||
|
fn to_packet(self<#
|
||||||
|
if msg_group.default.response { #>, return_code: Option<&str><# } #>) -> OutCommand
|
||||||
|
where Self: Sized {
|
||||||
|
Out<#= msg.name #>Message::new(self<#
|
||||||
|
if msg_group.default.response { #>, return_code<# } #>)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<<# if uses_lifetime { #>'a, <# } #>> OutMessage<# if msg_group.default.response { #>WithReturn<# } #>Trait for <#= part_name #> {
|
||||||
|
fn to_packet(self<#
|
||||||
|
if msg_group.default.response { #>, return_code: Option<&str><# } #>) -> OutCommand
|
||||||
|
where Self: Sized {
|
||||||
|
Out<#= msg.name #>Message::new(&mut std::iter::once(self)<#
|
||||||
|
if msg_group.default.response { #>, return_code<# } #>)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
<# } #>
|
||||||
|
pub struct Out<#= msg.name #>Message;
|
||||||
|
impl Out<#= msg.name #>Message {
|
||||||
|
#[allow(clippy::let_and_return, clippy::new_ret_no_self)]
|
||||||
|
pub fn new(<# if has_attributes { #>parts: &mut dyn Iterator<Item=Out<#= msg.name #>Part><#
|
||||||
|
if msg_group.default.response { #>, return_code: Option<&str><# } } #>) -> OutCommand {
|
||||||
|
let<# if has_attributes { #> mut<# } #> packet = OutCommand::new(
|
||||||
|
Direction::<#= if msg_group.default.s2c { "S2C" } else { "C2S" } #>,
|
||||||
|
Flags::<#= if msg_group.default.np { "NEWPROTOCOL" } else { "empty()" } #>,
|
||||||
|
PacketType::Command<# if msg_group.default.low { #>Low<# } #>,
|
||||||
|
"<#= msg.notify.as_ref().map(|s| s.as_str()).unwrap_or("") #>",
|
||||||
|
);
|
||||||
|
<# if msg_group.default.response { #>
|
||||||
|
if let Some(r) = return_code {
|
||||||
|
packet.write_arg("return_code", &r);
|
||||||
|
}
|
||||||
|
<# } #>
|
||||||
|
<# if !msg.attributes.is_empty() { #>
|
||||||
|
let mut first = true;
|
||||||
|
for p in parts {
|
||||||
|
if first {
|
||||||
|
first = false;
|
||||||
|
} else {
|
||||||
|
packet.start_new_part();
|
||||||
|
}
|
||||||
|
<# for a in &msg.attributes {
|
||||||
|
let field = self.0.get_field(a);
|
||||||
|
if a.ends_with('?') { #>
|
||||||
|
if let Some(val) = p.<#= field.get_rust_name() #> { packet.write_arg("<#= field.ts #>", <#= generate_serializer(field, "val") #>); }
|
||||||
|
<# } else { #>
|
||||||
|
packet.write_arg("<#= field.ts #>", <#= generate_serializer(field, &format!("p.{}", field.get_rust_name())) #>);
|
||||||
|
<# } #>
|
||||||
|
<# } #>
|
||||||
|
}
|
||||||
|
<# } #>
|
||||||
|
|
||||||
|
packet
|
||||||
|
}
|
||||||
|
}
|
||||||
|
<# }
|
||||||
|
} #>
|
||||||
@@ -0,0 +1,439 @@
|
|||||||
|
<#@ template cleanws="true" #>
|
||||||
|
<#
|
||||||
|
/// Push into events the difference between two arrays.
|
||||||
|
///
|
||||||
|
/// The old value is stored in `old`, the `new` in the book.
|
||||||
|
fn diff(_fmt: &mut std::fmt::Formatter, new: &str, event: &Event, p: &Property, from: &Field) -> std::fmt::Result {
|
||||||
|
let mut ids = event.get_id_args("m");
|
||||||
|
let type_s = p.get_inner_type_as_name()?;
|
||||||
|
let added;
|
||||||
|
let removed;
|
||||||
|
let modifier = from.modifier.as_ref().unwrap();
|
||||||
|
if modifier == "array" {
|
||||||
|
added = format!("iter().filter(|n| !old.contains(n))");
|
||||||
|
removed = format!("into_iter().filter(|o| !{}.contains(o))", new);
|
||||||
|
} else if modifier == "set" {
|
||||||
|
added = format!("difference(&old)");
|
||||||
|
removed = format!("difference(&{})", new);
|
||||||
|
} else {
|
||||||
|
panic!("Unsupported modifier {}", modifier);
|
||||||
|
}
|
||||||
|
#>
|
||||||
|
// Added
|
||||||
|
for i in <#= new #>.<#= added #> {
|
||||||
|
events.push(Event::PropertyAdded {
|
||||||
|
id: PropertyId::<#= event.book_struct.name #><#= p.get_name() #>(<#= ids #>, *i),
|
||||||
|
invoker: invoker.clone(),
|
||||||
|
extra: ExtraInfo {
|
||||||
|
reason,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Removed
|
||||||
|
for i in old.<#= removed #> {
|
||||||
|
events.push(Event::PropertyRemoved {
|
||||||
|
id: PropertyId::<#= event.book_struct.name #><#= p.get_name() #>(<#= ids #>, i),
|
||||||
|
old: PropertyValue::<#= type_s #>(i),
|
||||||
|
invoker: invoker.clone(),
|
||||||
|
extra: ExtraInfo {
|
||||||
|
reason,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
<#
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_event(_fmt: &mut std::fmt::Formatter, event: &Event, change: &str, old: bool) -> std::fmt::Result {
|
||||||
|
let ids = embrace(&event.get_id_args("m"));
|
||||||
|
#>
|
||||||
|
events.push(Event::Property<#= change #> {
|
||||||
|
id: PropertyId::<#= event.book_struct.name #><#= ids #>,
|
||||||
|
<# if old { #>
|
||||||
|
old: PropertyValue::<#= event.book_struct.name #>(old),
|
||||||
|
<# } #>
|
||||||
|
invoker: invoker.clone(),
|
||||||
|
extra: ExtraInfo { reason },
|
||||||
|
});
|
||||||
|
<#
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_add_rule(_fmt: &mut std::fmt::Formatter, event: &Event) -> std::fmt::Result {
|
||||||
|
// Create a new object
|
||||||
|
// First, call all functions
|
||||||
|
for fun in event.rules.iter().filter(|r| r.is_function()) {
|
||||||
|
if let RuleKind::Function { name, to } = fun {
|
||||||
|
let return_match = if to.len() == 1 {
|
||||||
|
to[0].name.to_snake_case()
|
||||||
|
} else {
|
||||||
|
format!("({})", to.iter().map(|p| p.name.to_snake_case()).collect::<Vec<_>>().join(", "))
|
||||||
|
}; #>
|
||||||
|
let <#= return_match #> = self.<#= name.to_snake_case() #>(m, &mut events)?;
|
||||||
|
<# }
|
||||||
|
} #>
|
||||||
|
let r = <#= event.book_struct.name #> {
|
||||||
|
<#
|
||||||
|
// Add ids
|
||||||
|
for (id, fld) in event.book_struct.id.iter().zip(event.id.iter()) { #>
|
||||||
|
<#= PropId::from(id).get_attr_name(&event.book_struct) #>: m.<#= fld.get_rust_name() #>.clone(),
|
||||||
|
<# }
|
||||||
|
|
||||||
|
let v = vec![];
|
||||||
|
// Function return values
|
||||||
|
for p in event.rules.iter()
|
||||||
|
.flat_map(|f| if let RuleKind::Function { to, .. } = f {
|
||||||
|
to
|
||||||
|
} else {
|
||||||
|
&v
|
||||||
|
}) { #>
|
||||||
|
<#= p.name.to_snake_case() #>,
|
||||||
|
<# }
|
||||||
|
for p in event.rules.iter() {
|
||||||
|
if let RuleKind::Map { from, to, op } = p {
|
||||||
|
if *op != RuleOp::Update {
|
||||||
|
panic!("Cannot add or remove when adding a new struct");
|
||||||
|
}
|
||||||
|
let transform_func = if to.is_set() {
|
||||||
|
// Convert to set
|
||||||
|
".iter().cloned().collect()"
|
||||||
|
} else if !to.get_type()?.is_primitive() {
|
||||||
|
".clone()"
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
};
|
||||||
|
// to is optional, but from not
|
||||||
|
let from_opt = from.is_opt(&event.msg); #>
|
||||||
|
<#= to.name.to_snake_case() #>: <#
|
||||||
|
if to.opt && !from_opt {
|
||||||
|
#>Some(m.<#= from.get_rust_name() #><#= transform_func #>),
|
||||||
|
<# } else {
|
||||||
|
#>m.<#= from.get_rust_name() #><#= transform_func #>,
|
||||||
|
<# }
|
||||||
|
}
|
||||||
|
} #>
|
||||||
|
};
|
||||||
|
<#
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#>
|
||||||
|
impl Connection {
|
||||||
|
/// Return if the message was handled and the generated events.
|
||||||
|
fn handle_command_generated(&mut self, msg: &InMessage) -> Result<(bool, Vec<Event>)> {
|
||||||
|
let mut events = Vec::new();
|
||||||
|
match msg {
|
||||||
|
<#
|
||||||
|
// Group events by message
|
||||||
|
let mut groups = HashMap::new();
|
||||||
|
for event in &self.decls {
|
||||||
|
let group = groups.entry(event.msg.name.as_str()).or_insert_with(Vec::new);
|
||||||
|
group.push(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (msg_name, group) in groups {
|
||||||
|
let event = &group[0]; #>
|
||||||
|
InMessage::<#= msg_name #>(m) => for m in m.iter() {
|
||||||
|
#[allow(unused_variables)]
|
||||||
|
let invoker = m.get_invoker();
|
||||||
|
#[allow(unused_variables)]
|
||||||
|
<# if event.msg.attributes.iter().any(|a| a == "reasonid") { #>
|
||||||
|
let reason = Some(m.reason);
|
||||||
|
<# } else if event.msg.attributes.iter().any(|a| a == "reasonid?") { #>
|
||||||
|
let reason = m.reason;
|
||||||
|
<# } else { #>
|
||||||
|
let reason: Option<Reason> = None;
|
||||||
|
<# } #>
|
||||||
|
<#
|
||||||
|
for event in group {
|
||||||
|
let book_name = &event.book_struct.name;
|
||||||
|
#>
|
||||||
|
|
||||||
|
<# if event.op == RuleOp::Remove {
|
||||||
|
let function_name = format!("remove_{}", book_name.to_snake_case());
|
||||||
|
let mut ids = event.get_id_args("m");
|
||||||
|
if !ids.is_empty() { ids.push_str(", "); }
|
||||||
|
if !event.book_struct.opt { #>
|
||||||
|
let old = self.<#= function_name #>(<#= ids #>&mut events)?
|
||||||
|
.ok_or(Error::RemoveNotFound("<#= book_name #>"))?;
|
||||||
|
<# } else { #>
|
||||||
|
let old = self.<#= function_name #>(<#= ids #>&mut events)?;
|
||||||
|
<# }
|
||||||
|
create_event(_fmt, event, "Removed", true)?;
|
||||||
|
} else if event.op == RuleOp::Update && !event.book_struct.opt {
|
||||||
|
// Update the object
|
||||||
|
// Functions first
|
||||||
|
let mut rule_count = event.rules.len();
|
||||||
|
for rule in &event.rules {
|
||||||
|
if let RuleKind::Function { name, to } = rule {
|
||||||
|
rule_count -= 1; #>
|
||||||
|
self.<#= name.to_snake_case() #>(<#= event.get_id_args("m") #>, m, &mut events)?;
|
||||||
|
<# }
|
||||||
|
}
|
||||||
|
let function_name = format!("get_mut_{}", book_name.to_snake_case());
|
||||||
|
|
||||||
|
// Only print if necessary
|
||||||
|
if rule_count > 0 { #>
|
||||||
|
let r = self.<#= function_name #>(<#= event.get_id_args("m") #>)?;
|
||||||
|
<# }
|
||||||
|
for rule in &event.rules {
|
||||||
|
match rule {
|
||||||
|
RuleKind::Map { from, to, op } => {
|
||||||
|
// Put field from packet into bookkeeping struct
|
||||||
|
match op {
|
||||||
|
RuleOp::Update => {
|
||||||
|
let from_opt = from.is_opt(&event.msg);
|
||||||
|
// to/book is optional, but from/message not
|
||||||
|
if to.opt && !from_opt { #>
|
||||||
|
let old = mem::replace(&mut r.<#= to.name.to_snake_case() #>, Some(m.<#= from.get_rust_name() #><# if !to.get_type()?.is_primitive() { #>.clone()<# } #>));
|
||||||
|
events.push(Event::PropertyChanged {
|
||||||
|
id: <#= event.get_property_id(to, from, "m") #>,
|
||||||
|
old: <#= get_property(to, "old") #>,
|
||||||
|
invoker: invoker.clone(),
|
||||||
|
extra: ExtraInfo { reason },
|
||||||
|
});
|
||||||
|
<# } else if from_opt {
|
||||||
|
let mut prefix = "";
|
||||||
|
let transform_func = if to.is_set() {
|
||||||
|
".iter().cloned().collect()"
|
||||||
|
} else if !to.get_type()?.is_primitive() {
|
||||||
|
".clone()"
|
||||||
|
} else {
|
||||||
|
prefix = "*";
|
||||||
|
""
|
||||||
|
}; #>
|
||||||
|
if let Some(val) = &m.<#= from.get_rust_name() #> {
|
||||||
|
<# if to.opt { #>
|
||||||
|
let old = mem::replace(&mut r.<#= to.name.to_snake_case() #>, Some(<#= prefix #>val<#= transform_func #>));
|
||||||
|
<# } else { #>
|
||||||
|
let old = mem::replace(&mut r.<#= to.name.to_snake_case() #>, <#= prefix #>val<#= transform_func #>);
|
||||||
|
<# } #>
|
||||||
|
<# if from.modifier.as_ref().map(|s| s == "array" || s == "set").unwrap_or(false) {
|
||||||
|
diff(_fmt, &format!("r.{}", to.name.to_snake_case()), event, to, from)?;
|
||||||
|
} else { #>
|
||||||
|
events.push(Event::PropertyChanged {
|
||||||
|
id: <#= event.get_property_id(to, from, "m") #>,
|
||||||
|
old: <#= get_property(to, "old") #>,
|
||||||
|
invoker: invoker.clone(),
|
||||||
|
extra: ExtraInfo { reason },
|
||||||
|
});
|
||||||
|
<# } #>
|
||||||
|
}
|
||||||
|
<# } else {
|
||||||
|
// Nothing is optional
|
||||||
|
#>
|
||||||
|
let old = mem::replace(&mut r.<#= to.name.to_snake_case() #>, m.<#= from.get_rust_name() #>.clone());
|
||||||
|
events.push(Event::PropertyChanged {
|
||||||
|
id: <#= event.get_property_id(to, from, "m") #>,
|
||||||
|
old: <#= get_property(to, "old") #>,
|
||||||
|
invoker: invoker.clone(),
|
||||||
|
extra: ExtraInfo { reason },
|
||||||
|
});
|
||||||
|
<# }
|
||||||
|
}
|
||||||
|
// The field in the struct is a vector
|
||||||
|
RuleOp::Add => {
|
||||||
|
if to.is_set() { #>
|
||||||
|
r.<#= to.name.to_snake_case() #>.insert(m.<#= from.get_rust_name() #>.clone());
|
||||||
|
<# } else { #>
|
||||||
|
r.<#= to.name.to_snake_case() #>.push(m.<#= from.get_rust_name() #>.clone());
|
||||||
|
<# } #>
|
||||||
|
events.push(Event::PropertyAdded {
|
||||||
|
id: <#= event.get_property_id(to, from, "m") #>,
|
||||||
|
invoker: invoker.clone(),
|
||||||
|
extra: ExtraInfo { reason },
|
||||||
|
});
|
||||||
|
<# }
|
||||||
|
RuleOp::Remove => {
|
||||||
|
if to.is_set() { #>
|
||||||
|
if r.<#= to.name.to_snake_case() #>.remove(&m.<#= from.get_rust_name() #>) {
|
||||||
|
let old = m.<#= from.get_rust_name() #>;
|
||||||
|
<# } else { #>
|
||||||
|
// Find index and remove
|
||||||
|
if let Some(i) = r.<#= to.name.to_snake_case() #>.iter().position(|i| *i == m.<#= from.get_rust_name() #>) {
|
||||||
|
let old = r.<#= to.name.to_snake_case() #>.remove(i);
|
||||||
|
<# } #>
|
||||||
|
events.push(Event::PropertyRemoved {
|
||||||
|
id: <#= event.get_property_id(to, from, "m") #>,
|
||||||
|
old: <#= get_property(to, "old") #>,
|
||||||
|
invoker: invoker.clone(),
|
||||||
|
extra: ExtraInfo { reason },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
<# }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RuleKind::Function { to, .. } => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if event.op == RuleOp::Update && event.book_struct.opt {
|
||||||
|
// Optional structs that get only updated as a whole
|
||||||
|
|
||||||
|
// Create a new object
|
||||||
|
// First, call all functions
|
||||||
|
for fun in event.rules.iter().filter(|r| r.is_function()) {
|
||||||
|
if let RuleKind::Function { name, to } = fun {
|
||||||
|
let return_match = if to.len() == 1 {
|
||||||
|
to[0].name.to_snake_case()
|
||||||
|
} else {
|
||||||
|
format!("({})", to.iter().map(|p| p.name.to_snake_case()).collect::<Vec<_>>().join(", "))
|
||||||
|
}; #>
|
||||||
|
let <#= return_match #> = self.<#= name.to_snake_case() #>(m, &mut events)?;
|
||||||
|
<# }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if all required data are available
|
||||||
|
// Pairs of (property, string to get the property)
|
||||||
|
let mut opt_props = Vec::new();
|
||||||
|
let mut props = Vec::new();
|
||||||
|
let v = Vec::new();
|
||||||
|
// Function return values
|
||||||
|
for p in event.rules.iter()
|
||||||
|
.flat_map(|f| if let RuleKind::Function { to, .. } = f {
|
||||||
|
to
|
||||||
|
} else {
|
||||||
|
&v
|
||||||
|
}) {
|
||||||
|
opt_props.push((p.name.to_snake_case(), p.name.to_snake_case()));
|
||||||
|
}
|
||||||
|
|
||||||
|
for p in event.rules.iter() {
|
||||||
|
if let RuleKind::Map { from, to, op } = p {
|
||||||
|
if *op != RuleOp::Update {
|
||||||
|
panic!("Cannot add or remove when adding a new struct");
|
||||||
|
}
|
||||||
|
let transform_func = if to.is_set() {
|
||||||
|
// Convert to set
|
||||||
|
".iter().cloned().collect()"
|
||||||
|
} else if !to.get_type()?.is_primitive() {
|
||||||
|
".clone()"
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
};
|
||||||
|
let from_opt = from.is_opt(&event.msg);
|
||||||
|
if to.opt && !from_opt {
|
||||||
|
// to is optional, but from not
|
||||||
|
let getter = format!("Some(m.{}{})", from.get_rust_name(), transform_func);
|
||||||
|
props.push((to.name.to_snake_case(), getter));
|
||||||
|
} else {
|
||||||
|
let getter = format!("m.{}{}", from.get_rust_name(), transform_func);
|
||||||
|
if from_opt && !to.opt {
|
||||||
|
opt_props.push((to.name.to_snake_case(), getter));
|
||||||
|
} else {
|
||||||
|
props.push((to.name.to_snake_case(), getter));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !opt_props.is_empty() {
|
||||||
|
let mut matcher = opt_props.iter().map(|(p, _)| format!("Some({})", p)).collect::<Vec<_>>().join(", ");
|
||||||
|
let mut getter = opt_props.iter().map(|(_, p)| p.as_str()).collect::<Vec<_>>().join(", ");
|
||||||
|
if opt_props.len() > 1 {
|
||||||
|
matcher = format!("({})", matcher);
|
||||||
|
getter = format!("({})", getter);
|
||||||
|
}
|
||||||
|
#>
|
||||||
|
if let <#= matcher #> = <#= getter #> {
|
||||||
|
<# } #>
|
||||||
|
let r = <#= event.book_struct.name #> {
|
||||||
|
<#
|
||||||
|
// Add ids
|
||||||
|
for (id, fld) in event.book_struct.id.iter().zip(event.id.iter()) { #>
|
||||||
|
<#= PropId::from(id).get_attr_name(&event.book_struct) #>: m.<#= fld.get_rust_name() #>.clone(),
|
||||||
|
<# }
|
||||||
|
for (p, _) in &opt_props { #>
|
||||||
|
<#= p #>,
|
||||||
|
<# }
|
||||||
|
for (p, g) in &props {
|
||||||
|
if p != g { #>
|
||||||
|
<#= p #>: <#= g #>,
|
||||||
|
<# } else { #>
|
||||||
|
<#= p #>,
|
||||||
|
<# }
|
||||||
|
} #>
|
||||||
|
};
|
||||||
|
<#
|
||||||
|
let function_name = format!("replace_{}", book_name.to_snake_case());
|
||||||
|
let ids = event.get_id_args("m");
|
||||||
|
let comma = if ids.is_empty() { "" } else { ", " };
|
||||||
|
#>
|
||||||
|
let old = self.<#= function_name #>(<#= ids #><#= comma #>r, &mut events)?;
|
||||||
|
<# create_event(_fmt, event, "Changed", true)?;
|
||||||
|
if !opt_props.is_empty() { #>
|
||||||
|
}
|
||||||
|
<# }
|
||||||
|
} else if event.op == RuleOp::Add {
|
||||||
|
// Create a new object
|
||||||
|
// First, call all functions
|
||||||
|
for fun in event.rules.iter().filter(|r| r.is_function()) {
|
||||||
|
if let RuleKind::Function { name, to } = fun {
|
||||||
|
let return_match = if to.len() == 1 {
|
||||||
|
to[0].name.to_snake_case()
|
||||||
|
} else {
|
||||||
|
format!("({})", to.iter().map(|p| p.name.to_snake_case()).collect::<Vec<_>>().join(", "))
|
||||||
|
}; #>
|
||||||
|
let <#= return_match #> = self.<#= name.to_snake_case() #>(m, &mut events)?;
|
||||||
|
<# }
|
||||||
|
} #>
|
||||||
|
let r = <#= event.book_struct.name #> {
|
||||||
|
<#
|
||||||
|
// Add ids
|
||||||
|
for (id, fld) in event.book_struct.id.iter().zip(event.id.iter()) { #>
|
||||||
|
<#= PropId::from(id).get_attr_name(&event.book_struct) #>: m.<#= fld.get_rust_name() #><# if !id.find_property(&self.book.structs).get_type()?.is_primitive() { #>.clone()<# } #>,
|
||||||
|
<# }
|
||||||
|
|
||||||
|
let v = vec![];
|
||||||
|
// Function return values
|
||||||
|
for p in event.rules.iter()
|
||||||
|
.flat_map(|f| if let RuleKind::Function { to, .. } = f {
|
||||||
|
to
|
||||||
|
} else {
|
||||||
|
&v
|
||||||
|
}) { #>
|
||||||
|
<#= p.name.to_snake_case() #>,
|
||||||
|
<# }
|
||||||
|
for p in event.rules.iter() {
|
||||||
|
if let RuleKind::Map { from, to, op } = p {
|
||||||
|
if *op != RuleOp::Update {
|
||||||
|
panic!("Cannot add or remove when adding a new struct");
|
||||||
|
}
|
||||||
|
let transform_func = if to.is_set() {
|
||||||
|
// Convert to set
|
||||||
|
".iter().cloned().collect()"
|
||||||
|
} else if !to.get_type()?.is_primitive() {
|
||||||
|
".clone()"
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
};
|
||||||
|
// to is optional, but from not
|
||||||
|
let from_opt = from.is_opt(&event.msg); #>
|
||||||
|
<#= to.name.to_snake_case() #>: <#
|
||||||
|
if to.opt && !from_opt {
|
||||||
|
#>Some(m.<#= from.get_rust_name() #><#= transform_func #>),
|
||||||
|
<# } else {
|
||||||
|
#>m.<#= from.get_rust_name() #><#= transform_func #>,
|
||||||
|
<# }
|
||||||
|
}
|
||||||
|
} #>
|
||||||
|
};
|
||||||
|
<#
|
||||||
|
// TODO Previous function end
|
||||||
|
let function_name = format!("add_{}", book_name.to_snake_case());
|
||||||
|
let ids = event.get_id_args("m"); #>
|
||||||
|
self.<#= function_name #>(<#= ids #>, r, &mut events)?;
|
||||||
|
<# create_event(_fmt, event, "Added", false)?;
|
||||||
|
} #>
|
||||||
|
<# } #>
|
||||||
|
}
|
||||||
|
<# } #>
|
||||||
|
_ => {
|
||||||
|
// Ignore unmentioned messages
|
||||||
|
return Ok((false, events));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok((true, events))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
<#@ template cleanws="true" #>
|
||||||
|
impl Connection {
|
||||||
|
/// Get a property by its id.
|
||||||
|
pub fn get_property(&self, id: &PropertyId) -> Result<PropertyValueRef<'_>> {
|
||||||
|
Ok(match id {
|
||||||
|
<# for struc in &self.0.structs {
|
||||||
|
let mut ids = embrace(&get_ids(struc));
|
||||||
|
let mut ids2 = get_ids2(&self.0.structs, struc);
|
||||||
|
ids2 = format!("({})", ids2); #>
|
||||||
|
PropertyId::<#= struc.name #><#= ids #> => PropertyValueRef::<#= struc.name #>(self.get_<#= struc.name.to_snake_case() #><#= ids2 #>?),
|
||||||
|
<# } #>
|
||||||
|
|
||||||
|
<# for struc in self.0.structs.iter().filter(|s| !s.opt) {
|
||||||
|
for p in struc.get_properties(&self.0.structs) {
|
||||||
|
let type_s = p.get_inner_type_as_name()?;
|
||||||
|
|
||||||
|
let mut ids = get_ids(struc);
|
||||||
|
if p.modifier.is_some() {
|
||||||
|
if !ids.is_empty() {
|
||||||
|
ids.push_str(", ");
|
||||||
|
}
|
||||||
|
ids.push_str("m");
|
||||||
|
}
|
||||||
|
ids = embrace(&ids);
|
||||||
|
|
||||||
|
let mut ids2 = format!("({})", get_ids2(&self.0.structs, struc));
|
||||||
|
#>
|
||||||
|
PropertyId::<#= struc.name #><#= p.get_name() #><#= ids
|
||||||
|
#> => PropertyValueRef::<#= type_s #>(self.get_<#=
|
||||||
|
struc.name.to_snake_case() #><#= ids2 #>?.<#=
|
||||||
|
p.name.to_snake_case() #><#
|
||||||
|
if p.modifier.as_ref().map(|s| s == "map").unwrap_or(false) {
|
||||||
|
#>.get(*m)
|
||||||
|
.ok_or_else(|| Error::NotFound("<#= p.name #>", m.to_string()))?<#
|
||||||
|
} else if p.modifier.as_ref().map(|s| s == "array").unwrap_or(false) {
|
||||||
|
#>.iter()<#
|
||||||
|
if p.type_s != "str" { #>.cloned().find(|i| i == m)<#
|
||||||
|
} else { #>.find(|i| *i == m)<# } #>
|
||||||
|
.ok_or_else(|| Error::NotFound("<#= p.name #>", m.to_string()))?<#
|
||||||
|
} else if p.modifier.as_ref().map(|s| s == "set").unwrap_or(false) {
|
||||||
|
#>.get(m)<#
|
||||||
|
if p.type_s != "str" { #>.cloned()<# } #>
|
||||||
|
.ok_or_else(|| Error::NotFound("<#= p.name #>", m.to_string()))?<#
|
||||||
|
}
|
||||||
|
|
||||||
|
if p.opt && (p.type_s == "str" || p.type_s == "Uid") {
|
||||||
|
#>.as_ref().map(|r| r.as_ref())<#
|
||||||
|
} else if p.type_s == "str" || p.type_s == "Uid" || ["TalkPowerRequest", "EccKeyPubP256"].contains(&p.type_s.as_str()) {
|
||||||
|
#>.as_ref()<#
|
||||||
|
} #>),
|
||||||
|
<# }
|
||||||
|
} #>
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
use std::default::Default;
|
||||||
|
|
||||||
|
use t4rust_derive::Template;
|
||||||
|
use tsproto_structs::*;
|
||||||
|
|
||||||
|
#[derive(Template)]
|
||||||
|
#[TemplatePath = "build/BookDeclarations.tt"]
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct BookDeclarations<'a>(pub &'a book::BookDeclarations);
|
||||||
|
|
||||||
|
impl Default for BookDeclarations<'static> {
|
||||||
|
fn default() -> Self { BookDeclarations(&tsproto_structs::book::DATA) }
|
||||||
|
}
|
||||||
+71
@@ -0,0 +1,71 @@
|
|||||||
|
use std::default::Default;
|
||||||
|
use std::ops::Deref;
|
||||||
|
|
||||||
|
use heck::*;
|
||||||
|
use t4rust_derive::Template;
|
||||||
|
use tsproto_structs::book_to_messages::*;
|
||||||
|
use tsproto_structs::messages::Field;
|
||||||
|
use tsproto_structs::*;
|
||||||
|
|
||||||
|
#[derive(Template)]
|
||||||
|
#[TemplatePath = "build/BookToMessages.tt"]
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct BookToMessagesDeclarations<'a>(&'a book_to_messages::BookToMessagesDeclarations<'a>);
|
||||||
|
|
||||||
|
impl<'a> Deref for BookToMessagesDeclarations<'a> {
|
||||||
|
type Target = book_to_messages::BookToMessagesDeclarations<'a>;
|
||||||
|
fn deref(&self) -> &Self::Target { self.0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for BookToMessagesDeclarations<'static> {
|
||||||
|
fn default() -> Self { BookToMessagesDeclarations(&DATA) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_to_list(to: &[&Field]) -> String {
|
||||||
|
let mut res = String::new();
|
||||||
|
if to.len() > 1 {
|
||||||
|
res.push('(');
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut first = true;
|
||||||
|
for t in to {
|
||||||
|
if !first {
|
||||||
|
res.push_str(", ");
|
||||||
|
} else {
|
||||||
|
first = false;
|
||||||
|
}
|
||||||
|
res.push_str(&t.get_rust_name());
|
||||||
|
}
|
||||||
|
|
||||||
|
if to.len() > 1 {
|
||||||
|
res.push(')');
|
||||||
|
}
|
||||||
|
res
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The prefix is written before from, if from is a mapped argument
|
||||||
|
fn rule_has_to(r: &RuleKind, field: &Field) -> bool {
|
||||||
|
match r {
|
||||||
|
RuleKind::Map { to, .. } | RuleKind::ArgumentMap { to, .. } => to == &field,
|
||||||
|
RuleKind::ArgumentFunction { to, .. } | RuleKind::Function { to, .. } => {
|
||||||
|
to.contains(&field)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finds a matching rule in either the event ids or the given rule.
|
||||||
|
fn find_rule<'a>(
|
||||||
|
e: &'a Event, r: Option<&'a RuleKind>, field: &Field,
|
||||||
|
) -> (bool, Option<&'a RuleKind<'a>>) {
|
||||||
|
if let Some(r) = r {
|
||||||
|
if rule_has_to(r, field) {
|
||||||
|
return (true, Some(r));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for r in &e.ids {
|
||||||
|
if rule_has_to(r, field) {
|
||||||
|
return (false, Some(r));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(false, None)
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
use std::env;
|
||||||
|
use std::fs::File;
|
||||||
|
use std::io::prelude::*;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
mod book_parser;
|
||||||
|
mod book_to_messages_parser;
|
||||||
|
mod events;
|
||||||
|
mod message_parser;
|
||||||
|
mod messages_to_book_parser;
|
||||||
|
mod properties;
|
||||||
|
|
||||||
|
use crate::book_parser::BookDeclarations;
|
||||||
|
use crate::book_to_messages_parser::BookToMessagesDeclarations;
|
||||||
|
use crate::events::EventDeclarations;
|
||||||
|
use crate::message_parser::MessageDeclarations;
|
||||||
|
use crate::messages_to_book_parser::MessagesToBookDeclarations;
|
||||||
|
use crate::properties::Properties;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let out_dir = env::var("OUT_DIR").unwrap();
|
||||||
|
|
||||||
|
// Book declarations
|
||||||
|
let path = Path::new(&out_dir);
|
||||||
|
let mut structs = File::create(path.join("structs.rs")).unwrap();
|
||||||
|
write!(&mut structs, "{}", BookDeclarations::default()).unwrap();
|
||||||
|
|
||||||
|
// Messages to book
|
||||||
|
let mut structs = File::create(path.join("m2bdecls.rs")).unwrap();
|
||||||
|
write!(&mut structs, "{}", MessagesToBookDeclarations::default()).unwrap();
|
||||||
|
|
||||||
|
// Write messages
|
||||||
|
let decls = MessageDeclarations::s2c();
|
||||||
|
let mut structs = File::create(path.join("s2c_messages.rs")).unwrap();
|
||||||
|
write!(&mut structs, "{}", MessageDeclarations(&decls)).unwrap();
|
||||||
|
|
||||||
|
let decls = MessageDeclarations::c2s();
|
||||||
|
let mut structs = File::create(path.join("c2s_messages.rs")).unwrap();
|
||||||
|
write!(&mut structs, "{}", MessageDeclarations(&decls)).unwrap();
|
||||||
|
|
||||||
|
// Book to messages
|
||||||
|
let mut structs = File::create(path.join("b2mdecls.rs")).unwrap();
|
||||||
|
write!(&mut structs, "{}", BookToMessagesDeclarations::default()).unwrap();
|
||||||
|
|
||||||
|
// Events
|
||||||
|
let mut structs = File::create(path.join("events.rs")).unwrap();
|
||||||
|
write!(&mut structs, "{}", EventDeclarations::default()).unwrap();
|
||||||
|
|
||||||
|
// Properties
|
||||||
|
let mut structs = File::create(path.join("properties.rs")).unwrap();
|
||||||
|
write!(&mut structs, "{}", Properties::default()).unwrap();
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
use std::collections::HashSet;
|
||||||
|
use std::default::Default;
|
||||||
|
use std::ops::Deref;
|
||||||
|
|
||||||
|
use t4rust_derive::Template;
|
||||||
|
use tsproto_structs::book::*;
|
||||||
|
|
||||||
|
#[derive(Template)]
|
||||||
|
#[TemplatePath = "build/Events.tt"]
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct EventDeclarations<'a>(&'a BookDeclarations);
|
||||||
|
|
||||||
|
impl<'a> Deref for EventDeclarations<'a> {
|
||||||
|
type Target = BookDeclarations;
|
||||||
|
fn deref(&self) -> &Self::Target { self.0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for EventDeclarations<'static> {
|
||||||
|
fn default() -> Self { EventDeclarations(&DATA) }
|
||||||
|
}
|
||||||
@@ -0,0 +1,299 @@
|
|||||||
|
use std::default::Default;
|
||||||
|
|
||||||
|
use itertools::Itertools;
|
||||||
|
use t4rust_derive::Template;
|
||||||
|
use tsproto_structs::messages::*;
|
||||||
|
use tsproto_structs::{indent, messages, InnerRustType, RustType};
|
||||||
|
|
||||||
|
#[derive(Template)]
|
||||||
|
#[TemplatePath = "build/MessageDeclarations.tt"]
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct MessageDeclarations<'a>(pub &'a messages::MessageDeclarations);
|
||||||
|
|
||||||
|
impl MessageDeclarations<'static> {
|
||||||
|
pub fn s2c() -> messages::MessageDeclarations {
|
||||||
|
let mut res = DATA.clone();
|
||||||
|
res.msg_group.retain(|g| g.default.s2c);
|
||||||
|
res
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn c2s() -> messages::MessageDeclarations {
|
||||||
|
let mut res = DATA.clone();
|
||||||
|
res.msg_group.retain(|g| g.default.c2s);
|
||||||
|
res
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for MessageDeclarations<'static> {
|
||||||
|
fn default() -> Self { MessageDeclarations(&DATA) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn generate_deserializer(field: &Field) -> String {
|
||||||
|
let rust_type = field.get_type("").unwrap();
|
||||||
|
if let InnerRustType::Vec(inner) = rust_type.inner {
|
||||||
|
vector_value_deserializer(field, (*inner).into())
|
||||||
|
} else {
|
||||||
|
single_value_deserializer(field, &rust_type.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn single_value_deserializer(field: &Field, rust_type: &str) -> String {
|
||||||
|
let res = match rust_type {
|
||||||
|
"i8" | "u8" | "i16" | "u16" | "i32" | "u32" | "i64" | "u64" => format!(
|
||||||
|
"val.parse().map_err(|e| ParseError::ParseInt {{
|
||||||
|
arg: \"{}\",
|
||||||
|
value: val.to_string(),
|
||||||
|
source: e,
|
||||||
|
}})?",
|
||||||
|
field.pretty
|
||||||
|
),
|
||||||
|
"f32" | "f64" => format!(
|
||||||
|
"val.parse().map_err(|e| ParseError::ParseFloat {{
|
||||||
|
arg: \"{}\",
|
||||||
|
value: val.to_string(),
|
||||||
|
source: e,
|
||||||
|
}})?",
|
||||||
|
field.pretty
|
||||||
|
),
|
||||||
|
"bool" => format!(
|
||||||
|
"match val {{ \"0\" => false, \"1\" => true, _ => return Err(ParseError::ParseBool {{
|
||||||
|
arg: \"{}\",
|
||||||
|
value: val.to_string(),
|
||||||
|
}}), }}",
|
||||||
|
field.pretty
|
||||||
|
),
|
||||||
|
"UidBuf" => "UidBuf(if let Ok(uid) = BASE64_STANDARD.decode(val) { uid } else { \
|
||||||
|
val.as_bytes().to_vec() })"
|
||||||
|
.into(),
|
||||||
|
"&str" => "val".into(),
|
||||||
|
"String" => "val.to_string()".into(),
|
||||||
|
"IconId" => format!(
|
||||||
|
"IconId(if val.starts_with('-') {{
|
||||||
|
val.parse::<i32>().map(|i| i as u32)
|
||||||
|
}} else {{
|
||||||
|
val.parse::<u64>().map(|i| i as u32)
|
||||||
|
}}.map_err(|e| ParseError::ParseInt {{
|
||||||
|
arg: \"{}\",
|
||||||
|
value: val.to_string(),
|
||||||
|
source: e,
|
||||||
|
}})?)",
|
||||||
|
field.pretty
|
||||||
|
),
|
||||||
|
"ClientId" | "ClientDbId" | "ChannelId" | "ServerGroupId" | "ChannelGroupId" => format!(
|
||||||
|
"{}(val.parse().map_err(|e| ParseError::ParseInt {{
|
||||||
|
arg: \"{}\",
|
||||||
|
value: val.to_string(),
|
||||||
|
source: e,
|
||||||
|
}})?)",
|
||||||
|
rust_type, field.pretty
|
||||||
|
),
|
||||||
|
"IpAddr" | "SocketAddr" => format!(
|
||||||
|
"val.parse().map_err(|e| ParseError::ParseAddr {{
|
||||||
|
arg: \"{}\",
|
||||||
|
value: val.to_string(),
|
||||||
|
source: e,
|
||||||
|
}})?",
|
||||||
|
field.pretty
|
||||||
|
),
|
||||||
|
"ClientType" => format!(
|
||||||
|
"match val {{
|
||||||
|
\"0\" => ClientType::Normal,
|
||||||
|
\"1\" => ClientType::Query {{ admin: false }},
|
||||||
|
_ => return Err(ParseError::InvalidValue {{
|
||||||
|
arg: \"{}\",
|
||||||
|
value: val.to_string(),
|
||||||
|
}}),
|
||||||
|
}}",
|
||||||
|
field.pretty
|
||||||
|
),
|
||||||
|
"TextMessageTargetMode"
|
||||||
|
| "HostMessageMode"
|
||||||
|
| "HostBannerMode"
|
||||||
|
| "LicenseType"
|
||||||
|
| "LogLevel"
|
||||||
|
| "Codec"
|
||||||
|
| "CodecEncryptionMode"
|
||||||
|
| "Reason"
|
||||||
|
| "GroupNamingMode"
|
||||||
|
| "GroupType"
|
||||||
|
| "Permission"
|
||||||
|
| "PermissionType"
|
||||||
|
| "TokenType"
|
||||||
|
| "PluginTargetMode"
|
||||||
|
| "Error" => format!(
|
||||||
|
"{}::from_u32(val.parse().map_err(|e| ParseError::ParseInt {{
|
||||||
|
arg: \"{}\",
|
||||||
|
value: val.to_string(),
|
||||||
|
source: e,
|
||||||
|
}})?).ok_or(ParseError::InvalidValue {{
|
||||||
|
arg: \"{1}\",
|
||||||
|
value: val.to_string(),
|
||||||
|
}})?",
|
||||||
|
rust_type, field.pretty
|
||||||
|
),
|
||||||
|
"ChannelPermissionHint" | "ClientPermissionHint" => format!(
|
||||||
|
"{}::from_bits(val.parse().map_err(|e| ParseError::ParseInt {{
|
||||||
|
arg: \"{}\",
|
||||||
|
value: val.to_string(),
|
||||||
|
source: e,
|
||||||
|
}})?).ok_or(ParseError::InvalidValue {{
|
||||||
|
arg: \"{1}\",
|
||||||
|
value: val.to_string(),
|
||||||
|
}})?",
|
||||||
|
rust_type, field.pretty
|
||||||
|
),
|
||||||
|
"Duration" => {
|
||||||
|
if field.type_s == "DurationSeconds" {
|
||||||
|
format!(
|
||||||
|
"let val = val.parse::<i64>().map_err(|e| ParseError::ParseInt {{
|
||||||
|
arg: \"{}\",
|
||||||
|
value: val.to_string(),
|
||||||
|
source: e,
|
||||||
|
}})?;
|
||||||
|
if val.checked_mul(1000).is_some() {{ Duration::seconds(val) }}
|
||||||
|
else {{ return Err(ParseError::InvalidValue {{
|
||||||
|
arg: \"{0}\",
|
||||||
|
value: val.to_string(),
|
||||||
|
}}); }}",
|
||||||
|
field.pretty
|
||||||
|
)
|
||||||
|
} else if field.type_s == "DurationMilliseconds" {
|
||||||
|
format!(
|
||||||
|
"Duration::milliseconds(val.parse::<i64>().map_err(|e| ParseError::ParseInt \
|
||||||
|
{{
|
||||||
|
arg: \"{}\",
|
||||||
|
value: val.to_string(),
|
||||||
|
source: e,
|
||||||
|
}})?)",
|
||||||
|
field.pretty
|
||||||
|
)
|
||||||
|
} else if field.type_s == "DurationMillisecondsFloat" {
|
||||||
|
format!(
|
||||||
|
"Duration::microseconds((1000.0 * val.parse::<f32>().map_err(|e| \
|
||||||
|
ParseError::ParseFloat {{
|
||||||
|
arg: \"{}\",
|
||||||
|
value: val.to_string(),
|
||||||
|
source: e,
|
||||||
|
}})?) as i64)",
|
||||||
|
field.pretty
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
panic!("Unknown original time type {} found.", field.type_s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"OffsetDateTime" => format!(
|
||||||
|
"OffsetDateTime::from_unix_timestamp(
|
||||||
|
val.parse().map_err(|e| ParseError::ParseInt {{
|
||||||
|
arg: \"{}\",
|
||||||
|
value: val.to_string(),
|
||||||
|
source: e,
|
||||||
|
}})?).map_err(|e| ParseError::ParseDate {{
|
||||||
|
arg: \"{}\",
|
||||||
|
value: val.to_string(),
|
||||||
|
source: e,
|
||||||
|
}})?",
|
||||||
|
field.pretty, field.pretty
|
||||||
|
),
|
||||||
|
_ => panic!("Unknown type '{}' when trying to deserialize {:?}", rust_type, field),
|
||||||
|
};
|
||||||
|
if res.contains('\n') { indent(&res, 2) } else { res }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn vector_value_deserializer(field: &Field, rust_type: RustType) -> String {
|
||||||
|
format!(
|
||||||
|
"val.split(',')
|
||||||
|
.filter_map(|val| {{
|
||||||
|
let val = val.trim();
|
||||||
|
if val.is_empty() {{
|
||||||
|
None
|
||||||
|
}} else {{
|
||||||
|
Some(val)
|
||||||
|
}}
|
||||||
|
}}).map(|val| {{
|
||||||
|
let val = val.trim();
|
||||||
|
Ok({})
|
||||||
|
}}).collect::<Result<Vec<{}>>>()?",
|
||||||
|
single_value_deserializer(field, &rust_type.to_string()),
|
||||||
|
rust_type,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn generate_serializer(field: &Field, name: &str) -> String {
|
||||||
|
let rust_type = field.get_type("").unwrap();
|
||||||
|
if let InnerRustType::Vec(inner) = rust_type.inner {
|
||||||
|
let inner_type: RustType = (*inner).into();
|
||||||
|
vector_value_serializer(field, &inner_type.to_string(), name)
|
||||||
|
} else {
|
||||||
|
single_value_serializer(field, &rust_type.to_string(), name, false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn single_value_serializer(field: &Field, rust_type: &str, name: &str, is_ref: bool) -> String {
|
||||||
|
let ref_amp = if is_ref { "" } else { "&" };
|
||||||
|
let ref_star = if is_ref { "*" } else { "" };
|
||||||
|
match rust_type {
|
||||||
|
"i8" | "u8" | "i16" | "u16" | "i32" | "u32" | "i64" | "u64" | "f32" | "f64" | "String"
|
||||||
|
| "IpAddr" | "SocketAddr" => format!("{}{}", ref_amp, name),
|
||||||
|
"bool" => format!("if {}{} {{ &\"1\" }} else {{ &\"0\" }}", ref_star, name),
|
||||||
|
"&str" => name.to_string(),
|
||||||
|
"UidBuf" | "&Uid" => format!(
|
||||||
|
"&if {0}.is_server_admin() {{ Cow::Borrowed(\"ServerAdmin\") }}
|
||||||
|
else {{ Cow::<str>::Owned(BASE64_STANDARD.encode(&{0}.0)) }}",
|
||||||
|
name,
|
||||||
|
),
|
||||||
|
"ClientId" | "ClientDbId" | "ChannelId" | "ServerGroupId" | "ChannelGroupId" | "IconId" => {
|
||||||
|
format!("&{}.0", name)
|
||||||
|
}
|
||||||
|
"ClientType" => format!(
|
||||||
|
"match {} {{
|
||||||
|
ClientType::Normal => &\"0\",
|
||||||
|
ClientType::Query {{ .. }} => &\"1\",
|
||||||
|
}}",
|
||||||
|
name
|
||||||
|
),
|
||||||
|
"TextMessageTargetMode"
|
||||||
|
| "HostMessageMode"
|
||||||
|
| "HostBannerMode"
|
||||||
|
| "LicenseType"
|
||||||
|
| "LogLevel"
|
||||||
|
| "Codec"
|
||||||
|
| "CodecEncryptionMode"
|
||||||
|
| "Reason"
|
||||||
|
| "GroupNamingMode"
|
||||||
|
| "GroupType"
|
||||||
|
| "Permission"
|
||||||
|
| "PermissionType"
|
||||||
|
| "TokenType"
|
||||||
|
| "PluginTargetMode"
|
||||||
|
| "Error" => format!("&{}.to_u32().unwrap()", name),
|
||||||
|
"ChannelPermissionHint" | "ClientPermissionHint" => format!("&{}.bits()", name),
|
||||||
|
"Duration" => {
|
||||||
|
if field.type_s == "DurationSeconds" {
|
||||||
|
format!("&{}.whole_seconds()", name)
|
||||||
|
} else if field.type_s == "DurationMilliseconds" {
|
||||||
|
format!("&{}.whole_milliseconds()", name)
|
||||||
|
} else if field.type_s == "DurationMillisecondsFloat" {
|
||||||
|
format!("&({}.whole_microseconds() as f32 / 1000.0)", name)
|
||||||
|
} else {
|
||||||
|
panic!("Unknown original time type {} found.", field.type_s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"OffsetDateTime" => format!("&{}.unix_timestamp()", name),
|
||||||
|
_ => panic!("Unknown type '{}'", rust_type),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn vector_value_serializer(field: &Field, inner_type: &str, name: &str) -> String {
|
||||||
|
// TODO Vector serialization creates an intermediate string which is not necessary
|
||||||
|
format!(
|
||||||
|
"&{{ let mut s = String::new();
|
||||||
|
for val in {}.as_ref() {{
|
||||||
|
if !s.is_empty() {{ s += \",\" }}
|
||||||
|
write!(&mut s, \"{{}}\", {}).unwrap();
|
||||||
|
}}
|
||||||
|
s
|
||||||
|
}}",
|
||||||
|
name,
|
||||||
|
single_value_serializer(field, inner_type, "val", true)
|
||||||
|
)
|
||||||
|
}
|
||||||
+28
@@ -0,0 +1,28 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
|
use std::default::Default;
|
||||||
|
use std::ops::Deref;
|
||||||
|
|
||||||
|
use heck::*;
|
||||||
|
use t4rust_derive::Template;
|
||||||
|
use tsproto_structs::book::{PropId, Property};
|
||||||
|
use tsproto_structs::messages::Field;
|
||||||
|
use tsproto_structs::messages_to_book::*;
|
||||||
|
use tsproto_structs::*;
|
||||||
|
|
||||||
|
#[derive(Template)]
|
||||||
|
#[TemplatePath = "build/MessagesToBook.tt"]
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct MessagesToBookDeclarations<'a>(&'a messages_to_book::MessagesToBookDeclarations<'a>);
|
||||||
|
|
||||||
|
impl<'a> Deref for MessagesToBookDeclarations<'a> {
|
||||||
|
type Target = messages_to_book::MessagesToBookDeclarations<'a>;
|
||||||
|
fn deref(&self) -> &Self::Target { self.0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for MessagesToBookDeclarations<'static> {
|
||||||
|
fn default() -> Self { MessagesToBookDeclarations(&DATA) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_property(p: &Property, name: &str) -> String {
|
||||||
|
format!("PropertyValue::{}({})", p.get_inner_type_as_name().unwrap(), name)
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
//! Access properties of a connection with the property structs from events.
|
||||||
|
use std::default::Default;
|
||||||
|
use std::fmt::Write;
|
||||||
|
|
||||||
|
use heck::*;
|
||||||
|
use t4rust_derive::Template;
|
||||||
|
use tsproto_structs::book::*;
|
||||||
|
use tsproto_structs::embrace;
|
||||||
|
|
||||||
|
#[derive(Template)]
|
||||||
|
#[TemplatePath = "build/Properties.tt"]
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Properties<'a>(&'a BookDeclarations);
|
||||||
|
|
||||||
|
impl Default for Properties<'static> {
|
||||||
|
fn default() -> Self { Properties(&DATA) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_ids(struc: &Struct) -> String {
|
||||||
|
let mut res = String::new();
|
||||||
|
for i in 0..struc.id.len() {
|
||||||
|
if !res.is_empty() {
|
||||||
|
res.push_str(", ");
|
||||||
|
}
|
||||||
|
let _ = write!(res, "s{}", i);
|
||||||
|
}
|
||||||
|
res
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_ids2(structs: &[Struct], struc: &Struct) -> String {
|
||||||
|
let mut res = String::new();
|
||||||
|
for (i, id) in struc.id.iter().enumerate() {
|
||||||
|
let p = id.find_property(structs);
|
||||||
|
if !res.is_empty() {
|
||||||
|
res.push_str(", ");
|
||||||
|
}
|
||||||
|
if p.type_s != "str" {
|
||||||
|
res.push('*');
|
||||||
|
}
|
||||||
|
let _ = write!(res, "s{}", i);
|
||||||
|
}
|
||||||
|
res
|
||||||
|
}
|
||||||
Loaded 100 of 247 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user