Unmodified copy of the tsclientlib workspace crates (MIT OR Apache-2.0)
with the tsdeclarations submodule (83cb8a9) flattened into plain files.
See crates/proto/UPSTREAM.md for the path mapping.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-25 12:46:11 +00:00
commit 7b6959c4cc
119 files changed
+24322

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
version = "Two"
edition = "2018"
newline_style = "Unix"
hard_tabs = true
use_small_heuristics = "Max"
use_try_shorthand = true
# Unstable
where_single_line = true
fn_params_layout = "Compressed"
fn_single_line = true
format_strings = true
overflow_delimited_expr = true
+61
View File
@@ -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
+201
View File
@@ -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
View File
@@ -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.
+115
View File
@@ -0,0 +1,115 @@
# TsClientlib [![Build status](https://ci.appveyor.com/api/projects/status/ylne3ku7265xa22j/branch/master?svg=true)](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.
+33
View File
@@ -0,0 +1,33 @@
# Vendored upstream: ReSpeak/tsclientlib
The crates in this directory are a vendored fork of
[ReSpeak/tsclientlib](https://github.com/ReSpeak/tsclientlib), licensed
`MIT OR Apache-2.0` (see `LICENSE-MIT` and `LICENSE-APACHE` in this directory).
| Item | Source |
|---|---|
| tsclientlib | `ee3bc6f45a7137db7793ba5593a321df400d53e5` (master) |
| `tsproto-structs/declarations` (was a git submodule) | [ReSpeak/tsdeclarations](https://github.com/ReSpeak/tsdeclarations) `83cb8a94b65021bb8ec4beb339e5bfbdd93df60f` (MIT OR Apache-2.0, own `LICENSE-*` kept inside the directory) |
## Layout mapping
| Upstream path | Here |
|---|---|
| `tsclientlib/` | `crates/proto/tsclientlib/` |
| `tsproto/` | `crates/proto/tsproto/` |
| `utils/ts-bookkeeping/` | `crates/proto/ts-bookkeeping/` |
| `utils/tsproto-packets/` | `crates/proto/tsproto-packets/` |
| `utils/tsproto-structs/` | `crates/proto/tsproto-structs/` (submodule flattened into plain files) |
| `utils/tsproto-types/` | `crates/proto/tsproto-types/` |
| `README.md`, `CHANGELOG.md`, `.rustfmt.toml`, `clippy.toml` | `crates/proto/README.upstream.md`, `CHANGELOG.md`, `.rustfmt.toml`, `clippy.toml` |
Not vendored: `.appveyor/`, `tools/measure-latency.sh`, `tslientlib.code-workspace`,
the upstream root `Cargo.toml` (replaced by this repository's workspace).
## Local patches
The import commit contains the upstream files unmodified. Every later change to
files in this directory is listed here, newest last, so it can be diffed
against or offered back to upstream.
<!-- patches -->
+1
View File
@@ -0,0 +1 @@
doc-valid-idents = ["MiB", "GiB", "TiB", "PiB", "EiB", "TeamSpeak", "TeamSpeak3", "PRIME256v1"]
+44
View File
@@ -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
+21
View File
@@ -0,0 +1,21 @@
# ts-bookkeeping [![docs.rs](https://docs.rs/ts-bookkeeping/badge.svg)](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.
+10
View File
@@ -0,0 +1,10 @@
# ts-bookkeeping [![docs.rs](https://docs.rs/ts-bookkeeping/badge.svg)](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) }
}
@@ -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)
)
}
@@ -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
}
File diff suppressed because it is too large. Load diff
+79
View File
@@ -0,0 +1,79 @@
use serde::{Deserialize, Serialize};
use time::{Duration, OffsetDateTime};
use tsproto_types::crypto::EccKeyPubP256;
use crate::data::{
Channel, ChannelGroup, Client, Connection, ConnectionClientData, ConnectionServerData,
OptionalChannelData, OptionalClientData, OptionalServerData, Server, ServerGroup,
};
use crate::*;
include!(concat!(env!("OUT_DIR"), "/events.rs"));
/// Additional data for some events.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct ExtraInfo {
/// Set for e.g. new clients to distinguish if they joined or are made available because we
/// subscribed to a channel.
pub reason: Option<Reason>,
}
/// An event gets fired when something in the data structure of a connection
/// changes or something happens like we receive a text message or get poked.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub enum Event {
/// The object with this id was added.
///
/// You can find the new object inside the connection data structure.
///
/// Like a client gets assigned a new server group or a new client joins the
/// server.
PropertyAdded { id: PropertyId, invoker: Option<Invoker>, extra: ExtraInfo },
/// The attribute with this id has changed.
///
/// The second tuple item holds the old value of the changed attribute.
///
/// E.g. a client changes its nickname or switches to another channel.
PropertyChanged {
id: PropertyId,
old: PropertyValue,
invoker: Option<Invoker>,
extra: ExtraInfo,
},
/// The object with this id was removed.
///
/// The object is not accessible anymore in the connection data structure,
/// but the second tuple item holds the removed object.
///
/// This happens when a client leaves the server (including our own client)
/// or a channel is removed.
PropertyRemoved {
id: PropertyId,
old: PropertyValue,
invoker: Option<Invoker>,
extra: ExtraInfo,
},
Message {
/// Where this message was sent to, in the server or channel chat or
/// directly to client.
///
/// This is our own client for private messages from others.
target: MessageTarget,
/// The user who wrote the message.
invoker: Invoker,
/// The content of the message.
message: String,
},
}
impl Event {
pub fn get_invoker(&self) -> Option<&Invoker> {
match self {
Event::PropertyAdded { invoker, .. }
| Event::PropertyChanged { invoker, .. }
| Event::PropertyRemoved { invoker, .. } => invoker.as_ref(),
Event::Message { invoker, .. } => Some(invoker),
}
}
}
+246
View File
@@ -0,0 +1,246 @@
//! `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.
use std::fmt;
use std::net::{IpAddr, SocketAddr};
use serde::{Deserialize, Serialize};
use thiserror::Error;
pub mod data;
pub mod events;
pub mod messages;
// Reexports
pub use tsproto_types::errors::Error as TsError;
pub use tsproto_types::versions::Version;
pub use tsproto_types::{
ChannelGroupId, ChannelId, ChannelPermissionHint, ChannelType, ClientDbId, ClientId,
ClientPermissionHint, ClientType, Codec, CodecEncryptionMode, GroupNamingMode, GroupType,
HostBannerMode, HostMessageMode, IconId, Invoker, InvokerRef, LicenseType, LogLevel,
MaxClients, Permission, PermissionType, PluginTargetMode, Reason, ServerGroupId,
TalkPowerRequest, TextMessageTargetMode, TokenType, Uid, UidBuf,
};
type Result<T> = std::result::Result<T, Error>;
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
#[error("Target client id missing for a client text message")]
MessageWithoutTargetClientId,
#[error("Unknown TextMessageTargetMode")]
UnknownTextMessageTargetMode,
#[error("{0} {1} not found")]
NotFound(&'static str, String),
#[error("{0} should be removed but does not exist")]
RemoveNotFound(&'static str),
#[error("Failed to parse connection ip: {0}")]
InvalidConnectionIp(#[source] std::net::AddrParseError),
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum ServerAddress {
SocketAddr(SocketAddr),
Other(String),
}
impl From<SocketAddr> for ServerAddress {
fn from(addr: SocketAddr) -> Self { ServerAddress::SocketAddr(addr) }
}
impl From<String> for ServerAddress {
fn from(addr: String) -> Self { ServerAddress::Other(addr) }
}
impl<'a> From<&'a str> for ServerAddress {
fn from(addr: &'a str) -> Self { ServerAddress::Other(addr.to_string()) }
}
impl fmt::Display for ServerAddress {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ServerAddress::SocketAddr(a) => fmt::Display::fmt(a, f),
ServerAddress::Other(a) => fmt::Display::fmt(a, f),
}
}
}
/// All possible targets to send messages.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum MessageTarget {
Server,
Channel,
Client(ClientId),
Poke(ClientId),
}
/// The configuration to create a new connection.
#[derive(Deserialize, Serialize)]
pub struct ConnectOptions {
address: ServerAddress,
local_address: Option<SocketAddr>,
name: String,
version: Version,
log_commands: bool,
log_packets: bool,
log_udp_packets: bool,
}
impl ConnectOptions {
/// Start creating the configuration of a new connection.
///
/// # Arguments
/// The address of the server has to be supplied. The address can be a
/// [`SocketAddr`](std::net::SocketAddr), a string or directly a [`ServerAddress`]. A string
/// will automatically be resolved from all formats supported by TeamSpeak.
/// For details, see [`resolver::resolve`].
#[inline]
pub fn new<A: Into<ServerAddress>>(address: A) -> Self {
Self {
address: address.into(),
local_address: None,
name: String::from("TeamSpeakUser"),
version: Version::Linux_3_2_1,
log_commands: false,
log_packets: false,
log_udp_packets: false,
}
}
/// The address for the socket of our client
///
/// # Default
/// The default is `0.0.0:0` when connecting to an IPv4 address and `[::]:0`
/// when connecting to an IPv6 address.
#[inline]
pub fn local_address(mut self, local_address: SocketAddr) -> Self {
self.local_address = Some(local_address);
self
}
/// The name of the user.
///
/// # Default
/// `TeamSpeakUser`
#[inline]
pub fn name(mut self, name: String) -> Self {
self.name = name;
self
}
/// The displayed version of the client.
///
/// # Default
/// `3.2.1 on Linux`
#[inline]
pub fn version(mut self, version: Version) -> Self {
self.version = version;
self
}
/// If the content of all commands should be written to the logger.
///
/// # Default
/// `false`
#[inline]
pub fn log_commands(mut self, log_commands: bool) -> Self {
self.log_commands = log_commands;
self
}
/// If the content of all packets in high-level form should be written to
/// the logger.
///
/// # Default
/// `false`
#[inline]
pub fn log_packets(mut self, log_packets: bool) -> Self {
self.log_packets = log_packets;
self
}
/// If the content of all udp packets in byte-array form should be written
/// to the logger.
///
/// # Default
/// `false`
#[inline]
pub fn log_udp_packets(mut self, log_udp_packets: bool) -> Self {
self.log_udp_packets = log_udp_packets;
self
}
}
impl fmt::Debug for ConnectOptions {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Error if attributes are added
let ConnectOptions {
address,
local_address,
name,
version,
log_commands,
log_packets,
log_udp_packets,
} = self;
write!(
f,
"ConnectOptions {{ address: {:?}, local_address: {:?}, name: {}, version: {}, \
log_commands: {}, log_packets: {}, log_udp_packets: {} }}",
address, local_address, name, version, log_commands, log_packets, log_udp_packets,
)?;
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct DisconnectOptions {
reason: Option<Reason>,
message: Option<String>,
}
impl Default for DisconnectOptions {
#[inline]
fn default() -> Self { Self { reason: None, message: None } }
}
impl DisconnectOptions {
#[inline]
pub fn new() -> Self { Self::default() }
/// Set the reason for leaving.
///
/// # Default
///
/// None
#[inline]
pub fn reason(mut self, reason: Reason) -> Self {
self.reason = Some(reason);
self
}
/// Set the leave message.
///
/// You also have to set the reason, otherwise the message will not be
/// displayed.
///
/// # Default
///
/// None
#[inline]
pub fn message<S: Into<String>>(mut self, message: S) -> Self {
self.message = Some(message.into());
self
}
}
@@ -0,0 +1,80 @@
use std::net::IpAddr;
use thiserror::Error;
use time::{Duration, OffsetDateTime};
use tsproto_packets::commands::CommandParser;
use tsproto_packets::packets::{Direction, InHeader, OutCommand, PacketType};
use tsproto_types::errors::Error;
use crate::*;
type Result<T> = std::result::Result<T, ParseError>;
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum ParseError {
#[error(transparent)]
Base64(#[from] base64::DecodeError),
#[error("Parameter {arg} not found in {name}")]
ParameterNotFound { arg: &'static str, name: &'static str },
#[error("Parameter {arg} not found in {name}")]
ParameterNotFound2 { arg: String, name: String },
#[error("Command {0} is unknown")]
UnknownCommand(String),
#[error(transparent)]
StringParse(#[from] std::str::Utf8Error),
#[error(transparent)]
TsProto(#[from] tsproto_packets::Error),
/// Gets thrown when parsing a specific command with the wrong input.
#[error("Command {0} is wrong")]
WrongCommand(String),
#[error("Wrong newprotocol flag ({0})")]
WrongNewprotocol(bool),
#[error("Wrong packet type {0:?}")]
WrongPacketType(PacketType),
#[error("Wrong direction {0:?}")]
WrongDirection(Direction),
#[error("Cannot parse \"{value}\" as int for parameter {arg} ({source})")]
ParseInt { arg: &'static str, value: String, source: std::num::ParseIntError },
#[error("Cannot parse \"{value}\" as SocketAddr for parameter {arg} ({source})")]
ParseAddr { arg: &'static str, value: String, source: std::net::AddrParseError },
#[error("Cannot parse \"{value}\" as float for parameter {arg} ({source})")]
ParseFloat { arg: &'static str, value: String, source: std::num::ParseFloatError },
#[error("Cannot parse \"{value}\" as bool for parameter {arg}")]
ParseBool { arg: &'static str, value: String },
#[error("Cannot parse \"{value}\" as SocketAddr for parameter {arg} ({source})")]
ParseUid { arg: &'static str, value: String, source: base64::DecodeError },
#[error("Cannot parse \"{value}\" as DateTimeOffset for parameter {arg} ({source})")]
ParseDate { arg: &'static str, value: String, source: time::error::ComponentRange },
#[error("Invalid value \"{value}\" for parameter {arg}")]
InvalidValue { arg: &'static str, value: String },
}
pub trait InMessageTrait {
fn new(header: &InHeader, args: CommandParser) -> Result<Self>
where Self: Sized;
}
pub trait OutMessageTrait {
fn to_packet(self) -> OutCommand;
}
pub trait OutMessageWithReturnTrait {
fn to_packet(self, return_code: Option<&str>) -> OutCommand;
}
impl OutMessageTrait for OutCommand {
fn to_packet(self) -> OutCommand { self }
}
pub mod s2c {
#![allow(mismatched_lifetime_syntaxes)]
use super::*;
include!(concat!(env!("OUT_DIR"), "/s2c_messages.rs"));
}
pub mod c2s {
#![allow(mismatched_lifetime_syntaxes)]
use super::*;
include!(concat!(env!("OUT_DIR"), "/c2s_messages.rs"));
}
+64
View File
@@ -0,0 +1,64 @@
[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"]
# 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
View File
@@ -0,0 +1,21 @@
# TsClientlib [![docs.rs](https://docs.rs/tsclientlib/badge.svg)](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.
+10
View File
@@ -0,0 +1,10 @@
# TsClientlib [![docs.rs](https://docs.rs/tsclientlib/badge.svg)](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(())
}
+127
View File
@@ -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(())
}
+86
View File
@@ -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()
}
+77
View File
@@ -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
View File
@@ -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)
}
}
File diff suppressed because it is too large. Load diff
+4
View File
@@ -0,0 +1,4 @@
pub use ts_bookkeeping::data::exts::*;
pub use ts_bookkeeping::messages::OutMessageTrait;
pub use crate::OutCommandExt as _;
+514
View File
@@ -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
View File
@@ -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(feature = "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(feature = "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(feature = "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)?
}
}
+37
View File
@@ -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); }
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "tsproto-packets"
version = "0.1.0"
authors = ["Flakebi <flakebi@t-online.de>"]
description = "Parse and serialize TeamSpeak packets and commands."
repository = "https://github.com/ReSpeak/tsclientlib/tree/master/utils/tsproto-packets"
readme = "README.md"
keywords = ["teamspeak3", "ts3"]
license = "MIT OR Apache-2.0"
edition = "2018"
include = [
"/Cargo.toml",
"/README.md",
"/src/*.rs",
]
[dependencies]
base64 = "0.22"
bitflags = "2"
num-derive = "0.4"
num-traits = "0.2"
omnom = "3"
self_cell = "1"
serde = { version = "1", features = ["derive"] }
thiserror = "2"
+10
View File
@@ -0,0 +1,10 @@
# tsproto-packets [![docs.rs](https://docs.rs/tsproto-packets/badge.svg)](https://docs.rs/tsproto-packets)
`tsproto-packets` parses and serializes TeamSpeak packets and commands.
## License
Licensed under either of
* [Apache License, Version 2.0](../../LICENSE-APACHE)
* [MIT license](../../LICENSE-MIT)
at your option.
+10
View File
@@ -0,0 +1,10 @@
# tsproto-packets [![docs.rs](https://docs.rs/tsproto-packets/badge.svg)](https://docs.rs/tsproto-packets)
{{readme}}
## License
Licensed under either of
* [Apache License, Version 2.0](../../LICENSE-APACHE)
* [MIT license](../../LICENSE-MIT)
at your option.
@@ -0,0 +1,293 @@
use std::borrow::Cow;
use std::str::{self, FromStr};
use crate::{Error, Result};
/// Parses arguments of a command.
#[derive(Clone, Debug)]
pub struct CommandParser<'a> {
data: &'a [u8],
index: usize,
}
#[derive(Clone, Debug)]
pub enum CommandItem<'a> {
Argument(CommandArgument<'a>),
/// Pipe symbol marking the start of the next command.
NextCommand,
}
#[derive(Clone, Debug)]
pub struct CommandArgument<'a> {
name: &'a [u8],
value: CommandArgumentValue<'a>,
}
#[derive(Clone, Debug)]
pub struct CommandArgumentValue<'a> {
raw: &'a [u8],
/// The number of escape sequences in this value.
escapes: usize,
}
impl<'a> CommandParser<'a> {
/// Returns the name and arguments of the given command.
#[inline]
pub fn new(data: &'a [u8]) -> (&'a [u8], Self) {
let mut name_end = 0;
while name_end < data.len() {
if !data[name_end].is_ascii_alphanumeric() {
if data[name_end] == b' ' {
break;
}
// Not a command name
name_end = 0;
break;
}
name_end += 1;
}
(&data[..name_end], Self { data, index: name_end })
}
fn cur(&self) -> u8 { self.data[self.index] }
fn cur_in(&self, cs: &[u8]) -> bool { cs.contains(&self.cur()) }
/// Advance
fn adv(&mut self) { self.index += 1; }
fn at_end(&self) -> bool { self.index >= self.data.len() }
fn skip_space(&mut self) {
while !self.at_end() && self.cur_in(b"\x0b\x0c\t\r\n ") {
self.adv();
}
}
}
impl<'a> Iterator for CommandParser<'a> {
type Item = CommandItem<'a>;
fn next(&mut self) -> Option<Self::Item> {
self.skip_space();
if self.at_end() {
return None;
}
if self.cur() == b'|' {
self.adv();
return Some(CommandItem::NextCommand);
}
let name_start = self.index;
while !self.at_end() && !self.cur_in(b" =|") {
self.adv();
}
let name_end = self.index;
if self.at_end() || self.cur() != b'=' {
return Some(CommandItem::Argument(CommandArgument {
name: &self.data[name_start..name_end],
value: CommandArgumentValue { raw: &[], escapes: 0 },
}));
}
self.adv();
let value_start = self.index;
let mut escapes = 0;
while !self.at_end() {
if self.cur_in(b"\x0b\x0c\t\r\n| ") {
break;
}
if self.cur() == b'\\' {
escapes += 1;
self.adv();
if self.at_end() || self.cur_in(b"\x0b\x0c\t\r\n| ") {
break;
}
}
self.adv();
}
let value_end = self.index;
Some(CommandItem::Argument(CommandArgument {
name: &self.data[name_start..name_end],
value: CommandArgumentValue { raw: &self.data[value_start..value_end], escapes },
}))
}
}
impl<'a> CommandArgument<'a> {
#[inline]
pub fn name(&self) -> &'a [u8] { self.name }
#[inline]
pub fn value(&self) -> &CommandArgumentValue<'a> { &self.value }
}
impl<'a> CommandArgumentValue<'a> {
fn unescape(&self) -> Vec<u8> {
let mut res = Vec::with_capacity(self.raw.len() - self.escapes);
let mut i = 0;
while i < self.raw.len() {
if self.raw[i] == b'\\' {
i += 1;
if i == self.raw.len() {
return res;
}
res.push(match self.raw[i] {
b'v' => b'\x0b',
b'f' => b'\x0c',
b't' => b'\t',
b'r' => b'\r',
b'n' => b'\n',
b'p' => b'|',
b's' => b' ',
c => c,
});
} else {
res.push(self.raw[i]);
}
i += 1;
}
res
}
#[inline]
pub fn get_raw(&self) -> &'a [u8] { self.raw }
#[inline]
pub fn get(&self) -> Cow<'a, [u8]> {
if self.escapes == 0 { Cow::Borrowed(self.raw) } else { Cow::Owned(self.unescape()) }
}
#[inline]
pub fn get_str(&self) -> Result<Cow<'a, str>> {
if self.escapes == 0 {
Ok(Cow::Borrowed(str::from_utf8(self.raw)?))
} else {
Ok(Cow::Owned(String::from_utf8(self.unescape())?))
}
}
#[inline]
pub fn get_parse<E, T: FromStr>(&self) -> std::result::Result<T, E>
where
E: From<<T as FromStr>::Err>,
E: From<Error>,
{
Ok(self.get_str()?.as_ref().parse()?)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::packets::{Direction, Flags, OutCommand, PacketType};
use std::str;
/// Parse and write again.
fn test_loop_with_result(data: &[u8], result: &[u8]) {
let (name, parser) = CommandParser::new(data);
let name = str::from_utf8(name).unwrap();
let mut out_command =
OutCommand::new(Direction::S2C, Flags::empty(), PacketType::Command, name);
println!("\nParsing {}", str::from_utf8(data).unwrap());
for item in parser {
println!("Item: {:?}", item);
match item {
CommandItem::NextCommand => out_command.start_new_part(),
CommandItem::Argument(arg) => {
out_command.write_arg(
str::from_utf8(arg.name()).unwrap(),
&arg.value().get_str().unwrap(),
);
}
}
}
let packet = out_command.into_packet();
let in_str = str::from_utf8(result).unwrap();
let out_str = str::from_utf8(packet.content()).unwrap();
assert_eq!(in_str, out_str);
}
/// Parse and write again.
fn test_loop(data: &[u8]) { test_loop_with_result(data, data); }
const TEST_COMMANDS: &[&str] = &[
"cmd a=1 b=2 c=3",
"cmd a=\\s\\\\ b=\\p c=abc\\tdef",
"cmd a=1 c=3 b=2|b=4|b=5",
"initivexpand2 l=AQCVXTlKF+UQc0yga99dOQ9FJCwLaJqtDb1G7xYPMvHFMwIKVfKADF6zAAcAAAAgQW5vbnltb3VzAAAKQo71lhtEMbqAmtuMLlY8Snr0k2Wmymv4hnHNU6tjQCALKHewCykgcA== beta=\\/8kL8lcAYyMJovVOP6MIUC1oZASyuL\\/Y\\/qjVG06R4byuucl9oPAvR7eqZI7z8jGm9jkGmtJ6 omega=MEsDAgcAAgEgAiBxu2eCLQf8zLnuJJ6FtbVjfaOa1210xFgedoXuGzDbTgIgcGk35eqFavKxS4dROi5uKNSNsmzIL4+fyh5Z\\/+FWGxU= ot=1 proof=MEUCIQDRCP4J9e+8IxMJfCLWWI1oIbNPGcChl+3Jr2vIuyDxzAIgOrzRAFPOuJZF4CBw\\/xgbzEsgKMtEtgNobF6WXVNhfUw= tvd time=1544221457",
"clientinitiv alpha=41Te9Ar7hMPx+A== omega=MEwDAgcAAgEgAiEAq2iCMfcijKDZ5tn2tuZcH+\\/GF+dmdxlXjDSFXLPGadACIHzUnbsPQ0FDt34Su4UXF46VFI0+4wjMDNszdoDYocu0 ip",
// Well, that's more corrupted packet, but the parser should be robust
"initserver virtualserver_name=Server\\sder\\sVerplanten \
virtualserver_welcomemessage=This\\sis\\sSplamys\\sWorld \
virtualserver_platform=Linux \
virtualserver_version=3.0.13.8\\s[Build:\\s1500452811] \
virtualserver_maxclients=32 virtualserver_created=0 \
virtualserver_nodec_encryption_mode=1 \
virtualserver_hostmessage=Lé\\sServer\\sde\\sSplamy \
virtualserver_name=Server_mode=0 virtualserver_default_server \
group=8 virtualserver_default_channel_group=8 \
virtualserver_hostbanner_url virtualserver_hostmessagegfx_url \
virtualserver_hostmessagegfx_interval=2000 \
virtualserver_priority_speaker_dimm_modificat",
"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•\\s1\\s\\p\\sSplamy´s\\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",
"notifychannelsubscribed cid=2|cid=4 es=3867|cid=5 es=18694|cid=6 es=18694|cid=7 es=18694|cid=11 es=18694|cid=13 es=18694|cid=14 es=18694|cid=16 es=18694|cid=22 es=18694|cid=23 es=18694|cid=24 es=18694|cid=25 es=18694|cid=30 es=18694|cid=163 es=18694",
"notifypermissionlist group_id_end=0|group_id_end=7|group_id_end=13|group_id_end=18|group_id_end=21|group_id_end=21|group_id_end=33|group_id_end=47|group_id_end=77|group_id_end=82|group_id_end=83|group_id_end=106|group_id_end=126|group_id_end=132|group_id_end=143|group_id_end=151|group_id_end=160|group_id_end=162|group_id_end=170|group_id_end=172|group_id_end=190|group_id_end=197|group_id_end=215|group_id_end=227|group_id_end=232|group_id_end=248|permname=b_serverinstance_help_view permdesc=Retrieve\\sinformation\\sabout\\sServerQuery\\scommands|permname=b_serverinstance_version_view permdesc=Retrieve\\sglobal\\sserver\\sversion\\s(including\\splatform\\sand\\sbuild\\snumber)|permname=b_serverinstance_info_view permdesc=Retrieve\\sglobal\\sserver\\sinformation|permname=b_serverinstance_virtualserver_list permdesc=List\\svirtual\\sservers\\sstored\\sin\\sthe\\sdatabase",
// Server query
"cmd=1 cid=2",
"channellistfinished",
// With newlines
"sendtextmessage text=\\nmess\\nage\\n return_code=11",
];
#[test]
fn loop_test() {
for cmd in TEST_COMMANDS {
test_loop(cmd.as_bytes());
}
}
#[test]
fn optional_arg() {
test_loop(b"cmd a");
test_loop(b"cmd a b=1");
test_loop_with_result(b"cmd a=", b"cmd a");
test_loop_with_result(b"cmd a= b=1", b"cmd a b=1");
}
#[test]
fn no_slash_escape() {
let in_cmd = "clientinitiv alpha=giGMvmfHzbY3ig== omega=MEsDAgcAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITsC/50= ot=1 ip";
let out_cmd = "clientinitiv alpha=giGMvmfHzbY3ig== omega=MEsDAgcAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITsC\\/50= ot=1 ip";
test_loop_with_result(in_cmd.as_bytes(), out_cmd.as_bytes());
}
}
+62
View File
@@ -0,0 +1,62 @@
//! `tsproto-packets` parses and serializes TeamSpeak packets and commands.
use std::fmt;
use thiserror::Error;
pub mod commands;
pub mod packets;
type Result<T, E = Error> = std::result::Result<T, E>;
pub const S2C_HEADER_LEN: usize = 11;
pub const C2S_HEADER_LEN: usize = 13;
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
#[error(transparent)]
Base64(#[from] base64::DecodeError),
#[error(transparent)]
Io(#[from] std::io::Error),
#[error(transparent)]
ParseInt(#[from] std::num::ParseIntError),
#[error(transparent)]
Utf8(#[from] std::str::Utf8Error),
#[error(transparent)]
StringUtf8(#[from] std::string::FromUtf8Error),
#[error("Invalid init step {0}")]
InvalidInitStep(u8),
#[error("Invalid audio codec {0}")]
InvalidCodec(u8),
#[error("Packet content is too short (length {0})")]
PacketContentTooShort(usize),
#[error("Packet is too short (length {0})")]
PacketTooShort(usize),
#[error("Cannot parse command ({0})")]
ParseCommand(String),
#[error("Got a packet with unknown type ({0})")]
UnknownPacketType(u8),
#[error("Tried to parse a packet from the wrong direction")]
WrongDirection,
#[error("Wrong mac, expected TS3INIT1 but got {0:?}")]
WrongInitMac(Vec<u8>),
#[error("Wrong packet type ({0:?})")]
WrongPacketType(packets::PacketType),
}
pub struct HexSlice<'a, T: fmt::LowerHex + 'a>(pub &'a [T]);
impl<'a> fmt::Display for HexSlice<'a, u8> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Hex[")?;
if let Some((l, m)) = self.0.split_last() {
for b in m {
write!(f, "{:02x} ", b)?;
}
write!(f, "{:02x}", l)?;
}
write!(f, "]")
}
}
File diff suppressed because it is too large. Load diff
+31
View File
@@ -0,0 +1,31 @@
[package]
name = "tsproto-structs"
version = "0.2.0"
authors = ["Flakebi <flakebi@t-online.de>", "Splamy <splamyn@gmail.com>"]
description = "Resource files for several TeamSpeak related data."
repository = "https://github.com/ReSpeak/tsclientlib/tree/master/utils/tsproto-structs"
readme = "README.md"
keywords = ["teamspeak3", "ts3"]
license = "MIT OR Apache-2.0"
edition = "2018"
include = [
"/Cargo.toml",
"/README.md",
"/src/*.rs",
"/declarations/Book.toml",
"/declarations/BookToMessages.toml",
"/declarations/Enums.toml",
"/declarations/Errors.csv",
"/declarations/Messages.toml",
"/declarations/MessagesToBook.toml",
"/declarations/Permissions.csv",
"/declarations/Versions.csv",
]
[dependencies]
base64 = "0.22"
csv = "1"
heck = "0.5"
once_cell = "1"
serde = { version = "1", features = ["derive"] }
toml = "1"
+13
View File
@@ -0,0 +1,13 @@
# tsproto-structs [![docs.rs](https://docs.rs/tsproto-structs/badge.svg)](https://docs.rs/tsproto-structs)
`tsproto-structs` contains machine readable data for several TeamSpeak related topics.
The underlying data files can be found in the
[tsdeclarations](https://github.com/ReSpeak/tsdeclarations) repository.
## License
Licensed under either of
* [Apache License, Version 2.0](../../LICENSE-APACHE)
* [MIT license](../../LICENSE-MIT)
at your option.
+10
View File
@@ -0,0 +1,10 @@
# tsproto-structs [![docs.rs](https://docs.rs/tsproto-structs/badge.svg)](https://docs.rs/tsproto-structs)
{{readme}}
## License
Licensed under either of
* [Apache License, Version 2.0](../../LICENSE-APACHE)
* [MIT license](../../LICENSE-MIT)
at your option.
@@ -0,0 +1,67 @@
# LaTeX files
*.synctex.gz
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
@@ -0,0 +1,83 @@
uid,name,description,filename,codes
4b27be5a-b92a-4b30-8b2d-14b59653f427,20th Anniversary,Celebrating 20 Years of TeamSpeak,20_years,
f81ad44d-e931-47d1-a3ef-5fd160217cf8,4Netplayers,4Netplayers customer,4netplayers,
b78a0f3e-8758-4572-b102-42a79b4a0342,????,Reads between the line,hat,
2bf80270-8efe-46dc-a472-3280a0479145,Alpha Tester,Helped to test our software. THANK YOU!,Alpha,
05114019-6b46-4b13-b5a1-e5179ef69fb5,April Fools!,"Roses are red, gaming is fun, you are carrying too much to be able to run :(",rpg,
1a518885-520c-4f54-9f49-8b1acb674771,Braindance,I’m chippin’ in,Braindance,P4TEKZ80PZ
cbf5aafd-2554-4053-80bb-0cf82ec0a430,Bright Idea,TeamSpeak took my idea on board,FeatureBadge_Lightbulb,
d6062d9c-42a3-49c9-91dd-8c43a5a46805,Bug Catcher,I found a bug!,BugBadge_Splat,
dfc70674-0fd0-431e-b3a1-edc32d7b09b2,Challenge Accepted,"Unlocked at SCILL Play — Challenges, tournaments and more!",scill,
f85f7e21-753a-4566-b26a-4e3e9155d2ef,Cyberpunk,We have a city to burn,Cyberpunk,
c028298c-84ff-4e22-be4e-b8c17552b4bb,Digi,Digi joined your channel #DIGWIN,digi,
56df5ce2-6c5a-4a24-90e2-29e497e26170,Drone Champions League,I follow the Drone Champions League,DCL_Badge,DRONECHAMP
935e5a2a-954a-44ca-aa7a-55c79285b601,E3 2018 - Winner,Discovered at E3 2018,E3-2018,
61723e54-3da2-4f19-a33f-fcdc8ef5eaa0,Father's Day 2022,Not all heroes wear capes,fathersday2022,
b9c7d6ad-5b99-40fb-988c-1d02ab6cc130,Found Tim Speak,Found Tim Speak at Gamescom 2018,met_tim,XJN4WJZEJN
62444179-0d99-42ba-a45c-c6b1557d079a,Gamescom 2014,Registered at Gamescom 2014,gamescom_2014,
50bbdbc8-0f2a-46eb-9808-602225b49627,Gamescom 2016,Registered during Gamescom 2016,gamescom_2016,
534c9582-ab02-4267-aec6-2d94361daa2a,Gamescom 2017,Visited TeamSpeak at Gamescom 2017,gamescom_2017,DK9JGRJH1Q
4eef1ecf-a0ea-423d-bfd0-496543a00305,Gamescom 2018,Visited TeamSpeak at Gamescom 2018,gamescom_2018,8CXB49KPJ4
b82a45a5-b235-4926-be77-de102222e5eb,Gamescom 2019,Visited TeamSpeak at Gamescom 2019,Gamescom19,PNKCB76VZ8
34dbfa8f-bd27-494c-aa08-a312fc0bb240,Gamescom Hero 2017,Gaming Hero at Gamescom 2017,hero_2017,
24512806-f886-4440-b579-9e26e4219ef6,Gamescom Hero 2018,Gamescom Exclusive Gaming Hero 2018,gamescom_2018_played,BJCFQBU53C
d49fd07e-99fb-41de-8d7b-c98064713171,GommeHD.net,Your #1 Minecraft Network for over 10 years,GMHD,
c565972a-3912-457b-826f-84820c1ba6ca,Halloween 2021,Happy Halloween 2021,halloween21,
133595e7-950f-4ef2-b113-f91a68b5770d,Halloween 2021 Special,Earned by participating in our Halloween 2021 special stream,halloween21_special,
fb154277-5fe7-428a-85a4-43c0bdcdda3d,Halloween 2022,Spooky_Scary_Skeletons.mp4,halloween22,
e6679ce2-d458-493c-8ffb-5660e47ac99f,Happy Hanami,Enjoy the view,hanami2023,
de7bd960-eb02-47e1-9ce2-a44f6e255d8f,Happy Holidays 2019,Happy holidays from everyone at TeamSpeak!,Happy_Holidays,
d4ea0251-ba46-4c1a-83b7-59db3f89e52c,Happy New Year 2021,Survived the great toilet paper crisis of 2020,firework_2020,
1519e001-06a0-458c-9195-a8a6d0ec87fc,Happy New Year 2023,"Aw man, here we go again",2023_NewYear,
c68bcc52-7aeb-4868-b4d2-e7b20716f9ba,Heatwave 2022,I'm melting... help,summer_icecream,
94242c4e-6742-4540-8b66-ce951ed57159,Helping Hand,\ pushed some buttons *beep* *bop* ~ thanks!,homebase,
288a56c6-4da3-48de-9c9f-bd9eede5d832,Immortal Roleplay,This is your life.,Immortal_Roleplay,
69bfffc8-e9c0-4f70-8a37-47cb8c73fb1d,International Peace Day,"United we stand, divided we fall",peaceday2022,
9ea23c77-8755-4d82-b30c-92f4aac109ef,International Women's Day 2021,"To all the mums, sisters, aunties, nieces and beyond, Happy Women's Day!",wft,
7d9fa2b1-b6fa-47ad-9838-c239a4ddd116,MIFCOM,MIFCOM | Entered Performance,mifcom,
ed85bdff-2a2b-4bea-a1a5-4d06fcc0d776,Merry Christmas 2019,It’s the most wonderful ‘Tim’ of the Year,Christmas,
c6480fe2-ee25-4ee8-9853-243652c8ec54,Merry Christmas 2020,"Let it snow, let it snow, let it snow!",Christmas2020,
0581aa0f-8c2d-4681-bb9f-8492fec49977,Merry Christmas 2021,Look what Santa's left under the server tree!,christmas2021,
d4875b30-9908-43cb-a1eb-1a958e226078,Merry Christmas 2022,There's snow place like home,christmas2022,
87ccf9ea-67c9-45e5-adbc-77e210e6128a,Met Tim,Met Tim Speak IRL,tim_irl,
0d98391c-ecdf-4f26-931a-49bfd669cda7,Mind Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_MindEgg,
2fdda3c6-20e0-48f1-9c12-f39239a2ed02,Mother's Day 2022,Thanks for bearing with us,rose,
c3f823eb-5d5c-40f9-9dbd-3437d59a539d,Official TeamSpeak Gamer,New myTeamSpeak member,TS-2018,
8dfa37ac-b40d-4466-b393-ff2184a9adf3,Overwatch League,I follow the Overwatch League,OWL_Badge,
4ce435d1-6ac5-4530-b81d-6d14ddaaa1ac,PGL Antwerp 2022,Watched the PGL CS:GO Major,PGLant,
fa3ece28-64df-431f-b1b3-90844bfdd2d9,Paris Games Week 2014,Registered at Paris Games Week 2014,paris_gamesweek_2014,
d95f9901-c42d-4bac-8849-7164fd9e2310,Paris Games Week 2016,Registered during Paris Games Week 2016,paris_gamesweek_2016,
0005232e-538e-4cb2-93b6-d7d83e873829,PietSmiet,Werde Snob auf PietSmiet.de ;),PietSmiet,
be932556-dfa9-4dc6-afd0-98de0ab25777,PolTeamgeist,WooOOHoohOOHooo,PolTeamgeist,
5f6d49e4-35c8-4809-8c81-6e71f7f749e9,Power Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_PowerEgg,
ceee2445-4fbf-4f06-9421-286f0f4e875a,Pride,Never be afraid to show your colors.,pride,
1aa375e8-7207-45bf-8b80-556bafafc834,Reality Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_RealityEgg,
f22c22f1-8e2d-4d99-8de9-f352dc26ac5b,Rocket Beans TV,Rocket Beans TV Community,rbtv,RWGE2NURJZ
2c9698c1-1fec-4baa-a28f-4845f045f42f,Soul Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_SoulEgg,
641a4d85-2351-482c-97a1-02fc3b6abbb5,Space Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_SpaceEgg,
63261116-4359-4842-873e-56820afbe068,SpartaTheOriginal,Olaf Toast @ twitch.tv/SpartaTheOriginal,Toast,
ef567ec5-f46e-4520-be07-6021023cf6bd,Sponsorship License,Sponsored by TeamSpeak,Sponsorship,
7a627d47-5496-4d68-83b5-2c4eafff9b30,"Stay Home, Stay Safe","Playing Apart, Staying Connected",StaySafeStayHome,
7262a528-c7df-4369-bc2c-d34bf5853d7b,TS Chat Alpha Tester,"Helped us test our new mobile app, thanks!",slim_golden,
6eee759e-b1e9-4937-b023-07fc778532a2,TS Gameday Participant,At least i tried...,silvered,
e1447b99-53b0-448a-98b7-ee7bad8bd268,TS Gameday Winner,As shiny as the golden frying pan,goldenjoystick,
1cb07348-34a4-4741-b50f-c41e584370f7,TeamSpeak Addon Author,Creator of TeamSpeak Addons,addon_author,
450f81c1-ab41-4211-a338-222fa94ed157,TeamSpeak Addon Developer (Bronze),Creator of at least 1 TeamSpeak Addon,addon_author_bronze,
94ec66de-5940-4e38-b002-970df0cf6c94,TeamSpeak Addon Developer (Gold),Creator of at least 5 TeamSpeak Addons,addon_author_gold,
c9e97536-5a2d-4c8e-a135-af404587a472,TeamSpeak Addon Developer (Silver),Creator of at least 3 TeamSpeak Addons,addon_author_silver,
9cd152a7-bf65-4ece-aeba-62d27678f79a,TeamSpeak Competition Winner Badge,TeamSpeak Competition Winner,CompWinnerBadge,
64221fd1-706c-4bb2-ba55-996c39effa79,TeamSpeak Jedi,myTeamSpeak early adopter,TS-OG,
6b187e83-873b-46b0-b2c2-a31af15e76a4,TeamSpeak Merch Badge,TeamSpeak Merch Owner - 1st Edition,cap_red,
22b9ec39-7694-453e-864c-dfc7b1b0d7c7,TeamSpeak Merch Badge 2.0,TeamSpeak Merch Owner - 2nd Edition,topper,
205916f3-a953-4754-8905-bc15069b1f91,TeamSpeak Merch Badge 3.0,TeamSpeak Merch Owner — 3rd Edition,Merch3,
c2368518-3728-4260-bcd1-8b85e9f8984c,Test,"Testing, Testing.",Testing,
4086a249-a503-4f31-9e83-8a0a8e3089bd,Tim-o'-Lantern,Mwuhaahaahaahaahaa,Tim-O-Lantern,JQGCTAQWHT
089c7295-3aa2-48b0-b2f1-2dd1bec12caf,Time Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_TimeEgg,
904e232c-f369-44db-87f7-5142e15620cc,Time Machine,Worked like a machine to update addons in super-quick time.,time_machine,
4b0fd4f5-d456-4294-973d-853a1db5c7d8,Valentim's Day 2019,Valentim's Day 2019,Valentines_Badge,
92801833-e721-4b7e-84d4-6c02dbb332b9,Valentim's Day 2020,Valentim's Day 2020,Valentim2020,
958f904b-8260-48a4-a961-f786cbd39411,Valentine's Day 2023,Love you like my Tamagotchi,ValentinesDay23,
a676c708-da67-4784-ba7f-3fb7e8d2e865,Valentines Day 2021,"Roses are red, TS is blue, Servers are Sweet and so are you.",valentine21,
8c22fe26-30ac-4231-8b31-67d8a75c808a,Year of the Ox 2021,Only listen to the fortune cookie; disregard all other fortune telling units.,ox21,
970c70e6-00a1-41c1-ac5c-81c89a06c7a6,Year of the Rabbit 2023,Do a barrel roll!,chineseNY2023,
92356386-0451-4a97-87d9-10ff4f43260c,Year of the Tiger 2022,Rocky sends his regards,tiger,
1 uid name description filename codes
2 4b27be5a-b92a-4b30-8b2d-14b59653f427 20th Anniversary Celebrating 20 Years of TeamSpeak 20_years
3 f81ad44d-e931-47d1-a3ef-5fd160217cf8 4Netplayers 4Netplayers customer 4netplayers
4 b78a0f3e-8758-4572-b102-42a79b4a0342 ???? Reads between the line hat
5 2bf80270-8efe-46dc-a472-3280a0479145 Alpha Tester Helped to test our software. THANK YOU! Alpha
6 05114019-6b46-4b13-b5a1-e5179ef69fb5 April Fools! Roses are red, gaming is fun, you are carrying too much to be able to run :( rpg
7 1a518885-520c-4f54-9f49-8b1acb674771 Braindance I’m chippin’ in Braindance P4TEKZ80PZ
8 cbf5aafd-2554-4053-80bb-0cf82ec0a430 Bright Idea TeamSpeak took my idea on board FeatureBadge_Lightbulb
9 d6062d9c-42a3-49c9-91dd-8c43a5a46805 Bug Catcher I found a bug! BugBadge_Splat
10 dfc70674-0fd0-431e-b3a1-edc32d7b09b2 Challenge Accepted Unlocked at SCILL Play — Challenges, tournaments and more! scill
11 f85f7e21-753a-4566-b26a-4e3e9155d2ef Cyberpunk We have a city to burn Cyberpunk
12 c028298c-84ff-4e22-be4e-b8c17552b4bb Digi Digi joined your channel #DIGWIN digi
13 56df5ce2-6c5a-4a24-90e2-29e497e26170 Drone Champions League I follow the Drone Champions League DCL_Badge DRONECHAMP
14 935e5a2a-954a-44ca-aa7a-55c79285b601 E3 2018 - Winner Discovered at E3 2018 E3-2018
15 61723e54-3da2-4f19-a33f-fcdc8ef5eaa0 Father's Day 2022 Not all heroes wear capes fathersday2022
16 b9c7d6ad-5b99-40fb-988c-1d02ab6cc130 Found Tim Speak Found Tim Speak at Gamescom 2018 met_tim XJN4WJZEJN
17 62444179-0d99-42ba-a45c-c6b1557d079a Gamescom 2014 Registered at Gamescom 2014 gamescom_2014
18 50bbdbc8-0f2a-46eb-9808-602225b49627 Gamescom 2016 Registered during Gamescom 2016 gamescom_2016
19 534c9582-ab02-4267-aec6-2d94361daa2a Gamescom 2017 Visited TeamSpeak at Gamescom 2017 gamescom_2017 DK9JGRJH1Q
20 4eef1ecf-a0ea-423d-bfd0-496543a00305 Gamescom 2018 Visited TeamSpeak at Gamescom 2018 gamescom_2018 8CXB49KPJ4
21 b82a45a5-b235-4926-be77-de102222e5eb Gamescom 2019 Visited TeamSpeak at Gamescom 2019 Gamescom19 PNKCB76VZ8
22 34dbfa8f-bd27-494c-aa08-a312fc0bb240 Gamescom Hero 2017 Gaming Hero at Gamescom 2017 hero_2017
23 24512806-f886-4440-b579-9e26e4219ef6 Gamescom Hero 2018 Gamescom Exclusive Gaming Hero 2018 gamescom_2018_played BJCFQBU53C
24 d49fd07e-99fb-41de-8d7b-c98064713171 GommeHD.net Your #1 Minecraft Network for over 10 years GMHD
25 c565972a-3912-457b-826f-84820c1ba6ca Halloween 2021 Happy Halloween 2021 halloween21
26 133595e7-950f-4ef2-b113-f91a68b5770d Halloween 2021 Special Earned by participating in our Halloween 2021 special stream halloween21_special
27 fb154277-5fe7-428a-85a4-43c0bdcdda3d Halloween 2022 Spooky_Scary_Skeletons.mp4 halloween22
28 e6679ce2-d458-493c-8ffb-5660e47ac99f Happy Hanami Enjoy the view hanami2023
29 de7bd960-eb02-47e1-9ce2-a44f6e255d8f Happy Holidays 2019 Happy holidays from everyone at TeamSpeak! Happy_Holidays
30 d4ea0251-ba46-4c1a-83b7-59db3f89e52c Happy New Year 2021 Survived the great toilet paper crisis of 2020 firework_2020
31 1519e001-06a0-458c-9195-a8a6d0ec87fc Happy New Year 2023 Aw man, here we go again 2023_NewYear
32 c68bcc52-7aeb-4868-b4d2-e7b20716f9ba Heatwave 2022 I'm melting... help summer_icecream
33 94242c4e-6742-4540-8b66-ce951ed57159 Helping Hand \ pushed some buttons *beep* *bop* ~ thanks! homebase
34 288a56c6-4da3-48de-9c9f-bd9eede5d832 Immortal Roleplay This is your life. Immortal_Roleplay
35 69bfffc8-e9c0-4f70-8a37-47cb8c73fb1d International Peace Day United we stand, divided we fall peaceday2022
36 9ea23c77-8755-4d82-b30c-92f4aac109ef International Women's Day 2021 To all the mums, sisters, aunties, nieces and beyond, Happy Women's Day! wft
37 7d9fa2b1-b6fa-47ad-9838-c239a4ddd116 MIFCOM MIFCOM | Entered Performance mifcom
38 ed85bdff-2a2b-4bea-a1a5-4d06fcc0d776 Merry Christmas 2019 It’s the most wonderful ‘Tim’ of the Year Christmas
39 c6480fe2-ee25-4ee8-9853-243652c8ec54 Merry Christmas 2020 Let it snow, let it snow, let it snow! Christmas2020
40 0581aa0f-8c2d-4681-bb9f-8492fec49977 Merry Christmas 2021 Look what Santa's left under the server tree! christmas2021
41 d4875b30-9908-43cb-a1eb-1a958e226078 Merry Christmas 2022 There's snow place like home christmas2022
42 87ccf9ea-67c9-45e5-adbc-77e210e6128a Met Tim Met Tim Speak IRL tim_irl
43 0d98391c-ecdf-4f26-931a-49bfd669cda7 Mind Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_MindEgg
44 2fdda3c6-20e0-48f1-9c12-f39239a2ed02 Mother's Day 2022 Thanks for bearing with us rose
45 c3f823eb-5d5c-40f9-9dbd-3437d59a539d Official TeamSpeak Gamer New myTeamSpeak member TS-2018
46 8dfa37ac-b40d-4466-b393-ff2184a9adf3 Overwatch League I follow the Overwatch League OWL_Badge
47 4ce435d1-6ac5-4530-b81d-6d14ddaaa1ac PGL Antwerp 2022 Watched the PGL CS:GO Major PGLant
48 fa3ece28-64df-431f-b1b3-90844bfdd2d9 Paris Games Week 2014 Registered at Paris Games Week 2014 paris_gamesweek_2014
49 d95f9901-c42d-4bac-8849-7164fd9e2310 Paris Games Week 2016 Registered during Paris Games Week 2016 paris_gamesweek_2016
50 0005232e-538e-4cb2-93b6-d7d83e873829 PietSmiet Werde Snob auf PietSmiet.de ;) PietSmiet
51 be932556-dfa9-4dc6-afd0-98de0ab25777 PolTeamgeist WooOOHoohOOHooo PolTeamgeist
52 5f6d49e4-35c8-4809-8c81-6e71f7f749e9 Power Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_PowerEgg
53 ceee2445-4fbf-4f06-9421-286f0f4e875a Pride Never be afraid to show your colors. pride
54 1aa375e8-7207-45bf-8b80-556bafafc834 Reality Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_RealityEgg
55 f22c22f1-8e2d-4d99-8de9-f352dc26ac5b Rocket Beans TV Rocket Beans TV Community rbtv RWGE2NURJZ
56 2c9698c1-1fec-4baa-a28f-4845f045f42f Soul Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_SoulEgg
57 641a4d85-2351-482c-97a1-02fc3b6abbb5 Space Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_SpaceEgg
58 63261116-4359-4842-873e-56820afbe068 SpartaTheOriginal Olaf Toast @ twitch.tv/SpartaTheOriginal Toast
59 ef567ec5-f46e-4520-be07-6021023cf6bd Sponsorship License Sponsored by TeamSpeak Sponsorship
60 7a627d47-5496-4d68-83b5-2c4eafff9b30 Stay Home, Stay Safe Playing Apart, Staying Connected StaySafeStayHome
61 7262a528-c7df-4369-bc2c-d34bf5853d7b TS Chat Alpha Tester Helped us test our new mobile app, thanks! slim_golden
62 6eee759e-b1e9-4937-b023-07fc778532a2 TS Gameday Participant At least i tried... silvered
63 e1447b99-53b0-448a-98b7-ee7bad8bd268 TS Gameday Winner As shiny as the golden frying pan goldenjoystick
64 1cb07348-34a4-4741-b50f-c41e584370f7 TeamSpeak Addon Author Creator of TeamSpeak Addons addon_author
65 450f81c1-ab41-4211-a338-222fa94ed157 TeamSpeak Addon Developer (Bronze) Creator of at least 1 TeamSpeak Addon addon_author_bronze
66 94ec66de-5940-4e38-b002-970df0cf6c94 TeamSpeak Addon Developer (Gold) Creator of at least 5 TeamSpeak Addons addon_author_gold
67 c9e97536-5a2d-4c8e-a135-af404587a472 TeamSpeak Addon Developer (Silver) Creator of at least 3 TeamSpeak Addons addon_author_silver
68 9cd152a7-bf65-4ece-aeba-62d27678f79a TeamSpeak Competition Winner Badge TeamSpeak Competition Winner CompWinnerBadge
69 64221fd1-706c-4bb2-ba55-996c39effa79 TeamSpeak Jedi myTeamSpeak early adopter TS-OG
70 6b187e83-873b-46b0-b2c2-a31af15e76a4 TeamSpeak Merch Badge TeamSpeak Merch Owner - 1st Edition cap_red
71 22b9ec39-7694-453e-864c-dfc7b1b0d7c7 TeamSpeak Merch Badge 2.0 TeamSpeak Merch Owner - 2nd Edition topper
72 205916f3-a953-4754-8905-bc15069b1f91 TeamSpeak Merch Badge 3.0 TeamSpeak Merch Owner — 3rd Edition Merch3
73 c2368518-3728-4260-bcd1-8b85e9f8984c Test Testing, Testing. Testing
74 4086a249-a503-4f31-9e83-8a0a8e3089bd Tim-o'-Lantern Mwuhaahaahaahaahaa Tim-O-Lantern JQGCTAQWHT
75 089c7295-3aa2-48b0-b2f1-2dd1bec12caf Time Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_TimeEgg
76 904e232c-f369-44db-87f7-5142e15620cc Time Machine Worked like a machine to update addons in super-quick time. time_machine
77 4b0fd4f5-d456-4294-973d-853a1db5c7d8 Valentim's Day 2019 Valentim's Day 2019 Valentines_Badge
78 92801833-e721-4b7e-84d4-6c02dbb332b9 Valentim's Day 2020 Valentim's Day 2020 Valentim2020
79 958f904b-8260-48a4-a961-f786cbd39411 Valentine's Day 2023 Love you like my Tamagotchi ValentinesDay23
80 a676c708-da67-4784-ba7f-3fb7e8d2e865 Valentines Day 2021 Roses are red, TS is blue, Servers are Sweet and so are you. valentine21
81 8c22fe26-30ac-4231-8b31-67d8a75c808a Year of the Ox 2021 Only listen to the fortune cookie; disregard all other fortune telling units. ox21
82 970c70e6-00a1-41c1-ac5c-81c89a06c7a6 Year of the Rabbit 2023 Do a barrel roll! chineseNY2023
83 92356386-0451-4a97-87d9-10ff4f43260c Year of the Tiger 2022 Rocky sends his regards tiger
@@ -0,0 +1,327 @@
[[struct]]
name = "ServerGroup"
id = [
{ struct="ServerGroup", prop="Id" },
]
doc = "Get in notifyservergrouplist"
properties = [
{ name="Id", type="ServerGroupId" },
{ name="Name", type="str" },
{ name="GroupType", type="GroupType" },
{ name="Icon", type="IconId" },
{ name="IsPermanent", type="bool", doc="If the group is saved to the server database" },
{ name="SortId", type="i32" },
{ name="NamingMode", type="GroupNamingMode" },
{ name="NeededModifyPower", type="i32" },
{ name="NeededMemberAddPower", type="i32" },
{ name="NeededMemberRemovePower", type="i32", opt=true },
]
[[struct]]
name = "ChannelGroup"
id = [
{ struct="ChannelGroup", prop="Id" },
]
doc = "Get in notifychannelgrouplist"
properties = [
{ name="Id", type="ChannelGroupId" },
{ name="Name", type="str" },
{ name="GroupType", type="GroupType" },
{ name="Icon", type="IconId" },
{ name="IsPermanent", type="bool", doc="If the group is saved to the server database" },
{ name="SortId", type="i32" },
{ name="NamingMode", type="GroupNamingMode" },
{ name="NeededModifyPower", type="i32" },
{ name="NeededMemberAddPower", type="i32" },
{ name="NeededMemberRemovePower", type="i32", opt=true },
]
[[struct]]
name = "OptionalChannelData"
opt = true
id = [
{ struct="Channel", prop="Id" },
]
doc = "Get in notifychanneledited by channelgetdescription"
properties = [
{ name="Description", type="str" },
]
[[struct]]
name = "Channel"
id = [
{ struct="Channel", prop="Id" },
]
doc = "Get in channellist"
properties = [
{ name="Id", type="ChannelId" },
{ name="Guid", type="str", opt=true },
{ name="Parent", type="ChannelId", doc="0 means root channel" },
{ name="Name", type="str" },
{ name="Topic", type="str", opt=true },
{ name="Codec", type="Codec" },
{ name="CodecQuality", type="u8", opt=true },
{ name="MaxClients", type="MaxClients", opt=true, doc="The maximum number of clients in the channel." },
{ name="MaxFamilyClients", type="MaxClients", opt=true, doc="Maximum number of clients in this and all child channels." },
{ name="Order", type="ChannelId", doc="The preceding channel id." },
{ name="ChannelType", type="ChannelType" },
{ name="IsDefault", type="bool", opt=true, doc="Whether it is the default channel" },
{ name="HasPassword", type="bool", opt=true, doc="Whether this channel has a password" },
{ name="CodecLatencyFactor", type="i32", opt=true, doc="TODO Type?" },
{ name="IsUnencrypted", type="bool", opt=true },
{ name="DeleteDelay", type="Duration", opt=true },
{ name="NeededTalkPower", type="i32", opt=true },
{ name="ForcedSilence", type="bool" },
{ name="PhoneticName", type="str", opt=true },
{ name="Icon", type="IconId", opt=true },
{ name="IsPrivate", type="bool", opt=true },
{ name="StorageQuota", type="u32", opt=true },
{ name="Subscribed", type="bool" },
{ name="PermissionHints", type="ChannelPermissionHint", opt=true },
{ name="OptionalData", type="OptionalChannelData", opt=true },
]
[[struct]]
name = "OptionalClientData"
opt = true
id = [
{ struct="Client", prop="Id" },
]
doc = "Get in notifyclientupdated by clientgetvariables"
properties = [
{ name="Version", type="str" },
{ name="VersionSign", type="str", opt=true },
{ name="Platform", type="str" },
{ name="LoginName", type="str", opt=true, doc="Set only for server queries" },
{ name="Created", type="DateTime" },
{ name="LastConnected", type="DateTime" },
{ name="ConnectionsTotal", type="u32" },
{ name="BytesUploadedMonth", type="u64" },
{ name="BytesDownloadedMonth", type="u64" },
{ name="BytesUploadedTotal", type="u64" },
{ name="BytesDownloadedTotal", type="u64" },
]
[[struct]]
name = "ConnectionClientData"
opt = true
id = [
{ struct="Client", prop="Id" },
]
doc = "Get in notifyconnectioninfo by getconnectioninfo"
properties = [
{ name="Ping", type="Duration", opt=true },
{ name="PingDeviation", type="Duration", opt=true },
{ name="ConnectedTime", type="Duration", opt=true },
{ name="ClientAddress", type="SocketAddr", opt=true, doc="Only available if we have the permission to view it" },
{ name="PacketsSentSpeech", type="u64", opt=true },
{ name="PacketsSentKeepalive", type="u64", opt=true },
{ name="PacketsSentControl", type="u64", opt=true },
{ name="BytesSentSpeech", type="u64", opt=true },
{ name="BytesSentKeepalive", type="u64", opt=true },
{ name="BytesSentControl", type="u64", opt=true },
{ name="PacketsReceivedSpeech", type="u64", opt=true },
{ name="PacketsReceivedKeepalive", type="u64", opt=true },
{ name="PacketsReceivedControl", type="u64", opt=true },
{ name="BytesReceivedSpeech", type="u64", opt=true },
{ name="BytesReceivedKeepalive", type="u64", opt=true },
{ name="BytesReceivedControl", type="u64", opt=true },
{ name="ServerToClientPacketlossSpeech", type="f32", opt=true },
{ name="ServerToClientPacketlossKeepalive", type="f32", opt=true },
{ name="ServerToClientPacketlossControl", type="f32", opt=true },
{ name="ServerToClientPacketlossTotal", type="f32", opt=true },
{ name="ClientToServerPacketlossSpeech", type="f32" },
{ name="ClientToServerPacketlossKeepalive", type="f32" },
{ name="ClientToServerPacketlossControl", type="f32" },
{ name="ClientToServerPacketlossTotal", type="f32" },
{ name="BandwidthSentLastSecondSpeech", type="u64", opt=true },
{ name="BandwidthSentLastSecondKeepalive", type="u64", opt=true },
{ name="BandwidthSentLastSecondControl", type="u64", opt=true },
{ name="BandwidthSentLastMinuteSpeech", type="u64", opt=true },
{ name="BandwidthSentLastMinuteKeepalive", type="u64", opt=true },
{ name="BandwidthSentLastMinuteControl", type="u64", opt=true },
{ name="BandwidthReceivedLastSecondSpeech", type="u64", opt=true },
{ name="BandwidthReceivedLastSecondKeepalive", type="u64", opt=true },
{ name="BandwidthReceivedLastSecondControl", type="u64", opt=true },
{ name="BandwidthReceivedLastMinuteSpeech", type="u64", opt=true },
{ name="BandwidthReceivedLastMinuteKeepalive", type="u64", opt=true },
{ name="BandwidthReceivedLastMinuteControl", type="u64", opt=true },
{ name="FiletransferBandwidthSent", type="u64", opt=true },
{ name="FiletransferBandwidthReceived", type="u64", opt=true },
{ name="IdleTime", type="Duration" },
]
[[struct]]
name = "Client"
id = [
{ struct="Client", prop="Id" },
]
doc = "Get in notifycliententerview"
properties = [
{ name="Id", type="ClientId" },
{ name="Channel", type="ChannelId" },
{ name="Uid", type="Uid", opt=true, doc="Unique Identifier" },
{ name="Name", type="str" },
{ name="InputMuted", type="bool", doc="`true` if muted, `false` otherwise" },
{ name="OutputMuted", type="bool", doc="`true` if muted, `false` otherwise" },
{ name="OutputOnlyMuted", type="bool", doc="`true` if muted, `false` otherwise" },
{ name="InputHardwareEnabled", type="bool", doc="`true` if enabled, `false` if disabled" },
{ name="OutputHardwareEnabled", type="bool", doc="`true` if enabled, `false` if disabled" },
{ name="TalkPowerGranted", type="bool", doc="If the client is granted talk power" },
{ name="Metadata", type="str", doc="Set by client" },
{ name="IsRecording", type="bool", doc="Whether the client is recording" },
{ name="DatabaseId", type="ClientDbId" },
{ name="ChannelGroup", type="ChannelGroupId" },
{ name="ServerGroups", type="ServerGroupId", mod="set" },
{ name="AwayMessage", type="str", opt=true, doc="Contains the away message if the client is away" },
{ name="ClientType", type="ClientType", doc="If this client is a server query or not" },
{ name="AvatarHash", type="str", doc="MD5 hash of the avatar, used to retrieve the avatar" },
{ name="TalkPower", type="i32" },
{ name="TalkPowerRequest", type="TalkPowerRequest", opt=true, doc="Contains a message and timestamp from the client if he requests talk power" },
{ name="Description", type="str" },
{ name="IsPrioritySpeaker", type="bool" },
{ name="UnreadMessages", type="u32" },
{ name="PhoneticName", type="str" },
{ name="NeededServerqueryViewPower", type="i32" },
{ name="Icon", type="IconId" },
{ name="IsChannelCommander", type="bool" },
{ name="CountryCode", type="str", doc="Like US, DE" },
{ name="InheritedChannelGroupFromChannel", type="ChannelId" },
{ name="Badges", type="str" },
{ name="UserTag", type="str", opt=true },
{ name="PermissionHints", type="ClientPermissionHint", opt=true },
{ name="OptionalData", type="OptionalClientData", opt=true },
{ name="ConnectionData", type="ConnectionClientData", opt=true },
]
[[struct]]
name = "OptionalServerData"
opt = true
id = [
]
doc = "Get by notifyserverupdated after requested by servergetvariables"
properties = [
{ name="Uptime", type="Duration" },
{ name="HasPassword", type="bool" },
{ name="DefaultChannelAdminGroup", type="ChannelGroupId", doc="The channel group which will be given to channel creators" },
{ name="MaxDownloadBandwidthTotal", type="u64" },
{ name="MaxUploadBandwidthTotal", type="u64" },
{ name="ComplainAutobanCount", type="u32" },
{ name="ComplainAutobanTime", type="Duration" },
{ name="ComplainRemoveTime", type="Duration" },
{ name="MinClientsInChannelBeforeForcedSilence", type="u32", doc="How many clients can be in a server before silence is forced" },
{ name="AntifloodPointsTickReduce", type="u32" },
{ name="AntifloodPointsToCommandBlock", type="u32" },
{ name="AntifloodPointsToIpBlock", type="u32" },
{ name="AntifloodPointsToPluginBlock", type="u32" },
{ name="ConnectionCountTotal", type="u64", doc="The amount of connections on this server.\n\nThis includes normal clients and server queries." },
{ name="ChannelCount", type="u64", doc="The amount of channels on the server" },
{ name="ClientCount", type="u16", doc="The amount of clients which are online on the server" },
{ name="QueryCountTotal", type="u64", doc="Amount of server queries connected to the server" },
{ name="QueryCount", type="u32", doc="Amount of server queries connected and online/visible on the server" },
{ name="DownloadQuota", type="u64" },
{ name="UploadQuota", type="u64" },
{ name="BytesDownloadedMonth", type="u64" },
{ name="BytesUploadedMonth", type="u64" },
{ name="BytesDownloadedTotal", type="u64" },
{ name="BytesUploadedTotal", type="u64" },
{ name="Port", type="u16" },
{ name="Autostart", type="bool" },
{ name="MachineId", type="str" },
{ name="NeededIdentitySecurityLevel", type="u8" },
{ name="LogClient", type="bool" },
{ name="LogQuery", type="bool" },
{ name="LogChannel", type="bool" },
{ name="LogPermissions", type="bool" },
{ name="LogServer", type="bool" },
{ name="LogFiletransfer", type="bool" },
{ name="MinClientVersion", type="DateTime" },
{ name="ReservedSlots", type="u16" },
{ name="TotalPacketlossSpeech", type="f32" },
{ name="TotalPacketlossKeepalive", type="f32" },
{ name="TotalPacketlossControl", type="f32" },
{ name="TotalPacketloss", type="f32" },
{ name="TotalPing", type="Duration" },
{ name="WeblistEnabled", type="bool" },
{ name="MinAndroidVersion", type="DateTime", doc="TODO Maybe str" },
{ name="MinIosVersion", type="DateTime" },
]
[[struct]]
name = "ConnectionServerData"
opt = true
id = [
]
doc = "Get by notifyserverconnectioninfo after serverrequestconnectioninfo"
properties = [
{ name="FiletransferBandwidthSent", type="u64" },
{ name="FiletransferBandwidthReceived", type="u64" },
{ name="FiletransferBytesSentTotal", type="u64" },
{ name="FiletransferBytesReceivedTotal", type="u64" },
{ name="PacketsSentTotal", type="u64" },
{ name="BytesSentTotal", type="u64" },
{ name="PacketsReceivedTotal", type="u64" },
{ name="BytesReceivedTotal", type="u64" },
{ name="BandwidthSentLastSecondTotal", type="u64" },
{ name="BandwidthSentLastMinuteTotal", type="u64" },
{ name="BandwidthReceivedLastSecondTotal", type="u64" },
{ name="BandwidthReceivedLastMinuteTotal", type="u64" },
{ name="ConnectedTimeTotal", type="Duration" },
{ name="PacketlossTotal", type="f32" },
{ name="Ping", type="Duration" },
]
[[struct]]
name = "Server"
id = [
]
doc = "Get in initserver"
properties = [
{ name="PublicKey", type="EccKeyPubP256" },
{ name="Id", type="u64", doc="The virtual server id" },
# `Uid` is generated from public key
{ name="Name", type="str" },
{ name="Nickname", type="str", opt=true },
{ name="WelcomeMessage", type="str", doc="Welcome message when connecting to a server" },
{ name="Platform", type="str" },
{ name="Version", type="str" },
{ name="MaxClients", type="u16", doc="The maximum number of clients on the server" },
{ name="Created", type="DateTime", doc="Seems to be always 0" },
{ name="CodecEncryptionMode", type="CodecEncryptionMode" },
{ name="Hostmessage", type="str" },
{ name="HostmessageMode", type="HostMessageMode" },
{ name="DefaultServerGroup", type="ServerGroupId" },
{ name="DefaultChannelGroup", type="ChannelGroupId" },
{ name="HostbannerUrl", type="str" },
{ name="HostbannerGfxUrl", type="str" },
{ name="HostbannerGfxInterval", type="Duration", doc="How often the hostbanner should be updated" },
{ name="PrioritySpeakerDimmModificator", type="f32" },
{ name="HostbuttonTooltip", type="str" },
{ name="HostbuttonUrl", type="str" },
{ name="HostbuttonGfxUrl", type="str" },
{ name="PhoneticName", type="str" },
{ name="Icon", type="IconId", doc="Should be an u32, sometimes the server sends an u64 or an i32 for reasons which has to be cut to 32 bit" },
{ name="Ips", type="IpAddr", mod="array", doc="A list of listen ips, can be empty" },
{ name="AskForPrivilegekey", type="bool" },
{ name="HostbannerMode", type="HostBannerMode" },
{ name="TempChannelDefaultDeleteDelay", type="Duration" },
{ name="ProtocolVersion", type="u16" },
{ name="License", type="LicenseType" },
{ name="AdministrativeDomain", type="str", opt=true },
{ name="OptionalData", type="OptionalServerData", opt=true },
{ name="ConnectionData", type="ConnectionServerData", opt=true },
]
[[struct]]
name = "Connection"
id = [
]
doc = "A connection from our client to a server"
properties = [
{ name="OwnClient", type="ClientId", doc="The id of our own client on the server" },
{ name="Server", type="Server", doc="The server of this connection" },
{ name="Clients", type="Client", mod="map", key="ClientId", doc="All clients which are visible for us" },
{ name="Channels", type="Channel", mod="map", key="ChannelId", doc="All channels on the server" },
{ name="ServerGroups", type="ServerGroup", mod="map", key="ServerGroupId", doc="All server groups on the server" },
{ name="ChannelGroups", type="ChannelGroup", mod="map", key="ChannelGroupId", doc="All channel groups on the server" },
]
@@ -0,0 +1,393 @@
# As in M2B from/to properties can be automatically mapped when they have
# the same high-level name.
[[rule]]
# From the Book
from = "Channel"
# Into message
to = "ChannelEdit"
operation = "update"
# The static message parameters
# Can be often empty
# Can be inferred from required message parameters
ids = [
{ from="Id", to="ChannelId" },
]
# The dynamic message parameters
# from is the property which gets updated, to is the field in the message
properties = [
# Function which reads a value form the book and splits it up
# into multiple message parameters
# fn bla(Channel, MaxClientChannelInherited) -> (type of asd)
#{ from="MaxClientChannelInherited", function="Bla", tolist=["asd"] },
{ from="password", type="str?", function="PasswordFlaggedB2m", tolist=["HasPassword", "Password"] }, # 'password' is a helper
{ from="ChannelType", type="ChannelType", function="ChannelTypeFunB2m", tolist=["IsSemiPermanent", "IsPermanent"] },
{ from="MaxClients", type="MaxClients", function="MaxClientsFunB2m", tolist=["MaxClients", "IsMaxClientsUnlimited"] },
{ from="MaxFamilyClients", type="MaxClients", function="MaxFamilyClientsFunB2m", tolist=["MaxFamilyClients", "IsMaxFamilyClientsUnlimited", "InheritsMaxFamilyClients"] },
{ from="Description", to="Description" }, # From optional data
]
[[rule]]
from = "Channel"
to = "ChannelAddPerm"
operation = "update"
ids = [
{ from="Id", to="ChannelId" },
{ from="Value", to="PermissionValue" },
]
properties = [
{ from="PermissionId", to ="PermissionId" },
{ from="PermissionName", to ="PermissionNameId" },
]
# Define Client-Channel-Permissions on the channel, because a channel always exists and we need to
# be able to change permissions, even if a client is not online.
[[rule]]
from = "Channel"
to = "ChannelClientAddPerm"
operation = "update"
ids = [
{ from="Id", to="ChannelId" },
{ from="ClientDbId", to="ClientDbId" },
{ from="Value", to="PermissionValue" },
]
properties = [
{ from="PermissionId", to ="PermissionId" },
{ from="PermissionName", to ="PermissionNameId" },
]
[[rule]]
from = "Channel"
to = "ChannelClientDelPerm"
operation = "update"
ids = [
{ from="Id", to="ChannelId" },
{ from="ClientDbId", to="ClientDbId" },
]
properties = [
{ from="PermissionId", to ="PermissionId" },
{ from="PermissionName", to ="PermissionNameId" },
]
[[rule]]
from = "Channel"
to = "ChannelClientPermListRequest"
operation = "update"
ids = [
{ from="Id", to="ChannelId" },
{ from="ClientDbId", to="ClientDbId" },
]
[[rule]]
from = "Channel"
to = "ChannelDelPerm"
operation = "update"
ids = [
{ from="Id", to="ChannelId" },
]
properties = [
{ from="PermissionId", to ="PermissionId" },
{ from="PermissionName", to ="PermissionNameId" },
]
[[rule]]
from = "Channel"
to = "ChannelDescriptionRequest"
operation = "update"
ids = [
{ from="Id", to="ChannelId" },
]
[[rule]]
from = "Channel"
to = "ChannelMove"
operation = "update"
ids = [
{ from="Id", to="ChannelId" },
{ from="Parent", type="ChannelId", function="ChannelIdB2m", tolist=["ParentId"] },
{ from="Order", type="ChannelId", function="ChannelIdB2m", tolist=["Order"] },
]
[[rule]]
from = "Channel"
to = "ChannelPermListRequest"
operation = "update"
ids = [
{ from="Id", to="ChannelId" },
]
# Filetransfer stuff for Channel
[[rule]]
from = "Channel"
to = "CreateDirectory"
operation = "update"
ids = [
{ from="Id", to="ChannelId" },
{ from="Password", type="str", function="PasswordB2m", tolist=["ChannelPassword"] },
{ from="Path", to="DirectoryName" },
]
[[rule]]
from = "Channel"
to = "DeleteFile"
operation = "update"
ids = [
{ from="Id", to="ChannelId" },
{ from="Password", type="str", function="PasswordB2m", tolist=["ChannelPassword"] },
{ from="Path", to="Name" },
]
[[rule]]
from = "Channel"
to = "FileListRequest"
operation = "update"
ids = [
{ from="Id", to="ChannelId" },
{ from="Password", type="str", function="PasswordB2m", tolist=["ChannelPassword"] },
{ from="Path", to="Path" },
]
[[rule]]
from = "Channel"
to = "RenameFile"
operation = "update"
ids = [
{ from="Id", to="ChannelId" },
{ from="Password", type="str", function="PasswordB2m", tolist=["ChannelPassword"] },
{ from="FromPath", to="OldName" },
{ from="ToPath", to="NewName" },
]
properties = [
{ from="ToChannel", to="TargetChannelId" },
{ from="ToChannelPassword", type="str", function="PasswordB2m2", tolist=["TargetChannelPassword"] },
]
[[rule]]
from = "Client"
to = "ClientAddPerm"
operation = "update"
ids = [
{ from="DatabaseId", to="ClientDbId" },
{ from="Value", to="PermissionValue" },
{ from="Skip", to="PermissionSkip" },
]
properties = [
{ from="PermissionId", to ="PermissionId" },
{ from="PermissionName", to ="PermissionNameId" },
]
[[rule]]
from = "Client"
to = "ClientConnectionInfoRequest"
operation = "update"
ids = [
{ from="Id", to="ClientId" },
]
[[rule]]
from = "Client"
to = "ClientDelPerm"
operation = "update"
ids = [
{ from="DatabaseId", to="ClientDbId" },
]
properties = [
{ from="PermissionId", to ="PermissionId" },
{ from="PermissionName", to ="PermissionNameId" },
]
[[rule]]
from = "Client"
to = "ClientPermListRequest"
operation = "update"
ids = [
{ from="DatabaseId", to="ClientDbId" },
]
[[rule]]
from = "Client"
to = "ClientVariablesRequest"
operation = "update"
ids = [
{ from="Id", to="ClientId" },
]
[[rule]]
from = "Client"
to = "ClientEdit"
operation = "update"
ids = [
{ from="Id", to="ClientId" },
]
[[rule]]
from = "Connection"
to = "ClientUpdate"
operation = "update"
properties = [
# The original properties are on the client object, but we can only change
# our own properties, so these methods are available on the connection.
{ from="Name", to="Name" },
{ from="PhoneticName", to="PhoneticName" },
{ from="InputMuted", to="InputMuted" },
{ from="OutputMuted", to="OutputMuted" },
{ from="InputHardwareEnabled", to="InputHardwareEnabled" },
{ from="OutputHardwareEnabled", to="OutputHardwareEnabled" },
{ from="IsChannelCommander", to="IsChannelCommander" },
{ from="IsRecording", to="IsRecording" },
{ from="AvatarHash", to="AvatarHash" },
{ from="Away", type="str?", function="AwayFunB2m", tolist=["IsAway", "AwayMessage"] },
{ from="TalkPowerRequest", type="str?", function="AwayFunB2m", tolist=["TalkPowerRequest", "TalkPowerRequestMessage"] },
]
[[rule]]
from = "Connection"
to = "Disconnect"
operation = "remove"
[[rule]]
from = "Connection"
to = "PluginCommandRequest"
operation = "update"
ids = [
{ from="Name", to="Name" },
{ from="Data", to="Data" },
{ from="Target", to="Target" },
# TODO optional
{ from="TargetClientId", to="TargetClientId" },
]
[[rule]]
from = "Client"
to = "ServerGroupAddClient"
operation = "add"
ids = [
{ from="DatabaseId", to="ClientDbId" },
]
properties = [
{ from="ServerGroup", to="ServerGroupId" },
]
[[rule]]
from = "Client"
to = "ServerGroupDelClient"
operation = "remove"
ids = [
{ from="DatabaseId", to="ClientDbId" },
]
properties = [
{ from="ServerGroup", to="ServerGroupId" },
]
[[rule]]
from = "Client"
to = "ClientMove"
operation = "update"
ids = [
{ from="Id", to="ClientId" },
{ from="Channel", type="ChannelId", function="ChannelIdB2m", tolist=["ChannelId"] },
]
properties = [
{ from="Password", type="str", function="PasswordB2m", tolist=["ChannelPassword"] },
]
[[rule]]
from = "Client"
to = "ClientKick"
operation = "update"
ids = [
{ from="Id", to="ClientId" },
{ from="Reason", to="Reason" },
]
properties = [
{ from="ReasonMessage", to="ReasonMessage" },
]
[[rule]]
from = "Server"
to = "FileListRequest"
operation = "update"
ids = [
{ function="ZeroChannelId", tolist=["ChannelId"] },
{ function="EmptyString", tolist=["ChannelPassword"] },
{ from="Path", to="Path" },
]
[[rule]]
from = "Server"
to = "DeleteFile"
operation = "update"
ids = [
{ function="ZeroChannelId", tolist=["ChannelId"] },
{ function="EmptyString", tolist=["ChannelPassword"] },
{ from="Path", to="Name" },
]
[[rule]]
from = "Server"
to = "PermListRequest"
operation = "update"
ids = [
]
[[rule]]
from = "Server"
to = "ServerVariablesRequest"
operation = "update"
ids = [
]
[[rule]]
from = "Server"
to = "ServerConnectionInfoRequest"
operation = "update"
ids = [
]
[[rule]]
from = "Server"
to = "LogView"
operation = "update"
ids = [
]
properties = [
{ from="Lines", to="Lines" },
{ from="Reverse", to="Reverse" },
{ from="InstanceLog", to="InstanceLog" },
{ from="Offset", to="Offset" },
]
[[rule]]
from = "Server"
to = "ServerEdit"
operation = "update"
ids = [
]
properties = [
{ from="Password", type="str?", function="PasswordB2m", tolist=["Password"] },
]
[[rule]]
from = "ServerGroup"
to = "ServerGroupAddClient"
operation = "add"
ids = [
{ from="Id", to="ServerGroupId" },
]
properties = [
{ from="Client", to="ClientDbId" },
]
[[rule]]
from = "ServerGroup"
to = "ServerGroupDelClient"
operation = "remove"
ids = [
{ from="Id", to="ServerGroupId" },
# Not an id attribute of the server group, but we want to have it as an
# argument.
{ from="Client", to="ClientDbId" },
]
@@ -0,0 +1,172 @@
[[enum]]
name = "PermissionType"
#type = "u32"
#doc = ""
variants = [
{ name="ServerGroup", doc="Server group permission. (id1: ServerGroupId, id2: 0)" },
{ name="GlobalClient", doc="Client specific permission. (id1: ClientDbId, id2: 0)" },
{ name="Channel", doc="Channel specific permission. (id1: ChannelId, id2: 0)" },
{ name="ChannelGroup", doc="Channel group permission. (id1: ChannelId, id2: ChannelGroupId)" },
{ name="ChannelClient", doc="Channel-client specific permission. (id1: ChannelId, id2: ClientDbId)" },
]
[[enum]]
name = "TextMessageTargetMode"
variants = [
{ name="Unknown", doc="Maybe to all servers?" },
{ name="Client", doc="Send to specific client" },
{ name="Channel", doc="Send to current channel" },
{ name="Server", doc="Send to server chat" },
]
[[enum]]
name = "HostMessageMode"
variants = [
{ name="None", doc="Dont display anything" },
{ name="Log", doc="Display message inside log" },
{ name="Modal", doc="Display message inside a modal dialog" },
{ name="Modalquit", doc="Display message inside a modal dialog and quit/close server/connection" },
]
[[enum]]
name = "HostBannerMode"
variants = [
{ name="NoAdjust", doc="Do not adjust" },
{ name="AdjustIgnoreAspect", doc="Adjust and ignore aspect ratio" },
{ name="AdjustKeepAspect", doc="Adjust and keep aspect ratio" },
]
[[enum]]
name = "Codec"
variants = [
{ name="SpeexNarrowband", doc="Mono, 16bit, 8kHz, bitrate dependent on the quality setting" },
{ name="SpeexWideband", doc="Mono, 16bit, 16kHz, bitrate dependent on the quality setting" },
{ name="SpeexUltrawideband", doc="Mono, 16bit, 32kHz, bitrate dependent on the quality setting" },
{ name="CeltMono", doc="Mono, 16bit, 48kHz, bitrate dependent on the quality setting" },
{ name="OpusVoice", doc="Mono, 16bit, 48kHz, bitrate dependent on the quality setting, optimized for voice" },
{ name="OpusMusic", doc="Stereo, 16bit, 48kHz, bitrate dependent on the quality setting, optimized for music" },
]
[[enum]]
name = "CodecEncryptionMode"
variants = [
{ name="PerChannel", doc="Voice encryption is configured per channel" },
{ name="ForcedOff", doc="Voice encryption is globally off" },
{ name="ForcedOn", doc="Voice encryption is globally on" },
]
[[enum]]
name = "Reason"
variants = [
{ name="None", doc="No reason data" },
{ name="Moved", doc="Has invoker" },
{ name="Subscription", doc="No reason data" },
{ name="LostConnection", doc="Timeout" },
{ name="KickChannel", doc="Has invoker" },
{ name="KickServer", doc="Has invoker" },
{ name="KickServerBan", doc="Has invoker, bantime" },
{ name="Serverstop", doc="" },
{ name="Clientdisconnect", doc="" },
{ name="Channelupdate", doc="No reason data" },
{ name="Channeledit", doc="Has invoker" },
{ name="ClientdisconnectServerShutdown", doc="" },
]
[[enum]]
name = "GroupNamingMode"
variants = [
{ name="None", doc="No group name is displayed." },
{ name="Before", doc="Group name is displayed before the client name." },
{ name="After", doc="Group name is displayed after the client name." },
]
[[enum]]
name = "GroupType"
variants = [
{ name="Template", doc="Template group (used for new virtual servers)." },
{ name="Regular", doc="Regular group (used for regular clients)." },
{ name="Query", doc="Global query group (used for server query clients)." },
]
[[enum]]
name = "LicenseType"
variants = [
{ name="NoLicense", doc="No licence" },
{ name="Offline", doc="Offline/LAN license" },
{ name="Sdk", doc="TeamSpeak SDK license" },
{ name="SdkOffline", doc="TeamSpeak SDK offline license" },
{ name="Npl", doc="Non-Profit License (NPL)" },
{ name="Athp", doc="Authorised TeamSpeak Host Provider License (ATHP)" },
{ name="Aal", doc="Annual activation license (AAL)" },
{ name="Default", doc="Default license with 32 slots" },
{ name="Gamer", doc="Gamer license" },
{ name="Sponsorship", doc="Licenses sponsored by TeamSpeak" },
{ name="Commercial", doc="For use inside corporates" },
]
[[enum]]
name = "ChannelType"
variants = [
{ name="Permanent", doc="Normal channel" },
{ name="SemiPermanent", doc="Deleted when the server restarts" },
{ name="Temporary", doc="Deleted when empty" },
]
[[enum]]
name = "TokenType"
variants = [
{ name="ServerGroup", doc="Server group token (`id1={groupId}, id2=0`)" },
{ name="ChannelGroup", doc="Channel group token (`id1={groupId}, id2={channelId}`)" },
]
[[enum]]
name = "PluginTargetMode"
variants = [
{ name="CurrentChannel", doc="Send to all clients in the current channel." },
{ name="Server", doc="Send to all clients on the server." },
{ name="Client", doc="Send to all given clients ids." },
{ name="CurrentChannelSubsribedClients", doc="Send to all given clients which are subscribed to the current channel (i.e. which see the this client)." },
]
[[enum]]
name = "LogLevel"
variants = [
{ name="Error", doc="Everything that is really bad.", value=1 },
{ name="Warning", doc="Everything that might be bad." },
{ name="Debug", doc="Output that might help find a problem." },
{ name="Info", doc="Informational output." },
]
[[bitflag]]
name = "ChannelPermissionHint"
doc = "Hints if the client has the permission to make specific actions."
variants = [
{ name="Join", doc="b_channel_join_*", value=1 },
{ name="Modify", doc="i_channel_modify_power", value=2 },
{ name="ForceDelete", doc="b_channel_delete_flag_force", value=4 },
{ name="Delete", doc="b_channel_delete_*", value=8 },
{ name="Subscribe", doc="i_channel_subscribe_power", value=16 },
{ name="ViewDescription", doc="i_channel_description_view_power", value=32 },
{ name="FileUpload", doc="i_ft_file_upload_power", value=64 },
{ name="FileDownload", doc="i_ft_needed_file_download_power", value=128 },
{ name="FileDelete", doc="i_ft_file_delete_power", value=256 },
{ name="FileRename", doc="i_ft_file_rename_power", value=512 },
{ name="FileBrowse", doc="i_ft_file_browse_power", value=1024 },
{ name="FileDirectoryCreate", doc="i_ft_directory_create_power", value=2048 },
{ name="ModifyPermissions", doc="i_channel_permission_modify_power", value=4096 },
]
[[bitflag]]
name = "ClientPermissionHint"
doc = "Hints if the client has the permission to make specific actions."
variants = [
{ name="KickServer", doc="i_client_kick_from_server_power", value=1 },
{ name="KickChannel", doc="i_client_kick_from_channel_power", value=2 },
{ name="Ban", doc="i_client_ban_power", value=4 },
{ name="MoveClient", doc="i_client_move_power", value=8 },
{ name="PrivateMessage", doc="i_client_private_textmessage_power", value=16 },
{ name="Poke", doc="i_client_poke_power", value=32 },
{ name="Whisper", doc="i_client_whisper_power", value=64 },
{ name="Complain", doc="i_client_complain_power", value=128 },
{ name="ModifyPermissions", doc="i_client_permission_modify_power", value=256 },
]
@@ -0,0 +1,197 @@
name,doc,num
ok,unknown error code,0x0000
undefined,undefined error,0x0001
not_implemented,not implemented,0x0002
ok_no_update,,0x0003
dont_notify,,0x0004
lib_time_limit_reached,library time limit reached,0x0005
command_not_found,command not found,0x0100
unable_to_bind_network_port,unable to bind network port,0x0101
no_network_port_available,no network port available,0x0102
client_invalid_id,invalid clientID,0x0200
client_nickname_inuse,nickname is already in use,0x0201
client_invalid_error_code,invalid error code,0x0202
client_protocol_limit_reached,max clients protocol limit reached,0x0203
client_invalid_type,invalid client type,0x0204
client_already_subscribed,already subscribed,0x0205
client_not_logged_in,not logged in,0x0206
client_could_not_validate_identity,could not validate client identity,0x0207
client_invalid_password,invalid loginname or password,0x0208
client_too_many_clones_connected,too many clones already connected,0x0209
client_version_outdated,"client version outdated, please update",0x020a
client_is_online,client is online,0x020b
client_is_flooding,client is flooding,0x020c
client_hacked,client is modified,0x020d
client_cannot_verify_now,can not verify client at this moment,0x020e
client_login_not_permitted,client is not permitted to log in,0x020f
client_not_subscribed,client is not subscribed to the channel,0x0210
channel_invalid_id,invalid channelID,0x0300
channel_protocol_limit_reached,max channels protocol limit reached,0x0301
channel_already_in,already member of channel,0x0302
channel_name_inuse,channel name is already in use,0x0303
channel_not_empty,channel not empty,0x0304
channel_can_not_delete_default,can not delete default channel,0x0305
channel_default_require_permanent,default channel requires permanent,0x0306
channel_invalid_flags,invalid channel flags,0x0307
channel_parent_not_permanent,permanent channel can not be child of non permanent channel,0x0308
channel_maxclients_reached,channel maxclient reached,0x0309
channel_maxfamily_reached,channel maxfamily reached,0x030a
channel_invalid_order,invalid channel order,0x030b
channel_no_filetransfer_supported,channel does not support filetransfers,0x030c
channel_invalid_password,invalid channel password,0x030d
channel_is_private_channel,channel is private channel,0x030e
channel_invalid_security_hash,invalid security hash supplied by client,0x030f
server_invalid_id,invalid serverID,0x0400
server_running,server is running,0x0401
server_is_shutting_down,server is shutting down,0x0402
server_maxclients_reached,server maxclient reached,0x0403
server_invalid_password,invalid server password,0x0404
server_deployment_active,deployment active,0x0405
server_unable_to_stop_own_server,unable to stop own server in your connection class,0x0406
server_is_virtual,server is virtual,0x0407
server_wrong_machineid,server wrong machineID,0x0408
server_is_not_running,server is not running,0x0409
server_is_booting,server is booting up,0x040a
server_status_invalid,server got an invalid status for this operation,0x040b
server_modal_quit,server modal quit,0x040c
server_version_outdated,server version is too old for command,0x040d
database,database error,0x0500
database_empty_result,database empty result set,0x0501
database_duplicate_entry,database duplicate entry,0x0502
database_no_modifications,database no modifications,0x0503
database_constraint,database invalid constraint,0x0504
database_reinvoke,database reinvoke command,0x0505
parameter_quote,invalid quote,0x0600
parameter_invalid_count,invalid parameter count,0x0601
parameter_invalid,invalid parameter,0x0602
parameter_not_found,parameter not found,0x0603
parameter_convert,convert error,0x0604
parameter_invalid_size,invalid parameter size,0x0605
parameter_missing,missing required parameter,0x0606
parameter_checksum,invalid checksum,0x0607
vs_critical,virtual server got a critical error,0x0700
connection_lost,Connection lost,0x0701
not_connected,not connected,0x0702
no_cached_connection_info,no cached connection info,0x0703
currently_not_possible,currently not possible,0x0704
failed_connection_initialisation,failed connection initialization,0x0705
could_not_resolve_hostname,could not resolve hostname,0x0706
invalid_server_connection_handler_id,invalid server connection handler ID,0x0707
could_not_initialise_input_manager,could not initialize Input Manager,0x0708
clientlibrary_not_initialised,client library not initialized,0x0709
serverlibrary_not_initialised,server library not initialized,0x070a
whisper_too_many_targets,too many whisper targets,0x070b
whisper_no_targets,no whisper targets found,0x070c
file_invalid_name,invalid file name,0x0800
file_invalid_permissions,invalid file permissions,0x0801
file_already_exists,file already exists,0x0802
file_not_found,file not found,0x0803
file_io_error,file input/output error,0x0804
file_invalid_transfer_id,invalid file transfer ID,0x0805
file_invalid_path,invalid file path,0x0806
file_no_files_available,no files available,0x0807
file_overwrite_excludes_resume,overwrite excludes resume,0x0808
file_invalid_size,invalid file size,0x0809
file_already_in_use,file already in use,0x080a
file_could_not_open_connection,could not open file transfer connection,0x080b
file_no_space_left_on_device,no space left on device (disk full?),0x080c
file_exceeds_file_system_maximum_size,file exceeds file system's maximum file size,0x080d
file_transfer_connection_timeout,file transfer connection timeout,0x080e
file_connection_lost,lost file transfer connection,0x080f
file_exceeds_supplied_size,file exceeds supplied file size,0x0810
file_transfer_complete,file transfer complete,0x0811
file_transfer_canceled,file transfer canceled,0x0812
file_transfer_interrupted,file transfer interrupted,0x0813
file_transfer_server_quota_exceeded,file transfer server quota exceeded,0x0814
file_transfer_client_quota_exceeded,file transfer client quota exceeded,0x0815
file_transfer_reset,file transfer reset,0x0816
file_transfer_limit_reached,file transfer limit reached,0x0817
sound_preprocessor_disabled,preprocessor disabled,0x0900
sound_internal_preprocessor,internal preprocessor,0x0901
sound_internal_encoder,internal encoder,0x0902
sound_internal_playback,internal playback,0x0903
sound_no_capture_device_available,no capture device available,0x0904
sound_no_playback_device_available,no playback device available,0x0905
sound_could_not_open_capture_device,could not open capture device,0x0906
sound_could_not_open_playback_device,could not open playback device,0x0907
sound_handler_has_device,ServerConnectionHandler has a device registered,0x0908
sound_invalid_capture_device,invalid capture device,0x0909
sound_invalid_playback_device,invalid clayback device,0x090a
sound_invalid_wave,invalid wave file,0x090b
sound_unsupported_wave,wave file type not supported,0x090c
sound_open_wave,could not open wave file,0x090d
sound_internal_capture,internal capture,0x090e
sound_device_in_use,device still in use,0x090f
sound_device_already_registerred,device already registerred,0x0910
sound_unknown_device,device not registered/known,0x0911
sound_unsupported_frequency,unsupported frequency,0x0912
sound_invalid_channel_count,invalid channel count,0x0913
sound_read_wave,read error in wave,0x0914
sound_need_more_data,sound need more data,0x0915
sound_device_busy,sound device was busy,0x0916
sound_no_data,there is no sound data for this period,0x0917
sound_channel_mask_mismatch,Channelmask set bits count (speakers) is not the same as (count),0x0918
permission_invalid_group_id,invalid group ID,0x0a00
permission_duplicate_entry,duplicate entry,0x0a01
permission_invalid_perm_id,invalid permission ID,0x0a02
permission_empty_result,empty result set,0x0a03
permission_default_group_forbidden,access to default group is forbidden,0x0a04
permission_invalid_size,invalid size,0x0a05
permission_invalid_value,invalid value,0x0a06
permissions_group_not_empty,group is not empty,0x0a07
permissions_client_insufficient,insufficient client permissions,0x0a08
permissions_insufficient_group_power,insufficient group modify power,0x0a09
permissions_insufficient_permission_power,insufficient permission modify power,0x0a0a
permission_template_group_is_used,template group is currently used,0x0a0b
permissions,permission error,0x0a0c
accounting_virtualserver_limit_reached,virtualserver limit reached,0x0b00
accounting_slot_limit_reached,max slot limit reached,0x0b01
accounting_license_file_not_found,license file not found,0x0b02
accounting_license_date_not_ok,license date not ok,0x0b03
accounting_unable_to_connect_to_server,unable to connect to accounting server,0x0b04
accounting_unknown_error,unknown accounting error,0x0b05
accounting_server_error,accounting server error,0x0b06
accounting_instance_limit_reached,instance limit reached,0x0b07
accounting_instance_check_error,instance check error,0x0b08
accounting_license_file_invalid,license file invalid,0x0b09
accounting_running_elsewhere,virtualserver is running elsewhere,0x0b0a
accounting_instance_duplicated,virtualserver running in same instance already,0x0b0b
accounting_already_started,virtualserver already started,0x0b0c
accounting_not_started,virtualserver not started,0x0b0d
accounting_to_many_starts,,0x0b0e
message_invalid_id,invalid message id,0x0c00
ban_invalid_id,invalid ban id,0x0d00
connect_failed_banned,"connection failed, you are banned",0x0d01
rename_failed_banned,"rename failed, new name is banned",0x0d02
ban_flooding,flood ban,0x0d03
tts_unable_to_initialize,unable to initialize tts,0x0e00
privilege_key_invalid,invalid privilege key,0x0f00
voip_pjsua,,0x1000
voip_already_initialized,,0x1001
voip_too_many_accounts,,0x1002
voip_invalid_account,,0x1003
voip_internal_error,,0x1004
voip_invalid_connectionId,,0x1005
voip_cannot_answer_initiated_call,,0x1006
voip_not_initialized,,0x1007
provisioning_invalid_password,invalid password,0x1100
provisioning_invalid_request,invalid request,0x1101
provisioning_no_slots_available,no(more) slots available,0x1102
provisioning_pool_missing,pool missing,0x1103
provisioning_pool_unknown,pool unknown,0x1104
provisioning_unknown_ip_location,unknown ip location(perhaps LAN ip?),0x1105
provisioning_internal_tries_exceeded,internal error(tried exceeded),0x1106
provisioning_too_many_slots_requested,too many slots requested,0x1107
provisioning_too_many_reserved,too many reserved,0x1108
provisioning_could_not_connect,could not connect to provisioning server,0x1109
provisioning_auth_server_not_connected,authentication server not connected,0x1110
provisioning_auth_data_too_large,authentication data too large,0x1111
provisioning_already_initialized,already initialized,0x1112
provisioning_not_initialized,not initialized,0x1113
provisioning_connecting,already connecting,0x1114
provisioning_already_connected,already connected,0x1115
provisioning_not_connected,,0x1116
provisioning_io_error,io_error,0x1117
provisioning_invalid_timeout,,0x1118
provisioning_ts3server_not_found,,0x1119
provisioning_no_permission,unknown permissionID,0x111A
1 name doc num
2 ok unknown error code 0x0000
3 undefined undefined error 0x0001
4 not_implemented not implemented 0x0002
5 ok_no_update 0x0003
6 dont_notify 0x0004
7 lib_time_limit_reached library time limit reached 0x0005
8 command_not_found command not found 0x0100
9 unable_to_bind_network_port unable to bind network port 0x0101
10 no_network_port_available no network port available 0x0102
11 client_invalid_id invalid clientID 0x0200
12 client_nickname_inuse nickname is already in use 0x0201
13 client_invalid_error_code invalid error code 0x0202
14 client_protocol_limit_reached max clients protocol limit reached 0x0203
15 client_invalid_type invalid client type 0x0204
16 client_already_subscribed already subscribed 0x0205
17 client_not_logged_in not logged in 0x0206
18 client_could_not_validate_identity could not validate client identity 0x0207
19 client_invalid_password invalid loginname or password 0x0208
20 client_too_many_clones_connected too many clones already connected 0x0209
21 client_version_outdated client version outdated, please update 0x020a
22 client_is_online client is online 0x020b
23 client_is_flooding client is flooding 0x020c
24 client_hacked client is modified 0x020d
25 client_cannot_verify_now can not verify client at this moment 0x020e
26 client_login_not_permitted client is not permitted to log in 0x020f
27 client_not_subscribed client is not subscribed to the channel 0x0210
28 channel_invalid_id invalid channelID 0x0300
29 channel_protocol_limit_reached max channels protocol limit reached 0x0301
30 channel_already_in already member of channel 0x0302
31 channel_name_inuse channel name is already in use 0x0303
32 channel_not_empty channel not empty 0x0304
33 channel_can_not_delete_default can not delete default channel 0x0305
34 channel_default_require_permanent default channel requires permanent 0x0306
35 channel_invalid_flags invalid channel flags 0x0307
36 channel_parent_not_permanent permanent channel can not be child of non permanent channel 0x0308
37 channel_maxclients_reached channel maxclient reached 0x0309
38 channel_maxfamily_reached channel maxfamily reached 0x030a
39 channel_invalid_order invalid channel order 0x030b
40 channel_no_filetransfer_supported channel does not support filetransfers 0x030c
41 channel_invalid_password invalid channel password 0x030d
42 channel_is_private_channel channel is private channel 0x030e
43 channel_invalid_security_hash invalid security hash supplied by client 0x030f
44 server_invalid_id invalid serverID 0x0400
45 server_running server is running 0x0401
46 server_is_shutting_down server is shutting down 0x0402
47 server_maxclients_reached server maxclient reached 0x0403
48 server_invalid_password invalid server password 0x0404
49 server_deployment_active deployment active 0x0405
50 server_unable_to_stop_own_server unable to stop own server in your connection class 0x0406
51 server_is_virtual server is virtual 0x0407
52 server_wrong_machineid server wrong machineID 0x0408
53 server_is_not_running server is not running 0x0409
54 server_is_booting server is booting up 0x040a
55 server_status_invalid server got an invalid status for this operation 0x040b
56 server_modal_quit server modal quit 0x040c
57 server_version_outdated server version is too old for command 0x040d
58 database database error 0x0500
59 database_empty_result database empty result set 0x0501
60 database_duplicate_entry database duplicate entry 0x0502
61 database_no_modifications database no modifications 0x0503
62 database_constraint database invalid constraint 0x0504
63 database_reinvoke database reinvoke command 0x0505
64 parameter_quote invalid quote 0x0600
65 parameter_invalid_count invalid parameter count 0x0601
66 parameter_invalid invalid parameter 0x0602
67 parameter_not_found parameter not found 0x0603
68 parameter_convert convert error 0x0604
69 parameter_invalid_size invalid parameter size 0x0605
70 parameter_missing missing required parameter 0x0606
71 parameter_checksum invalid checksum 0x0607
72 vs_critical virtual server got a critical error 0x0700
73 connection_lost Connection lost 0x0701
74 not_connected not connected 0x0702
75 no_cached_connection_info no cached connection info 0x0703
76 currently_not_possible currently not possible 0x0704
77 failed_connection_initialisation failed connection initialization 0x0705
78 could_not_resolve_hostname could not resolve hostname 0x0706
79 invalid_server_connection_handler_id invalid server connection handler ID 0x0707
80 could_not_initialise_input_manager could not initialize Input Manager 0x0708
81 clientlibrary_not_initialised client library not initialized 0x0709
82 serverlibrary_not_initialised server library not initialized 0x070a
83 whisper_too_many_targets too many whisper targets 0x070b
84 whisper_no_targets no whisper targets found 0x070c
85 file_invalid_name invalid file name 0x0800
86 file_invalid_permissions invalid file permissions 0x0801
87 file_already_exists file already exists 0x0802
88 file_not_found file not found 0x0803
89 file_io_error file input/output error 0x0804
90 file_invalid_transfer_id invalid file transfer ID 0x0805
91 file_invalid_path invalid file path 0x0806
92 file_no_files_available no files available 0x0807
93 file_overwrite_excludes_resume overwrite excludes resume 0x0808
94 file_invalid_size invalid file size 0x0809
95 file_already_in_use file already in use 0x080a
96 file_could_not_open_connection could not open file transfer connection 0x080b
97 file_no_space_left_on_device no space left on device (disk full?) 0x080c
98 file_exceeds_file_system_maximum_size file exceeds file system's maximum file size 0x080d
99 file_transfer_connection_timeout file transfer connection timeout 0x080e
100 file_connection_lost lost file transfer connection 0x080f
101 file_exceeds_supplied_size file exceeds supplied file size 0x0810
102 file_transfer_complete file transfer complete 0x0811
103 file_transfer_canceled file transfer canceled 0x0812
104 file_transfer_interrupted file transfer interrupted 0x0813
105 file_transfer_server_quota_exceeded file transfer server quota exceeded 0x0814
106 file_transfer_client_quota_exceeded file transfer client quota exceeded 0x0815
107 file_transfer_reset file transfer reset 0x0816
108 file_transfer_limit_reached file transfer limit reached 0x0817
109 sound_preprocessor_disabled preprocessor disabled 0x0900
110 sound_internal_preprocessor internal preprocessor 0x0901
111 sound_internal_encoder internal encoder 0x0902
112 sound_internal_playback internal playback 0x0903
113 sound_no_capture_device_available no capture device available 0x0904
114 sound_no_playback_device_available no playback device available 0x0905
115 sound_could_not_open_capture_device could not open capture device 0x0906
116 sound_could_not_open_playback_device could not open playback device 0x0907
117 sound_handler_has_device ServerConnectionHandler has a device registered 0x0908
118 sound_invalid_capture_device invalid capture device 0x0909
119 sound_invalid_playback_device invalid clayback device 0x090a
120 sound_invalid_wave invalid wave file 0x090b
121 sound_unsupported_wave wave file type not supported 0x090c
122 sound_open_wave could not open wave file 0x090d
123 sound_internal_capture internal capture 0x090e
124 sound_device_in_use device still in use 0x090f
125 sound_device_already_registerred device already registerred 0x0910
126 sound_unknown_device device not registered/known 0x0911
127 sound_unsupported_frequency unsupported frequency 0x0912
128 sound_invalid_channel_count invalid channel count 0x0913
129 sound_read_wave read error in wave 0x0914
130 sound_need_more_data sound need more data 0x0915
131 sound_device_busy sound device was busy 0x0916
132 sound_no_data there is no sound data for this period 0x0917
133 sound_channel_mask_mismatch Channelmask set bits count (speakers) is not the same as (count) 0x0918
134 permission_invalid_group_id invalid group ID 0x0a00
135 permission_duplicate_entry duplicate entry 0x0a01
136 permission_invalid_perm_id invalid permission ID 0x0a02
137 permission_empty_result empty result set 0x0a03
138 permission_default_group_forbidden access to default group is forbidden 0x0a04
139 permission_invalid_size invalid size 0x0a05
140 permission_invalid_value invalid value 0x0a06
141 permissions_group_not_empty group is not empty 0x0a07
142 permissions_client_insufficient insufficient client permissions 0x0a08
143 permissions_insufficient_group_power insufficient group modify power 0x0a09
144 permissions_insufficient_permission_power insufficient permission modify power 0x0a0a
145 permission_template_group_is_used template group is currently used 0x0a0b
146 permissions permission error 0x0a0c
147 accounting_virtualserver_limit_reached virtualserver limit reached 0x0b00
148 accounting_slot_limit_reached max slot limit reached 0x0b01
149 accounting_license_file_not_found license file not found 0x0b02
150 accounting_license_date_not_ok license date not ok 0x0b03
151 accounting_unable_to_connect_to_server unable to connect to accounting server 0x0b04
152 accounting_unknown_error unknown accounting error 0x0b05
153 accounting_server_error accounting server error 0x0b06
154 accounting_instance_limit_reached instance limit reached 0x0b07
155 accounting_instance_check_error instance check error 0x0b08
156 accounting_license_file_invalid license file invalid 0x0b09
157 accounting_running_elsewhere virtualserver is running elsewhere 0x0b0a
158 accounting_instance_duplicated virtualserver running in same instance already 0x0b0b
159 accounting_already_started virtualserver already started 0x0b0c
160 accounting_not_started virtualserver not started 0x0b0d
161 accounting_to_many_starts 0x0b0e
162 message_invalid_id invalid message id 0x0c00
163 ban_invalid_id invalid ban id 0x0d00
164 connect_failed_banned connection failed, you are banned 0x0d01
165 rename_failed_banned rename failed, new name is banned 0x0d02
166 ban_flooding flood ban 0x0d03
167 tts_unable_to_initialize unable to initialize tts 0x0e00
168 privilege_key_invalid invalid privilege key 0x0f00
169 voip_pjsua 0x1000
170 voip_already_initialized 0x1001
171 voip_too_many_accounts 0x1002
172 voip_invalid_account 0x1003
173 voip_internal_error 0x1004
174 voip_invalid_connectionId 0x1005
175 voip_cannot_answer_initiated_call 0x1006
176 voip_not_initialized 0x1007
177 provisioning_invalid_password invalid password 0x1100
178 provisioning_invalid_request invalid request 0x1101
179 provisioning_no_slots_available no(more) slots available 0x1102
180 provisioning_pool_missing pool missing 0x1103
181 provisioning_pool_unknown pool unknown 0x1104
182 provisioning_unknown_ip_location unknown ip location(perhaps LAN ip?) 0x1105
183 provisioning_internal_tries_exceeded internal error(tried exceeded) 0x1106
184 provisioning_too_many_slots_requested too many slots requested 0x1107
185 provisioning_too_many_reserved too many reserved 0x1108
186 provisioning_could_not_connect could not connect to provisioning server 0x1109
187 provisioning_auth_server_not_connected authentication server not connected 0x1110
188 provisioning_auth_data_too_large authentication data too large 0x1111
189 provisioning_already_initialized already initialized 0x1112
190 provisioning_not_initialized not initialized 0x1113
191 provisioning_connecting already connecting 0x1114
192 provisioning_already_connected already connected 0x1115
193 provisioning_not_connected 0x1116
194 provisioning_io_error io_error 0x1117
195 provisioning_invalid_timeout 0x1118
196 provisioning_ts3server_not_found 0x1119
197 provisioning_no_permission unknown permissionID 0x111A
@@ -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.
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015 Sebastian Neubauer
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.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,268 @@
# All properties which have an identical 'High-Level' name are copied implicitly
[[rule]]
from = "ChannelCreated"
id = ["ChannelId"]
to = "Channel"
# add/update/remove
operation = "add"
properties = [
{ from="ParentId", to="Parent" },
{ function="ChannelTypeCcFun", tolist=["ChannelType"] },
{ function="ChannelOrderCcFun", tolist=["Order"] },
{ function="MaxClientsCcFun", tolist=["MaxClients", "MaxFamilyClients"] },
# Default codec is opus voice
{ function="ChannelCodecCcFun", tolist=["Codec"] },
{ function="ReturnFalse", tolist=["ForcedSilence"] },
{ function="ReturnFalse", tolist=["Subscribed"] },
{ function="ReturnNone", tolist=["IsPrivate"] },
{ function="ReturnNone", tolist=["Guid"] },
{ function="ReturnNone", tolist=["OptionalData"] },
{ function="ReturnNone", tolist=["PermissionHints"] },
]
[[rule]]
from = "ChannelDeleted"
id = ["ChannelId"]
to = "Channel"
operation = "remove"
[[rule]]
from = "ChannelEdited"
id = ["ChannelId"]
to = "Channel"
operation = "update"
properties = [
{ function="MaxClientsCeFun", tolist=["MaxClients", "MaxFamilyClients"] },
{ function="ChannelTypeCeFun", tolist=["ChannelType"] },
{ function="ChannelOrderCeFun", tolist=["Order"] },
]
[[rule]]
from = "ChannelEdited"
id = ["ChannelId"]
to = "OptionalChannelData"
operation = "update"
properties = [
]
[[rule]]
from = "ChannelEditedLow"
id = ["ChannelId"]
to = "OptionalChannelData"
operation = "update"
properties = [
]
[[rule]]
from = "ChannelDescriptionChanged"
id = ["ChannelId"]
to = "OptionalChannelData"
operation = "remove"
[[rule]]
from = "ChannelGroupList"
id = ["ChannelGroup"]
to = "ChannelGroup"
operation = "add"
[[rule]]
from = "ChannelList"
id = ["ChannelId"]
to = "Channel"
operation = "add"
properties = [
{ from="ParentId", to="Parent" },
{ function="MaxClientsClFun", tolist=["MaxClients", "MaxFamilyClients"] },
{ function="ChannelTypeClFun", tolist=["ChannelType"] },
{ function="ReturnFalse", tolist=["Subscribed"] },
{ function="ReturnNone", tolist=["PermissionHints"] },
{ function="ReturnNone", tolist=["OptionalData"] },
]
[[rule]]
from = "ChannelMoved"
id = ["ChannelId"]
to = "Channel"
operation = "update"
properties = [
{ from="ParentId", to="Parent" },
{ function="ChannelOrderCmFun", tolist=["Order"] },
]
[[rule]]
from = "ChannelPermissionHints"
id = ["ChannelId"]
to = "Channel"
operation = "update"
properties = [
{ from="Flags", to="PermissionHints" },
]
[[rule]]
from = "ChannelSubscribed"
id = ["ChannelId"]
to = "Channel"
operation = "update"
properties = [
{ function="ChannelSubscribeFun", tolist=["Subscribed"] },
]
[[rule]]
from = "ChannelUnsubscribed"
id = ["ChannelId"]
to = "Channel"
operation = "update"
properties = [
{ function="ChannelUnsubscribeFun", tolist=["Subscribed"] },
]
[[rule]]
from = "ClientChannelGroupChanged"
id = ["ClientId"]
to = "Client"
operation = "update"
[[rule]]
from = "ClientEnterView"
id = ["ClientId"]
to = "Client"
operation = "add"
properties = [
{ from="TargetChannelId", to="Channel" },
{ function="AwayCevFun", tolist=["AwayMessage"] },
{ function="ClientTypeCevFun", tolist=["ClientType"] },
{ function="TalkPowerCevFun", tolist=["TalkPowerRequest"] },
{ function="ReturnNone", tolist=["PermissionHints"] },
{ function="ReturnNone", tolist=["OptionalData"] },
{ function="ReturnNone", tolist=["ConnectionData"] },
]
[[rule]]
from = "ClientLeftView"
id = ["ClientId"]
to = "Client"
operation = "remove"
[[rule]]
from = "ClientMoved"
id = ["ClientId"]
to = "Client"
operation = "update"
properties = [
{ from="TargetChannelId", to="Channel" },
# Set channel subscribed when the current client is moved
{ function="SubscribeChannelFun", tolist=[] },
]
[[rule]]
from = "ClientConnectionInfo"
id = ["ClientId"]
to = "ConnectionClientData"
operation = "update"
properties = [
{ function="AddressFun", tolist=["ClientAddress"] },
]
[[rule]]
from = "ClientServerGroupAdded"
id = ["ClientId"]
to = "Client"
operation = "update"
properties = [
{ from="ServerGroupId", to="ServerGroups", operation="add" },
# We explicitly throw away the server group name.
# Otherwise it would overwrite our client name because of automated
# matching.
{ function="VoidFun", tolist=["Name"] },
]
[[rule]]
from = "ClientServerGroupRemoved"
id = ["ClientId"]
to = "Client"
operation = "update"
properties = [
{ from="ServerGroupId", to="ServerGroups", operation="remove" },
{ function="VoidFun", tolist=["Name"] },
]
[[rule]]
from = "ClientUpdated"
id = ["ClientId"]
to = "Client"
operation = "update"
properties = [
{ function="AwayCuFun", tolist=["AwayMessage"] },
{ function="TalkPowerCuFun", tolist=["TalkPowerRequest"] },
]
[[rule]]
from = "ClientUpdated"
id = ["ClientId"]
to = "OptionalClientData"
operation = "update"
properties = [
{ function="ReturnSomeNone", tolist=["VersionSign"] },
]
[[rule]]
from = "ClientPermissionHints"
id = ["ClientId"]
to = "Client"
operation = "update"
properties = [
{ from="Flags", to="PermissionHints" },
]
[[rule]]
from = "InitServer"
id = []
to = "Server"
operation = "add"
properties = [
{ from="VirtualServerId", to="Id" },
# `Uid` is generated from public key
# ClientName, ClientId, TalkPower, NeededServerqueryViewPower
{ function="SetClientDataFun", tolist=[] },
]
[[rule]]
from = "ServerEdited"
id = []
to = "Server"
operation = "update"
[[rule]]
from = "ServerEdited"
id = []
to = "OptionalServerData"
operation = "remove"
[[rule]]
from = "ServerUpdated"
id = []
to = "Server"
operation = "update"
[[rule]]
from = "ServerGroupList"
id = ["ServerGroupId"]
to = "ServerGroup"
operation = "add"
[[rule]]
from = "ServerConnectionInfo"
id = []
to = "ConnectionServerData"
operation = "update"
properties = [
]
[[rule]]
from = "ServerUpdated"
id = []
to = "OptionalServerData"
operation = "update"
properties = [
]
@@ -0,0 +1,151 @@
Packet
// Content
Header
// name type ?value
/// EAX Message Authentication Code
mac [u8; 8]
/// Packet id
p_id u16
/// Client id
?c_id u16
// Pre condition
++ *from_client
/// Flags:
///
/// - 0x80 Unencrypted
/// - 0x40 Compressed
/// - 0x20 Newprotocol
/// - 0x10 Fragmented
flags -
/// Packet type: Higher nibble: Flags; Lower nibble: Packet type
///
/// Packet types:
///
/// - 0x0 Voice
/// - 0x1 Voice whisper
/// - 0x2 Command
/// - 0x3 Command low
/// - 0x4 Ping
/// - 0x5 Pong
/// - 0x6 Ack
/// - 0x7 Ack low
/// - 0x8 Init
p_type u8
// Post conditions
++ (res.p_type & 0xf) <= 8
// Enum
#Data
#C2SInit
++ header.mac.iter().eq(b"TS3INIT1")
++ header.c_id.is_some()
++ header.get_type() == PacketType::Init
Init0
/// Teamspeak version as timestamp
version u32
/// Init packet step number
- u8 0
/// Current timestamp
timestamp u32
random0 [u8; 4]
/// Reserved
- [u8; 8] [0; 8]
Init2
/// Teamspeak version as timestamp
version u32
/// Init packet step number
- u8 2
random1 [u8; 16]
random0_r [u8; 4]
Init4
/// Teamspeak version as timestamp
version u32
/// Init packet step number
- u8 4
x [u8; 64]
n [u8; 64]
level u32
random2 [u8; 100]
/// y = x ^ (2 ^ level) % n
y [u8; 64]
command Command
++ if let C2SInit::Init4 { ref command, .. } = res { command.command == "clientinitiv" && command.has_arg("alpha") && command.has_arg("omega") } else { true }
#S2CInit
++ header.mac.iter().eq(b"TS3INIT1")
++ header.c_id.is_none()
++ header.get_type() == PacketType::Init
Init1
/// Init packet step number
- u8 1
random1 [u8; 16]
/// Reversed `random0`
random0_r [u8; 4]
Init3
/// Init packet step number
- u8 3
x [u8; 64]
n [u8; 64]
level u32
random2 [u8; 100]
Init127
/// Init packet step number
- u8 127
- u8 0
VoiceC2S
++ header.get_type() == PacketType::Voice
++ header.c_id.is_some()
id u16
codec_type u8
voice_data Vec<u8>
VoiceS2C
++ header.get_type() == PacketType::Voice
++ header.c_id.is_none()
id u16
/// The id of the talking client
from_id u16
codec_type u8
voice_data Vec<u8>
VoiceWhisperC2S
++ header.get_type() == PacketType::VoiceWhisper
++ header.c_id.is_some()
++ !header.get_newprotocol()
id u16
codec_type u8
channel_count u8
client_count u8
/// [u64; channel_count], [u16; client_count], voice_data
data Vec<u8>
VoiceWhisperNewC2S
++ header.get_type() == PacketType::VoiceWhisper
++ header.c_id.is_some()
++ header.get_newprotocol()
id u16
codec_type u8
whisper_type u8
whisper_target u8
/// The targeted channel or group id (or 0 if not applicable)
target_id u64
voice_data Vec<u8>
VoiceWhisperS2C
++ header.get_type() == PacketType::VoiceWhisper
++ header.c_id.is_none()
id u16
/// The id of the talking client
from_id u16
codec_type u8
voice_data Vec<u8>
Command Command
++ header.get_type() == PacketType::Command
CommandLow Command
++ header.get_type() == PacketType::CommandLow
Ping
++ header.get_type() == PacketType::Ping
//- u16 0xeee9
/// Pong with packet id
Pong u16
++ header.get_type() == PacketType::Pong
/// Pong with packet id
Ack u16
++ header.get_type() == PacketType::Ack
/// Pong with packet id
AckLow u16
++ header.get_type() == PacketType::AckLow
@@ -0,0 +1,250 @@
name,doc
unknown,May occur on error returns with no associated permission
b_serverinstance_help_view,Retrieve information about ServerQuery commands
b_serverinstance_version_view,Retrieve global server version (including platform and build number)
b_serverinstance_info_view,Retrieve global server information
b_serverinstance_virtualserver_list,List virtual servers stored in the database
b_serverinstance_binding_list,List active IP bindings on multi-homed machines
b_serverinstance_permission_list,List permissions available available on the server instance
b_serverinstance_permission_find,Search permission assignments by name or ID
b_virtualserver_create,Create virtual servers
b_virtualserver_delete,Delete virtual servers
b_virtualserver_start_any,Start any virtual server in the server instance
b_virtualserver_stop_any,Stop any virtual server in the server instance
b_virtualserver_change_machine_id,Change a virtual servers machine ID
b_virtualserver_change_template,Edit virtual server default template values
b_serverquery_login,Login to ServerQuery
b_serverinstance_textmessage_send,Send text messages to all virtual servers at once
b_serverinstance_log_view,Retrieve global server log
b_serverinstance_log_add,Write to global server log
b_serverinstance_stop,Shutdown the server process
b_serverinstance_modify_settings,Edit global settings
b_serverinstance_modify_querygroup,Edit global ServerQuery groups
b_serverinstance_modify_templates,Edit global template groups
b_virtualserver_select,Select a virtual server
b_virtualserver_info_view,Retrieve virtual server information
b_virtualserver_connectioninfo_view,Retrieve virtual server connection information
b_virtualserver_channel_list,List channels on a virtual server
b_virtualserver_channel_search,Search for channels on a virtual server
b_virtualserver_client_list,List clients online on a virtual server
b_virtualserver_client_search,Search for clients online on a virtual server
b_virtualserver_client_dblist,List client identities known by the virtual server
b_virtualserver_client_dbsearch,Search for client identities known by the virtual server
b_virtualserver_client_dbinfo,Retrieve client information
b_virtualserver_permission_find,Find permissions
b_virtualserver_custom_search,Find custom fields
b_virtualserver_start,Start own virtual server
b_virtualserver_stop,Stop own virtual server
b_virtualserver_token_list,List privilege keys available
b_virtualserver_token_add,Create new privilege keys
b_virtualserver_token_use,Use a privilege keys to gain access to groups
b_virtualserver_token_delete,Delete a privilege key
b_virtualserver_log_view,Retrieve virtual server log
b_virtualserver_log_add,Write to virtual server log
b_virtualserver_join_ignore_password,Join virtual server ignoring its password
b_virtualserver_notify_register,Register for server notifications
b_virtualserver_notify_unregister,Unregister from server notifications
b_virtualserver_snapshot_create,Create server snapshots
b_virtualserver_snapshot_deploy,Deploy server snapshots
b_virtualserver_permission_reset,Reset the server permission settings to default values
b_virtualserver_modify_name,Modify server name
b_virtualserver_modify_welcomemessage,Modify welcome message
b_virtualserver_modify_maxclients,Modify servers max clients
b_virtualserver_modify_reserved_slots,Modify reserved slots
b_virtualserver_modify_password,Modify server password
b_virtualserver_modify_default_servergroup,Modify default Server Group
b_virtualserver_modify_default_channelgroup,Modify default Channel Group
b_virtualserver_modify_default_channeladmingroup,Modify default Channel Admin Group
b_virtualserver_modify_channel_forced_silence,Modify channel force silence value
b_virtualserver_modify_complain,Modify individual complain settings
b_virtualserver_modify_antiflood,Modify individual antiflood settings
b_virtualserver_modify_ft_settings,Modify file transfer settings
b_virtualserver_modify_ft_quotas,Modify file transfer quotas
b_virtualserver_modify_hostmessage,Modify individual hostmessage settings
b_virtualserver_modify_hostbanner,Modify individual hostbanner settings
b_virtualserver_modify_hostbutton,Modify individual hostbutton settings
b_virtualserver_modify_port,Modify server port
b_virtualserver_modify_autostart,Modify server autostart
b_virtualserver_modify_needed_identity_security_level,Modify required identity security level
b_virtualserver_modify_priority_speaker_dimm_modificator,Modify priority speaker dimm modificator
b_virtualserver_modify_log_settings,Modify log settings
b_virtualserver_modify_min_client_version,Modify min client version
b_virtualserver_modify_icon_id,Modify server icon
b_virtualserver_modify_weblist,Modify web server list reporting settings
b_virtualserver_modify_codec_encryption_mode,Modify codec encryption mode
b_virtualserver_modify_temporary_passwords,Modify temporary serverpasswords
b_virtualserver_modify_temporary_passwords_own,Modify own temporary serverpasswords
b_virtualserver_modify_channel_temp_delete_delay_default,Modify default temporary channel delete delay
b_virtualserver_modify_nickname,Modify server nicknames
b_virtualserver_modify_integrations,Modify integrations
i_channel_min_depth,Min channel creation depth in hierarchy
i_channel_max_depth,Max channel creation depth in hierarchy
b_channel_group_inheritance_end,Stop inheritance of channel group permissions
i_channel_permission_modify_power,Modify channel permission power
i_channel_needed_permission_modify_power,Needed modify channel permission power
b_channel_info_view,Retrieve channel information
b_channel_create_child,Create sub-channels
b_channel_create_permanent,Create permanent channels
b_channel_create_semi_permanent,Create semi-permanent channels
b_channel_create_temporary,Create temporary channels
b_channel_create_private,Create private channel
b_channel_create_with_topic,Create channels with a topic
b_channel_create_with_description,Create channels with a description
b_channel_create_with_password,Create password protected channels
b_channel_create_modify_with_codec_speex8,Create channels using Speex Narrowband (8 kHz) codecs
b_channel_create_modify_with_codec_speex16,Create channels using Speex Wideband (16 kHz) codecs
b_channel_create_modify_with_codec_speex32,Create channels using Speex Ultra-Wideband (32 kHz) codecs
b_channel_create_modify_with_codec_celtmono48,Create channels using the CELT Mono (48 kHz) codec
b_channel_create_modify_with_codec_opusvoice,Create channels using OPUS (voice) codec
b_channel_create_modify_with_codec_opusmusic,Create channels using OPUS (music) codec
i_channel_create_modify_with_codec_maxquality,Create channels with custom codec quality
i_channel_create_modify_with_codec_latency_factor_min,Create channels with minimal custom codec latency factor
b_channel_create_with_maxclients,Create channels with custom max clients
b_channel_create_with_maxfamilyclients,Create channels with custom max family clients
b_channel_create_with_sortorder,Create channels with custom sort order
b_channel_create_with_default,Create default channels
b_channel_create_with_needed_talk_power,Create channels with needed talk power
b_channel_create_modify_with_force_password,Create new channels only with password
i_channel_create_modify_with_temp_delete_delay,Max delete delay for temporary channels
b_channel_modify_parent,Move channels
b_channel_modify_make_default,Make channel default
b_channel_modify_make_permanent,Make channel permanent
b_channel_modify_make_semi_permanent,Make channel semi-permanent
b_channel_modify_make_temporary,Make channel temporary
b_channel_modify_name,Modify channel name
b_channel_modify_topic,Modify channel topic
b_channel_modify_description,Modify channel description
b_channel_modify_password,Modify channel password
b_channel_modify_codec,Modify channel codec
b_channel_modify_codec_quality,Modify channel codec quality
b_channel_modify_codec_latency_factor,Modify channel codec latency factor
b_channel_modify_maxclients,Modify channels max clients
b_channel_modify_maxfamilyclients,Modify channels max family clients
b_channel_modify_sortorder,Modify channel sort order
b_channel_modify_needed_talk_power,Change needed channel talk power
i_channel_modify_power,Channel modify power
i_channel_needed_modify_power,Needed channel modify power
b_channel_modify_make_codec_encrypted,Make channel codec encrypted
b_channel_modify_temp_delete_delay,Modify temporary channel delete delay
b_channel_delete_permanent,Delete permanent channels
b_channel_delete_semi_permanent,Delete semi-permanent channels
b_channel_delete_temporary,Delete temporary channels
b_channel_delete_flag_force,Force channel delete
i_channel_delete_power,Delete channel power
i_channel_needed_delete_power,Needed delete channel power
b_channel_join_permanent,Join permanent channels
b_channel_join_semi_permanent,Join semi-permanent channels
b_channel_join_temporary,Join temporary channels
b_channel_join_ignore_password,Join channel ignoring its password
b_channel_join_ignore_maxclients,Ignore channels max clients limit
i_channel_join_power,Channel join power
i_channel_needed_join_power,Needed channel join power
i_channel_subscribe_power,Channel subscribe power
i_channel_needed_subscribe_power,Needed channel subscribe power
i_channel_description_view_power,Channel description view power
i_channel_needed_description_view_power,Needed channel needed description view power
i_icon_id,Group icon identifier
i_max_icon_filesize,Max icon filesize in bytes
b_icon_manage,Enables icon management
b_group_is_permanent,Group is permanent
i_group_auto_update_type,Group auto-update type
i_group_auto_update_max_value,Group auto-update max value
i_group_sort_id,Group sort id
i_group_show_name_in_tree,Show group name in tree depending on selected mode
b_virtualserver_servergroup_list,List server groups
b_virtualserver_servergroup_permission_list,List server group permissions
b_virtualserver_servergroup_client_list,List clients from a server group
b_virtualserver_channelgroup_list,List channel groups
b_virtualserver_channelgroup_permission_list,List channel group permissions
b_virtualserver_channelgroup_client_list,List clients from a channel group
b_virtualserver_client_permission_list,List client permissions
b_virtualserver_channel_permission_list,List channel permissions
b_virtualserver_channelclient_permission_list,List channel client permissions
b_virtualserver_servergroup_create,Create server groups
b_virtualserver_channelgroup_create,Create channel groups
i_group_modify_power,Group modify power
i_group_needed_modify_power,Needed group modify power
i_group_member_add_power,Group member add power
i_group_needed_member_add_power,Needed group member add power
i_group_member_remove_power,Group member delete power
i_group_needed_member_remove_power,Needed group member delete power
i_permission_modify_power,Permission modify power
b_permission_modify_power_ignore,Ignore needed permission modify power
b_virtualserver_servergroup_delete,Delete server groups
b_virtualserver_channelgroup_delete,Delete channel groups
i_client_permission_modify_power,Client permission modify power
i_client_needed_permission_modify_power,Needed client permission modify power
i_client_max_clones_uid,Max additional connections per client identity
i_client_max_idletime,Max idle time in seconds
i_client_max_avatar_filesize,Max avatar filesize in bytes
i_client_max_channel_subscriptions,Max channel subscriptions
b_client_is_priority_speaker,Client is priority speaker
b_client_skip_channelgroup_permissions,Ignore channel group permissions
b_client_force_push_to_talk,Force Push-To-Talk capture mode
b_client_ignore_bans,Ignore bans
b_client_ignore_antiflood,Ignore antiflood measurements
b_client_issue_client_query_command,Issue query commands from client
b_client_use_reserved_slot,Use an reserved slot
b_client_use_channel_commander,Use channel commander
b_client_request_talker,Allow to request talk power
b_client_avatar_delete_other,Allow deletion of avatars from other clients
b_client_is_sticky,Client will be sticked to current channel
b_client_ignore_sticky,Client ignores sticky flag
b_client_info_view,Retrieve client information
b_client_permissionoverview_view,Retrieve client permissions overview
b_client_permissionoverview_own,Retrieve clients own permissions overview
b_client_remoteaddress_view,View client IP address and port
i_client_serverquery_view_power,ServerQuery view power
i_client_needed_serverquery_view_power,Needed ServerQuery view power
b_client_custom_info_view,View custom fields
i_client_kick_from_server_power,Client kick power from server
i_client_needed_kick_from_server_power,Needed client kick power from server
i_client_kick_from_channel_power,Client kick power from channel
i_client_needed_kick_from_channel_power,Needed client kick power from channel
i_client_ban_power,Client ban power
i_client_needed_ban_power,Needed client ban power
i_client_move_power,Client move power
i_client_needed_move_power,Needed client move power
i_client_complain_power,Complain power
i_client_needed_complain_power,Needed complain power
b_client_complain_list,Show complain list
b_client_complain_delete_own,Delete own complains
b_client_complain_delete,Delete complains
b_client_ban_list,Show banlist
b_client_ban_create,Add a ban
b_client_ban_delete_own,Delete own bans
b_client_ban_delete,Delete bans
i_client_ban_max_bantime,Max bantime
i_client_private_textmessage_power,Client private message power
i_client_needed_private_textmessage_power,Needed client private message power
b_client_server_textmessage_send,Send text messages to virtual server
b_client_channel_textmessage_send,Send text messages to channel
b_client_offline_textmessage_send,Send offline messages to clients
i_client_talk_power,Client talk power
i_client_needed_talk_power,Needed client talk power
i_client_poke_power,Client poke power
i_client_needed_poke_power,Needed client poke power
b_client_set_flag_talker,Set the talker flag for clients and allow them to speak
i_client_whisper_power,Client whisper power
i_client_needed_whisper_power,Client needed whisper power
b_client_modify_description,Edit a clients description
b_client_modify_own_description,Allow client to edit own description
b_client_modify_dbproperties,Edit a clients properties in the database
b_client_delete_dbproperties,Delete a clients properties in the database
b_client_create_modify_serverquery_login,Create or modify own ServerQuery account
b_ft_ignore_password,Browse files without channel password
b_ft_transfer_list,Retrieve list of running filetransfers
i_ft_file_upload_power,File upload power
i_ft_needed_file_upload_power,Needed file upload power
i_ft_file_download_power,File download power
i_ft_needed_file_download_power,Needed file download power
i_ft_file_delete_power,File delete power
i_ft_needed_file_delete_power,Needed file delete power
i_ft_file_rename_power,File rename power
i_ft_needed_file_rename_power,Needed file rename power
i_ft_file_browse_power,File browse power
i_ft_needed_file_browse_power,Needed file browse power
i_ft_directory_create_power,Create directory power
i_ft_needed_directory_create_power,Needed create directory power
i_ft_quota_mb_download_per_client,Download quota per client in MByte
i_ft_quota_mb_upload_per_client,Upload quota per client in MByte
1 name doc
2 unknown May occur on error returns with no associated permission
3 b_serverinstance_help_view Retrieve information about ServerQuery commands
4 b_serverinstance_version_view Retrieve global server version (including platform and build number)
5 b_serverinstance_info_view Retrieve global server information
6 b_serverinstance_virtualserver_list List virtual servers stored in the database
7 b_serverinstance_binding_list List active IP bindings on multi-homed machines
8 b_serverinstance_permission_list List permissions available available on the server instance
9 b_serverinstance_permission_find Search permission assignments by name or ID
10 b_virtualserver_create Create virtual servers
11 b_virtualserver_delete Delete virtual servers
12 b_virtualserver_start_any Start any virtual server in the server instance
13 b_virtualserver_stop_any Stop any virtual server in the server instance
14 b_virtualserver_change_machine_id Change a virtual servers machine ID
15 b_virtualserver_change_template Edit virtual server default template values
16 b_serverquery_login Login to ServerQuery
17 b_serverinstance_textmessage_send Send text messages to all virtual servers at once
18 b_serverinstance_log_view Retrieve global server log
19 b_serverinstance_log_add Write to global server log
20 b_serverinstance_stop Shutdown the server process
21 b_serverinstance_modify_settings Edit global settings
22 b_serverinstance_modify_querygroup Edit global ServerQuery groups
23 b_serverinstance_modify_templates Edit global template groups
24 b_virtualserver_select Select a virtual server
25 b_virtualserver_info_view Retrieve virtual server information
26 b_virtualserver_connectioninfo_view Retrieve virtual server connection information
27 b_virtualserver_channel_list List channels on a virtual server
28 b_virtualserver_channel_search Search for channels on a virtual server
29 b_virtualserver_client_list List clients online on a virtual server
30 b_virtualserver_client_search Search for clients online on a virtual server
31 b_virtualserver_client_dblist List client identities known by the virtual server
32 b_virtualserver_client_dbsearch Search for client identities known by the virtual server
33 b_virtualserver_client_dbinfo Retrieve client information
34 b_virtualserver_permission_find Find permissions
35 b_virtualserver_custom_search Find custom fields
36 b_virtualserver_start Start own virtual server
37 b_virtualserver_stop Stop own virtual server
38 b_virtualserver_token_list List privilege keys available
39 b_virtualserver_token_add Create new privilege keys
40 b_virtualserver_token_use Use a privilege keys to gain access to groups
41 b_virtualserver_token_delete Delete a privilege key
42 b_virtualserver_log_view Retrieve virtual server log
43 b_virtualserver_log_add Write to virtual server log
44 b_virtualserver_join_ignore_password Join virtual server ignoring its password
45 b_virtualserver_notify_register Register for server notifications
46 b_virtualserver_notify_unregister Unregister from server notifications
47 b_virtualserver_snapshot_create Create server snapshots
48 b_virtualserver_snapshot_deploy Deploy server snapshots
49 b_virtualserver_permission_reset Reset the server permission settings to default values
50 b_virtualserver_modify_name Modify server name
51 b_virtualserver_modify_welcomemessage Modify welcome message
52 b_virtualserver_modify_maxclients Modify servers max clients
53 b_virtualserver_modify_reserved_slots Modify reserved slots
54 b_virtualserver_modify_password Modify server password
55 b_virtualserver_modify_default_servergroup Modify default Server Group
56 b_virtualserver_modify_default_channelgroup Modify default Channel Group
57 b_virtualserver_modify_default_channeladmingroup Modify default Channel Admin Group
58 b_virtualserver_modify_channel_forced_silence Modify channel force silence value
59 b_virtualserver_modify_complain Modify individual complain settings
60 b_virtualserver_modify_antiflood Modify individual antiflood settings
61 b_virtualserver_modify_ft_settings Modify file transfer settings
62 b_virtualserver_modify_ft_quotas Modify file transfer quotas
63 b_virtualserver_modify_hostmessage Modify individual hostmessage settings
64 b_virtualserver_modify_hostbanner Modify individual hostbanner settings
65 b_virtualserver_modify_hostbutton Modify individual hostbutton settings
66 b_virtualserver_modify_port Modify server port
67 b_virtualserver_modify_autostart Modify server autostart
68 b_virtualserver_modify_needed_identity_security_level Modify required identity security level
69 b_virtualserver_modify_priority_speaker_dimm_modificator Modify priority speaker dimm modificator
70 b_virtualserver_modify_log_settings Modify log settings
71 b_virtualserver_modify_min_client_version Modify min client version
72 b_virtualserver_modify_icon_id Modify server icon
73 b_virtualserver_modify_weblist Modify web server list reporting settings
74 b_virtualserver_modify_codec_encryption_mode Modify codec encryption mode
75 b_virtualserver_modify_temporary_passwords Modify temporary serverpasswords
76 b_virtualserver_modify_temporary_passwords_own Modify own temporary serverpasswords
77 b_virtualserver_modify_channel_temp_delete_delay_default Modify default temporary channel delete delay
78 b_virtualserver_modify_nickname Modify server nicknames
79 b_virtualserver_modify_integrations Modify integrations
80 i_channel_min_depth Min channel creation depth in hierarchy
81 i_channel_max_depth Max channel creation depth in hierarchy
82 b_channel_group_inheritance_end Stop inheritance of channel group permissions
83 i_channel_permission_modify_power Modify channel permission power
84 i_channel_needed_permission_modify_power Needed modify channel permission power
85 b_channel_info_view Retrieve channel information
86 b_channel_create_child Create sub-channels
87 b_channel_create_permanent Create permanent channels
88 b_channel_create_semi_permanent Create semi-permanent channels
89 b_channel_create_temporary Create temporary channels
90 b_channel_create_private Create private channel
91 b_channel_create_with_topic Create channels with a topic
92 b_channel_create_with_description Create channels with a description
93 b_channel_create_with_password Create password protected channels
94 b_channel_create_modify_with_codec_speex8 Create channels using Speex Narrowband (8 kHz) codecs
95 b_channel_create_modify_with_codec_speex16 Create channels using Speex Wideband (16 kHz) codecs
96 b_channel_create_modify_with_codec_speex32 Create channels using Speex Ultra-Wideband (32 kHz) codecs
97 b_channel_create_modify_with_codec_celtmono48 Create channels using the CELT Mono (48 kHz) codec
98 b_channel_create_modify_with_codec_opusvoice Create channels using OPUS (voice) codec
99 b_channel_create_modify_with_codec_opusmusic Create channels using OPUS (music) codec
100 i_channel_create_modify_with_codec_maxquality Create channels with custom codec quality
101 i_channel_create_modify_with_codec_latency_factor_min Create channels with minimal custom codec latency factor
102 b_channel_create_with_maxclients Create channels with custom max clients
103 b_channel_create_with_maxfamilyclients Create channels with custom max family clients
104 b_channel_create_with_sortorder Create channels with custom sort order
105 b_channel_create_with_default Create default channels
106 b_channel_create_with_needed_talk_power Create channels with needed talk power
107 b_channel_create_modify_with_force_password Create new channels only with password
108 i_channel_create_modify_with_temp_delete_delay Max delete delay for temporary channels
109 b_channel_modify_parent Move channels
110 b_channel_modify_make_default Make channel default
111 b_channel_modify_make_permanent Make channel permanent
112 b_channel_modify_make_semi_permanent Make channel semi-permanent
113 b_channel_modify_make_temporary Make channel temporary
114 b_channel_modify_name Modify channel name
115 b_channel_modify_topic Modify channel topic
116 b_channel_modify_description Modify channel description
117 b_channel_modify_password Modify channel password
118 b_channel_modify_codec Modify channel codec
119 b_channel_modify_codec_quality Modify channel codec quality
120 b_channel_modify_codec_latency_factor Modify channel codec latency factor
121 b_channel_modify_maxclients Modify channels max clients
122 b_channel_modify_maxfamilyclients Modify channels max family clients
123 b_channel_modify_sortorder Modify channel sort order
124 b_channel_modify_needed_talk_power Change needed channel talk power
125 i_channel_modify_power Channel modify power
126 i_channel_needed_modify_power Needed channel modify power
127 b_channel_modify_make_codec_encrypted Make channel codec encrypted
128 b_channel_modify_temp_delete_delay Modify temporary channel delete delay
129 b_channel_delete_permanent Delete permanent channels
130 b_channel_delete_semi_permanent Delete semi-permanent channels
131 b_channel_delete_temporary Delete temporary channels
132 b_channel_delete_flag_force Force channel delete
133 i_channel_delete_power Delete channel power
134 i_channel_needed_delete_power Needed delete channel power
135 b_channel_join_permanent Join permanent channels
136 b_channel_join_semi_permanent Join semi-permanent channels
137 b_channel_join_temporary Join temporary channels
138 b_channel_join_ignore_password Join channel ignoring its password
139 b_channel_join_ignore_maxclients Ignore channels max clients limit
140 i_channel_join_power Channel join power
141 i_channel_needed_join_power Needed channel join power
142 i_channel_subscribe_power Channel subscribe power
143 i_channel_needed_subscribe_power Needed channel subscribe power
144 i_channel_description_view_power Channel description view power
145 i_channel_needed_description_view_power Needed channel needed description view power
146 i_icon_id Group icon identifier
147 i_max_icon_filesize Max icon filesize in bytes
148 b_icon_manage Enables icon management
149 b_group_is_permanent Group is permanent
150 i_group_auto_update_type Group auto-update type
151 i_group_auto_update_max_value Group auto-update max value
152 i_group_sort_id Group sort id
153 i_group_show_name_in_tree Show group name in tree depending on selected mode
154 b_virtualserver_servergroup_list List server groups
155 b_virtualserver_servergroup_permission_list List server group permissions
156 b_virtualserver_servergroup_client_list List clients from a server group
157 b_virtualserver_channelgroup_list List channel groups
158 b_virtualserver_channelgroup_permission_list List channel group permissions
159 b_virtualserver_channelgroup_client_list List clients from a channel group
160 b_virtualserver_client_permission_list List client permissions
161 b_virtualserver_channel_permission_list List channel permissions
162 b_virtualserver_channelclient_permission_list List channel client permissions
163 b_virtualserver_servergroup_create Create server groups
164 b_virtualserver_channelgroup_create Create channel groups
165 i_group_modify_power Group modify power
166 i_group_needed_modify_power Needed group modify power
167 i_group_member_add_power Group member add power
168 i_group_needed_member_add_power Needed group member add power
169 i_group_member_remove_power Group member delete power
170 i_group_needed_member_remove_power Needed group member delete power
171 i_permission_modify_power Permission modify power
172 b_permission_modify_power_ignore Ignore needed permission modify power
173 b_virtualserver_servergroup_delete Delete server groups
174 b_virtualserver_channelgroup_delete Delete channel groups
175 i_client_permission_modify_power Client permission modify power
176 i_client_needed_permission_modify_power Needed client permission modify power
177 i_client_max_clones_uid Max additional connections per client identity
178 i_client_max_idletime Max idle time in seconds
179 i_client_max_avatar_filesize Max avatar filesize in bytes
180 i_client_max_channel_subscriptions Max channel subscriptions
181 b_client_is_priority_speaker Client is priority speaker
182 b_client_skip_channelgroup_permissions Ignore channel group permissions
183 b_client_force_push_to_talk Force Push-To-Talk capture mode
184 b_client_ignore_bans Ignore bans
185 b_client_ignore_antiflood Ignore antiflood measurements
186 b_client_issue_client_query_command Issue query commands from client
187 b_client_use_reserved_slot Use an reserved slot
188 b_client_use_channel_commander Use channel commander
189 b_client_request_talker Allow to request talk power
190 b_client_avatar_delete_other Allow deletion of avatars from other clients
191 b_client_is_sticky Client will be sticked to current channel
192 b_client_ignore_sticky Client ignores sticky flag
193 b_client_info_view Retrieve client information
194 b_client_permissionoverview_view Retrieve client permissions overview
195 b_client_permissionoverview_own Retrieve clients own permissions overview
196 b_client_remoteaddress_view View client IP address and port
197 i_client_serverquery_view_power ServerQuery view power
198 i_client_needed_serverquery_view_power Needed ServerQuery view power
199 b_client_custom_info_view View custom fields
200 i_client_kick_from_server_power Client kick power from server
201 i_client_needed_kick_from_server_power Needed client kick power from server
202 i_client_kick_from_channel_power Client kick power from channel
203 i_client_needed_kick_from_channel_power Needed client kick power from channel
204 i_client_ban_power Client ban power
205 i_client_needed_ban_power Needed client ban power
206 i_client_move_power Client move power
207 i_client_needed_move_power Needed client move power
208 i_client_complain_power Complain power
209 i_client_needed_complain_power Needed complain power
210 b_client_complain_list Show complain list
211 b_client_complain_delete_own Delete own complains
212 b_client_complain_delete Delete complains
213 b_client_ban_list Show banlist
214 b_client_ban_create Add a ban
215 b_client_ban_delete_own Delete own bans
216 b_client_ban_delete Delete bans
217 i_client_ban_max_bantime Max bantime
218 i_client_private_textmessage_power Client private message power
219 i_client_needed_private_textmessage_power Needed client private message power
220 b_client_server_textmessage_send Send text messages to virtual server
221 b_client_channel_textmessage_send Send text messages to channel
222 b_client_offline_textmessage_send Send offline messages to clients
223 i_client_talk_power Client talk power
224 i_client_needed_talk_power Needed client talk power
225 i_client_poke_power Client poke power
226 i_client_needed_poke_power Needed client poke power
227 b_client_set_flag_talker Set the talker flag for clients and allow them to speak
228 i_client_whisper_power Client whisper power
229 i_client_needed_whisper_power Client needed whisper power
230 b_client_modify_description Edit a clients description
231 b_client_modify_own_description Allow client to edit own description
232 b_client_modify_dbproperties Edit a clients properties in the database
233 b_client_delete_dbproperties Delete a clients properties in the database
234 b_client_create_modify_serverquery_login Create or modify own ServerQuery account
235 b_ft_ignore_password Browse files without channel password
236 b_ft_transfer_list Retrieve list of running filetransfers
237 i_ft_file_upload_power File upload power
238 i_ft_needed_file_upload_power Needed file upload power
239 i_ft_file_download_power File download power
240 i_ft_needed_file_download_power Needed file download power
241 i_ft_file_delete_power File delete power
242 i_ft_needed_file_delete_power Needed file delete power
243 i_ft_file_rename_power File rename power
244 i_ft_needed_file_rename_power Needed file rename power
245 i_ft_file_browse_power File browse power
246 i_ft_needed_file_browse_power Needed file browse power
247 i_ft_directory_create_power Create directory power
248 i_ft_needed_directory_create_power Needed create directory power
249 i_ft_quota_mb_download_per_client Download quota per client in MByte
250 i_ft_quota_mb_upload_per_client Upload quota per client in MByte
@@ -0,0 +1,26 @@
# TeamSpeak Declarations
This repository contains all kind of data which is related to TeamSpeak.
This data is used for code generation in various projects, therefore all the data is machine readable.
- [Errors.csv](Errors.csv): The error codes of TeamSpeak
- [Permissions.csv](Permissions.csv): The permissions in TeamSpeak
- [Messages.toml](Messages.toml): Commands, sent over TeamSpeak connections
- [Book.toml](Book.toml): Declarations for keeping track of all things which happen on a server
- [Enums.toml](Enums.toml): Various enums used in commands
- [MessagesToBook.toml](MessagesToBook.toml): Mappings from commands to book structs that allow to automatically update the tracked state
- [BookToMessages.toml](BookToMessages.toml): Functions that can be called on book structs and generate commands
- [Versions.csv](Versions.csv): A bunch of client versions where the versionHash is known
- [Badges.csv](Badges.csv): List of known badges
The low level TeamSpeak protocol is described in [ts3protocol.md](ts3protocol.md).
## License
Licensed under either of
* [Apache License, Version 2.0](LICENSE-APACHE)
* [MIT license](LICENSE-MIT)
at your option.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,864 @@
TS3 PROTOCOL PAPER
==================
# 0. Naming Conventions
- `(Client -> Server)` denotes packets from client to server.
- `(Client <- Server)` denotes packets from server to client.
- All datatypes are sent in network order (Big Endian) unless otherwise
specified.
- Datatypes are declared with a prefixing `u` or `i` for unsigned and signed
and a number for the bitlength.
For example `u8` would be the C equivalent of `uint8` or `unsigned char`
- Arrays are represented by the underlying datatype in square brackets,
additionally if the length is known it is added in the brackets, separated by
a semicolon. Eg: `[u8]`, `[i32; 16]`
- Array ranges (parts of an array) are specified in square brackets with the
included lower bound, two points (`..`) and the excluded upper bound. Eg: `[0..10]`
# 1. Low-Level Packets
## 1.1 Packet structure
- The packets are build in a fixed scheme,
though have differences depending in which direction.
- Every column here represents 1 byte.
- The entire packet size must be at max 500 bytes.
### 1.1.1 (Client -> Server)
+--+--+--+--+--+--+--+--+--+--+--+--+--+---------//----------+
| MAC | PId | CId |PT| Data |
+--+--+--+--+--+--+--+--+--+--+--+--+--+---------//----------+
| \ Meta |
\ Header /
| Name | Size | Datatype | Explanation |
|------|-------------|----------|---------------------------------|
| MAC | 8 bytes | [u8] | EAX Message Authentication Code |
| PId | 2 bytes | u16 | Packet Id |
| CId | 2 bytes | u16 | Client Id |
| PT | 1 byte | u8 | Packet Type + Flags |
| Data | ≤487 bytes | [u8] | The packet payload |
### 1.1.2 (Client <- Server)
+--+--+--+--+--+--+--+--+--+--+--+------------//-------------+
| MAC | PId |PT| Data |
+--+--+--+--+--+--+--+--+--+--+--+------------//-------------+
| \ Meta |
\ Header /
| Name | Size | Datatype | Explanation |
|------|-------------|----------|---------------------------------|
| MAC | 8 bytes | [u8] | EAX Message Authentication Code |
| PId | 2 bytes | u16 | Packet Id |
| PT | 1 byte | u8 | Packet Type + Flags |
| Data | ≤489 bytes | [u8] | The packet payload |
## 1.2 Packet Types
- `0x00` Voice
- `0x01` VoiceWhisper
- `0x02` Command
- `0x03` CommandLow
- `0x04` Ping
- `0x05` Pong
- `0x06` Ack
- `0x07` AckLow
- `0x08` Init1
## 1.3 Packet Type + Flags byte
The final byte then looks like this
MSB LSB
+--+--+--+--+--+--+--+--+
|UE|CP|NP|FR| Type |
+--+--+--+--+--+--+--+--+
| Name | Size | Hex | Explanation |
|------|-------|------|-----------------|
| UE | 1 bit | 0x80 | Unencrypted |
| CP | 1 bit | 0x40 | Compressed |
| NP | 1 bit | 0x20 | Newprotocol |
| FR | 1 bit | 0x10 | Fragmented |
| Type | 4 bit | 0-8 | The packet type |
## 1.4 Packet Compression
To reduce packet size, the data can be compressed.
When the data is compressed the `Compressed` flag must be set.
The algorithm "QuickLZ" with Level 1 is used for compression.
## 1.5 Packet Splitting
When the packet payload exceeds the maximum datablock size the data can be
split up across multiple packets.
The current protocol only allows `Command` and `CommandLow` to be split and/or
compressed.
When splitting occurs, the `Fragmented` flag must be set on the first and
the last packet.
The `Unencrypted` and `Compressed` flag, if set in the original
packet, are only set on the first packet. (Though commands always have to be
encrypted)
The `Newprotocol` flag has to be set on all commands and therefore also has to
be applied on all splitted command packets.
The data can additionally be compressed *before* splitting.
*Example*:
The packet to split has the following flags:
[__|CP|NP|__] Packet Id: 42
it must be split into:
[__|CP|NP|FR] Packet Id: 42
[__|__|NP|__] Packet Id: 43
[__|__|NP|FR] Packet Id: 44
## 1.6 Packet Encryption
When a packet is not encrypted the `Unencrypted` flag is set. For encrypted
packets the flag gets cleared.
Packets get encrypted with EAX mode (AES_128_CTR with OMAC).
The en/decryption parameters are generated for each packet as follows
### 1.6.1 Inputs
| Name | Type | Explanation |
|------|----------|---------------------------------|
| PT | u8 | Packet Type |
| PId | u16 | Packet Id |
| PGId | u32 | Packet GenerationId (see 1.9.2) |
| PD | bool | Packet Direction |
| SIV | [u8; 20] | Shared IV (see 3.2) |
### 1.6.2 Generation pseudocode
The temporary variable will have a different length depending on the result
from the crypto init handshake. The old protocol SharedIV will be 20 bytes long,
since it is generated with sha1, while the new protocol SharedIV will have
64 bytes, since it is generated with sha512.
let temporary: [u8; 26] OR [u8; 70]
temporary[0] = 0x30 if (Client <- Server)
0x31 if (Client -> Server)
temporary[1] = PT
temporary[2..6] = (PGId in network order)[0..4]
if SIV.length == 20
temporary[6..26] = SIV[0..20]
else
temporary[6..70] = SIV[0..64]
let keynonce: [u8; 32]
keynonce = sha256(temporary)
key: [u8; 16] = keynonce[ 0..16]
nonce: [u8; 16] = keynonce[16..32]
key[0] = key[0] xor ((PId & 0xFF00) >> 8)
key[1] = key[1] xor ((PId & 0x00FF) >> 0)
### 1.6.3 Encryption
The data can now be encrypted with the `key` and `nonce` from (see 1.6.2) as the
EAX key and nonce and the packet `Meta` as defined in (see 1.1) as the EAX
header (sometimes called "Associated Text"). The resulting EAX mac (sometimes
called "Tag") will be stored in the `MAC` field as defined in (see 2.1).
### 1.6.4 Not encrypted packets
When a packet is not encrypted, no MAC can be generated by EAX. In this case
the SharedMac (see 3.2) will be used instead.
## 1.7 Packet Stack Wrap-up
This stack is a reference for the execution order of the set data operations.
For incoming packets the stack is executed bot to top, for outgoing packets
top to bot.
Send Receive
+-----------+ +-----------+
| Data | | Λ | Data |
+-----------+ | | +-----------+
| Compress | | | | Decompress|
+-----------+ | | +-----------+
| Split | | | | Merge |
+-----------+ | | +-----------+
| Encrypt | V | | Decrypt |
+-----------+ +-----------+
## 1.8 Packet Types Data Structures
The following chapter describes the data structure for different packet types.
### 1.8.1.1 Voice (Client -> Server)
+--+--+--+---------//---------+
| VId |C | Data |
+--+--+--+---------//---------+
| Name | Type | Explanation |
|------|------|-----------------|
| VId | u16 | Voice Packet Id |
| C | u8 | Codec Type |
| Data | var | Voice Data |
### 1.8.1.2 Voice (Client <- Server)
+--+--+--+--+--+---------//---------+
| VId | CId |C | Data |
+--+--+--+--+--+---------//---------+
| Name | Type | Explanation |
|------|------|-----------------|
| VId | u16 | Voice Packet Id |
| CId | u16 | Talking Client |
| C | u8 | Codec Type |
| Data | var | Voice Data |
### 1.8.2.1 VoiceWhisper (Client -> Server)
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+---------//---------+
| VId |C |N |M | U* | T* | Data |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+---------//---------+
For direct user/channel targeting
The `Newprotocol` Flag must be *unset*
| Name | Type | Explanation |
|------|-------|---------------------------------------|
| VId | u16 | Voice Packet Id |
| C | u8 | Codec Type |
| N | u8 | Count of ChannelIds to send to |
| M | u8 | Count of ClientIds to send to |
| U | [u64] | Targeted ChannelIds, repeated N times |
| T | [u16] | Targeted ClientIds, repeated M times |
| Data | var | Voice Data |
OR
+--+--+--+--+--+--+--+--+--+--+--+--+--+---------//---------+
| VId |C |TY|TA| U | Data |
+--+--+--+--+--+--+--+--+--+--+--+--+--+---------//---------+
For targeting special groups
The `Newprotocol` Flag must be *set*
| Name | Type | Explanation |
|------|-------|---------------------------------------------------------|
| VId | u16 | Voice Packet Id |
| C | u8 | Codec Type |
| TY | u8 | GroupWhisperType (see below) |
| TA | u8 | GroupWhisperTarget (see below) |
| U | u64 | the targeted channelId or groupId (0 if not applicable) |
| Data | var | Voice Data |
```
enum GroupWhisperType : u8
{
// Targets all users in the specified server group.
ServerGroup = 0 /* U = servergroup targetId */,
// Targets all users in the specified channel group.
ChannelGroup = 1 /* U = channelgroup targetId */,
// Targets all users with channel commander.
ChannelCommander = 2, /* U = 0 (ignored) */,
// Targets all users on the server.
AllClients = 3, /* U = 0 (ignored) */,
}
enum GroupWhisperTarget : u8
{
AllChannels = 0,
CurrentChannel = 1,
ParentChannel = 2,
AllParentChannel = 3,
ChannelFamily = 4,
CompleteChannelFamily = 5,
Subchannels = 6,
}
```
### 1.8.2.2 VoiceWhisper (Client <- Server)
+--+--+--+--+--+---------//---------+
| VId | CId |C | Data |
+--+--+--+--+--+---------//---------+
| Name | Type | Explanation |
|------|------|-----------------|
| VId | u16 | Voice Packet Id |
| CId | u16 | Talking Client |
| C | u8 | Codec Type |
| Data | var | Voice Data |
### 1.8.3-4 Command and CommandLow
The TeamSpeak3 Query like command string encoded in UTF-8
### 1.8.5 Ping
Empty.
### 1.8.6-8 Pong, Ack and AckLow
+--+--+
| PId |
+--+--+
| Name | Type | Explanation |
|------|------|------------------------------------|
| PId | u16 | The packet id that is acknowledged |
- In case of `Pong` a matching ping packet id is acknowledged.
- In case of `Ack` or `AckLow` a matching `Command` or `CommandLow` packet id
respectively is acknowledged.
### 1.8.9 Init1
(see 2.1)-(see 2.5)
## 1.9 Packet Ids and Generations
### 1.9.1 Packet Ids
Each packet type and packet direction must be maintained by an own packet id
counter.
This means the client has 9 different packet id counter for outgoing packets.
For each new packet the counter gets increased by 1. This also applies to
split packets.
The client must also maintain packet ids for incoming packets in case of
packets arriving out of order.
All Packet Ids start at 1 unless otherwise specified.
### 1.9.2 Generations
Packet Ids are stored as u16, this means they range from 0 up to 65535 included.
When the packet id overflows from 65535 to 0 at a packet,
the generation counter for this packet type gets increased by 1.
Note that the new generation id immediately applies to the 'overflowing' packet.
The generation id counter is solely used for encryption (see 1.6).
## 1.10 Packet Acknowledgement / Packet Loss
In order to reliably send packets over UDP some packet types must get
acknowledged when received (see 1.11).
The protocol uses selective repeat for lost packets. This means each packet has
its own timeout. Already acknowledged later packets must not be resent.
When a packet times out, the exact same packet should be resent until properly
acknowledged by the server.
If after 30 seconds no resent packet gets acknowledged the connection should be
closed.
Packet resend timeouts should be calculated with an exponential backoff to
prevent network congestion.
## 1.11 Wrap-up
| Type | Acknowledged (by) | Resend | Encrypted | Splittable | Compressible |
|--------------|-------------------|--------|-----------|------------|--------------|
| Voice | ✗ | ✗ | Optional | ✗ | ✗ |
| VoiceWhisper | ✗ | ✗ | Optional | ✗ | ✗ |
| Command | ✓ (Ack) | ✓ | ✓ | ✓ | ✓ |
| CommandLow | ✓ (AckLow) | ✓ | ✓ | ✓ | ✓ |
| Ping | ✓ (Pong) | ✗ | ✗ | ✗ | ✗ |
| Pong | ✗ | ✗ | ✗ | ✗ | ✗ |
| Ack | ✗ | ✓ | ✓ | ✗ | ✗ |
| AckLow | ✗ | ✓ | ✓ | ✗ | ✗ |
| Init1 | ✓ (next Init1) | ✓ | ✗ | ✗ | ✗ |
# 2. The (Low-Level) Initiation/Handshake
A connection is started from the client by sending the first handshake
packet. The handshake process consists of 5 different init packets. This
includes the so called RSA puzzle to prevent DOS attacks.
The packet header values are set as following for all packets here:
| Parameter | Value |
|-----------|--------------------------------------------------------|
| MAC | [u8]{ 0x54, 0x53, 0x33, 0x49, 0x4E, 0x49, 0x54, 0x31 } |
| key | N/A |
| nonce | N/A |
| Type | Init1 |
| Encrypted | ✗ |
| Packet Id | u16: 101 |
| Client Id | u16: 0 |
Init packets from the client contain a version field, which is the build
timestamp of the client. This is a unix timestamp subtracted with 1356998400.
The unix timestamp 1461588969 (date 2016-04-25) is encoded as
1461588969 - 1356998400 = 0x063bece9 = { 0x06, 0x3b, 0xec, 0xe9 }.
## 2.1 Packet 0 (Client -> Server)
04 bytes : Version of the TeamSpeak client as timestamp
Example: { 0x06, 0x3b, 0xec, 0xe9 }
01 bytes : Init-packet step number
Const: 0x00
04 bytes : Current timestamp in unix format
04 bytes : Random bytes := [A0]
08 bytes : Zeros, reserved.
## 2.2 Packet 1 (Client <- Server)
01 bytes : Init-packet step number
Const: 0x01
16 bytes : Server stuff := [A1]
04 bytes : The bytes from [A0] in reversed order (not always) := [A0r]
This packets usually contains the bytes from [A0] in reversed order, except when
connecting from some networks for a yet unknown reason.
## 2.3 Packet 2 (Client -> Server)
04 bytes : Version of the TeamSpeak client as timestamp
01 bytes : Init-packet step number
Const: 0x02
16 bytes : The bytes from [A1]
04 bytes : The bytes from [A0r]
## 2.4 Packet 3 (Client <- Server)
01 bytes : Init-packet step number
Const: 0x03
64 bytes : 'x', an unsigned BigInteger
64 bytes : 'n', an unsigned BigInteger
04 bytes : 'level' a u32
100 bytes : Server stuff := [A2]
Note:
- Sometimes, instead of sending an init with step 3, the server responds with
an init that contains 127 as step number. In that case, the client has to
restart the connection by sending packet 0 again.
## 2.5 Packet 4 (Client -> Server)
04 bytes : Version of the TeamSpeak client as timestamp
01 bytes : Init-packet step number
Const: 0x04
64 bytes : the received 'x'
64 bytes : the received 'n'
04 bytes : the received 'level'
100 bytes : The bytes from [A2]
64 bytes : 'y' which is the result of x ^ (2 ^ level) % n as an unsigned
BigInteger. Padded from the lower side with '0x00' when shorter
than 64 bytes.
Example: { 0x00, 0x00, data ... data}
var bytes : The clientinitiv command data as explained in (see 3.1)
Note:
- `^` in this context means 'power to'
- To calculate the power of such a high number use a language integrated
function like `ModPow` or similar, when available.
If you don't have this function available you can multiply x iteratively
and apply the modulo operation after each multiplication.
# 3. The (High-Level) Initiation/Handshake
In this phase the client and server exchange basic information and
agree on/calculate the symmetric AES encryption key with the ECDH
public/private key exchange technique.
Both the client and the server will need a EC public/private key. This key
is also the identity which the server uses to recognize a user again.
The curve used is 'prime256v1'.
All high level packets specified in this chapter are sent as `Command` Type
packets as explained in (see 2.8.3). Additionally the `Newprotocol` flag
(see 2.3) must be set on all `Command`, `CommandLow` and `Init1` packets.
All commands are specified in the `Messages.txt` file.
The packet header/encryption values for (see 3.1) and (see 3.2) are as following:
| Parameter | Value |
|-----------|------------------------------------------------------------------------------------------------------|
| MAC | (Generated by EAX) |
| key | [u8]{0x63, 0x3A, 0x5C, 0x77, 0x69, 0x6E, 0x64, 0x6F, 0x77, 0x73, 0x5C, 0x73, 0x79, 0x73, 0x74, 0x65} |
| nonce | [u8]{0x6D, 0x5C, 0x66, 0x69, 0x72, 0x65, 0x77, 0x61, 0x6C, 0x6C, 0x33, 0x32, 0x2E, 0x63, 0x70, 0x6C} |
| Type | Command |
| Encrypted | ✓ |
| Packet Id | u16: 0 |
| Client Id | u16: 0 |
The acknowledgement packets use the same parameters as the commands, except with
the Type `Ack`.
_(Maybe add a #3.0 Prelude for required cryptographic values, if yes move the
omega ASN.1 encoding here)_
## 3.1 clientinitiv (Client -> Server)
The first packet is sent (Client -> Server) although this is only sent for
legacy reasons since newer servers (at least 3.0.13.0?) use the data part
embedded in the last `Init1` packet from the low-level handshake (see 2.5).
clientinitiv alpha={alpha} omega={omega} ot={ot} ip={ip}
- `alpha` is set to `base64(random[u8; 10])`
which are 10 random bytes for entropy.
- `omega` is set to `base64(publicKey[u8])`
omega is an ASN.1-DER encoded public key from the ECDH parameters as following:
| Type | Value | Explanation |
|------------|----------------|-------------------------------------------|
| BIT STRING | 1bit, Value: 0 | LibTomCrypt uses 0 for a public key |
| INTEGER | 32 | The LibTomCrypt used keysize |
| INTEGER | publicKey.x | The affine X-Coordinate of the public key |
| INTEGER | publicKey.y | The affine Y-Coordinate of the public key |
- `ot` should always be `1`
- `ip` should be set to the final resolved ip address of the server you are
actually connecting to.
## 3.2 initivexpand/initivexpand2 (Client <- Server)
Depending on the server version the server will send a different init request.
- TS3 server <3.1 will send `initivexpand`. Continue with (see 3.2.1)
- TS3 server ≥3.1 will send `initivexpand2`. Continue with (see 3.2.2)
If you want to support both protocol standards you don't need to check/know the
server version. The client just has to act accordingly depending on which
packet the server sends.
### 3.2.1 initivexpand (Client <- Server)
The server responds with this command.
initivexpand alpha={alpha} beta={beta} omega={omega}
- `alpha` must have the same value as sent to the server in the previous step.
- `beta` is set to `base64(random[u8; 10])`
by the server.
- `omega` is set to `base64(publicKey[u8])`
with the public key from the server, encoded same as in (see 3.1)
With this information the client now must calculate the shared secret.
let sharedSecret: ECPoint
let x: [u8]
let sharedData: [u8; 32]
let SharedIV: [u8; 20]
let SharedMac: [u8; 8]
let ECDH(A, B) := (A * B).Normalize
sharedSecret = ECDH(serverPublicKey, ownPrivateKey)
x = sharedSecret.x.AsByteArray()
if x.length < 32
sharedData[ 0..(32-x.length)] = [0..0]
sharedData[(32-x.length)..32] = x[0..x.length]
elseif x.length == 32
sharedData[0..32] = x[0..32]
elseif x.length > 32
sharedData[0..32] = x[(x.length-32)..x.length]
SharedIV = sha1(sharedData)
SharedIV[0..10] = SharedIV[0..10] xor alpha.decode64()
SharedIV[10..20] = SharedIV[10..20] xor beta.decode64()
SharedMac[0..8] = sha1(SharedIV)[0..8]
### 3.2.2 initivexpand2 (Client <- Server)
The server responds with this command.
initivexpand2 l={l} beta={beta} omega={omega} ot={ot} proof={proof} tvd={tvd}
- `l` the server license (see 3.2.2.2)
- `beta` is set to `base64(random[u8; 54])`
by the server.
- `omega` is a `base64(publicKey[u8])`
with the public key from the server, encoded same as in (see 3.1)
- `ot` should always be `1`
- `proof` is a `base64(ecdh_sign(l))`
- `tvd` (base64, unknown; only set on servers with a license)
#### 3.2.2.1 Verify integrity
This step **must** be done to verity the integrity of the connection.
The `proof` parameter is the sign of the `l` parameter (*not* base64 encoded).
The client can verify the `l` parameter with the public key of the server
which is sent in `omega`.
Both proofs which are exchanged (the one you received in (see 3.2.2), and the
one sent in (see 3.2.2.5)) use 'prime256v1 with sha256, DER encoded'.
Note that the identity keys from client/server already should be keys
on 'prime256v1' as noted in (see 3).
#### 3.2.2.2 Parsing the license
The license has a small header continued by a list of blocks. Each block may
vary in length and must be parsed sequentially therefore.
The license header:
01 bytes : License version
Const: 0x01
The block base layout:
01 bytes : Key type
Const: 0x00 (public key)
32 bytes : Block public key
01 bytes : License block type
04 bytes : Not valid before date
04 bytes : Not valid after date
var bytes : (Content from the block type)
There are currently 4 different `License block type`s used.
- `00` Intermediate.
`content`:
```
04 bytes : Unknown
var bytes : A null terminated string, which describes the issuer of this certificate.
```
- `01` Website/`03` Code
`content`:
```
var bytes : A null terminated string, which describes the issuer of this certificate.
```
- `02` TS3 Server
`content`:
```
01 bytes : Server License Type
04 bytes : Max clients allowed on the server
var bytes : A null terminated string, which describes the issuer of this certificate.
```
- `08` TS5 Server
`content`:
```
01 bytes : Server License Type
01 bytes : Property count
var bytes : Properties, see following description on how each property is encoded
Per property:
01 bytes : Length of following data
01 bytes : Property Id
01 bytes : Data Type
var bytes : Content depending on data type, see below
```
Data Types:
- `00`: Null-terminated string
- `01`/`03`: 4 byte data
- `02`/`04`: 8 byte data
Property Id:
- `01` (type `01`): Unknown
- `02` (type `00`): Issuer of the certificate
- `03` (type `01`): Max clients allowed on the server, defaults to 32 if not present
- `32` Ephemeral
`content`: none
Both dates are stored in BigEndian, when read you must add `0x50e22700` to the
number and import as a unix timestamp.
Each `Not valid before` and `Not valid after` timespan must be within the range
of the parent license block.
The license must consist of `2 ≤ count ≤ 8` blocks.
The second to last block must be of type `Server`
and the last block must be of type `Ephemeral`.
#### 3.2.2.4 Calculating the shared secret
All elliptic curve operations for this step are done on the Curve25519.
You might find more tools looking for Ed25519 but keep in mind that Ed25519
describes an EdDsa signing/verify operation and is not the curve itself.
To calculate the shared secret each license block now must be processed
sequentially the following way:
next_key = public_key * clamp(sha512(block[1..])[0..32]) + parent
Where:
- `public_key` is the `Block public key` taken from the current license block.
This array must be imported as a compressed Curve25519 EC point.
- `sha512(block[1..])[0..32]` is the sha512 of the current license block.
Note that the first byte (`Key type`) is skipped for the sha calculation.
For the result only the first 32 bytes are used.
This resulting array must be imported as a Curve25519 private key.
- `parent` which is the resulting `next_key` from the previous block.
This is a compressed Curve25519 EC point.
- `clamp(num)` is a function describing `abs(num) mod B` where `B` is the base
point of Curve25519. This function can usually be implemented conveniently
on the number buffer like this:
```
let buffer: [u8; 32]
buffer[0] &= 0xF8
buffer[31] &= 0x3F
buffer[31] |= 0x40
```
Since the first block has no predecessor.
A fixed 'root' key is used as `parent`.
This key must be imported as a compressed Curve25519 EC point.
[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 last `next_key` is now used as the public key from the server
(see pseudocode below).
The client now has to create a temporary Curve25519 public/private keypair.
We will call them `client_public_key` and `client_private_key`.
Now the `SharedIV` and `SharedMac` which will be used in the encryption, just as
in the old protocol, can be calculated.
let SharedIV: [u8; 64]
let SharedMac: [u8; 8]
let sharedData: [u8; 32]
sharedData = next_key * client_private_key
SharedIV = sha512(sharedData[0..32])
SharedIV[ 0..10] = SharedIV[ 0..10] xor alpha.decode64()
SharedIV[10..64] = SharedIV[10..64] xor beta.decode64()
SharedMac[0..8] = sha1(SharedIV)[0..8]
#### 3.2.2.5 clientek (Client -> Server)
clientek ek={ek} proof={proof}
- `ek` is `base64(client_public_key)`
which the ephemeral (temporary) key created in (see 3.2.2.4) by the client.
This should obviously be the public key part only.
- `proof` is `base64(client_public_key + beta)`
which is a sign of the client_public_key (the `ek`) concatenated with the
`beta` parameter from the `initivexpand2` command.
The sign must be done with the private key from the identity keypair.
The normal packet id counting starts with this packet. This means that
`clientek` already has the packet id `1` and the next command will continue
with `2`.
### 3.2.3 **Notes**:
- Only `SharedIV` and `SharedMac` are needed. The other values can (and should)
be discarded.
- The crypto handshake is now completed. The normal encryption scheme (see 1.6)
is from now on used.
- All `Command`, `CommandLow`, `Ack` and `AckLow` packets must get encrypted.
- `Voice` packets (and `VoiceWhisper` when wanted) should be encrypted when the
channel encryption or server wide encryption flag is set.
- `Ping` and `Pong` must not be encrypted.
## 3.3 clientinit (Client -> Server)
clientinit client_nickname client_version client_platform client_input_hardware client_output_hardware client_default_channel client_default_channel_password client_server_password client_meta_data client_version_sign client_key_offset client_nickname_phonetic client_default_token hwid
- `client_nickname` the desired nickname
- `client_version` the client version
- `client_platform` the client platform
- `client_input_hardware` whether an input device is available
- `client_output_hardware` whether an output device is available
- `client_default_channel` the default channel to join. This can be a channel
path or `/<id>` (eg `/1`) for a channel id.
- `client_default_channel_password` the password for the join channel, prepared
the following way `base64(sha1(password))`
- `client_server_password` the password to enter the server, prepared the
following way `base64(sha1(password))`
- `client_meta_data` (can be left empty)
- `client_version_sign` a cryptographic sign to verify the genuinity of the
client
- `client_key_offset` the number offset used to calculate the hashcash (see 4.1)
value of the used identity
- `client_nickname_phonetic` the phonetic nickname for text-to-speech
- `client_default_token` permission token to be used when connecting to a server
- `hwid` hardware identification string
**Notes**:
- Since client signs are only generated and distributed by TeamSpeak systems,
this the recommended client triple, as it is the reference for this paper
- Version: `3.0.19.3 [Build: 1466672534]`
- Platform: `Windows`
- Sign: `a1OYzvM18mrmfUQBUgxYBxYz2DUU6y5k3/mEL6FurzU0y97Bd1FL7+PRpcHyPkg4R+kKAFZ1nhyzbgkGphDWDg==`
- The `hwid` usually consists of two 32 char strings concatenated with `,` and
looks like `87056c6e1268aaf5055abf8256415e0e,408978b6d98810cc03f0aa16a4c75600`
but even empty strings are accepted.
On windows the hwid seems to be generated from a registry key
(`HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProductId`).
On linux and macOS it seems to derive from the MAC address of the primary
Ethernet/Wifi adapter.
- Parameters which are empty or not used must be declared but left without
value and the `=` character
## 3.4 initserver (Client <- Server)
The server sends the `initserver` command.
Note:
- From this point on the client knows his client id, therefore it must be set
in the header of each packet.
- Newer versions of the server send parts of the `clientinit` command in the `initserver` command.
## 3.5 Further notifications
The server will now send all needed information to display the entire
server properly. Those notifications are in no fixed order, although they
are most of the time sent in the here declared order.
### 3.5.1 channellist and channellistfinished
The `channellist` notification type will be sent multiple times as needed to
transfer the entire server structure.
After the last `channellist` notification the server will send
`channellistfinished`
### 3.5.2 notifycliententerview
The `notifycliententerview` notification will be sent multiple times as needed
for each client currently connected.
This is the same notification as when a new client connects.
# 4. Further concepts
## 4.1 Hashcash
To prevent client spamming (connecting to a server with many different clients)
the server requires a certain hashcash level on each identity. This level has a
exponentially growing calculation time with increasing level. This ensures that
a user wanting to spam a certain server needs to invest some time into
calculating the required level.
- The publicKey is a string encoded as in (see 3.1) the omega value.
- The key offset is a u64 number, which gets converted to a string when
concatenated.
The first step is to calculate a hash as following
let data: [u8; 20] = sha1(publicKey + keyOffset)
The level can now be calculated by counting the continuous leading zero bits in
the data array.
The bytes in the array get counted from 0 to 20 and the bits in each byte
from least significant to most significant.
## 4.2 Uid
To calculate the uid of an identity the public key is required. Therefore you
can only calculate the uid of your own identity and the servers identity you
are connecting to.
The publicKey is a string encoded as in (see 3.1) the omega value.
The uid can be calculated as following
let uid: string = base64(sha1(publicKey))
## 4.3 Ping/Pong
The server will regularly send ping packets to check if a client is still alive.
The client must answer them with the according pong packet.
The client should also send ping packets to the server to check for connection.
They will be answered with according pong packets.
Sending ping packets from the client side should not be started before the
crypto handshake has been completed (see 3.3)
## 4.4 Passwords
All passwords when sent are hashed and encoded with `base64(sha1(password))`
## 4.5 Importing/Deobfuscating Identities from the TeamSpeak3 Client
The TeamSpeak3 Client exports identities the following way:
<key_offset> + 'V' + <obfuscaded_identity>
(For an explanation of the key offset (see 4.1))
```ts
const staticObfucationKey = b"b9dfaa7bee6ac57ac7b65f1094a1c155e747327bc2fe5d51c512023fe54a280201004e90ad1daaae1075d53b7d571c30e063b5a62a4a017bb394833aa0983e6e"
let ident = obfuscaded_identity.decode64()
let sha_part = ident[20..]
let idx = sha_part.indexof('\0') // where '\0' is the null-byte
let sha = sha1(sha_part[..idx])
ident[0..20] = ident[0..20] xor sha[0..20]
let xorlen = min(ident.length, 100)
ident[0..xorlen] = ident[0..xorlen] xor staticObfucationKey[0..xorlen]
```
## 4.6 Audio
When the Opus codec is used, Voice and VoiceWhisper packets are using a sampling
rate of 48 kHz. An voice packat without audio data signals the end of a stream.
## 4.7 Permissions
`permissionlist` requests the list of all permissions of the server.
`notifypermissionlist` returns the list of permissions and a grouping as a list
of `group_id_end`s. The end ids are excluding, so a `group_id_end=6` for the first
group means the first 6 permissions (`perms[0..6]`) are in this group.
## 4.8 Channel Subscription
Clients can subscribe channels, so they get notifications when someone enters or
leaves from a subscribed channel. If a new channel is subscribed, the server
usually sends a notification, except in some cases:
- If the client server groups or permissions change, it stays subscribed, even
if it does not have the power anymore
- If the channel permissions change, the server sends a notification if the
subscription status changed
- If a client enters a channel, it gets subscribed but there is no notification
- If a client leaves a channel, there is a notification that it unsubscribed
- If a new channel is created, clients are not automatically subscribed
## 4.? Differences between Query and Full Client
- notifyconnectioninforequest
- => setconnectioninfo
+207
View File
@@ -0,0 +1,207 @@
use heck::*;
use once_cell::sync::Lazy;
use serde::Deserialize;
use crate::*;
pub const DATA_STR: &str =
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/declarations/Book.toml"));
pub static DATA: Lazy<BookDeclarations> = Lazy::new(|| toml::from_str(DATA_STR).unwrap());
#[derive(Deserialize, Debug)]
#[serde(deny_unknown_fields)]
pub struct BookDeclarations {
#[serde(rename = "struct")]
pub structs: Vec<Struct>,
}
impl BookDeclarations {
pub fn get_struct(&self, name: &str) -> &Struct {
if let Some(s) = self.structs.iter().find(|s| s.name == name) {
s
} else {
panic!("Cannot find bookkeeping struct {}", name);
}
}
}
#[derive(Deserialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
pub struct Id {
#[serde(rename = "struct")]
pub struct_name: String,
pub prop: String,
}
impl Id {
pub fn find_property<'a>(&self, structs: &'a [Struct]) -> &'a Property {
// Find struct
for s in structs {
if s.name == self.struct_name {
// Find property
for p in &s.properties {
if p.name == self.prop {
return p;
}
}
}
}
panic!("Cannot find struct {} of id", self.struct_name);
}
}
#[derive(Deserialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
pub struct Struct {
pub name: String,
#[serde(default = "get_false")]
pub opt: bool,
pub id: Vec<Id>,
pub doc: String,
pub properties: Vec<Property>,
}
#[derive(Deserialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
pub struct Property {
/// The name of this property (in PascalCase) which can be called from rust
/// when generated.
pub name: String,
/// The rust declaration type.
#[serde(rename = "type")]
pub type_s: String,
pub doc: Option<String>,
#[serde(default = "get_false")]
pub opt: bool,
#[serde(rename = "mod")]
pub modifier: Option<String>,
pub key: Option<String>,
}
impl Struct {
pub fn get_type(&self) -> Result<RustType> { RustType::with_opt(&self.name, self.opt) }
pub fn get_ids(&self, structs: &[Struct]) -> String {
let mut res = String::new();
for id in &self.id {
let p = id.find_property(structs);
if !res.is_empty() {
res.push_str(", ");
}
res.push_str(&p.get_type().unwrap().to_string());
}
embrace(&res)
}
pub fn get_properties(&self, structs: &[Struct]) -> Vec<&Property> {
self.properties.iter().filter(|p| !structs.iter().any(|s| s.name == p.type_s)).collect()
}
/// Get all properties, including foreign ids (own ids are listed in properties).
pub fn get_all_properties(&self) -> impl Iterator<Item = PropId<'_>> {
self.id.iter()
// Only foreign ids, others are also stored in the properties
.filter_map(move |i| if i.struct_name != self.name { Some(PropId::from(i)) }
else { None })
.chain(self.properties.iter().map(|p| p.into()))
}
}
impl Property {
pub fn get_inner_type(&self) -> Result<RustType> { RustType::with_opt(&self.type_s, self.opt) }
pub fn get_type(&self) -> Result<RustType> {
let key = if self.is_map() {
Some(self.key.as_deref().ok_or_else(|| {
eprintln!("Specified map without key");
fmt::Error
})?)
} else {
None
};
RustType::with(&self.type_s, self.opt, key, self.is_set(), self.is_array())
}
/// Gets the type as a name, used for storing it in an enum.
pub fn get_inner_type_as_name(&self) -> Result<String> { Ok(self.get_inner_type()?.to_name()) }
pub fn get_ids(&self, structs: &[Struct], struc: &Struct) -> String {
let mut ids = struc.get_ids(structs);
if !ids.is_empty() {
ids.remove(0);
ids.pop();
}
if let Some(m) = &self.modifier {
if !ids.is_empty() {
ids.push_str(", ");
}
if m == "map" {
// The key is part of the id
ids.push_str(self.key.as_ref().unwrap());
} else if m == "array" || m == "set" {
// Take the element itself as part of the id.
// It has to be copied but most of the times it is an id itself.
ids.push_str(&self.get_inner_type().unwrap().to_string());
} else {
panic!("Unknown modifier {}", m);
}
}
embrace(&ids)
}
/// Get the name without trailing `s`.
pub fn get_name(&self) -> &str {
if self.modifier.is_some() && self.name.ends_with('s') {
&self.name[..self.name.len() - 1]
} else {
&self.name
}
}
pub fn is_array(&self) -> bool { self.modifier.as_ref().map(|s| s == "array").unwrap_or(false) }
pub fn is_set(&self) -> bool { self.modifier.as_ref().map(|s| s == "set").unwrap_or(false) }
pub fn is_map(&self) -> bool { self.modifier.as_ref().map(|s| s == "map").unwrap_or(false) }
}
pub enum PropId<'a> {
Prop(&'a Property),
Id(&'a Id),
}
impl<'a> PropId<'a> {
pub fn get_attr_name(&self, struc: &Struct) -> String {
match *self {
PropId::Prop(p) => p.name.to_snake_case(),
PropId::Id(id) => {
if struc.name == id.struct_name {
id.prop.to_snake_case()
} else {
format!("{}_{}", id.struct_name.to_snake_case(), id.prop.to_snake_case(),)
}
}
}
}
pub fn get_doc(&self) -> Option<&str> {
match *self {
PropId::Prop(p) => p.doc.as_deref(),
PropId::Id(_) => None,
}
}
pub fn get_type(&self, structs: &[Struct]) -> Result<RustType> {
match *self {
PropId::Prop(p) => p.get_type(),
PropId::Id(id) => id.find_property(structs).get_type(),
}
}
}
impl<'a> From<&'a Property> for PropId<'a> {
fn from(p: &'a Property) -> Self { PropId::Prop(p) }
}
impl<'a> From<&'a Id> for PropId<'a> {
fn from(p: &'a Id) -> Self { PropId::Id(p) }
}
@@ -0,0 +1,344 @@
use std::str::FromStr;
use heck::*;
use once_cell::sync::Lazy;
use serde::Deserialize;
use crate::book::{BookDeclarations, Property, Struct};
use crate::messages::{Field, Message, MessageDeclarations};
use crate::*;
pub const DATA_STR: &str =
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/declarations/BookToMessages.toml"));
pub static DATA: Lazy<BookToMessagesDeclarations<'static>> = Lazy::new(|| {
let rules: TomlStruct = toml::from_str(DATA_STR).unwrap();
let book = &book::DATA;
let messages = &messages::DATA;
let decls: Vec<_> = rules
.rule
.into_iter()
.map(|r| {
let msg = messages.get_message(&r.to);
let msg_fields =
msg.attributes.iter().map(|a| messages.get_field(a)).collect::<Vec<_>>();
let book_struct = book
.structs
.iter()
.find(|s| s.name == r.from)
.unwrap_or_else(|| panic!("Cannot find struct {}", r.from));
let find_prop =
|name: &str, book_struct: &'static Struct| -> Option<&'static Property> {
book_struct.properties.iter().find(|p| p.name == *name)
};
// Map RuleProperty to RuleKind
let to_rule_kind = |p: RuleProperty| {
p.assert_valid();
if p.function.is_some() {
if p.type_s.is_some() {
RuleKind::ArgumentFunction {
type_s: p.type_s.unwrap(),
from: p.from.unwrap(),
name: p.function.unwrap(),
to: p
.tolist
.unwrap()
.into_iter()
.map(|p| find_field(&p, &msg_fields))
.collect(),
}
} else {
RuleKind::Function {
from: p.from.as_ref().map(|p| {
find_prop(p, book_struct).unwrap_or_else(|| {
panic!("No such (nested) property {} found in struct", p)
})
}),
name: p.function.unwrap(),
to: p
.tolist
.unwrap()
.into_iter()
.map(|p| find_field(&p, &msg_fields))
.collect(),
}
}
} else if let Some(prop) = find_prop(p.from.as_ref().unwrap(), book_struct) {
RuleKind::Map { from: prop, to: find_field(&p.to.unwrap(), &msg_fields) }
} else {
RuleKind::ArgumentMap {
from: p.from.unwrap(),
to: find_field(&p.to.unwrap(), &msg_fields),
}
}
};
let mut ev = Event {
op: r.operation.parse().expect("Failed to parse operation"),
ids: r.ids.into_iter().map(to_rule_kind).collect(),
msg,
book_struct,
rules: r.properties.into_iter().map(to_rule_kind).collect(),
};
// Add ids, which are required fields in the message.
// The filter checks that the message is not optional.
for field in msg_fields.iter().filter(|f| msg.attributes.iter().any(|a| *a == f.map)) {
if !ev.ids.iter().any(|i| match i {
RuleKind::Map { to, .. } => to == field,
RuleKind::ArgumentMap { to, .. } => to == field,
RuleKind::Function { to, .. } | RuleKind::ArgumentFunction { to, .. } => {
to.contains(field)
}
}) {
// Try to find matching property
if let Some(prop) = book
.get_struct(&ev.book_struct.name)
.properties
.iter()
.find(|p| !p.opt && p.name == field.pretty)
{
ev.ids.push(RuleKind::Map { from: prop, to: field })
}
// The property may be in the properties
}
}
// Add properties
for field in msg_fields.iter().filter(|f| !msg.attributes.iter().any(|a| *a == f.map)) {
if !ev.ids.iter().chain(ev.rules.iter()).any(|i| match i {
RuleKind::Map { to, .. } => to == field,
RuleKind::ArgumentMap { to, .. } => to == field,
RuleKind::Function { to, .. } | RuleKind::ArgumentFunction { to, .. } => {
to.contains(field)
}
}) {
// We ignore that properties are set as option. In all current cases, it
// makes no sense to set them to `None`, so we handle them the same way as
// non-optional properties.
if let Some(prop) = book
.get_struct(&ev.book_struct.name)
.properties
.iter()
.find(|p| p.name == field.pretty)
{
if !ev.ids.iter().chain(ev.rules.iter()).any(|i| i.from_name() == prop.name)
{
ev.rules.push(RuleKind::Map { from: prop, to: field })
}
}
}
}
ev
})
.collect();
BookToMessagesDeclarations { book, messages, decls }
});
#[derive(Debug)]
pub struct BookToMessagesDeclarations<'a> {
pub book: &'a BookDeclarations,
pub messages: &'a MessageDeclarations,
pub decls: Vec<Event<'a>>,
}
#[derive(Debug)]
pub struct Event<'a> {
pub op: RuleOp,
pub msg: &'a Message,
pub book_struct: &'a Struct,
pub ids: Vec<RuleKind<'a>>,
pub rules: Vec<RuleKind<'a>>,
}
#[derive(Debug)]
pub enum RuleKind<'a> {
Map { from: &'a Property, to: &'a Field },
ArgumentMap { from: String, to: &'a Field },
Function { from: Option<&'a Property>, name: String, to: Vec<&'a Field> },
ArgumentFunction { from: String, type_s: String, name: String, to: Vec<&'a Field> },
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum RuleOp {
Add,
Remove,
Update,
}
#[derive(Deserialize, Debug)]
#[serde(deny_unknown_fields)]
struct TomlStruct {
rule: Vec<Rule>,
}
#[derive(Clone, Deserialize, Debug)]
#[serde(deny_unknown_fields)]
pub struct Rule {
from: String,
to: String,
operation: String,
#[serde(default = "Vec::new")]
ids: Vec<RuleProperty>,
#[serde(default = "Vec::new")]
properties: Vec<RuleProperty>,
}
#[derive(Clone, Deserialize, Debug)]
#[serde(deny_unknown_fields)]
pub struct RuleProperty {
from: Option<String>,
to: Option<String>,
#[serde(rename = "type")]
type_s: Option<String>,
function: Option<String>,
tolist: Option<Vec<String>>,
}
impl RuleProperty {
fn assert_valid(&self) {
if let Some(to) = &self.to {
assert!(self.from.is_some(), "to-property '{}' is invalid. It needs a 'from'", to);
assert!(
self.function.is_none(),
"to-property '{}' is invalid. It must not have a 'function'",
to
);
assert!(
self.tolist.is_none(),
"to-property '{}' is invalid. It must not have a 'tolist'",
to
);
assert!(
self.type_s.is_none(),
"to-property '{}' is invalid. It must not have a 'type'",
to
);
} else if let Some(fun) = &self.function {
assert!(
self.tolist.is_some(),
"function-property '{}' is invalid. It needs 'tolist'",
fun
);
assert!(
self.type_s.is_none() || self.from.is_some(),
"function-property '{}' is invalid. If the type ({:?}) is set, from must be set \
too",
fun,
self.type_s
);
} else {
panic!(
"Property is invalid. It needs either a 'to' or 'tolist'+'function'.Info: \
tolist={:?} type={:?} from={:?}",
self.tolist, self.type_s, self.from
);
}
}
}
impl FromStr for RuleOp {
type Err = fmt::Error;
fn from_str(s: &str) -> Result<Self> {
if s == "add" {
Ok(RuleOp::Add)
} else if s == "remove" {
Ok(RuleOp::Remove)
} else if s == "update" {
Ok(RuleOp::Update)
} else {
eprintln!("Cannot parse operation, needs to be add, remove or update");
Err(fmt::Error)
}
}
}
// the in rust callable name (in PascalCase) from the field
fn find_field<'a>(name: &str, msg_fields: &[&'a Field]) -> &'a Field {
msg_fields
.iter()
.find(|f| f.pretty == name)
.unwrap_or_else(|| panic!("Cannot find field '{}'", name))
}
impl<'a> RuleKind<'a> {
pub fn from_name(&'a self) -> &'a str {
match self {
RuleKind::Map { from, .. } => &from.name,
RuleKind::ArgumentMap { from, .. } => from,
RuleKind::Function { from, name, .. } => {
&from.unwrap_or_else(|| panic!("From not set for function {}", name)).name
}
RuleKind::ArgumentFunction { from, .. } => from,
}
}
pub fn from_name_singular(&'a self) -> &'a str {
let name = self.from_name();
if let Some(s) = name.strip_suffix('s') { s } else { name }
}
pub fn from(&self) -> &'a Property {
match self {
RuleKind::Map { from, .. } => from,
RuleKind::Function { from, name, .. } => {
from.unwrap_or_else(|| panic!("From not set for function {}", name))
}
RuleKind::ArgumentMap { .. } | RuleKind::ArgumentFunction { .. } => {
panic!("From is not a property for argument functions")
}
}
}
pub fn is_function(&self) -> bool {
matches!(self, RuleKind::Function { .. } | RuleKind::ArgumentFunction { .. })
}
pub fn get_type(&self) -> RustType {
match self {
RuleKind::Map { .. } | RuleKind::Function { .. } => self.from().get_type().unwrap(),
RuleKind::ArgumentMap { to, .. } => to.get_type("").unwrap(),
RuleKind::ArgumentFunction { type_s, .. } => type_s.parse().unwrap(),
}
}
pub fn get_type_no_option(&self) -> RustType {
match self {
RuleKind::Map { .. } => {
let mut rust_type = self.from().clone();
rust_type.opt = false;
rust_type.get_type().unwrap()
}
_ => self.get_type(),
}
}
pub fn get_argument(&self) -> String {
format!("{}: {}", self.from_name().to_snake_case(), self.get_type().to_ref(true))
}
pub fn get_argument_no_option(&self) -> String {
format!("{}: {}", self.from_name().to_snake_case(), self.get_type_no_option().to_ref(true))
}
}
impl<'a> Event<'a> {
/// The name of the change, could be a keyword.
pub fn get_small_name(&self) -> String {
// Strip own struct name and 'Request'
self.msg.name.replace(&self.book_struct.name, "").replace("Request", "")
}
/// The small name, not a keyword
pub fn get_change_name(&self) -> String {
let small_change_name = self.get_small_name();
if small_change_name == "Move" { self.msg.name.clone() } else { small_change_name }
}
}
+52
View File
@@ -0,0 +1,52 @@
use once_cell::sync::Lazy;
use serde::Deserialize;
pub const DATA_STR: &str =
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/declarations/Enums.toml"));
pub static DATA: Lazy<Enums> = Lazy::new(|| toml::from_str(DATA_STR).unwrap());
#[derive(Deserialize, Debug)]
#[serde(deny_unknown_fields)]
pub struct Enums {
#[serde(rename = "enum")]
pub enums: Vec<Enum>,
#[serde(rename = "bitflag")]
pub bitflags: Vec<Enum>,
}
#[derive(Deserialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
pub struct Enum {
pub name: String,
pub doc: Option<String>,
#[serde(rename = "type")]
pub use_type: Option<String>,
pub variants: Vec<Variant>,
}
#[derive(Deserialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
pub struct Variant {
pub name: String,
pub doc: String,
pub value: Option<u64>,
}
impl Enum {
/// Computes the needed number of bits to store all possible variants.
pub fn bitwidth(&self) -> u32 {
let mut leading_zeros = 0;
let mut value: u64 = 0;
for v in &self.variants {
if let Some(v) = v.value {
leading_zeros = std::cmp::min(leading_zeros, value.leading_zeros());
value = v;
} else {
value += 1;
}
}
leading_zeros = std::cmp::min(leading_zeros, value.leading_zeros());
(64 - leading_zeros).next_power_of_two()
}
}
@@ -0,0 +1,20 @@
use std::result::Result;
use crate::*;
use once_cell::sync::Lazy;
pub const DATA_STR: &str =
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/declarations/Errors.csv"));
pub static DATA: Lazy<Errors> = Lazy::new(|| {
Errors(
csv::Reader::from_reader(DATA_STR.as_bytes())
.deserialize()
.collect::<Result<Vec<_>, _>>()
.unwrap(),
)
});
#[derive(Default, Debug)]
pub struct Errors(pub Vec<EnumValue>);
+398
View File
@@ -0,0 +1,398 @@
//! `tsproto-structs` contains machine readable data for several TeamSpeak related topics.
//!
//! The underlying data files can be found in the
//! [tsdeclarations](https://github.com/ReSpeak/tsdeclarations) repository.
use std::fmt;
use std::str::FromStr;
use heck::*;
use serde::Deserialize;
type Result<T> = std::result::Result<T, fmt::Error>;
pub mod book;
pub mod book_to_messages;
pub mod enums;
pub mod errors;
pub mod messages;
pub mod messages_to_book;
pub mod permissions;
pub mod versions;
#[derive(Debug, Deserialize)]
pub struct EnumValue {
pub name: String,
pub doc: String,
pub num: String,
}
#[derive(Clone, Debug)]
pub enum InnerRustType {
Primitive(String),
Struct(String),
Ref(Box<InnerRustType>),
Option(Box<InnerRustType>),
/// Key, value
Map(Box<InnerRustType>, Box<InnerRustType>),
Set(Box<InnerRustType>),
Vec(Box<InnerRustType>),
Cow(Box<InnerRustType>),
}
#[derive(Clone, Debug)]
pub struct RustType {
pub inner: InnerRustType,
/// Include a lifetime specifier 'a
pub lifetime: bool,
}
impl InnerRustType {
/// `lifetime`: Include 'a for references
/// `is_ref`: If this is a refercene, used to emit either `str` or `String` or slices
pub fn fmt(&self, f: &mut fmt::Formatter, lifetime: bool, is_ref: bool) -> fmt::Result {
let lifetime_str = if lifetime { "'a " } else { "" };
match self {
Self::Struct(s) if s == "str" => {
if is_ref {
write!(f, "str")?;
} else {
write!(f, "String")?;
}
}
Self::Struct(s) if s == "Uid" => {
write!(f, "{}", s)?;
}
Self::Primitive(s) | Self::Struct(s) => write!(f, "{}", s)?,
Self::Ref(i) => {
write!(f, "&{}", lifetime_str)?;
i.fmt(f, lifetime, true)?;
}
Self::Option(i) => {
write!(f, "Option<")?;
i.fmt(f, lifetime, false)?;
write!(f, ">")?;
}
Self::Map(k, v) => {
write!(f, "HashMap<")?;
k.fmt(f, lifetime, false)?;
write!(f, ", ")?;
v.fmt(f, lifetime, false)?;
write!(f, ">")?;
}
Self::Set(i) => {
write!(f, "HashSet<")?;
i.fmt(f, lifetime, false)?;
write!(f, ">")?;
}
Self::Vec(i) => {
if is_ref {
write!(f, "[")?;
i.fmt(f, lifetime, false)?;
write!(f, "]")?;
} else {
write!(f, "Vec<")?;
i.fmt(f, lifetime, false)?;
write!(f, ">")?;
}
}
Self::Cow(i) => {
write!(f, "Cow<{}, ", lifetime_str.trim())?;
i.fmt(f, false, true)?;
write!(f, ">")?;
}
}
Ok(())
}
/// Returns a converted type.
pub fn to_ref(&self) -> Self {
match self {
Self::Struct(s) if s == "UidBuf" => Self::Ref(Box::new(Self::Struct("Uid".into()))),
Self::Struct(s) if s == "String" => Self::Ref(Box::new(Self::Struct("str".into()))),
Self::Struct(_) | Self::Map(_, _) | Self::Set(_) | Self::Vec(_) => {
Self::Ref(Box::new(self.clone()))
}
Self::Primitive(_) | Self::Ref(_) | Self::Cow(_) => self.clone(),
Self::Option(i) => Self::Option(Box::new(i.to_ref())),
}
}
/// Returns a converted type.
pub fn to_cow(&self) -> Self {
match self {
Self::Struct(s) if s == "UidBuf" => Self::Cow(Box::new(Self::Struct("Uid".into()))),
Self::Struct(s) if s == "String" => Self::Cow(Box::new(Self::Struct("str".into()))),
Self::Struct(_) | Self::Map(_, _) | Self::Set(_) | Self::Vec(_) => {
Self::Cow(Box::new(self.clone()))
}
Self::Primitive(_) | Self::Ref(_) | Self::Cow(_) => self.clone(),
Self::Option(i) => Self::Option(Box::new(i.to_cow())),
}
}
/// Get code snippet for `as_ref`.
pub fn code_as_ref(&self, name: &str) -> String {
match self {
Self::Struct(s) if s == "UidBuf" || s == "str" => format!("{}.as_ref()", name),
Self::Struct(s) if s == "String" => format!("{}.as_str()", name),
Self::Struct(s) if s == "str" => name.into(),
Self::Struct(_) => format!("&{}", name),
Self::Map(_, _) | Self::Set(_) | Self::Vec(_) | Self::Cow(_) => {
format!("{}.as_ref()", name)
}
Self::Primitive(_) => name.into(),
Self::Ref(i) => {
let inner = i.code_as_ref(name);
if inner == name {
format!("*{}", name)
} else if inner.starts_with('&') && &inner[1..] == name {
name.into()
} else {
inner
}
}
Self::Option(i) => {
match &**i {
// Shortcut
Self::Struct(s) if s == "String" => format!("{}.as_deref()", name),
_ => {
let inner = i.code_as_ref(name);
if inner == name {
inner
} else if inner.starts_with('&') && &inner[1..] == name {
format!("{0}.as_ref()", name)
} else {
format!("{0}.as_ref().map(|{0}| {1})", name, inner)
}
}
}
}
}
}
pub fn uses_lifetime(&self) -> bool {
match self {
Self::Struct(s) if s == "Uid" => true,
Self::Ref(_) | Self::Cow(_) => true,
Self::Map(_, i) | Self::Set(i) | Self::Vec(i) | Self::Option(i) => i.uses_lifetime(),
_ => false,
}
}
}
impl FromStr for InnerRustType {
type Err = fmt::Error;
fn from_str(s: &str) -> Result<Self> {
if s == "DateTime" {
Ok(Self::Primitive("OffsetDateTime".into()))
} else if s.starts_with("Duration") {
Ok(Self::Primitive("Duration".into()))
} else if s == "PermissionId" {
Ok(Self::Primitive("Permission".into()))
} else if s == "Ts3ErrorCode" {
Ok(Self::Primitive("Error".into()))
} else if s == "bool"
|| s.starts_with('i')
|| s.starts_with('u')
|| s.starts_with('f')
|| s.ends_with("Id")
|| s.ends_with("Type")
|| s.ends_with("Mode")
|| s == "ChannelPermissionHint"
|| s == "ClientPermissionHint"
|| s == "Codec"
|| s == "LogLevel"
|| s == "MaxClients"
|| s == "IpAddr"
|| s == "Reason"
|| s == "SocketAddr"
{
Ok(Self::Primitive(s.into()))
} else if s == "Uid" {
Ok(Self::Struct("UidBuf".into()))
} else if s == "str" || s == "String" {
Ok(Self::Struct("String".into()))
} else if let Some(rest) = s.strip_prefix('&') {
let rest = if rest.starts_with('\'') {
let i = rest.find(' ').ok_or_else(|| {
eprintln!("Reference type with lifetime has no inner type: {:?}", s);
fmt::Error
})?;
&rest[i + 1..]
} else {
rest
};
Ok(Self::Ref(Box::new(rest.parse()?)))
} else if let Some(rest) = s.strip_suffix('?') {
Ok(Self::Option(Box::new(rest.parse()?)))
} else if s.starts_with("Option<") {
let rest = &s[7..s.len() - 1];
Ok(Self::Option(Box::new(rest.parse()?)))
} else if let Some(rest) = s.strip_suffix("[]") {
Ok(Self::Vec(Box::new(rest.parse()?)))
} else if s.starts_with("HashMap<") {
let rest = &s[8..s.len() - 1];
let i = rest.find(',').ok_or_else(|| {
eprintln!("HashMap without key: {:?}", s);
fmt::Error
})?;
Ok(Self::Map(Box::new(rest[..i].parse()?), Box::new(rest[i..].trim().parse()?)))
} else if s.starts_with("HashSet<") {
let rest = &s[8..s.len() - 1];
Ok(Self::Set(Box::new(rest.parse()?)))
} else if s.starts_with("Vec<") {
let rest = &s[4..s.len() - 1];
Ok(Self::Vec(Box::new(rest.parse()?)))
} else if s.starts_with('[') {
let rest = &s[1..s.len() - 1];
if rest.contains(';') {
// Slice with explicit length, take as struct
Ok(Self::Struct(s.into()))
} else {
Ok(Self::Vec(Box::new(rest.parse()?)))
}
} else if let Some(rest) = s.strip_suffix('T') {
rest.parse()
} else {
Ok(Self::Struct(s.into()))
}
}
}
impl FromStr for RustType {
type Err = fmt::Error;
fn from_str(s: &str) -> Result<Self> {
Ok(Self { inner: s.parse()?, lifetime: s.contains("&'") })
}
}
impl RustType {
pub fn with_opt(s: &str, opt: bool) -> Result<Self> {
let inner = s.parse()?;
let inner = if opt { InnerRustType::Option(Box::new(inner)) } else { inner };
Ok(Self { inner, lifetime: s.contains("&'") })
}
/// `map` has a key
pub fn with(s: &str, opt: bool, map: Option<&str>, set: bool, vec: bool) -> Result<Self> {
assert!(
[map.is_some(), set, vec].iter().filter(|b| **b).count() <= 1,
"Too many modifiers active (map: {:?}, set: {:?}, vec: {:?})",
map,
set,
vec
);
let mut inner = s.parse()?;
if let Some(key) = map {
inner = InnerRustType::Map(Box::new(key.parse()?), Box::new(inner));
}
if set {
inner = InnerRustType::Set(Box::new(inner));
}
if vec {
inner = InnerRustType::Vec(Box::new(inner));
}
inner = if opt { InnerRustType::Option(Box::new(inner)) } else { inner };
Ok(Self { inner, lifetime: s.contains("&'") })
}
pub fn to_opt(&self, opt: bool) -> Self {
if opt {
Self {
inner: InnerRustType::Option(Box::new(self.inner.clone())),
lifetime: self.lifetime,
}
} else {
self.clone()
}
}
pub fn to_ref(&self, as_ref: bool) -> Self {
if as_ref {
Self { inner: self.inner.to_ref(), lifetime: self.lifetime }
} else {
self.clone()
}
}
pub fn to_cow(&self) -> Self { Self { inner: self.inner.to_cow(), lifetime: self.lifetime } }
pub fn lifetime(&self, lifetime: bool) -> Self {
let mut r = self.clone();
r.lifetime = lifetime;
r
}
pub fn wrap_ref(&self) -> Self {
Self { inner: InnerRustType::Ref(Box::new(self.inner.clone())), lifetime: self.lifetime }
}
pub fn wrap_opt(&self) -> Self {
Self { inner: InnerRustType::Option(Box::new(self.inner.clone())), lifetime: self.lifetime }
}
pub fn is_opt(&self) -> bool { matches!(self.inner, InnerRustType::Option(_)) }
pub fn is_primitive(&self) -> bool {
let inner = if let InnerRustType::Option(t) = &self.inner { t } else { &self.inner };
matches!(inner, InnerRustType::Primitive(_))
}
pub fn is_vec(&self) -> bool { matches!(self.inner, InnerRustType::Vec(_)) }
pub fn is_cow(&self) -> bool {
let inner = if let InnerRustType::Option(i) = &self.inner { i } else { &self.inner };
matches!(inner, InnerRustType::Cow(_))
}
pub fn uses_lifetime(&self) -> bool { self.inner.uses_lifetime() }
/// Returns an identifier from this type in camelCase.
pub fn to_name(&self) -> String {
self.to_string().replace('<', "_").replace('>', "").to_upper_camel_case()
}
/// Get code snippet for `as_ref`.
pub fn code_as_ref(&self, name: &str) -> String { self.inner.code_as_ref(name) }
}
impl From<InnerRustType> for RustType {
fn from(inner: InnerRustType) -> Self { Self { inner, lifetime: false } }
}
impl fmt::Display for RustType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.inner.fmt(f, self.lifetime, false) }
}
fn get_false() -> bool { false }
/// Prepend `/// ` to each line of a string.
pub fn doc_comment(s: &str) -> String { s.lines().map(|l| format!("/// {}\n", l)).collect() }
/// Indent a string by a given count using tabs.
pub fn indent<S: AsRef<str>>(s: S, count: usize) -> String {
let sref = s.as_ref();
let line_count = sref.lines().count();
let mut result = String::with_capacity(sref.len() + line_count * count * 4);
for l in sref.lines() {
if !l.is_empty() {
result.push_str(&"\t".repeat(count));
}
result.push_str(l);
result.push('\n');
}
result
}
/// Unindent a string by a given count of tabs.
pub fn unindent(s: &mut String) {
std::mem::swap(&mut s.replace("\n\t", "\n"), s);
if s.get(0..1) == Some("\t") {
s.remove(0);
}
}
/// Returns an empty string if `s` is empty, otherwise `s` with braces.
pub fn embrace(s: &str) -> String { if s.is_empty() { String::new() } else { format!("({})", s) } }
@@ -0,0 +1,115 @@
use heck::*;
use once_cell::sync::Lazy;
use serde::Deserialize;
use crate::*;
pub const DATA_STR: &str =
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/declarations/Messages.toml"));
pub static DATA: Lazy<MessageDeclarations> = Lazy::new(|| toml::from_str(DATA_STR).unwrap());
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct MessageDeclarations {
pub fields: Vec<Field>,
pub msg_group: Vec<MessageGroup>,
}
impl MessageDeclarations {
pub fn get_message_opt(&self, name: &str) -> Option<&Message> {
self.msg_group.iter().flat_map(|g| g.msg.iter()).find(|m| m.name == name)
}
pub fn get_message(&self, name: &str) -> &Message {
self.get_message_opt(name).unwrap_or_else(|| panic!("Cannot find message {}", name))
}
pub fn get_message_group(&self, msg: &Message) -> &MessageGroup {
for g in &self.msg_group {
for m in &g.msg {
if std::ptr::eq(m, msg) {
return g;
}
}
}
panic!("Cannot find message group for message");
}
pub fn get_field(&self, mut map: &str) -> &Field {
if map.ends_with('?') {
map = &map[..map.len() - 1];
}
if let Some(f) = self.fields.iter().find(|f| f.map == map) {
f
} else {
panic!("Cannot find field {}", map);
}
}
pub fn uses_lifetime(&self, msg: &Message) -> bool {
for a in &msg.attributes {
let field = self.get_field(a);
if field.get_type(a).unwrap().to_ref(true).uses_lifetime() {
return true;
}
}
false
}
}
#[derive(Deserialize, Debug, Clone, Eq, Hash, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Field {
/// Internal name of this declarations file to map fields to messages.
pub map: String,
/// The name as called by TeamSpeak in messages.
pub ts: String,
/// The pretty name in PascalCase. This will be used for the fields in rust.
pub pretty: String,
#[serde(rename = "type")]
pub type_s: String,
#[serde(rename = "mod")]
pub modifier: Option<String>,
}
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct MessageGroup {
pub default: MessageGroupDefaults,
pub msg: Vec<Message>,
}
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct MessageGroupDefaults {
pub s2c: bool,
pub c2s: bool,
pub response: bool,
pub low: bool,
pub np: bool,
}
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct Message {
/// How we call this message.
pub name: String,
/// How TeamSpeak calls this message.
pub notify: Option<String>,
pub attributes: Vec<String>,
}
impl Field {
pub fn get_rust_name(&self) -> String { self.pretty.to_snake_case() }
/// Takes the attribute to look if it is optional
pub fn get_type(&self, a: &str) -> Result<RustType> {
RustType::with(&self.type_s, a.ends_with('?'), None, false, self.is_array())
}
/// Returns if this field is optional in the message.
pub fn is_opt(&self, msg: &Message) -> bool { !msg.attributes.iter().any(|a| *a == self.map) }
pub fn is_array(&self) -> bool { self.modifier.as_ref().map(|s| s == "array").unwrap_or(false) }
}
@@ -0,0 +1,263 @@
use std::collections::HashSet;
use std::fmt::Write;
use std::str::FromStr;
use once_cell::sync::Lazy;
use serde::Deserialize;
use crate::book::{BookDeclarations, Property, Struct};
use crate::messages::{Field, Message, MessageDeclarations};
use crate::*;
pub const DATA_STR: &str =
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/declarations/MessagesToBook.toml"));
pub static DATA: Lazy<MessagesToBookDeclarations<'static>> = Lazy::new(|| {
let rules: TomlStruct = toml::from_str(DATA_STR).unwrap();
let book = &book::DATA;
let messages = &messages::DATA;
let mut decls: Vec<_> = rules
.rule
.into_iter()
.map(|r| {
let msg = messages.get_message(&r.from);
let msg_fields =
msg.attributes.iter().map(|a| messages.get_field(a)).collect::<Vec<_>>();
let book_struct = book
.structs
.iter()
.find(|s| s.name == r.to)
.unwrap_or_else(|| panic!("Cannot find struct {}", r.to));
let mut ev = Event {
op: r.operation.parse().expect("Failed to parse operation"),
id: r.id.iter().map(|s| find_field(s, &msg_fields)).collect(),
msg,
book_struct,
rules: r
.properties
.into_iter()
.map(|p| {
assert!(p.is_valid());
let find_prop = |name, book_struct: &'static Struct| -> &'static Property {
if let Some(prop) =
book_struct.properties.iter().find(|p| p.name == name)
{
return prop;
}
panic!(
"No such (nested) property {} found in struct {}",
name, book_struct.name,
);
};
if p.function.is_some() {
RuleKind::Function {
name: p.function.unwrap(),
to: p
.tolist
.unwrap()
.into_iter()
.map(|p| find_prop(p, book_struct))
.collect(),
}
} else {
RuleKind::Map {
from: find_field(&p.from.unwrap(), &msg_fields),
to: find_prop(p.to.unwrap(), book_struct),
op: p
.operation
.map(|s| s.parse().expect("Invalid operation for property"))
.unwrap_or(RuleOp::Update),
}
}
})
.collect(),
};
// Add attributes with the same name automatically (if they are not
// yet there).
let used_flds = ev
.rules
.iter()
.filter_map(|f| match *f {
RuleKind::Map { from, .. } => Some(from),
_ => None,
})
.collect::<HashSet<_>>();
let mut used_props = vec![];
for rule in &ev.rules {
if let RuleKind::Function { to, .. } = rule {
for p in to {
used_props.push(p.name.clone());
}
}
}
for fld in &msg_fields {
if used_flds.contains(fld) {
continue;
}
if let Some(prop) = book
.get_struct(&ev.book_struct.name)
.properties
.iter()
.find(|p| p.name == fld.pretty)
{
if used_props.contains(&prop.name) {
continue;
}
ev.rules.push(RuleKind::Map { from: fld, to: prop, op: RuleOp::Update });
}
}
ev
})
.collect();
// InitServer is done manually
decls.retain(|ev| ev.msg.name != "InitServer");
MessagesToBookDeclarations { book, messages, decls }
});
#[derive(Debug)]
pub struct MessagesToBookDeclarations<'a> {
pub book: &'a BookDeclarations,
pub messages: &'a MessageDeclarations,
pub decls: Vec<Event<'a>>,
}
#[derive(Debug)]
pub struct Event<'a> {
pub op: RuleOp,
/// Unique access tuple to get the property
pub id: Vec<&'a Field>,
pub msg: &'a Message,
pub book_struct: &'a Struct,
pub rules: Vec<RuleKind<'a>>,
}
#[derive(Debug)]
pub enum RuleKind<'a> {
Map { from: &'a Field, to: &'a Property, op: RuleOp },
Function { name: String, to: Vec<&'a Property> },
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum RuleOp {
Add,
Remove,
Update,
}
#[derive(Clone, Deserialize, Debug)]
#[serde(deny_unknown_fields)]
struct TomlStruct {
rule: Vec<Rule>,
}
#[derive(Clone, Deserialize, Debug)]
#[serde(deny_unknown_fields)]
struct Rule {
id: Vec<String>,
from: String,
to: String,
operation: String,
#[serde(default = "Vec::new")]
properties: Vec<RuleProperty>,
}
#[derive(Clone, Deserialize, Debug)]
#[serde(deny_unknown_fields)]
struct RuleProperty {
from: Option<String>,
to: Option<String>,
operation: Option<String>,
function: Option<String>,
tolist: Option<Vec<String>>,
}
impl Event<'_> {
/// Fill the id of a `PropertyId`.
///
/// `msg` is the name of the message object.
pub fn get_id_args(&self, msg: &str) -> String {
let mut res = String::new();
for f in &self.id {
if !res.is_empty() {
res.push_str(", ");
}
if !f.get_type("").unwrap().is_primitive() {
res.push('&');
}
let _ = write!(res, "{}.{}", msg, f.get_rust_name());
}
res
}
/// Create a `PropertyId` from a message struct.
///
/// `msg` is the name of the message object.
pub fn get_property_id(&self, p: &Property, from: &Field, msg: &str) -> String {
let mut ids = self.get_id_args(msg);
if let Some(m) = &p.modifier {
if !ids.is_empty() {
ids.push_str(", ");
}
if m == "map" || m == "array" || m == "set" {
let _ = write!(ids, "{}.{}", msg, from.get_rust_name());
} else {
panic!("Unknown modifier {}", m);
}
}
format!("PropertyId::{}{}{}", self.book_struct.name, p.get_name(), embrace(&ids))
}
}
impl RuleProperty {
fn is_valid(&self) -> bool {
if self.from.is_some() {
self.to.is_some() && self.function.is_none() && self.tolist.is_none()
} else {
self.from.is_none()
&& self.to.is_none()
&& self.operation.is_none()
&& self.function.is_some()
&& self.tolist.is_some()
}
}
}
impl FromStr for RuleOp {
type Err = fmt::Error;
fn from_str(s: &str) -> Result<Self> {
if s == "add" {
Ok(RuleOp::Add)
} else if s == "remove" {
Ok(RuleOp::Remove)
} else if s == "update" {
Ok(RuleOp::Update)
} else {
eprintln!("Cannot parse operation, needs to be add, remove or update");
Err(fmt::Error)
}
}
}
// the in rust callable name (in PascalCase) from the field
fn find_field<'a>(name: &str, msg_fields: &[&'a Field]) -> &'a Field {
msg_fields
.iter()
.find(|f| f.pretty == name)
.unwrap_or_else(|| panic!("Cannot find field '{}'", name))
}
impl<'a> RuleKind<'a> {
pub fn is_function(&self) -> bool { matches!(self, RuleKind::Function { .. }) }
}
@@ -0,0 +1,26 @@
use std::result::Result;
use crate::*;
use once_cell::sync::Lazy;
pub const DATA_STR: &str =
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/declarations/Permissions.csv"));
pub static DATA: Lazy<Permissions> = Lazy::new(|| {
Permissions(
csv::Reader::from_reader(DATA_STR.as_bytes())
.deserialize()
.collect::<Result<Vec<_>, _>>()
.unwrap(),
)
});
#[derive(Debug, Deserialize)]
pub struct EnumValue {
pub name: String,
pub doc: String,
}
#[derive(Default, Debug)]
pub struct Permissions(pub Vec<EnumValue>);
@@ -0,0 +1,94 @@
use std::collections::HashMap;
use std::fmt::Write;
use std::result::Result;
use crate::*;
use base64::prelude::*;
use once_cell::sync::Lazy;
pub const DATA_STR: &str =
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/declarations/Versions.csv"));
pub static DATA: Lazy<Versions> = Lazy::new(|| {
let mut table = csv::Reader::from_reader(DATA_STR.as_bytes());
let mut vs = Versions(table.deserialize().collect::<Result<Vec<_>, _>>().unwrap());
// Add count if necessary
let mut counts: HashMap<_, u32> = HashMap::new();
for v in &vs.0 {
let key = VersionKey::new(v);
*counts.entry(key).or_default() += 1;
}
counts.retain(|_, c| *c > 1);
for v in vs.0.iter_mut().rev() {
let key = VersionKey::new(v);
if let Some(count) = counts.get_mut(&key) {
v.count = *count;
*count -= 1;
}
}
vs
});
#[derive(Debug, Deserialize, Clone)]
#[serde(deny_unknown_fields)]
pub struct Version {
pub version: String,
pub platform: String,
pub hash: String,
#[serde(default)]
count: u32,
}
impl Version {
pub fn get_enum_name(&self) -> String {
let mut res = String::new();
res.push_str(&self.platform.replace([' ', '.'], "_"));
let ver = self.version.split(' ').next().unwrap().replace('-', "_");
for num in ver.split('.') {
res.push('_');
if num != "?" {
res.push_str(num);
} else {
res.push('X');
}
}
if self.count != 0 {
res.push_str("__");
res.push_str(&self.count.to_string());
}
res
}
pub fn get_sign_array(&self) -> String {
let mut res = String::new();
for b in BASE64_STANDARD.decode(&self.hash).unwrap() {
if !res.is_empty() {
res.push_str(", ");
}
let _ = write!(res, "{:#x}", b);
}
res
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct VersionKey {
pub version: String,
pub platform: String,
}
impl VersionKey {
fn new(v: &Version) -> Self {
Self {
version: v.version.split(' ').next().unwrap().to_string(),
platform: v.platform.clone(),
}
}
}
#[derive(Default, Debug)]
pub struct Versions(pub Vec<Version>);
+40
View File
@@ -0,0 +1,40 @@
[package]
name = "tsproto-types"
version = "0.1.0"
authors = ["Flakebi <flakebi@t-online.de>"]
description = "Basic types and enums that are used within the TeamSpeak protocol."
repository = "https://github.com/ReSpeak/tsclientlib/tree/master/utils/tsproto-types"
readme = "README.md"
keywords = ["teamspeak3", "ts3"]
license = "MIT OR Apache-2.0"
build = "build/build.rs"
edition = "2018"
include = [
"/Cargo.toml",
"/README.md",
"**/*.rs",
"**/*.tt",
]
[dependencies]
base64 = "0.22"
bitflags = { version = "2", features = ["serde"] }
curve25519-dalek-ng = "4"
elliptic-curve = { version = "0.13", features = ["ecdh"] }
generic-array = "0.14"
num-bigint = "0.4"
num-derive = "0.4"
num-traits = "0.2"
p256 = { version = "0.13", features = ["ecdh", "ecdsa"] }
rand = "0.8"
ref-cast = "1"
serde = { version = "1", features = ["derive"] }
sha-1 = "0.10"
simple_asn1 = "0.6"
thiserror = "2"
time = { version = "0.3", features = ["serde"] }
[build-dependencies]
heck = "0.5"
t4rust-derive = "0.3"
tsproto-structs = { path = "../tsproto-structs", version = "0.2" }
+10
View File
@@ -0,0 +1,10 @@
# tsproto-types [![docs.rs](https://docs.rs/tsproto-types/badge.svg)](https://docs.rs/tsproto-types)
`tsproto-types` contains basic types and enums that are used within the TeamSpeak protocol.
## License
Licensed under either of
* [Apache License, Version 2.0](../../LICENSE-APACHE)
* [MIT license](../../LICENSE-MIT)
at your option.
+10
View File
@@ -0,0 +1,10 @@
# tsproto-types [![docs.rs](https://docs.rs/tsproto-types/badge.svg)](https://docs.rs/tsproto-types)
{{readme}}
## License
Licensed under either of
* [Apache License, Version 2.0](../../LICENSE-APACHE)
* [MIT license](../../LICENSE-MIT)
at your option.
+30
View File
@@ -0,0 +1,30 @@
<#@ template cleanws="true" #>
<# for e in &self.enums { #>
<# if let Some(doc) = &e.doc { #>
<#= doc_comment(doc) #>
<# } #>
#[derive(Clone, Copy, Debug, Deserialize, Eq, FromPrimitive, Hash, PartialEq, Serialize, ToPrimitive)]
pub enum <#= e.name #><# if let Some(ty) = &e.use_type { #>: <#= ty #><# } #> {
<# for v in &e.variants { #>
<#= indent(&doc_comment(&v.doc), 1) #>
<#= v.name #><# if let Some(val) = v.value { #> = <#= val #><# } #>,
<# } #>
}
<# }
for e in &self.bitflags { #>
bitflags! {
<# if let Some(doc) = &e.doc { #>
<#= indent(&doc_comment(doc), 1) #>
<# } #>
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct <#= e.name #>: <#= e.use_type.clone().unwrap_or_else(|| format!("u{}", e.bitwidth())) #> {
<# for v in &e.variants { #>
<#= indent(&doc_comment(&v.doc), 2) #>
const <#= v.name.to_shouty_snake_case() #><# if let Some(val) = v.value { #> = <#= val #><# } #>;
<# } #>
}
}
<# } #>
@@ -0,0 +1,13 @@
<#@ template cleanws="true" #>
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Deserialize, Eq, FromPrimitive, Hash, PartialEq, Serialize, ToPrimitive)]
#[non_exhaustive]
pub enum Error {
<# for e in &**self { #>
<# if !e.doc.is_empty() { #>
<#= indent(&doc_comment(&e.doc), 1) #>
<# } #>
<#= e.name.to_pascal_case() #> = <#= e.num #>,
<# } #>
}
@@ -0,0 +1,41 @@
<#@ template cleanws="true" #>
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[non_exhaustive]
#[allow(non_camel_case_types)]
pub enum Version {
<# for v in &**self { #>
<#= v.get_enum_name() #>,
<# } #>
Custom { platform: String, version: String, signature: Vec<u8> },
}
impl Version {
pub fn get_platform(&self) -> &str {
match *self {
<# for v in &**self { #>
Version::<#= v.get_enum_name() #> => "<#= v.platform #>",
<# } #>
Version::Custom { ref platform, .. } => platform,
}
}
pub fn get_version_string(&self) -> &str {
match *self {
<# for v in &**self { #>
Version::<#= v.get_enum_name() #> => "<#= v.version #>",
<# } #>
Version::Custom { ref version, .. } => version,
}
}
pub fn get_signature(&self) -> &[u8] {
match *self {
<# for v in &**self { #>
Version::<#= v.get_enum_name() #> => &[<#= v.get_sign_array() #>],
<# } #>
Version::Custom { ref signature, .. } => signature,
}
}
}
+30
View File
@@ -0,0 +1,30 @@
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
mod enums;
mod errors;
mod versions;
use crate::enums::Enums;
use crate::errors::Errors;
use crate::versions::Versions;
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
// Enums
let path = Path::new(&out_dir);
let mut structs = File::create(path.join("enums.rs")).unwrap();
write!(&mut structs, "{}", Enums).unwrap();
// Errors
let path = Path::new(&out_dir);
let mut structs = File::create(path.join("errors.rs")).unwrap();
write!(&mut structs, "{}", Errors).unwrap();
// Versions
let mut structs = File::create(path.join("versions.rs")).unwrap();
write!(&mut structs, "{}", Versions).unwrap();
}
+17
View File
@@ -0,0 +1,17 @@
use std::ops::Deref;
use heck::*;
use t4rust_derive::Template;
use tsproto_structs::enums;
use tsproto_structs::enums::*;
use tsproto_structs::{doc_comment, indent};
#[derive(Template)]
#[TemplatePath = "build/Enums.tt"]
#[derive(Default, Debug)]
pub struct Enums;
impl Deref for Enums {
type Target = enums::Enums;
fn deref(&self) -> &Self::Target { &DATA }
}
@@ -0,0 +1,17 @@
use std::ops::Deref;
use heck::*;
use t4rust_derive::Template;
use tsproto_structs::errors::*;
use tsproto_structs::EnumValue;
use tsproto_structs::{doc_comment, indent};
#[derive(Template)]
#[TemplatePath = "build/Errors.tt"]
#[derive(Default, Debug)]
pub struct Errors;
impl Deref for Errors {
type Target = Vec<EnumValue>;
fn deref(&self) -> &Self::Target { &DATA.0 }
}
@@ -0,0 +1,14 @@
use std::ops::Deref;
use t4rust_derive::Template;
use tsproto_structs::versions::*;
#[derive(Template)]
#[TemplatePath = "build/Versions.tt"]
#[derive(Default, Debug)]
pub struct Versions;
impl Deref for Versions {
type Target = Vec<Version>;
fn deref(&self) -> &Self::Target { &DATA.0 }
}
+609
View File
@@ -0,0 +1,609 @@
//! This module contains cryptography related code.
use std::convert::TryInto;
use std::{cmp, fmt, str};
use base64::prelude::*;
use curve25519_dalek_ng::constants;
use curve25519_dalek_ng::edwards::{CompressedEdwardsY, EdwardsPoint};
use curve25519_dalek_ng::scalar::Scalar;
use elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint};
use generic_array::GenericArray;
use generic_array::typenum::Unsigned;
use num_bigint::{BigInt, Sign};
use p256::ecdsa::signature::{Signer, Verifier};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use sha1::{Digest, Sha1};
use simple_asn1::ASN1Block;
use thiserror::Error;
type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug, Clone, Error)]
#[non_exhaustive]
pub enum Error {
#[error("More than one ASN.1 block")]
TooManyAsn1Blocks,
#[error("Invalid ASN.1: Expected a public key, not a private key")]
UnexpectedPrivateKey,
#[error("Invalid ASN.1: Does not contain a private key")]
NoPrivateKey,
#[error("Invalid ASN.1: Public key not found")]
PublicKeyNotFound,
#[error("Invalid ASN.1: Expected a bitstring")]
ExpectedBitString,
#[error("Invalid ASN.1: Expected a sequence")]
ExpectedSequence,
#[error("Key data is empty")]
EmptyKeyData,
#[error("Any known methods to decode the key failed")]
KeyDecodeError,
#[error("Failed to parse short private key")]
NoShortKey,
#[error("Not a obfuscated TeamSpeak key")]
NoObfuscatedKey,
#[error("Found no initial 'V' with a valid number before")]
NoCounterBlock,
#[error("Failed to parse public key")]
ParsePublicKeyFailed,
#[error("Wrong key length")]
WrongKeyLength,
#[error("Failed to parse public key, expected length {expected} but got {got}")]
WrongPublicKeyLength { expected: usize, got: usize },
#[error("Wrong signature")]
WrongSignature { key: EccKeyPubP256, data: Vec<u8>, signature: Vec<u8> },
#[error(transparent)]
Asn1Decode(#[from] simple_asn1::ASN1DecodeErr),
#[error(transparent)]
Asn1Encode(#[from] simple_asn1::ASN1EncodeErr),
#[error(transparent)]
Base64(#[from] base64::DecodeError),
#[error(transparent)]
Utf8(#[from] std::str::Utf8Error),
}
/// Xored onto saved identities in the TeamSpeak client settings file.
const IDENTITY_OBFUSCATION: [u8; 128] = *b"b9dfaa7bee6ac57ac7b65f1094a1c155\
e747327bc2fe5d51c512023fe54a280201004e90ad1daaae1075d53b7d571c30e063b5a\
62a4a017bb394833aa0983e6e";
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum KeyType {
Public,
Private,
}
/// A public ecc key.
///
/// The curve of this key is P-256, or PRIME256v1 as it is called by openssl.
#[derive(Clone, Deserialize, Eq, PartialEq, Serialize)]
pub struct EccKeyPubP256(
#[serde(
deserialize_with = "deserialize_ecc_key_pub_p256",
serialize_with = "serialize_ecc_key_pub_p256"
)]
p256::PublicKey,
);
/// A private ecc key.
///
/// The curve of this key is P-256, or PRIME256v1 as it is called by openssl.
#[derive(Clone)]
pub struct EccKeyPrivP256(p256::SecretKey);
/// A public ecc key.
///
/// The curve of this key is Ed25519.
#[derive(Clone)]
pub struct EccKeyPubEd25519(pub CompressedEdwardsY);
/// A private ecc key.
///
/// The curve of this key is Ed25519.
#[derive(Clone)]
pub struct EccKeyPrivEd25519(pub Scalar);
/// Passwords are encoded as base64(sha1(password)).
pub fn encode_password(password: &[u8]) -> String {
BASE64_STANDARD.encode(Sha1::digest(password).as_slice())
}
fn deserialize_ecc_key_pub_p256<'de, D: Deserializer<'de>>(
de: D,
) -> Result<p256::PublicKey, D::Error> {
let data: Vec<u8> = Deserialize::deserialize(de)?;
Ok(EccKeyPubP256::from_short(&data).map_err(serde::de::Error::custom)?.0)
}
fn serialize_ecc_key_pub_p256<S: Serializer>(
key: &p256::PublicKey, ser: S,
) -> Result<S::Ok, S::Error> {
Serialize::serialize(&EccKeyPubP256(*key).to_short().as_slice(), ser)
}
impl fmt::Debug for EccKeyPubP256 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "EccKeyPubP256({})", self.to_ts())
}
}
impl fmt::Debug for EccKeyPrivP256 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "EccKeyPrivP256({})", BASE64_STANDARD.encode(self.to_short()))
}
}
impl fmt::Debug for EccKeyPubEd25519 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "EccKeyPubEd25519({})", self.to_base64())
}
}
impl fmt::Debug for EccKeyPrivEd25519 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "EccKeyPrivEd25519({})", self.to_base64())
}
}
impl EccKeyPubP256 {
/// The shortest format of a public key.
///
/// This is just the `BigNum` of the x and y coordinates concatenated in
/// this order. Each of the coordinates takes half of the size.
pub fn from_short(data: &[u8]) -> Result<Self> {
p256::PublicKey::from_sec1_bytes(data).map_err(|_| Error::ParsePublicKeyFailed).map(Self)
}
/// From base64 encoded tomcrypt key.
pub fn from_ts(data: &str) -> Result<Self> {
Self::from_tomcrypt(&BASE64_STANDARD.decode(data)?)
}
/// Decodes the public key from an ASN.1 DER object how tomcrypt stores it.
///
/// The format is:
/// - `BitString` where the first bit is 1 if the private key is contained
/// - `Integer`: The key size (32)
/// - `Integer`: X coordinate of the public key
/// - `Integer`: Y coordinate of the public key
pub fn from_tomcrypt(data: &[u8]) -> Result<Self> {
let blocks = simple_asn1::from_der(data)?;
if blocks.len() != 1 {
return Err(Error::TooManyAsn1Blocks);
}
if let ASN1Block::Sequence(_, blocks) = &blocks[0] {
if let Some(ASN1Block::BitString(_, len, content)) = blocks.first() {
if *len != 1 || content[0] & 0x80 != 0 {
return Err(Error::UnexpectedPrivateKey);
}
if let (Some(ASN1Block::Integer(_, x)), Some(ASN1Block::Integer(_, y))) =
(blocks.get(2), blocks.get(3))
{
let field_size = elliptic_curve::FieldBytesSize::<p256::NistP256>::to_usize();
let to_coord = |src: &BigInt| -> Result<elliptic_curve::FieldBytes<p256::NistP256>> {
let (sign, mut bytes) = src.to_bytes_le();
if sign == Sign::Minus {
return Err(Error::ParsePublicKeyFailed);
}
if bytes.len() > field_size {
return Err(Error::WrongPublicKeyLength {
expected: field_size,
got: bytes.len(),
});
}
// Pad if most significant bytes are zero
bytes.resize(field_size, 0);
// Convert to big-endian
bytes.reverse();
Ok(*GenericArray::from_slice(&bytes))
};
let x_coord = to_coord(x)?;
let y_coord = to_coord(y)?;
let enc_point = p256::EncodedPoint::from_affine_coordinates(
&x_coord,
&y_coord,
false,
);
let enc_point = p256::PublicKey::from_encoded_point(&enc_point);
if enc_point.is_some().into() {
Ok(Self(enc_point.unwrap()))
} else {
Err(Error::ParsePublicKeyFailed)
}
} else {
Err(Error::PublicKeyNotFound)
}
} else {
Err(Error::ExpectedBitString)
}
} else {
Err(Error::ExpectedSequence)
}
}
/// Convert to base64 encoded public tomcrypt key.
pub fn to_ts(&self) -> String { BASE64_STANDARD.encode(self.to_tomcrypt()) }
pub fn to_tomcrypt(&self) -> Vec<u8> {
let enc_point = self.0.as_affine().to_encoded_point(false);
// We can unwrap here, creating the public key ensures that it is not the identity point,
// which is the only time this returns `None`.
let pubkey_x = BigInt::from_bytes_be(Sign::Plus, enc_point.x().unwrap());
let pubkey_y = BigInt::from_bytes_be(Sign::Plus, enc_point.y().unwrap());
// Only returns an error when encoding wrong objects, so fine to unwrap.
simple_asn1::to_der(&ASN1Block::Sequence(0, vec![
ASN1Block::BitString(0, 1, vec![0]),
ASN1Block::Integer(0, 32.into()),
ASN1Block::Integer(0, pubkey_x),
ASN1Block::Integer(0, pubkey_y),
]))
.unwrap()
}
/// Get the SEC1 encoding of the public key point on the curve.
pub fn to_short(&self) -> Vec<u8> {
// TODO Maybe compress?
self.0.as_affine().to_encoded_point(false).as_bytes().to_vec()
}
/// Compute the uid of this key without encoding it in base64.
///
/// returns sha1(ts encoded key)
pub fn get_uid_no_base64(&self) -> Vec<u8> {
Sha1::digest(self.to_ts().as_bytes()).as_slice().to_vec()
}
/// Compute the uid of this key.
///
/// Uid = base64(sha1(ts encoded key))
pub fn get_uid(&self) -> String { BASE64_STANDARD.encode(self.get_uid_no_base64()) }
pub fn verify(&self, data: &[u8], signature: &[u8]) -> Result<()> {
let sig =
p256::ecdsa::Signature::from_der(signature).map_err(|_| Error::WrongSignature {
key: self.clone(),
data: data.to_vec(),
signature: signature.to_vec(),
})?;
let key = p256::ecdsa::VerifyingKey::from(&self.0);
key.verify(data, &sig).map_err(|_| Error::WrongSignature {
key: self.clone(),
data: data.to_vec(),
signature: signature.to_vec(),
})
}
// For the bookkeeping
#[allow(clippy::should_implement_trait)]
pub fn as_ref(&self) -> &Self { self }
}
impl EccKeyPrivP256 {
/// Create a new key key pair.
pub fn create() -> Self { Self(p256::SecretKey::random(&mut rand::thread_rng())) }
/// Try to import the key from any of the known formats.
pub fn import(data: &[u8]) -> Result<Self> {
if data.is_empty() {
return Err(Error::EmptyKeyData);
}
if let Ok(s) = str::from_utf8(data) {
if let Ok(r) = Self::import_str(s) {
return Ok(r);
}
}
if let Ok(r) = Self::from_tomcrypt(data) {
return Ok(r);
}
if let Ok(r) = Self::from_short(data) {
return Ok(r);
}
Err(Error::KeyDecodeError)
}
/// Try to import the key from any of the known formats.
pub fn import_str(s: &str) -> Result<Self> {
if let Ok(r) = BASE64_STANDARD.decode(s) {
if let Ok(r) = Self::import(&r) {
return Ok(r);
}
}
if let Ok(r) = Self::from_ts_obfuscated(s) {
return Ok(r);
}
Err(Error::KeyDecodeError)
}
/// The shortest format of a private key.
///
/// This is just the `BigNum` of the private key.
pub fn from_short(data: &[u8]) -> Result<Self> {
// TODO !! p256::SecretKey::from_bytes panics when the data is not 32 long !!
// maybe create a pull request for that because das not good?!
if data.len() != 32 {
Err(Error::NoShortKey)
} else {
Ok(Self(
p256::SecretKey::from_bytes(p256::FieldBytes::from_slice(data))
.map_err(|_| Error::NoShortKey)?,
))
}
}
/// The shortest format of a private key.
///
/// This is just the `BigNum` of the private key.
pub fn to_short(&self) -> elliptic_curve::FieldBytes<p256::NistP256> { self.0.to_bytes() }
/// From base64 encoded tomcrypt key.
pub fn from_ts(data: &str) -> Result<Self> {
Self::from_tomcrypt(&BASE64_STANDARD.decode(data)?)
}
/// From the key representation which is used to store identities in the
/// TeamSpeak configuration file.
///
/// Format: Offset for identity level || 'V' || obfuscated key
///
/// This function takes only the obfuscated key without the level.
///
/// Thanks to landave, who put
/// [his deobfuscation code](https://github.com/landave/TSIdentityTool)
/// under the MIT license.
pub fn from_ts_obfuscated(data: &str) -> Result<Self> {
let mut data = BASE64_STANDARD.decode(data)?;
if data.len() < 20 {
return Err(Error::NoObfuscatedKey);
}
// Hash everything until the first 0 byte, starting after the first 20
// bytes.
let pos = data[20..].iter().position(|b| *b == b'\0').unwrap_or(data.len() - 20);
let hash = Sha1::digest(&data[20..20 + pos]);
let hash = hash.as_slice();
// Xor first 20 bytes of data with the hash
for i in 0..20 {
data[i] ^= hash[i];
}
// Xor first 100 bytes with a static value
#[allow(clippy::needless_range_loop)]
for i in 0..cmp::min(data.len(), 100) {
data[i] ^= IDENTITY_OBFUSCATION[i];
}
Self::from_ts(str::from_utf8(&data)?)
}
/// Decodes the private key from an ASN.1 DER object how tomcrypt stores it.
///
/// The format is:
/// - `BitString` where the first bit is 1 if the private key is contained
/// - `Integer`: The key size (32)
/// - `Integer`: X coordinate of the public key
/// - `Integer`: Y coordinate of the public key
/// - `Integer`: Private key
///
/// The TS3AudioBot stores two 1 bits in the first `BitString` and omits the
/// public key.
pub fn from_tomcrypt(data: &[u8]) -> Result<Self> {
let blocks = simple_asn1::from_der(data)?;
if blocks.len() != 1 {
return Err(Error::TooManyAsn1Blocks);
}
if let ASN1Block::Sequence(_, blocks) = &blocks[0] {
if let Some(ASN1Block::BitString(_, len, content)) = blocks.first() {
if (*len != 1 && *len != 2) || content[0] & 0x80 == 0 {
return Err(Error::NoPrivateKey);
}
if *len == 1 {
if let Some(ASN1Block::Integer(_, i)) = blocks.get(4) {
Self::from_short(&i.to_bytes_be().1)
} else {
Err(Error::NoPrivateKey)
}
} else if let Some(ASN1Block::Integer(_, i)) = blocks.get(2) {
Self::from_short(&i.to_bytes_be().1)
} else {
Err(Error::NoPrivateKey)
}
} else {
Err(Error::ExpectedBitString)
}
} else {
Err(Error::ExpectedSequence)
}
}
/// Convert to base64 encoded private tomcrypt key.
pub fn to_ts(&self) -> String { BASE64_STANDARD.encode(self.to_tomcrypt()) }
/// Store as obfuscated TeamSpeak identity.
pub fn to_ts_obfuscated(&self) -> String {
let mut data = self.to_ts().into_bytes();
// Xor first 100 bytes with a static value
#[allow(clippy::needless_range_loop)]
for i in 0..cmp::min(data.len(), 100) {
data[i] ^= IDENTITY_OBFUSCATION[i];
}
// Hash everything until the first 0 byte, starting after the first 20
// bytes.
let pos = data[20..].iter().position(|b| *b == b'\0').unwrap_or(data.len() - 20);
let hash = Sha1::digest(&data[20..20 + pos]);
let hash = hash.as_slice();
// Xor first 20 bytes of data with the hash
for i in 0..20 {
data[i] ^= hash[i];
}
BASE64_STANDARD.encode(data)
}
pub fn to_tomcrypt(&self) -> Vec<u8> {
let enc_point = self.0.public_key().as_affine().to_encoded_point(false);
// We can unwrap here, creating the public key ensures that it is not the identity point,
// which is the only time this returns `None`.
let pubkey_x = BigInt::from_bytes_be(Sign::Plus, enc_point.x().unwrap());
let pubkey_y = BigInt::from_bytes_be(Sign::Plus, enc_point.y().unwrap());
let privkey = BigInt::from_bytes_be(Sign::Plus, &self.0.to_bytes());
// Only returns an error when encoding wrong objects, so fine to unwrap.
simple_asn1::to_der(&ASN1Block::Sequence(0, vec![
ASN1Block::BitString(0, 1, vec![0x80]),
ASN1Block::Integer(0, 32.into()),
ASN1Block::Integer(0, pubkey_x),
ASN1Block::Integer(0, pubkey_y),
ASN1Block::Integer(0, privkey),
]))
.unwrap()
}
/// This has to be the private key, the other one has to be the public key.
pub fn create_shared_secret(
self, other: EccKeyPubP256,
) -> elliptic_curve::ecdh::SharedSecret<p256::NistP256> {
elliptic_curve::ecdh::diffie_hellman(self.0.to_nonzero_scalar(), other.0.as_affine())
}
pub fn sign(self, data: &[u8]) -> Vec<u8> {
let key = p256::ecdsa::SigningKey::from(self.0);
let sig: p256::ecdsa::DerSignature = key.sign(data);
sig.as_bytes().to_vec()
}
pub fn to_pub(&self) -> EccKeyPubP256 { self.into() }
}
impl<'a> From<&'a EccKeyPrivP256> for EccKeyPubP256 {
fn from(priv_key: &'a EccKeyPrivP256) -> Self { Self(priv_key.0.public_key()) }
}
impl EccKeyPubEd25519 {
pub fn from_bytes(data: [u8; 32]) -> Self { EccKeyPubEd25519(CompressedEdwardsY(data)) }
pub fn from_base64(data: &str) -> Result<Self> {
let decoded = BASE64_STANDARD.decode(data)?;
if decoded.len() != 32 {
return Err(Error::WrongKeyLength);
}
Ok(Self::from_bytes(decoded[..32].try_into().unwrap()))
}
pub fn to_base64(&self) -> String {
let EccKeyPubEd25519(CompressedEdwardsY(ref data)) = *self;
BASE64_STANDARD.encode(data)
}
}
impl EccKeyPrivEd25519 {
/// This is not used to create TeamSpeak keys, as they are not canonical.
pub fn create() -> Self { EccKeyPrivEd25519(Scalar::random(&mut rand::thread_rng())) }
pub fn from_base64(data: &str) -> Result<Self> {
let decoded = BASE64_STANDARD.decode(data)?;
if decoded.len() != 32 {
return Err(Error::WrongKeyLength);
}
Ok(Self::from_bytes(decoded[..32].try_into().unwrap()))
}
pub fn from_bytes(data: [u8; 32]) -> Self {
EccKeyPrivEd25519(Scalar::from_bytes_mod_order(data))
}
pub fn to_base64(&self) -> String { BASE64_STANDARD.encode(self.0.as_bytes()) }
/// This has to be the private key, the other one has to be the public key.
pub fn create_shared_secret(&self, pub_key: &EdwardsPoint) -> [u8; 32] {
let res = pub_key * self.0;
res.compress().0
}
pub fn to_pub(&self) -> EccKeyPubEd25519 { self.into() }
}
impl<'a> From<&'a EccKeyPrivEd25519> for EccKeyPubEd25519 {
fn from(priv_key: &'a EccKeyPrivEd25519) -> Self {
Self((&constants::ED25519_BASEPOINT_TABLE * &priv_key.0).compress())
}
}
#[cfg(test)]
mod tests {
use super::*;
const TEST_PRIV_KEY: &str = "MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTA\
O2+k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITsC/50CIA8M5nmDB\
nmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI";
#[test]
fn parse_p256_priv_key() { EccKeyPrivP256::from_ts(TEST_PRIV_KEY).unwrap(); }
#[test]
fn p256_ecdh() {
let priv_key1 = EccKeyPrivP256::create();
let pub_key1 = priv_key1.to_pub();
let priv_key2 = EccKeyPrivP256::create();
let pub_key2 = priv_key2.to_pub();
let res1 = priv_key1.create_shared_secret(pub_key2);
let res2 = priv_key2.create_shared_secret(pub_key1);
assert_eq!(res1.raw_secret_bytes(), res2.raw_secret_bytes());
}
#[test]
fn p256_signature() {
let license =
"AQBM0LZCVmZ7CX/\
miewqdjOyuKa6kI78Fk43LoypifqOkAIOkvUAEn46gAcAAAAgQW5vbnltb3VzAABoruUa34pO9zy1Z5zIOmrkIO06lKg/\
+mBrg6Mw1Rg4OyAPa7A3D2xY9w==";
let server_key = "MEwDAgcAAgEgAiEA96WgYeYU8zoPqXJqicita+rR92FvnTlxYcUUyIDkQ6cCIE/\
KPo+ms3BEzN/HBR71BJ/Z1Fv8918mdDKLetbOGKWt";
let signature = "MEUCIQC+ececxC0NCcuCtrXHAO5h7qbh1s/TGP/\
AaHa6+wV38wIgV9wwSppEdGjwuH3ETAME9tDj3aNkNvL25i0ikF9vs8M=";
let license = BASE64_STANDARD.decode(license).unwrap();
let signature = BASE64_STANDARD.decode(signature).unwrap();
let server_key = EccKeyPubP256::from_ts(server_key).unwrap();
server_key.verify(&license, &signature).unwrap();
}
#[test]
fn obfuscated_priv_key() {
let key = EccKeyPrivP256::from_ts(TEST_PRIV_KEY).unwrap();
let obf = key.to_ts_obfuscated();
let key2 = EccKeyPrivP256::from_ts_obfuscated(&obf).unwrap();
assert_eq!(key.to_short(), key2.to_short());
}
#[test]
fn obfuscated_identity() {
let key = EccKeyPrivP256::from_ts(TEST_PRIV_KEY).unwrap();
let uid = key.to_pub().get_uid();
let expected_uid = "lks7QL5OVMKo4pZ79cEOI5r5oEA=";
assert_eq!(expected_uid, &uid);
}
#[test]
fn tsaudiobot_identity() {
let key = EccKeyPrivP256::import_str(
"MCkDAgbAAgEgAiBhPImh+bO1xMGOrcplwN3G74bhE9XATm+DxVo3aNtBqg==",
)
.unwrap();
let uid = key.to_pub().get_uid();
let expected_uid = "test/9PZ9vww/Bpf5vJxtJhpz80=";
assert_eq!(expected_uid, &uid);
}
#[test]
fn test_p256_priv_key_short() {
let key = EccKeyPrivP256::from_ts(TEST_PRIV_KEY).unwrap();
let short = key.to_short();
let key = EccKeyPrivP256::from_short(short.as_slice()).unwrap();
let short2 = key.to_short();
assert_eq!(short, short2);
}
#[test]
fn parse_ed25519_pub_key() {
EccKeyPubEd25519::from_base64("zQ3irtRjRVCafjz9j2iz3HVVsp3M7HPNGHUPmTgSQIo=").unwrap();
}
}
+13
View File
@@ -0,0 +1,13 @@
use std::fmt;
use num_derive::{FromPrimitive, ToPrimitive};
include!(concat!(env!("OUT_DIR"), "/errors.rs"));
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(self, f) }
}
impl std::error::Error for Error {
fn description(&self) -> &str { "TeamSpeak error" }
}
+173
View File
@@ -0,0 +1,173 @@
//! `tsproto-types` contains basic types and enums that are used within the TeamSpeak protocol.
use std::borrow::{Borrow, Cow};
use std::fmt;
use base64::prelude::*;
use bitflags::bitflags;
use num_derive::{FromPrimitive, ToPrimitive};
use ref_cast::RefCast;
use serde::{Deserialize, Deserializer, Serialize};
use time::OffsetDateTime;
pub mod crypto;
pub mod errors;
pub mod versions;
include!(concat!(env!("OUT_DIR"), "/enums.rs"));
/// A `ClientId` identifies a client which is connected to a server.
///
/// Every client that we see on a server has a `ClientId`, even our own
/// connection.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct ClientId(pub u16);
/// Describes a client or server uid which is a base64
/// encoded hash or a special reserved name.
///
/// This is saved raw, so the base64-decoded TeamSpeak uid.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct UidBuf(pub Vec<u8>);
#[derive(Debug, Eq, PartialEq, RefCast, Serialize)]
#[repr(transparent)]
pub struct Uid(pub [u8]);
impl ToOwned for Uid {
type Owned = UidBuf;
fn to_owned(&self) -> Self::Owned { UidBuf(self.0.to_owned()) }
}
impl Borrow<Uid> for UidBuf {
fn borrow(&self) -> &Uid { Uid::ref_cast(self.0.borrow()) }
}
impl AsRef<Uid> for UidBuf {
fn as_ref(&self) -> &Uid { self.borrow() }
}
impl core::ops::Deref for UidBuf {
type Target = Uid;
fn deref(&self) -> &Self::Target { self.borrow() }
}
impl<'a> From<&'a Uid> for Cow<'a, Uid> {
fn from(u: &'a Uid) -> Self { Cow::Borrowed(u) }
}
impl Uid {
pub fn from_bytes(data: &'_ [u8]) -> &Self { Uid::ref_cast(data) }
/// TeamSpeak uses a different encoding of the uid for fetching avatars.
///
/// The raw data (base64-decoded) is encoded in hex, but instead of using
/// [0-9a-f] with [a-p].
pub fn as_avatar(&self) -> String {
let mut res = String::with_capacity(self.0.len() * 2);
for b in &self.0 {
res.push((b'a' + (b >> 4)) as char);
res.push((b'a' + (b & 0xf)) as char);
}
res
}
pub fn is_server_admin(&self) -> bool { &self.0 == b"ServerAdmin" }
}
impl<'a, 'de: 'a> Deserialize<'de> for &'a Uid {
fn deserialize<D>(d: D) -> Result<&'a Uid, D::Error>
where D: Deserializer<'de> {
let data = <&[u8]>::deserialize(d)?;
Ok(Uid::from_bytes(data))
}
}
/// The database id of a client.
///
/// This is the id which is saved for a client in the database of one specific
/// server.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct ClientDbId(pub u64);
/// Identifies a channel on a server.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct ChannelId(pub u64);
/// Identifies a server group on a server.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct ServerGroupId(pub u64);
/// Identifies a channel group on a server.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct ChannelGroupId(pub u64);
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct IconId(pub u32);
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct Permission(pub u32);
impl Permission {
/// Never fails
pub fn from_u32(i: u32) -> Option<Self> { Some(Permission(i)) }
/// Never fails
pub fn to_u32(self) -> Option<u32> { Some(self.0) }
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub enum ClientType {
Normal,
/// Server query client
Query {
admin: bool,
},
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub enum MaxClients {
Unlimited,
Inherited,
Limited(u16),
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct TalkPowerRequest {
pub time: OffsetDateTime,
pub message: String,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Invoker {
pub name: String,
pub id: ClientId,
pub uid: Option<UidBuf>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct InvokerRef<'a> {
pub name: &'a str,
pub id: ClientId,
pub uid: Option<&'a Uid>,
}
impl Invoker {
pub fn as_ref(&self) -> InvokerRef<'_> {
InvokerRef { name: &self.name, id: self.id, uid: self.uid.as_ref().map(|u| u.as_ref()) }
}
}
impl fmt::Display for ClientId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) }
}
impl fmt::Display for Uid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", BASE64_STANDARD.encode(&self.0))
}
}
impl fmt::Display for ClientDbId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) }
}
impl fmt::Display for ChannelId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) }
}
impl fmt::Display for ServerGroupId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) }
}
impl fmt::Display for ChannelGroupId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) }
}
@@ -0,0 +1,9 @@
use std::fmt;
include!(concat!(env!("OUT_DIR"), "/versions.rs"));
impl fmt::Display for Version {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {}", self.get_platform(), self.get_version_string())
}
}
+67
View File
@@ -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
View File
@@ -0,0 +1,21 @@
# TsProto &emsp; [![docs.rs](https://docs.rs/tsproto/badge.svg)](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
View File
@@ -0,0 +1,10 @@
# TsProto &emsp; [![docs.rs](https://docs.rs/tsproto/badge.svg)](https://docs.rs/tsproto)
{{readme}}
## License
Licensed under either of
* [Apache License, Version 2.0](../LICENSE-APACHE)
* [MIT license](../LICENSE-MIT)
at your option.
+77
View File
@@ -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);
+58
View File
@@ -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);
+69
View File
@@ -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);
Loaded 100 of 119 files, more files were not shown because too many files have changed in this diff. Show more