Skip to content

Commit 1aca25b

Browse files
committedOct 28, 2017
Initial commit
0 parents  commit 1aca25b

18 files changed

+4919
-0
lines changed
 

‎.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
target/
2+
Cargo.lock

‎Cargo.toml

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
[workspace]
2+
members = ["tsproto"]

‎LICENSE-APACHE

+201
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
Apache License
2+
Version 2.0, January 2004
3+
http://www.apache.org/licenses/
4+
5+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6+
7+
1. Definitions.
8+
9+
"License" shall mean the terms and conditions for use, reproduction,
10+
and distribution as defined by Sections 1 through 9 of this document.
11+
12+
"Licensor" shall mean the copyright owner or entity authorized by
13+
the copyright owner that is granting the License.
14+
15+
"Legal Entity" shall mean the union of the acting entity and all
16+
other entities that control, are controlled by, or are under common
17+
control with that entity. For the purposes of this definition,
18+
"control" means (i) the power, direct or indirect, to cause the
19+
direction or management of such entity, whether by contract or
20+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
21+
outstanding shares, or (iii) beneficial ownership of such entity.
22+
23+
"You" (or "Your") shall mean an individual or Legal Entity
24+
exercising permissions granted by this License.
25+
26+
"Source" form shall mean the preferred form for making modifications,
27+
including but not limited to software source code, documentation
28+
source, and configuration files.
29+
30+
"Object" form shall mean any form resulting from mechanical
31+
transformation or translation of a Source form, including but
32+
not limited to compiled object code, generated documentation,
33+
and conversions to other media types.
34+
35+
"Work" shall mean the work of authorship, whether in Source or
36+
Object form, made available under the License, as indicated by a
37+
copyright notice that is included in or attached to the work
38+
(an example is provided in the Appendix below).
39+
40+
"Derivative Works" shall mean any work, whether in Source or Object
41+
form, that is based on (or derived from) the Work and for which the
42+
editorial revisions, annotations, elaborations, or other modifications
43+
represent, as a whole, an original work of authorship. For the purposes
44+
of this License, Derivative Works shall not include works that remain
45+
separable from, or merely link (or bind by name) to the interfaces of,
46+
the Work and Derivative Works thereof.
47+
48+
"Contribution" shall mean any work of authorship, including
49+
the original version of the Work and any modifications or additions
50+
to that Work or Derivative Works thereof, that is intentionally
51+
submitted to Licensor for inclusion in the Work by the copyright owner
52+
or by an individual or Legal Entity authorized to submit on behalf of
53+
the copyright owner. For the purposes of this definition, "submitted"
54+
means any form of electronic, verbal, or written communication sent
55+
to the Licensor or its representatives, including but not limited to
56+
communication on electronic mailing lists, source code control systems,
57+
and issue tracking systems that are managed by, or on behalf of, the
58+
Licensor for the purpose of discussing and improving the Work, but
59+
excluding communication that is conspicuously marked or otherwise
60+
designated in writing by the copyright owner as "Not a Contribution."
61+
62+
"Contributor" shall mean Licensor and any individual or Legal Entity
63+
on behalf of whom a Contribution has been received by Licensor and
64+
subsequently incorporated within the Work.
65+
66+
2. Grant of Copyright License. Subject to the terms and conditions of
67+
this License, each Contributor hereby grants to You a perpetual,
68+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69+
copyright license to reproduce, prepare Derivative Works of,
70+
publicly display, publicly perform, sublicense, and distribute the
71+
Work and such Derivative Works in Source or Object form.
72+
73+
3. Grant of Patent License. Subject to the terms and conditions of
74+
this License, each Contributor hereby grants to You a perpetual,
75+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76+
(except as stated in this section) patent license to make, have made,
77+
use, offer to sell, sell, import, and otherwise transfer the Work,
78+
where such license applies only to those patent claims licensable
79+
by such Contributor that are necessarily infringed by their
80+
Contribution(s) alone or by combination of their Contribution(s)
81+
with the Work to which such Contribution(s) was submitted. If You
82+
institute patent litigation against any entity (including a
83+
cross-claim or counterclaim in a lawsuit) alleging that the Work
84+
or a Contribution incorporated within the Work constitutes direct
85+
or contributory patent infringement, then any patent licenses
86+
granted to You under this License for that Work shall terminate
87+
as of the date such litigation is filed.
88+
89+
4. Redistribution. You may reproduce and distribute copies of the
90+
Work or Derivative Works thereof in any medium, with or without
91+
modifications, and in Source or Object form, provided that You
92+
meet the following conditions:
93+
94+
(a) You must give any other recipients of the Work or
95+
Derivative Works a copy of this License; and
96+
97+
(b) You must cause any modified files to carry prominent notices
98+
stating that You changed the files; and
99+
100+
(c) You must retain, in the Source form of any Derivative Works
101+
that You distribute, all copyright, patent, trademark, and
102+
attribution notices from the Source form of the Work,
103+
excluding those notices that do not pertain to any part of
104+
the Derivative Works; and
105+
106+
(d) If the Work includes a "NOTICE" text file as part of its
107+
distribution, then any Derivative Works that You distribute must
108+
include a readable copy of the attribution notices contained
109+
within such NOTICE file, excluding those notices that do not
110+
pertain to any part of the Derivative Works, in at least one
111+
of the following places: within a NOTICE text file distributed
112+
as part of the Derivative Works; within the Source form or
113+
documentation, if provided along with the Derivative Works; or,
114+
within a display generated by the Derivative Works, if and
115+
wherever such third-party notices normally appear. The contents
116+
of the NOTICE file are for informational purposes only and
117+
do not modify the License. You may add Your own attribution
118+
notices within Derivative Works that You distribute, alongside
119+
or as an addendum to the NOTICE text from the Work, provided
120+
that such additional attribution notices cannot be construed
121+
as modifying the License.
122+
123+
You may add Your own copyright statement to Your modifications and
124+
may provide additional or different license terms and conditions
125+
for use, reproduction, or distribution of Your modifications, or
126+
for any such Derivative Works as a whole, provided Your use,
127+
reproduction, and distribution of the Work otherwise complies with
128+
the conditions stated in this License.
129+
130+
5. Submission of Contributions. Unless You explicitly state otherwise,
131+
any Contribution intentionally submitted for inclusion in the Work
132+
by You to the Licensor shall be under the terms and conditions of
133+
this License, without any additional terms or conditions.
134+
Notwithstanding the above, nothing herein shall supersede or modify
135+
the terms of any separate license agreement you may have executed
136+
with Licensor regarding such Contributions.
137+
138+
6. Trademarks. This License does not grant permission to use the trade
139+
names, trademarks, service marks, or product names of the Licensor,
140+
except as required for reasonable and customary use in describing the
141+
origin of the Work and reproducing the content of the NOTICE file.
142+
143+
7. Disclaimer of Warranty. Unless required by applicable law or
144+
agreed to in writing, Licensor provides the Work (and each
145+
Contributor provides its Contributions) on an "AS IS" BASIS,
146+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147+
implied, including, without limitation, any warranties or conditions
148+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149+
PARTICULAR PURPOSE. You are solely responsible for determining the
150+
appropriateness of using or redistributing the Work and assume any
151+
risks associated with Your exercise of permissions under this License.
152+
153+
8. Limitation of Liability. In no event and under no legal theory,
154+
whether in tort (including negligence), contract, or otherwise,
155+
unless required by applicable law (such as deliberate and grossly
156+
negligent acts) or agreed to in writing, shall any Contributor be
157+
liable to You for damages, including any direct, indirect, special,
158+
incidental, or consequential damages of any character arising as a
159+
result of this License or out of the use or inability to use the
160+
Work (including but not limited to damages for loss of goodwill,
161+
work stoppage, computer failure or malfunction, or any and all
162+
other commercial damages or losses), even if such Contributor
163+
has been advised of the possibility of such damages.
164+
165+
9. Accepting Warranty or Additional Liability. While redistributing
166+
the Work or Derivative Works thereof, You may choose to offer,
167+
and charge a fee for, acceptance of support, warranty, indemnity,
168+
or other liability obligations and/or rights consistent with this
169+
License. However, in accepting such obligations, You may act only
170+
on Your own behalf and on Your sole responsibility, not on behalf
171+
of any other Contributor, and only if You agree to indemnify,
172+
defend, and hold each Contributor harmless for any liability
173+
incurred by, or claims asserted against, such Contributor by reason
174+
of your accepting any such warranty or additional liability.
175+
176+
END OF TERMS AND CONDITIONS
177+
178+
APPENDIX: How to apply the Apache License to your work.
179+
180+
To apply the Apache License to your work, attach the following
181+
boilerplate notice, with the fields enclosed by brackets "[]"
182+
replaced with your own identifying information. (Don't include
183+
the brackets!) The text should be enclosed in the appropriate
184+
comment syntax for the file format. We also recommend that a
185+
file or class name and description of purpose be included on the
186+
same "printed page" as the copyright notice for easier
187+
identification within third-party archives.
188+
189+
Copyright [yyyy] [name of copyright owner]
190+
191+
Licensed under the Apache License, Version 2.0 (the "License");
192+
you may not use this file except in compliance with the License.
193+
You may obtain a copy of the License at
194+
195+
http://www.apache.org/licenses/LICENSE-2.0
196+
197+
Unless required by applicable law or agreed to in writing, software
198+
distributed under the License is distributed on an "AS IS" BASIS,
199+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200+
See the License for the specific language governing permissions and
201+
limitations under the License.

‎LICENSE-MIT

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
The MIT License (MIT)
2+
3+
Copyright (c) 2015 Sebastian Neubauer
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

‎README.md

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# TsProto
2+
3+
This repository implements the TeamSpeak3 protocol for usage in clients and bots.
4+
5+
If you are searching for a usable client, [Qint](https://github.com/ReSpeak/Qint)
6+
is a cross-platform TeamSpeak client, which ~~is~~ will be using this library.
7+
8+
## Build and run
9+
10+
Clone the repository
11+
12+
```
13+
git clone https://github.com/ReSpeak/tsclientlib.git
14+
cd tsclientlib
15+
git submodule update --init --recursive
16+
```
17+
18+
Build and run the example client
19+
20+
```
21+
cd tsproto
22+
cargo run --example client
23+
```
24+
25+
### Miscellaneous
26+
27+
This project is not an official TeamSpeak project. We started to write an own client for fun und because we want some features (and bugfixes) which are not available in the official client.
28+
29+
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.
30+
31+
Thanks TeamSpeak for your software!

‎rustfmt.toml

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
max_width = 80
2+
3+
format_strings = true
4+
reorder_imported_names = true
5+
imports_indent = "Block"
6+
where_pred_indent = "Block"
7+
reorder_imports = true
8+
reorder_imports_in_group = true
9+
use_try_shorthand = true

‎tsproto/Cargo.toml

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
[package]
2+
name = "tsproto"
3+
version = "0.1.0"
4+
authors = ["Flakebi <flakebi@t-online.de>"]
5+
description = """
6+
An implementation of the TeamSpeak3 protocol as a library for use in clients and bots.
7+
"""
8+
repository = "https://github.com/ReSpeak/tsclientlib"
9+
documentation = "https://docs.rs/tsproto"
10+
keywords = ["teamspeak3", "ts3", "voip"]
11+
categories = ["multimedia"]
12+
license = "MIT/Apache-2.0"
13+
build = "build/build.rs"
14+
workspace = ".."
15+
16+
[badges]
17+
travis-ci = { repository = "ReSpeak/tsclientlib" }
18+
19+
[features]
20+
server = []
21+
22+
[dependencies]
23+
base64 = "0.7"
24+
byteorder = "1"
25+
chrono = "0.4"
26+
error-chain = "0.11"
27+
futures = "0.1"
28+
nom = "3.2"
29+
num = "0.1"
30+
num-derive = "0.1"
31+
rand = "0.3"
32+
ring = "0.12"
33+
slog = "2"
34+
slog-async = "2"
35+
slog-perf = "0.2"
36+
slog-term = "2"
37+
tomcrypt = "0.1"
38+
tokio-core = "0.1"
39+
quicklz = "0.1"

‎tsproto/build/Packets.txt

+118
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
Packet
2+
// Content
3+
Header
4+
// name type ?value
5+
/// EAX Message Authentication Code
6+
mac [u8; 8]
7+
/// Packet id
8+
p_id u16
9+
/// Client id
10+
?c_id u16
11+
// Pre condition
12+
+ *from_client true
13+
/// Flags:
14+
///
15+
/// - 0x80 Unencrypted
16+
/// - 0x40 Compressed
17+
/// - 0x20 Newprotocol
18+
/// - 0x10 Fragmented
19+
flags -
20+
/// Packet type: Higher nibble: Flags; Lower nibble: Packet type
21+
///
22+
/// Packet types:
23+
///
24+
/// - 0x0 Voice
25+
/// - 0x1 Voice whisper
26+
/// - 0x2 Command
27+
/// - 0x3 Command low
28+
/// - 0x4 Ping
29+
/// - 0x5 Pong
30+
/// - 0x6 Ack
31+
/// - 0x7 Ack low
32+
/// - 0x8 Init
33+
p_type u8
34+
// Post conditions
35+
++ (res.p_type & 0xf) <= 8
36+
// Enum
37+
#Data
38+
#C2SInit
39+
++ header.mac.iter().eq("TS3INIT1".as_bytes())
40+
++ header.c_id.is_some()
41+
++ header.get_type() == PacketType::Init
42+
Init0
43+
/// Teamspeak version as timestamp
44+
version u32
45+
/// Init packet step number
46+
- u8 0
47+
/// Current timestamp
48+
timestamp u32
49+
random0 [u8; 4]
50+
/// Reserved
51+
- [u8; 8] [0; 8]
52+
Init2
53+
/// Teamspeak version as timestamp
54+
version u32
55+
/// Init packet step number
56+
- u8 2
57+
random1 [u8; 16]
58+
random0_r [u8; 4]
59+
Init4
60+
/// Teamspeak version as timestamp
61+
version u32
62+
/// Init packet step number
63+
- u8 4
64+
x [u8; 64]
65+
n [u8; 64]
66+
level u32
67+
random2 [u8; 100]
68+
/// y = x ^ (2 ^ level) % n
69+
y [u8; 64]
70+
command Command
71+
++ if let C2SInit::Init4 { ref command, .. } = res { command.command == "clientinitiv" && command.has_arg("alpha") && command.has_arg("omega") } else { true }
72+
#S2CInit
73+
++ header.mac.iter().eq("TS3INIT1".as_bytes())
74+
++ header.c_id.is_none()
75+
++ header.get_type() == PacketType::Init
76+
Init1
77+
/// Init packet step number
78+
- u8 1
79+
random1 [u8; 16]
80+
/// Reversed `random0`
81+
random0_r [u8; 4]
82+
Init3
83+
/// Init packet step number
84+
- u8 3
85+
x [u8; 64]
86+
n [u8; 64]
87+
level u32
88+
random2 [u8; 100]
89+
Voice
90+
++ header.get_type() == PacketType::Voice
91+
id u16
92+
codec_type u8
93+
voice_data Vec<u8>
94+
VoiceWhisper
95+
++ header.get_type() == PacketType::Voice
96+
id u16
97+
codec_type u8
98+
channel_count u8
99+
client_count u8
100+
/// [u64; channel_count], [u16; client_count], voice_data
101+
data Vec<u8>
102+
Command Command
103+
++ header.get_type() == PacketType::Command
104+
CommandLow Command
105+
++ header.get_type() == PacketType::CommandLow
106+
Ping
107+
++ header.get_type() == PacketType::Ping
108+
// TODO Use this?
109+
//- u16 0xeee9
110+
/// Pong with packet id
111+
Pong u16
112+
++ header.get_type() == PacketType::Pong
113+
/// Pong with packet id
114+
Ack u16
115+
++ header.get_type() == PacketType::Ack
116+
/// Pong with packet id
117+
AckLow u16
118+
++ header.get_type() == PacketType::AckLow

‎tsproto/build/build.rs

+1,177
Large diffs are not rendered by default.

‎tsproto/examples/client.rs

+81
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
extern crate futures;
2+
#[macro_use]
3+
extern crate slog;
4+
extern crate slog_async;
5+
extern crate slog_term;
6+
extern crate tokio_core;
7+
extern crate tsproto;
8+
9+
use std::env;
10+
use std::time::Duration;
11+
12+
use futures::{future, Sink, Stream, Future};
13+
use slog::Drain;
14+
use tokio_core::reactor::{Core, Timeout};
15+
use tsproto::*;
16+
use tsproto::packets::*;
17+
18+
fn main() {
19+
tsproto::init().unwrap();
20+
21+
// TODO use structopt
22+
let local_addr = "0.0.0.0:0".parse().unwrap();
23+
let addr = if env::args().skip(1).next().is_some() {
24+
// Fake server
25+
"127.0.0.1:9988"
26+
} else {
27+
"127.0.0.1:9987"
28+
}.parse().unwrap();
29+
let mut core = Core::new().unwrap();
30+
31+
let logger = {
32+
let decorator = slog_term::TermDecorator::new().build();
33+
let drain = slog_term::FullFormat::new(decorator).build().fuse();
34+
let drain = slog_async::Async::new(drain).build().fuse();
35+
36+
slog::Logger::root(drain, o!())
37+
};
38+
39+
let c = client::ClientData::new(local_addr, core.handle(), true, logger.clone()).unwrap();
40+
client::default_setup(c.clone());
41+
42+
// Listen for packets
43+
let listen = client::ClientData::get_packets(c.clone())
44+
.for_each(|_| future::ok(()))
45+
.map(|()| println!("Listening finished"))
46+
.map_err(|error| println!("Listening error: {:?}", error));
47+
core.handle().spawn(listen);
48+
49+
// Connect
50+
core.run(client::connect(c.clone(), addr)).unwrap();
51+
info!(logger, "Connected");
52+
53+
// Wait some time
54+
let action = Timeout::new(Duration::from_secs(5), &core.handle()).unwrap();
55+
core.run(action).unwrap();
56+
info!(logger, "Waited");
57+
58+
// Send packet
59+
let sink = client::ClientData::get_packets(c.clone());
60+
let mut header = Header::default();
61+
header.set_type(PacketType::Command);
62+
let mut cmd = commands::Command::new("sendtextmessage");
63+
64+
cmd.push("targetmode", "3");
65+
cmd.push("msg", "Hello");
66+
67+
let packet = Packet::new(header, Data::Command(cmd));
68+
core.run(sink.send((addr, packet))).unwrap();
69+
70+
// Wait some time
71+
let action = Timeout::new(Duration::from_secs(3), &core.handle()).unwrap();
72+
core.run(action).unwrap();
73+
74+
// Disconnect
75+
core.run(client::disconnect(c.clone(), addr)).unwrap();
76+
info!(logger, "Disconnected");
77+
78+
// Wait some time
79+
let action = Timeout::new(Duration::from_secs(3), &core.handle()).unwrap();
80+
core.run(action).unwrap();
81+
}

‎tsproto/src/algorithms.rs

+322
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,322 @@
1+
//! Handle packet splitting and cryptography
2+
use std::u64;
3+
4+
use {tomcrypt, base64};
5+
use byteorder::{NetworkEndian, WriteBytesExt};
6+
use num::BigUint;
7+
use ring::digest;
8+
9+
use Result;
10+
use packets::*;
11+
12+
pub(crate) fn must_encrypt(t: PacketType) -> bool {
13+
match t {
14+
PacketType::Command | PacketType::CommandLow => true,
15+
PacketType::Voice |
16+
PacketType::Ack |
17+
PacketType::AckLow |
18+
PacketType::VoiceWhisper |
19+
PacketType::Ping |
20+
PacketType::Pong |
21+
PacketType::Init => false,
22+
}
23+
}
24+
25+
pub(crate) fn should_encrypt(t: PacketType, voice_encryption: bool) -> bool {
26+
must_encrypt(t) || t == PacketType::Ack || t == PacketType::AckLow
27+
|| (voice_encryption && t.is_voice())
28+
}
29+
30+
/// Compresses and splits the packet data of a `Command` or `CommandLow` packet.
31+
///
32+
/// Returns the splitted packet data and their headers.
33+
/// The headers have their type and the compressed and fragmented flag set
34+
/// to the right value.
35+
///
36+
/// Returns an error if the packet is too large but cannot be splitted.
37+
/// Only `Command` and `CommandLow` packets can be compressed and splitted.
38+
pub(crate) fn compress_and_split(packet: &Packet) -> Vec<(Header, Vec<u8>)> {
39+
// Everything else (except whisper packets) have to be less than 500 bytes
40+
let header_size = {
41+
let mut buf = Vec::new();
42+
packet.header.write(&mut buf).unwrap();
43+
buf.len()
44+
};
45+
let mut data = Vec::new();
46+
packet.data.write(&mut data).unwrap();
47+
// The maximum packet size (including header) is 500 bytes.
48+
let max_size = 500 - header_size;
49+
// Split the data if it is necessary.
50+
// Compress also slightly smaller packets
51+
let (datas, compressed) = if data.len() > (max_size - 100) {
52+
// TODO Compress
53+
let mut data = data;
54+
// Ignore size limit for whisper packets
55+
if data.len() <= max_size
56+
|| packet.header.get_type() == PacketType::VoiceWhisper
57+
{
58+
(vec![data], false)
59+
} else {
60+
// Split
61+
let count = (data.len() + max_size - 1) / max_size;
62+
let mut splitted = Vec::with_capacity(count);
63+
// Split from the back so the buffer does not have to be moved each
64+
// time.
65+
// Rest
66+
let mut len = data.len();
67+
splitted.push(data.split_off(len - (len % max_size)));
68+
69+
while {
70+
len = data.len();
71+
len > 0
72+
} {
73+
splitted.push(data.split_off(len - max_size));
74+
}
75+
(splitted, false)
76+
}
77+
} else {
78+
(vec![data], false)
79+
};
80+
let len = datas.len();
81+
let fragmented = len > 1;
82+
let default_header = {
83+
let mut h = Header::default();
84+
h.set_type(packet.header.get_type());
85+
if compressed {
86+
h.set_compressed(true);
87+
}
88+
h
89+
};
90+
let mut packets = Vec::with_capacity(datas.len());
91+
for (i, d) in datas.into_iter().rev().enumerate() {
92+
let mut h = default_header.clone();
93+
if fragmented && (i == 0 || i == len - 1) {
94+
h.set_fragmented(true);
95+
}
96+
packets.push((h, d));
97+
}
98+
packets
99+
}
100+
101+
fn create_key_nonce(
102+
header: &Header,
103+
generation_id: u32,
104+
iv: &[u8; 20],
105+
) -> ([u8; 16], [u8; 16]) {
106+
let mut temp = [0; 26];
107+
if header.c_id.is_some() {
108+
temp[0] = 0x31;
109+
} else {
110+
temp[0] = 0x30;
111+
}
112+
temp[1] = header.p_type & 0xf;
113+
let mut buf = Vec::with_capacity(4);
114+
buf.write_u32::<NetworkEndian>(generation_id).unwrap();
115+
temp[2..6].copy_from_slice(&buf);
116+
temp[6..].copy_from_slice(iv);
117+
118+
let keynonce = digest::digest(&digest::SHA256, &temp);
119+
let keynonce = keynonce.as_ref();
120+
let mut key = [0; 16];
121+
let mut nonce = [0; 16];
122+
key.copy_from_slice(&keynonce[..16]);
123+
nonce.copy_from_slice(&keynonce[16..]);
124+
key[0] ^= (header.p_id >> 8) as u8;
125+
key[1] ^= (header.p_id & 0xff) as u8;
126+
(key, nonce)
127+
}
128+
129+
pub(crate) fn encrypt_key_nonce(
130+
header: &mut Header,
131+
data: &mut [u8],
132+
key: &[u8; 16],
133+
nonce: &[u8; 16],
134+
) -> Result<()> {
135+
let mut meta = Vec::with_capacity(5);
136+
header.write_meta(&mut meta)?;
137+
138+
let mut eax =
139+
tomcrypt::EaxState::new(tomcrypt::rijndael(), key, nonce, Some(&meta))?;
140+
141+
eax.encrypt_in_place(data)?;
142+
header.mac.copy_from_slice(&eax.finish(8)?);
143+
144+
Ok(())
145+
}
146+
147+
pub(crate) fn encrypt_fake(header: &mut Header, data: &mut [u8]) -> Result<()> {
148+
let mut key = [0; 16];
149+
key.copy_from_slice(::FAKE_KEY.as_bytes());
150+
let mut nonce = [0; 16];
151+
nonce.copy_from_slice(::FAKE_NONCE.as_bytes());
152+
encrypt_key_nonce(header, data, &key, &nonce)
153+
}
154+
155+
pub(crate) fn encrypt(
156+
header: &mut Header,
157+
data: &mut [u8],
158+
generation_id: u32,
159+
iv: &[u8; 20],
160+
) -> Result<()> {
161+
// TODO Cache this more efficiently for a generation
162+
let (key, nonce) = create_key_nonce(header, generation_id, iv);
163+
encrypt_key_nonce(header, data, &key, &nonce)
164+
}
165+
166+
pub(crate) fn decrypt_key_nonce(
167+
header: &Header,
168+
data: &mut [u8],
169+
key: &[u8; 16],
170+
nonce: &[u8; 16],
171+
) -> Result<()> {
172+
let mut meta = Vec::with_capacity(5);
173+
header.write_meta(&mut meta)?;
174+
175+
let mut eax =
176+
tomcrypt::EaxState::new(tomcrypt::rijndael(), key, nonce, Some(&meta))?;
177+
178+
eax.decrypt_in_place(data)?;
179+
if !header.mac.iter().eq(&eax.finish(8)?) {
180+
Err("Packet has wrong mac".into())
181+
} else {
182+
Ok(())
183+
}
184+
}
185+
186+
pub(crate) fn decrypt_fake(header: &Header, data: &mut [u8]) -> Result<()> {
187+
let mut key = [0; 16];
188+
key.copy_from_slice(::FAKE_KEY.as_bytes());
189+
let mut nonce = [0; 16];
190+
nonce.copy_from_slice(::FAKE_NONCE.as_bytes());
191+
decrypt_key_nonce(header, data, &key, &nonce)
192+
}
193+
194+
pub(crate) fn decrypt(
195+
header: &Header,
196+
data: &mut [u8],
197+
generation_id: u32,
198+
iv: &[u8; 20],
199+
) -> Result<()> {
200+
let (key, nonce) = create_key_nonce(header, generation_id, iv);
201+
decrypt_key_nonce(header, data, &key, &nonce)
202+
}
203+
204+
/// Compute shared iv and shared mac.
205+
pub(crate) fn compute_iv_mac(
206+
alpha: &[u8; 10],
207+
beta: &[u8; 10],
208+
our_key: &mut tomcrypt::EccKey,
209+
other_key: &mut tomcrypt::EccKey,
210+
) -> Result<([u8; 20], [u8; 8])> {
211+
let shared_secret =
212+
tomcrypt::EccKey::create_shared_secret(our_key, other_key, 32)?;
213+
let mut shared_iv = [0; 20];
214+
shared_iv.copy_from_slice(digest::digest(&digest::SHA1, &shared_secret)
215+
.as_ref());
216+
for i in 0..10 {
217+
shared_iv[i] ^= alpha[i];
218+
}
219+
for i in 0..10 {
220+
shared_iv[i + 10] ^= beta[i];
221+
}
222+
let mut shared_mac = [0; 8];
223+
shared_mac.copy_from_slice(
224+
&digest::digest(&digest::SHA1, &shared_iv).as_ref()[..8],
225+
);
226+
Ok((shared_iv, shared_mac))
227+
}
228+
229+
pub(crate) fn hash_cash(key: &mut tomcrypt::EccKey, level: u8) -> Result<u64> {
230+
let omega = base64::encode(&key.export_public()?);
231+
let mut offset = 0;
232+
while offset < u64::MAX && get_hash_cash_level(&omega, offset) < level {
233+
offset += 1;
234+
}
235+
Ok(offset)
236+
}
237+
238+
pub(crate) fn get_hash_cash_level(omega: &str, offset: u64) -> u8 {
239+
let data = digest::digest(
240+
&digest::SHA1,
241+
format!("{}{}", omega, offset).as_bytes(),
242+
);
243+
let mut res = 0;
244+
for &d in data.as_ref() {
245+
if d == 0 {
246+
res += 8;
247+
} else {
248+
res += d.leading_zeros() as u8;
249+
break;
250+
}
251+
}
252+
res
253+
}
254+
255+
pub(crate) fn biguint_to_array(i: &BigUint) -> [u8; 64] {
256+
let mut v = i.to_bytes_le();
257+
258+
// Extend with zeroes until 64 bytes
259+
let len = v.len();
260+
v.append(&mut vec![0; 64 - len]);
261+
v.reverse();
262+
263+
let mut a = [0; 64];
264+
a.copy_from_slice(&v);
265+
a
266+
}
267+
268+
#[cfg(feature = "server")]
269+
pub(crate) fn array_to_biguint(i: &[u8; 64]) -> BigUint {
270+
BigUint::from_bytes_be(i)
271+
}
272+
273+
#[cfg(test)]
274+
mod tests {
275+
use algorithms::*;
276+
use packets::{Data, Header, PacketType};
277+
278+
#[test]
279+
fn test_fake_crypt() {
280+
::init().unwrap();
281+
let data = (0..100).into_iter().collect::<Vec<_>>();
282+
let mut header = Header::default();
283+
let mut enc_data = data.clone();
284+
encrypt_fake(&mut header, &mut enc_data).unwrap();
285+
let mut dec_data = enc_data.clone();
286+
decrypt_fake(&header, &mut dec_data).unwrap();
287+
assert_eq!(&data, &dec_data);
288+
}
289+
290+
#[test]
291+
fn test_fake_encrypt() {
292+
let data = Data::Ack(0);
293+
let mut p_data = Vec::new();
294+
data.write(&mut p_data).unwrap();
295+
let mut header = Header::default();
296+
header.c_id = Some(0);
297+
header.set_type(PacketType::Ack);
298+
encrypt_fake(&mut header, &mut p_data).unwrap();
299+
300+
let mut buf = Vec::new();
301+
header.write(&mut buf).unwrap();
302+
buf.append(&mut p_data);
303+
let real_res: &[u8] = &[
304+
0xa4,
305+
0x7b,
306+
0x47,
307+
0x94,
308+
0xdb,
309+
0xa9,
310+
0x6a,
311+
0xc5,
312+
0,
313+
0,
314+
0,
315+
0,
316+
0x6,
317+
0xfe,
318+
0x18,
319+
];
320+
assert_eq!(real_res, buf.as_slice());
321+
}
322+
}

‎tsproto/src/client.rs

+596
Large diffs are not rendered by default.

‎tsproto/src/commands.rs

+361
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,361 @@
1+
use std::io::prelude::*;
2+
use std::str;
3+
4+
use nom::{self, alphanumeric, multispace};
5+
6+
use {Map, Result};
7+
8+
#[derive(Debug, Clone, PartialEq, Eq)]
9+
pub struct Command {
10+
pub command: String,
11+
static_args: Vec<(String, String)>,
12+
list_args: Vec<Vec<(String, String)>>,
13+
}
14+
15+
#[derive(Debug, Clone, PartialEq, Eq)]
16+
pub struct CanonicalCommand<'a> {
17+
pub command: &'a str,
18+
pub args: Map<&'a str, &'a str>,
19+
}
20+
21+
macro_rules! parse_to_string {
22+
($x:expr) => {
23+
String::from_utf8($x.iter().flat_map(|v| v.iter())
24+
.cloned().collect()).unwrap()
25+
};
26+
}
27+
28+
named!(command_arg<&[u8], (String, String)>, do_parse!(many0!(multispace) >>
29+
name: many1!(is_not!("\u{b}\u{c}\\\t\r\n| /=")) >> // Argument name
30+
value: alt!(
31+
map!(eof!(), |_| vec![]) |
32+
do_parse!( // Argument value
33+
tag!("=") >>
34+
value: many0!(alt!(
35+
map!(tag!("\\v"), |_| &b"\x0b"[..]) | // Vertical tab
36+
map!(tag!("\\f"), |_| &b"\x0c"[..]) | // Form feed
37+
map!(tag!("\\\\"), |_| &b"\\"[..]) |
38+
map!(tag!("\\t"), |_| &b"\t"[..]) |
39+
map!(tag!("\\r"), |_| &b"\r"[..]) |
40+
map!(tag!("\\n"), |_| &b"\n"[..]) |
41+
map!(tag!("\\p"), |_| &b"|"[..]) |
42+
map!(tag!("\\s"), |_| &b" "[..]) |
43+
map!(tag!("\\/"), |_| &b"/"[..]) |
44+
is_not!("\u{b}\u{c}\\\t\r\n| /")
45+
)) >>
46+
(value))
47+
| map!(tag!(""), |_| vec![])
48+
) >> (parse_to_string!(name), parse_to_string!(value))
49+
));
50+
51+
named!(parse_command<&[u8], Command>, do_parse!(
52+
command: many1!(alphanumeric) >> // Command
53+
static_args: many0!(command_arg) >>
54+
list_args: many0!(do_parse!(many0!(multispace) >>
55+
tag!("|") >>
56+
args: many1!(command_arg) >>
57+
(args)
58+
)) >>
59+
many0!(multispace) >>
60+
eof!() >>
61+
(Command {
62+
command: parse_to_string!(command),
63+
static_args,
64+
list_args,
65+
})
66+
));
67+
68+
impl Command {
69+
pub fn new<T: Into<String>>(command: T) -> Command {
70+
Command {
71+
command: command.into(),
72+
static_args: Vec::new(),
73+
list_args: Vec::new(),
74+
}
75+
}
76+
77+
pub fn push<K: Into<String>, V: Into<String>>(&mut self, key: K, val: V) {
78+
self.static_args.push((key.into(), val.into()));
79+
}
80+
81+
/// Replace an argument if it exists.
82+
pub fn replace<K: Into<String>, V: Into<String>>(
83+
&mut self,
84+
key: K,
85+
val: V,
86+
) {
87+
let key = key.into();
88+
for &mut (ref mut k, ref mut v) in &mut self.static_args {
89+
if key == *k {
90+
*v = val.into();
91+
break;
92+
}
93+
}
94+
}
95+
96+
/// Check, if each list argument is contained in each list.
97+
pub fn is_valid(&self) -> bool {
98+
if !self.list_args.is_empty() {
99+
let first = &self.list_args[0];
100+
for l in &self.list_args[1..] {
101+
if l.len() != first.len() {
102+
return false;
103+
}
104+
for &(ref arg, _) in first {
105+
if l.iter().any(|&(ref a, _)| a == arg) {
106+
return false;
107+
}
108+
}
109+
}
110+
}
111+
true
112+
}
113+
114+
pub fn read<T>(_: T, r: &mut Read) -> Result<Command> {
115+
let mut buf = Vec::new();
116+
r.read_to_end(&mut buf)?;
117+
// Check if the buffer contains valid UTF-8
118+
str::from_utf8(&buf)?;
119+
match parse_command(&buf) {
120+
nom::IResult::Done(_, mut cmd) => {
121+
// Some of the static args are variable so move the to the right
122+
// category.
123+
if !cmd.list_args.is_empty() {
124+
let mut la = Vec::new();
125+
for &(ref arg, _) in &cmd.list_args[0] {
126+
if let Some(i) = cmd.static_args
127+
.iter()
128+
.position(|&(ref k, _)| k == arg)
129+
{
130+
la.push(cmd.static_args.remove(i));
131+
} else {
132+
bail!("Not a valid command list");
133+
}
134+
}
135+
cmd.list_args.insert(0, la);
136+
}
137+
Ok(cmd)
138+
}
139+
error => Err(format!("Cannot parse a command: {:?}", error).into()),
140+
}
141+
}
142+
143+
fn write_escaped(w: &mut Write, s: &str) -> Result<()> {
144+
for c in s.chars() {
145+
match c {
146+
'\u{b}' => write!(w, "\\v"),
147+
'\u{c}' => write!(w, "\\f"),
148+
'\\' => write!(w, "\\\\"),
149+
'\t' => write!(w, "\\t"),
150+
'\r' => write!(w, "\\r"),
151+
'\n' => write!(w, "\\n"),
152+
'|' => write!(w, "\\p"),
153+
' ' => write!(w, "\\s"),
154+
'/' => write!(w, "\\/"),
155+
c => write!(w, "{}", c),
156+
}?;
157+
}
158+
Ok(())
159+
}
160+
161+
fn write_key_val(w: &mut Write, k: &str, v: &str) -> Result<()> {
162+
if v.is_empty() && k != "return_code" {
163+
write!(w, "{}", k)?;
164+
} else {
165+
write!(w, "{}=", k)?;
166+
Self::write_escaped(w, v)?;
167+
}
168+
Ok(())
169+
}
170+
171+
pub fn write(&self, w: &mut Write) -> Result<()> {
172+
w.write_all(self.command.as_bytes())?;
173+
for &(ref k, ref v) in &self.static_args {
174+
write!(w, " ")?;
175+
Self::write_key_val(w, k, v)?;
176+
}
177+
for (i, args) in self.list_args.iter().enumerate() {
178+
if i != 0 {
179+
write!(w, "|")?;
180+
}
181+
for (j, &(ref k, ref v)) in args.iter().enumerate() {
182+
if j != 0 || i == 0 {
183+
write!(w, " ")?;
184+
}
185+
Self::write_key_val(w, k, v)?;
186+
}
187+
}
188+
Ok(())
189+
}
190+
191+
pub fn has_arg(&self, arg: &str) -> bool {
192+
if self.static_args.iter().any(|&(ref a, _)| a == arg) {
193+
true
194+
} else if !self.list_args.is_empty() {
195+
self.list_args[0].iter().any(|&(ref a, _)| a == arg)
196+
} else {
197+
false
198+
}
199+
}
200+
201+
pub fn get_commands(&self) -> Vec<CanonicalCommand> {
202+
let mut res = Vec::new();
203+
let statics = self.static_args
204+
.iter()
205+
.map(|&(ref k, ref v)| (k.as_str(), v.as_str()))
206+
.collect();
207+
if self.list_args.is_empty() {
208+
res.push(CanonicalCommand {
209+
command: &self.command,
210+
args: statics,
211+
});
212+
} else {
213+
for l in &self.list_args {
214+
let mut v = statics.clone();
215+
v.extend(
216+
l.iter().map(|&(ref k, ref v)| (k.as_str(), v.as_str())),
217+
);
218+
res.push(CanonicalCommand {
219+
command: &self.command,
220+
args: v,
221+
});
222+
}
223+
}
224+
res
225+
}
226+
}
227+
228+
impl<'a> CanonicalCommand<'a> {
229+
pub fn has_arg(&self, arg: &str) -> bool {
230+
self.args.contains_key(arg)
231+
}
232+
}
233+
234+
#[cfg(test)]
235+
mod tests {
236+
use io::Cursor;
237+
use std::iter::FromIterator;
238+
239+
use Map;
240+
use commands::{CanonicalCommand, Command};
241+
242+
#[test]
243+
fn parse() {
244+
let s = b"cmd a=1 b=2 c=3";
245+
let mut cmd = Command::new("cmd");
246+
cmd.push("a", "1");
247+
cmd.push("b", "2");
248+
cmd.push("c", "3");
249+
250+
// Read
251+
let cmd_r = Command::read((), &mut Cursor::new(s)).unwrap();
252+
assert_eq!(cmd, cmd_r);
253+
// Write
254+
let mut s_r = Vec::new();
255+
cmd.write(&mut s_r).unwrap();
256+
assert_eq!(&s[..], s_r.as_slice());
257+
}
258+
259+
#[test]
260+
fn escape() {
261+
let s = b"cmd a=\\s\\\\ b=\\p c=abc\\tdef";
262+
let mut cmd = Command::new("cmd");
263+
cmd.push("a", " \\");
264+
cmd.push("b", "|");
265+
cmd.push("c", "abc\tdef");
266+
267+
// Read
268+
let cmd_r = Command::read((), &mut Cursor::new(s)).unwrap();
269+
assert_eq!(cmd, cmd_r);
270+
// Write
271+
let mut s_r = Vec::new();
272+
cmd.write(&mut s_r).unwrap();
273+
assert_eq!(&s[..], s_r.as_slice());
274+
}
275+
276+
#[test]
277+
fn array() {
278+
let s = b"cmd a=1 c=3 b=2|b=4|b=5";
279+
let mut cmd = Command::new("cmd");
280+
cmd.push("a", "1");
281+
cmd.push("c", "3");
282+
283+
cmd.list_args.push(vec![("b".into(), "2".into())]);
284+
cmd.list_args.push(vec![("b".into(), "4".into())]);
285+
cmd.list_args.push(vec![("b".into(), "5".into())]);
286+
287+
// Read
288+
let cmd_r = Command::read((), &mut Cursor::new(s)).unwrap();
289+
assert_eq!(cmd, cmd_r);
290+
// Write
291+
let mut s_r = Vec::new();
292+
cmd.write(&mut s_r).unwrap();
293+
assert_eq!(&s[..], s_r.as_slice());
294+
}
295+
296+
#[test]
297+
fn canonical_command() {
298+
let s = b"cmd a=1 b=2 c=3|b=4|b=5";
299+
let cmd = Command::read((), &mut Cursor::new(s)).unwrap();
300+
assert_eq!(
301+
cmd.get_commands(),
302+
vec![
303+
CanonicalCommand {
304+
command: "cmd",
305+
args: Map::from_iter(
306+
vec![("a", "1"), ("b", "2"), ("c", "3")]
307+
.iter()
308+
.cloned(),
309+
),
310+
},
311+
CanonicalCommand {
312+
command: "cmd",
313+
args: Map::from_iter(
314+
vec![("a", "1"), ("b", "4"), ("c", "3")]
315+
.iter()
316+
.cloned(),
317+
),
318+
},
319+
CanonicalCommand {
320+
command: "cmd",
321+
args: Map::from_iter(
322+
vec![("a", "1"), ("b", "5"), ("c", "3")]
323+
.iter()
324+
.cloned(),
325+
),
326+
},
327+
]
328+
);
329+
}
330+
331+
#[test]
332+
fn optional_arg() {
333+
let s = b"cmd a";
334+
Command::read((), &mut Cursor::new(s.as_ref())).unwrap();
335+
let s = b"cmd a b=1";
336+
Command::read((), &mut Cursor::new(s.as_ref())).unwrap();
337+
let s = b"cmd a=";
338+
Command::read((), &mut Cursor::new(s.as_ref())).unwrap();
339+
let s = b"cmd a= b=1";
340+
Command::read((), &mut Cursor::new(s.as_ref())).unwrap();
341+
}
342+
343+
#[test]
344+
fn clientinitiv() {
345+
let s = b"clientinitiv alpha=41Te9Ar7hMPx+A== omega=MEwDAgcAAgEgAiEAq2iCMfcijKDZ5tn2tuZcH+\\/GF+dmdxlXjDSFXLPGadACIHzUnbsPQ0FDt34Su4UXF46VFI0+4wjMDNszdoDYocu0 ip";
346+
Command::read((), &mut Cursor::new(s.as_ref())).unwrap();
347+
}
348+
349+
#[test]
350+
fn initserver() {
351+
// Well, that's more corrupted packet, but the parser should be robust
352+
let s = b"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\xc3\xa9\\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";
353+
Command::read((), &mut Cursor::new(s.as_ref())).unwrap();
354+
}
355+
356+
#[test]
357+
fn channellist() {
358+
let s = 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";
359+
Command::read((), &mut Cursor::new(s.as_ref())).unwrap();
360+
}
361+
}

‎tsproto/src/handler_data.rs

+439
Large diffs are not rendered by default.

‎tsproto/src/lib.rs

+159
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
// Limit for error_chain
2+
#![recursion_limit = "1024"]
3+
#![cfg_attr(feature = "cargo-clippy",
4+
allow(redundant_closure_call, clone_on_ref_ptr))]
5+
6+
extern crate base64;
7+
extern crate byteorder;
8+
extern crate chrono;
9+
#[macro_use]
10+
extern crate error_chain;
11+
extern crate futures;
12+
#[macro_use]
13+
extern crate nom;
14+
extern crate num;
15+
#[macro_use]
16+
extern crate num_derive;
17+
extern crate quicklz;
18+
extern crate rand;
19+
extern crate ring;
20+
#[macro_use]
21+
extern crate slog;
22+
extern crate slog_async;
23+
extern crate slog_perf;
24+
extern crate slog_term;
25+
extern crate tokio_core;
26+
extern crate tomcrypt;
27+
28+
use std::{fmt, io, str};
29+
use std::net::SocketAddr;
30+
31+
use futures::Future;
32+
use tokio_core::net::UdpCodec;
33+
34+
use packets::UdpPacket;
35+
36+
#[allow(unused_doc_comment)]
37+
pub mod errors {
38+
// Create the Error, ErrorKind, ResultExt, and Result types
39+
error_chain! {
40+
foreign_links {
41+
Io(::std::io::Error);
42+
Ring(::ring::error::Unspecified);
43+
Base64(::base64::DecodeError);
44+
Utf8(::std::str::Utf8Error);
45+
ParseInt(::std::num::ParseIntError);
46+
FutureCanceled(::futures::Canceled);
47+
}
48+
links {
49+
Tomcrypt(::tomcrypt::errors::Error, ::tomcrypt::errors::ErrorKind);
50+
Quicklz(::quicklz::errors::Error, ::quicklz::errors::ErrorKind);
51+
}
52+
}
53+
}
54+
use errors::*;
55+
56+
macro_rules! tryf {
57+
($e:expr) => {
58+
match $e {
59+
Ok(e) => e,
60+
Err(error) => return Box::new(future::err(error.into())),
61+
}
62+
};
63+
}
64+
65+
mod algorithms;
66+
pub mod client;
67+
pub mod commands;
68+
pub mod handler_data;
69+
pub mod log;
70+
pub mod packets;
71+
pub mod packet_codec;
72+
#[cfg(feature = "server")]
73+
pub mod server;
74+
75+
type BoxFuture<T, E> = Box<Future<Item = T, Error = E>>;
76+
type Map<K, V> = std::collections::HashMap<K, V>;
77+
78+
/// The maximum number of bytes for a fragmented packet.
79+
#[cfg_attr(feature = "cargo-clippy", allow(unreadable_literal))]
80+
const MAX_FRAGMENTS_LENGTH: usize = 40960;
81+
/// The maximum number of packets that are stored, if they receive out-of-order.
82+
const MAX_QUEUE_LEN: usize = 50;
83+
/// The maximum decompressed size of a packet.
84+
#[cfg_attr(feature = "cargo-clippy", allow(unreadable_literal))]
85+
const MAX_DECOMPRESSED_SIZE: usize = 40960;
86+
const FAKE_KEY: &str = "c:\\windows\\syste";
87+
const FAKE_NONCE: &str = "m\\firewall32.cpl";
88+
/// How long packets are resent until the connection is closed.
89+
const TIMEOUT_SECONDS: i64 = 30;
90+
91+
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
92+
pub struct ClientId(pub SocketAddr);
93+
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
94+
pub struct ServerId(pub SocketAddr);
95+
96+
#[derive(Default)]
97+
struct TsCodec;
98+
99+
struct HexSlice<'a, T: fmt::LowerHex + 'a>(&'a [T]);
100+
101+
impl<'a> fmt::Debug for HexSlice<'a, u8> {
102+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
103+
write!(f, "[")?;
104+
if let Some((l, m)) = self.0.split_last() {
105+
for b in m {
106+
if *b == 0 {
107+
write!(f, "0, ")?;
108+
} else {
109+
write!(f, "{:#02x}, ", b)?;
110+
}
111+
}
112+
if *l == 0 {
113+
write!(f, "0")?;
114+
} else {
115+
write!(f, "{:#02x}", l)?;
116+
}
117+
}
118+
write!(f, "]")
119+
}
120+
}
121+
122+
impl Into<SocketAddr> for ClientId {
123+
fn into(self) -> SocketAddr {
124+
self.0
125+
}
126+
}
127+
impl Into<SocketAddr> for ServerId {
128+
fn into(self) -> SocketAddr {
129+
self.0
130+
}
131+
}
132+
133+
impl UdpCodec for TsCodec {
134+
type In = (SocketAddr, UdpPacket);
135+
type Out = (SocketAddr, UdpPacket);
136+
137+
fn decode(&mut self, src: &SocketAddr, buf: &[u8]) -> io::Result<Self::In> {
138+
let mut res = Vec::with_capacity(buf.len());
139+
res.extend_from_slice(buf);
140+
Ok((*src, UdpPacket(res)))
141+
}
142+
143+
/// The input packet has to be compressed, encrypted and fragmented already.
144+
fn encode(
145+
&mut self,
146+
(addr, UdpPacket(mut packet)): Self::Out,
147+
buf: &mut Vec<u8>,
148+
) -> SocketAddr {
149+
buf.append(&mut packet);
150+
addr
151+
}
152+
}
153+
154+
pub fn init() -> Result<()> {
155+
tomcrypt::init();
156+
tomcrypt::register_sprng()?;
157+
tomcrypt::register_rijndael_cipher()?;
158+
Ok(())
159+
}

‎tsproto/src/log.rs

+306
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,306 @@
1+
use std::cell::RefCell;
2+
use std::net::SocketAddr;
3+
use std::rc::Rc;
4+
5+
use futures::{self, Sink, Stream};
6+
use slog::Logger;
7+
8+
use Error;
9+
use handler_data::Data;
10+
use packets::{Packet, UdpPacket};
11+
12+
pub struct PacketLogger;
13+
impl PacketLogger {
14+
fn prepare_logger(
15+
logger: &Logger,
16+
addr: SocketAddr,
17+
is_client: bool,
18+
incoming: bool,
19+
) -> Logger {
20+
let in_s = if incoming {
21+
"\x1b[1;32mIN\x1b[0m"
22+
} else {
23+
"\x1b[1;31mOUT\x1b[0m"
24+
};
25+
let to_s = if is_client { "S" } else { "C" };
26+
let addr_s = format!("{}", addr);
27+
logger.new(o!("dir" => in_s, "to" => to_s, "addr" => addr_s))
28+
}
29+
30+
pub fn log_udp_packet(
31+
logger: &Logger,
32+
addr: SocketAddr,
33+
is_client: bool,
34+
incoming: bool,
35+
packet: &UdpPacket,
36+
) {
37+
let logger = Self::prepare_logger(logger, addr, is_client, incoming);
38+
debug!(logger, "UdpPacket"; "content" => ?::HexSlice(&packet.0));
39+
}
40+
41+
pub fn log_packet(
42+
logger: &Logger,
43+
addr: SocketAddr,
44+
is_client: bool,
45+
incoming: bool,
46+
packet: &Packet,
47+
) {
48+
let logger = Self::prepare_logger(logger, addr, is_client, incoming);
49+
debug!(logger, "Packet"; "content" => ?packet);
50+
}
51+
}
52+
53+
pub fn apply_udp_packet_logger<CS: 'static>(data: Rc<RefCell<Data<CS>>>) {
54+
let data2 = data.clone();
55+
let mut data = data.borrow_mut();
56+
let stream = UdpPacketStreamLogger::new(
57+
data2.clone(),
58+
data.udp_packet_stream.take().unwrap(),
59+
data.logger.clone(),
60+
);
61+
data.udp_packet_stream = Some(Box::new(stream));
62+
let sink = UdpPacketSinkLogger::new(
63+
data2,
64+
data.udp_packet_sink.take().unwrap(),
65+
data.logger.clone(),
66+
);
67+
data.udp_packet_sink = Some(Box::new(sink));
68+
}
69+
70+
pub fn apply_packet_logger<CS: 'static>(data: Rc<RefCell<Data<CS>>>) {
71+
let data2 = data.clone();
72+
let mut data = data.borrow_mut();
73+
let stream = PacketStreamLogger::new(
74+
data2.clone(),
75+
data.packet_stream.take().unwrap(),
76+
data.logger.clone(),
77+
);
78+
data.packet_stream = Some(Box::new(stream));
79+
let sink = PacketSinkLogger::new(
80+
data2,
81+
data.packet_sink.take().unwrap(),
82+
data.logger.clone(),
83+
);
84+
data.packet_sink = Some(Box::new(sink));
85+
}
86+
87+
pub struct UdpPacketStreamLogger<
88+
CS,
89+
Inner: Stream<Item = (SocketAddr, UdpPacket), Error = Error>,
90+
> {
91+
data: Rc<RefCell<Data<CS>>>,
92+
inner: Inner,
93+
logger: Logger,
94+
}
95+
96+
// TODO Add into_inner, get_ref, get_mut to all Streams and Sinks
97+
impl<CS, Inner: Stream<Item = (SocketAddr, UdpPacket), Error = Error>>
98+
UdpPacketStreamLogger<CS, Inner> {
99+
pub fn new(
100+
data: Rc<RefCell<Data<CS>>>,
101+
inner: Inner,
102+
logger: Logger,
103+
) -> Self {
104+
Self {
105+
data,
106+
inner,
107+
logger,
108+
}
109+
}
110+
}
111+
112+
impl<CS, Inner: Stream<Item = (SocketAddr, UdpPacket), Error = Error>> Stream
113+
for UdpPacketStreamLogger<CS, Inner> {
114+
type Item = (SocketAddr, UdpPacket);
115+
type Error = Error;
116+
117+
fn poll(&mut self) -> futures::Poll<Option<Self::Item>, Self::Error> {
118+
let res = self.inner.poll();
119+
if let Ok(futures::Async::Ready(Some((addr, ref packet)))) = res {
120+
PacketLogger::log_udp_packet(
121+
&self.logger,
122+
addr,
123+
self.data.borrow().is_client,
124+
true,
125+
packet,
126+
);
127+
}
128+
res
129+
}
130+
}
131+
132+
pub struct UdpPacketSinkLogger<
133+
CS,
134+
Inner: Sink<SinkItem = (SocketAddr, UdpPacket), SinkError = Error>,
135+
> {
136+
data: Rc<RefCell<Data<CS>>>,
137+
inner: Inner,
138+
logger: Logger,
139+
/// The buffer to save a packet that is already logged.
140+
buf: Option<(SocketAddr, UdpPacket)>,
141+
}
142+
143+
impl<
144+
CS,
145+
Inner: Sink<SinkItem = (SocketAddr, UdpPacket), SinkError = Error>,
146+
> UdpPacketSinkLogger<CS, Inner> {
147+
pub fn new(
148+
data: Rc<RefCell<Data<CS>>>,
149+
inner: Inner,
150+
logger: Logger,
151+
) -> Self {
152+
Self {
153+
data,
154+
inner,
155+
logger,
156+
buf: None,
157+
}
158+
}
159+
}
160+
161+
impl<
162+
CS,
163+
Inner: Sink<SinkItem = (SocketAddr, UdpPacket), SinkError = Error>,
164+
> Sink for UdpPacketSinkLogger<CS, Inner> {
165+
type SinkItem = (SocketAddr, UdpPacket);
166+
type SinkError = Error;
167+
168+
fn start_send(
169+
&mut self,
170+
(addr, packet): Self::SinkItem,
171+
) -> futures::StartSend<Self::SinkItem, Self::SinkError> {
172+
// Check if the buffer is full
173+
if let Some(p) = self.buf.take() {
174+
if let futures::AsyncSink::NotReady(p) = self.inner.start_send(p)? {
175+
self.buf = Some(p);
176+
return Ok(futures::AsyncSink::NotReady((addr, packet)));
177+
}
178+
}
179+
180+
PacketLogger::log_udp_packet(
181+
&self.logger,
182+
addr,
183+
self.data.borrow().is_client,
184+
false,
185+
&packet,
186+
);
187+
let res = self.inner.start_send((addr, packet))?;
188+
// Buffer the packet if it was not sent
189+
if let futures::AsyncSink::NotReady(p) = res {
190+
self.buf = Some(p);
191+
Ok(futures::AsyncSink::Ready)
192+
} else {
193+
Ok(res)
194+
}
195+
}
196+
197+
fn poll_complete(&mut self) -> futures::Poll<(), Self::SinkError> {
198+
// Check if the buffer is full
199+
if let Some(p) = self.buf.take() {
200+
if let futures::AsyncSink::NotReady(p) = self.inner.start_send(p)? {
201+
self.buf = Some(p);
202+
return Ok(futures::Async::NotReady);
203+
}
204+
}
205+
206+
self.inner.poll_complete()
207+
}
208+
209+
fn close(&mut self) -> futures::Poll<(), Self::SinkError> {
210+
self.inner.poll_complete()
211+
}
212+
}
213+
214+
pub struct PacketStreamLogger<
215+
CS,
216+
Inner: Stream<Item = (SocketAddr, Packet), Error = Error>,
217+
> {
218+
data: Rc<RefCell<Data<CS>>>,
219+
inner: Inner,
220+
logger: Logger,
221+
}
222+
223+
impl<CS, Inner: Stream<Item = (SocketAddr, Packet), Error = Error>>
224+
PacketStreamLogger<CS, Inner> {
225+
pub fn new(
226+
data: Rc<RefCell<Data<CS>>>,
227+
inner: Inner,
228+
logger: Logger,
229+
) -> Self {
230+
Self {
231+
data,
232+
inner,
233+
logger,
234+
}
235+
}
236+
}
237+
238+
impl<CS, Inner: Stream<Item = (SocketAddr, Packet), Error = Error>> Stream
239+
for PacketStreamLogger<CS, Inner> {
240+
type Item = (SocketAddr, Packet);
241+
type Error = Error;
242+
243+
fn poll(&mut self) -> futures::Poll<Option<Self::Item>, Self::Error> {
244+
let res = self.inner.poll();
245+
if let Ok(futures::Async::Ready(Some((addr, ref packet)))) = res {
246+
PacketLogger::log_packet(
247+
&self.logger,
248+
addr,
249+
self.data.borrow().is_client,
250+
true,
251+
packet,
252+
);
253+
}
254+
res
255+
}
256+
}
257+
258+
pub struct PacketSinkLogger<
259+
CS,
260+
Inner: Sink<SinkItem = (SocketAddr, Packet), SinkError = Error>,
261+
> {
262+
data: Rc<RefCell<Data<CS>>>,
263+
inner: Inner,
264+
logger: Logger,
265+
}
266+
267+
impl<CS, Inner: Sink<SinkItem = (SocketAddr, Packet), SinkError = Error>>
268+
PacketSinkLogger<CS, Inner> {
269+
pub fn new(
270+
data: Rc<RefCell<Data<CS>>>,
271+
inner: Inner,
272+
logger: Logger,
273+
) -> Self {
274+
Self {
275+
data,
276+
inner,
277+
logger,
278+
}
279+
}
280+
}
281+
282+
impl<CS, Inner: Sink<SinkItem = (SocketAddr, Packet), SinkError = Error>> Sink
283+
for PacketSinkLogger<CS, Inner> {
284+
type SinkItem = (SocketAddr, Packet);
285+
type SinkError = Error;
286+
287+
fn start_send(
288+
&mut self,
289+
(addr, packet): Self::SinkItem,
290+
) -> futures::StartSend<Self::SinkItem, Self::SinkError> {
291+
PacketLogger::log_packet(
292+
&self.logger,
293+
addr,
294+
self.data.borrow().is_client,
295+
false,
296+
&packet,
297+
);
298+
self.inner.start_send((addr, packet))
299+
}
300+
fn poll_complete(&mut self) -> futures::Poll<(), Self::SinkError> {
301+
self.inner.poll_complete()
302+
}
303+
fn close(&mut self) -> futures::Poll<(), Self::SinkError> {
304+
self.inner.poll_complete()
305+
}
306+
}

‎tsproto/src/packet_codec.rs

+902
Large diffs are not rendered by default.

‎tsproto/src/packets.rs

+153
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
#![allow(unused_variables)]
2+
use std::{fmt, io};
3+
use std::io::prelude::*;
4+
5+
use byteorder::{NetworkEndian, ReadBytesExt, WriteBytesExt};
6+
use num::{FromPrimitive, ToPrimitive};
7+
8+
use {Error, HexSlice, Result};
9+
use commands::Command;
10+
11+
include!(concat!(env!("OUT_DIR"), "/packets.rs"));
12+
13+
#[derive(Debug, PartialEq, Eq, Clone, Copy, FromPrimitive, ToPrimitive, Hash)]
14+
#[repr(u8)]
15+
pub enum PacketType {
16+
Voice,
17+
VoiceWhisper,
18+
Command,
19+
CommandLow,
20+
Ping,
21+
Pong,
22+
Ack,
23+
AckLow,
24+
Init,
25+
}
26+
27+
impl PacketType {
28+
pub fn is_command(&self) -> bool {
29+
*self == PacketType::Command || *self == PacketType::CommandLow
30+
}
31+
pub fn is_voice(&self) -> bool {
32+
*self == PacketType::Voice || *self == PacketType::VoiceWhisper
33+
}
34+
}
35+
36+
#[repr(u8)]
37+
#[derive(Debug, PartialEq, Eq, Clone, Copy, FromPrimitive, ToPrimitive)]
38+
pub enum CodecType {
39+
/// Mono, 16 bit, 8 kHz, bitrate dependent on the quality setting
40+
SpeexNarrowband,
41+
/// Mono, 16 bit, 16 kHz, bitrate dependent on the quality setting
42+
SpeexWideband,
43+
/// Mono, 16 bit, 32 kHz, bitrate dependent on the quality setting
44+
SpeexUltrawideband,
45+
/// Mono, 16 bit, 48 kHz, bitrate dependent on the quality setting
46+
CeltMono,
47+
/// Mono, 16 bit, 48 kHz, bitrate dependent on the quality setting, optimized for voice
48+
OpusVoice,
49+
/// Stereo, 16 bit, 48 kHz, bitrate dependent on the quality setting, optimized for music
50+
OpusMusic,
51+
}
52+
53+
#[derive(Debug, PartialEq, Eq, Clone)]
54+
pub struct UdpPacket(pub Vec<u8>);
55+
56+
impl Packet {
57+
pub fn new(header: Header, data: Data) -> Packet {
58+
Packet { header, data }
59+
}
60+
}
61+
62+
impl Default for Header {
63+
fn default() -> Self {
64+
Header {
65+
mac: Default::default(),
66+
p_id: 0,
67+
c_id: None,
68+
p_type: 0,
69+
}
70+
}
71+
}
72+
73+
impl Header {
74+
pub fn new(p_type: PacketType) -> Header {
75+
let mut h = Header::default();
76+
h.set_type(p_type);
77+
h
78+
}
79+
80+
pub fn get_p_type(&self) -> u8 {
81+
self.p_type
82+
}
83+
pub fn set_p_type(&mut self, p_type: u8) {
84+
assert!((p_type & 0xf) <= 8);
85+
self.p_type = p_type;
86+
}
87+
88+
/// `true` if the packet is not encrypted.
89+
pub fn get_unencrypted(&self) -> bool {
90+
(self.get_p_type() & 0x80) != 0
91+
}
92+
/// `true` if the packet is compressed.
93+
pub fn get_compressed(&self) -> bool {
94+
(self.get_p_type() & 0x40) != 0
95+
}
96+
pub fn get_newprotocol(&self) -> bool {
97+
(self.get_p_type() & 0x20) != 0
98+
}
99+
/// `true` for the first and last packet of a compressed series of packets.
100+
pub fn get_fragmented(&self) -> bool {
101+
(self.get_p_type() & 0x10) != 0
102+
}
103+
104+
pub fn set_unencrypted(&mut self, value: bool) {
105+
let p_type = self.get_p_type();
106+
if value {
107+
self.set_p_type(p_type | 0x80);
108+
} else {
109+
self.set_p_type(p_type & !0x80);
110+
}
111+
}
112+
pub fn set_compressed(&mut self, value: bool) {
113+
let p_type = self.get_p_type();
114+
if value {
115+
self.set_p_type(p_type | 0x40);
116+
} else {
117+
self.set_p_type(p_type & !0x40);
118+
}
119+
}
120+
pub fn set_newprotocol(&mut self, value: bool) {
121+
let p_type = self.get_p_type();
122+
if value {
123+
self.set_p_type(p_type | 0x20);
124+
} else {
125+
self.set_p_type(p_type & !0x20);
126+
}
127+
}
128+
pub fn set_fragmented(&mut self, value: bool) {
129+
let p_type = self.get_p_type();
130+
if value {
131+
self.set_p_type(p_type | 0x10);
132+
} else {
133+
self.set_p_type(p_type & !0x10);
134+
}
135+
}
136+
137+
pub fn get_type(&self) -> PacketType {
138+
PacketType::from_u8(self.get_p_type() & 0xf).unwrap()
139+
}
140+
pub fn set_type(&mut self, t: PacketType) {
141+
let p_type = self.get_p_type();
142+
self.set_p_type((p_type & 0xf0) | t.to_u8().unwrap());
143+
}
144+
145+
pub fn write_meta(&self, w: &mut Write) -> Result<()> {
146+
w.write_u16::<NetworkEndian>(self.p_id)?;
147+
if let Some(c_id) = self.c_id {
148+
w.write_u16::<NetworkEndian>(c_id)?;
149+
}
150+
w.write_u8(self.p_type)?;
151+
Ok(())
152+
}
153+
}

0 commit comments

Comments
 (0)
Please sign in to comment.