Compare commits

..
16 Commits
Author SHA1 Message Date
erikbrockoandClaude Opus 5.5 004aa41732 Pad a short RSA puzzle answer instead of failing the connect
An answer with a leading zero byte comes out of toByteArray() as 63 bytes,
and copying it started one byte too far, failing about one connect in 256.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 20:17:49 +00:00
erikbrockoandClaude Opus 5.5 0549b6bf02 Sign myTeamSpeak identity into clientinit
Adds an authenticator hook that appends the myTeamSpeak parameters to
clientinit/updatemytsid, and the per-connection challenge they sign.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 20:04:55 +00:00
erikbrockoandClaude Opus 5.5 1430782e2a Send the microphone's voice as whispers to a target
setWhisperTarget routes voice into VOICE_WHISPER packets to channels and
clients until cleared; a voice session under way ends on its old route
first. Whisper packets carry their own packet id and get the redundant
copies voice does.

WhisperTargetMultiple sized its two counts as two bytes each, leaving
zero bytes after the voice data, and read the client ids by the channel
count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 22:18:07 +00:00
erikbrockoandClaude Opus 5.5 2d6f5cdf78 Send every ready live-capture frame per tick and cap the timer's catch-up burst
A mic running faster than the 20 ms timer filled the queue until frames were
dropped; live sources now drain each tick. The catch-up clamp was inverted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 20:14:42 +00:00
erikbrockoandClaude Opus 5.5 a4ce0feb61 Report a minute's bandwidth as bytes per second
setconnectioninfo sent the bytes of the whole last minute where the
server expects the minute's average rate, so others saw our bandwidth
60 times too high. PacketStatistics gains the per-second averages, and
the packets-last-minute count looked at the last second only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 20:26:59 +00:00
erikbrockoandClaude Opus 5.5 90bf6e030c Resend voice packets for loss resilience
A microphone can ask for every voice packet to be sent again, a number
of times at a fixed spacing. The copies are the same encrypted packet,
so listeners keep whichever arrives first. A TS3 server forwards them,
and a jitter buffer that sees them arrive late grows to wait for them:
the sender buys its listeners a deeper buffer, trading latency for
riding out loss, with native clients as much as with others.

Copies go out from the 20 ms microphone timer, so the spacing is best a
whole number of ticks. Copies of a connection that is gone are dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 20:17:13 +00:00
erikbrockoandClaude Opus 5.5 4cc27db0e8 Fail a refused connect with the server's reason
An error answering the handshake, such as "too many clones already
connected", used to surface only as "disconnected while waiting for
CONNECTED state". connect() now fails with the server's message, and
the CommandException carrying its error id is the cause.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 15:12:50 +00:00
erikbrockoandClaude Opus 5.5 d89a02957a Test SRV lookup against stubbed records, not the live DNS
The test resolved voice.teamspeak.com for real, so it failed whenever
that name, or the network, did not answer. It now checks the ordering
and parsing with a stubbed resolver.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:03:41 +00:00
erikbrockoandClaude Opus 5.5 c47bbdf96c Derive the server's unique id from its handshake key
TS3 derives a virtual server's unique identifier from its public key the
same way as a client's: base64(SHA-1(key)). The server never tells a
guest otherwise, as serverinfo is refused and neither initserver nor
notifyserverupdated carries it. The socket now keeps the key from
initivexpand(2) and offers getServerUid().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 10:35:41 +00:00
erikbrockoandClaude Opus 5.5 8273a27160 Ignore Maven's target/ directory
The pattern read targetId/, so build output showed up as untracked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 10:26:21 +00:00
erikbrockoandClaude Opus 5.5 4aa9341ec4 Drop the connection when a command never gets through
The server handles commands in order and holds back everything sent
after a lost one, so giving up on a command now ends the connection, as
in the official client. A connection lost without either side saying
goodbye (a timeout, or such a command) is now reported to listeners as
a disconnect ("connection lost").

- A command's acknowledgement is awaited in the background: ensureSent
  is often called from the packet handler thread, which must keep
  handling while resends go on. A command that fails makes way for the
  next one.
- One packet that fails to handle no longer ends the handler thread,
  which left everything after it unhandled while ACKs and pings kept the
  connection looking alive.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 10:08:09 +00:00
erikbrockoandClaude Opus 5.5 5a5fb6baaf Encrypt each packet with its own EAX cipher
TS3 derives a packet's key and nonce from its id, so resending a packet
encrypts it under the same pair again. BouncyCastle has since learned to
refuse that on a cipher that has already used the pair ("cannot reuse
nonce for EAX encryption"), which broke resends on the current version
the Android build uses. A fresh cipher per packet keeps them working.

Moves to bcprov-jdk18on 1.86, the maintained line, so every platform runs
the same BouncyCastle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 08:42:48 +00:00
erikbrockoandClaude Opus 5.5 3625cc24cf Look up SRV records without requiring JNDI
TS3DNS resolved SRV records through JNDI's DNS provider, which Android
does not have. The JNDI code moves into its own class that is only
loaded where JNDI exists; elsewhere a server is reached by its address,
as when it publishes no SRV record. TS3DNS.setSrvLookup lets a platform
supply its own resolver.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 08:13:09 +00:00
erikbrockoandClaude Opus 5.5 2018c1c593 Resend like the official client; keep the handshake consistent under loss
- Resend unacknowledged packets on the official client's schedule (mean RTT
  + 3 sigma + 50 ms over the last 20 samples, x1.4 per resend) and give up
  after 18 s, instead of a fixed 1 s x 30.
- Resend INIT1 packets until the server answers; they are never ACKed.
- Answer each server Init1 step once: a duplicated step-3 reply sent a second
  clientinitiv with a new alpha, leaving client and server with different
  keys (MAC check failures).
- Disconnect without blocking on an ACK the server may never send.
- Fail waitForState promptly when the connection drops, and name the packet
  in decrypt errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 04:58:21 +00:00
erikbrockoandClaude Opus 5.5 45cb8fd559 Send clientinit without waiting for clientek's ACK
The server does not acknowledge a resent clientek, so losing its first ACK
stalled the handshake: we kept resending clientek and never got to
clientinit. Send clientek without blocking (resends continue in the
background via the new writePacketAsync) and follow with clientinit right
away; the server cannot decrypt clientinit before it has processed
clientek, so the two stay in order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 23:21:44 +00:00
erikbrockoandClaude Opus 5.5 765bfb25fd Fall back to the handshake key when a packet fails to decrypt
The server encrypts initivexpand2 (COMMAND 0 and 1) with the handshake
key. If our ACK for one of those fragments is lost, its retransmit arrives
after we switched to the session key, fails with "mac check in EAX
failed", is never acknowledged and blocks the server's command stream
until it drops us. Common on lossy links such as mobile data.

Retry generation 0 packets that fail under the session key with the
handshake key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 23:21:44 +00:00
19 changed files with 844 additions and 247 deletions
+1 -1
View File
@@ -31,7 +31,7 @@ out/
.userlibraries .userlibraries
# Maven # Maven
targetId/ target/
pom.xml.tag pom.xml.tag
pom.xml.releaseBackup pom.xml.releaseBackup
pom.xml.versionsBackup pom.xml.versionsBackup
+2 -2
View File
@@ -36,8 +36,8 @@
<dependency> <dependency>
<groupId>org.bouncycastle</groupId> <groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId> <artifactId>bcprov-jdk18on</artifactId>
<version>1.67</version> <version>1.86</version>
</dependency> </dependency>
<dependency> <dependency>
@@ -12,4 +12,27 @@ public interface Microphone {
CodecType getCodec(); CodecType getCodec();
byte[] provide(); byte[] provide();
/**
* Milliseconds between a voice packet and each copy of it sent afterwards, or 0 to send it
* once. A copy is the same packet, so receivers keep whichever arrives first; a jitter buffer
* that sees copies arrive late grows to wait for them, trading latency for riding out loss.
*/
default int getRedundancyDelay() {
return 0;
}
/**
* Whether {@link #provide} hands out frames captured on a clock of their own, such as a sound
* card's. That clock drifts against the send timer, so each tick then sends every frame that is
* ready instead of one, keeping the drift from piling up as latency or overflowing a queue.
*/
default boolean isLiveCapture() {
return false;
}
/** How many copies follow each voice packet, {@link #getRedundancyDelay} apart. */
default int getRedundancyCopies() {
return 1;
}
} }
@@ -0,0 +1,38 @@
package com.github.manevolent.ts3j.protocol;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.InitialDirContext;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
/**
* SRV lookups through JNDI's DNS provider, which desktop JVMs ship. Kept apart from
* {@link TS3DNS} so runtimes without JNDI (Android) never load it.
*/
final class JndiSrvLookup implements TS3DNS.SrvLookup {
@Override
public List<String> lookup(String name) throws IOException {
Attribute attribute;
try {
Attributes attributes = new InitialDirContext().getAttributes("dns:/" + name, new String[] { "SRV" });
attribute = attributes.get("SRV");
} catch (NamingException e) {
throw new UnknownHostException("Host not found: " + name);
}
List<String> records = new ArrayList<>();
if (attribute == null) return records;
try {
for (int i = 0; i < attribute.size(); i++)
records.add((String) attribute.get(i));
} catch (NamingException e) {
throw new IOException(e);
}
return records;
}
}
@@ -1,9 +1,5 @@
package com.github.manevolent.ts3j.protocol; package com.github.manevolent.ts3j.protocol;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.InitialDirContext;
import java.io.IOException; import java.io.IOException;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
@@ -18,8 +14,28 @@ public class TS3DNS {
private static final String DNS_PREFIX_TCP = "_tsdns._tcp."; private static final String DNS_PREFIX_TCP = "_tsdns._tcp.";
private static final String DNS_PREFIX_UDP = "_ts3._udp."; private static final String DNS_PREFIX_UDP = "_ts3._udp.";
/** Looks up DNS SRV records; see {@link #setSrvLookup}. */
public interface SrvLookup {
/**
* @return each record as "priority weight port target", empty if there are none
* @throws UnknownHostException if the name does not exist
*/
List<String> lookup(String name) throws IOException;
}
/** Null until first use, when JNDI's DNS provider becomes the default. */
private static volatile SrvLookup srvLookup;
/** /**
* SRV record, as returned by JNDI: "priority weight port target." * Replaces how SRV records are looked up. The default goes through JNDI, which not every
* runtime has (Android doesn't); without it, servers are reached by address only.
*/
public static void setSrvLookup(SrvLookup lookup) {
srvLookup = lookup;
}
/**
* SRV record, as {@link SrvLookup} returns it: "priority weight port target."
*/ */
private static final class SrvRecord { private static final class SrvRecord {
private final int priority, weight, port; private final int priority, weight, port;
@@ -40,25 +56,12 @@ public class TS3DNS {
} }
private static List<InetSocketAddress> lookupSRV(String domain) throws IOException { private static List<InetSocketAddress> lookupSRV(String domain) throws IOException {
Attribute attribute; List<String> found = srvLookup().lookup(domain);
if (found.isEmpty()) throw new UnknownHostException("Host not found");
try { List<SrvRecord> records = new ArrayList<>(found.size());
Attributes attributes = new InitialDirContext().getAttributes("dns:/" + domain, new String[] { "SRV" }); for (String record : found)
attribute = attributes.get("SRV"); records.add(new SrvRecord(record));
} catch (NamingException e) {
throw new UnknownHostException("Host not found: " + domain);
}
if (attribute == null || attribute.size() <= 0) throw new UnknownHostException("Host not found");
List<SrvRecord> records = new ArrayList<>(attribute.size());
try {
for (int i = 0; i < attribute.size(); i++)
records.add(new SrvRecord((String) attribute.get(i)));
} catch (NamingException e) {
throw new IOException(e);
}
// Loose sorting // Loose sorting
records.sort(Comparator.comparingInt((SrvRecord x) -> x.priority).thenComparingInt(x -> x.weight)); records.sort(Comparator.comparingInt((SrvRecord x) -> x.priority).thenComparingInt(x -> x.weight));
@@ -70,6 +73,22 @@ public class TS3DNS {
return addresses; return addresses;
} }
private static SrvLookup srvLookup() {
SrvLookup lookup = srvLookup;
if (lookup != null) return lookup;
try {
Class.forName("javax.naming.directory.InitialDirContext");
lookup = new JndiSrvLookup();
} catch (ClassNotFoundException e) {
// No JNDI on this runtime: behave as if no server published an SRV record.
lookup = name -> {
throw new UnknownHostException("No SRV lookup available for " + name);
};
}
srvLookup = lookup;
return lookup;
}
public static List<InetSocketAddress> lookup(String domain) throws IOException { public static List<InetSocketAddress> lookup(String domain) throws IOException {
return lookupSRV(DNS_PREFIX_UDP + domain); return lookupSRV(DNS_PREFIX_UDP + domain);
} }
@@ -239,13 +239,13 @@ public class PacketBody1VoiceWhisper extends PacketBody {
channelIds[n] = (int) (buffer.getLong()); channelIds[n] = (int) (buffer.getLong());
clientIds = new int[clientIdCount]; clientIds = new int[clientIdCount];
for (int n = 0; n < channelIdCount; n ++) for (int n = 0; n < clientIdCount; n ++)
clientIds[n] = (buffer.getShort() & 0xFFFF); clientIds[n] = (buffer.getShort() & 0xFFFF);
} }
@Override @Override
public int getSize() { public int getSize() {
return 2 + 2 + return 1 + 1 +
(channelIds == null ? 0 : channelIds.length * 8) + (channelIds == null ? 0 : channelIds.length * 8) +
(clientIds == null ? 0 : clientIds.length * 2); (clientIds == null ? 0 : clientIds.length * 2);
} }
@@ -1,6 +1,7 @@
package com.github.manevolent.ts3j.protocol.packet.handler.client; package com.github.manevolent.ts3j.protocol.packet.handler.client;
import com.github.manevolent.ts3j.command.Command; import com.github.manevolent.ts3j.command.Command;
import com.github.manevolent.ts3j.command.CommandException;
import com.github.manevolent.ts3j.command.SingleCommand; import com.github.manevolent.ts3j.command.SingleCommand;
import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter;
import com.github.manevolent.ts3j.protocol.Packet; import com.github.manevolent.ts3j.protocol.Packet;
@@ -22,6 +23,9 @@ import java.nio.ByteBuffer;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.Base64; import java.util.Base64;
import java.util.Random; import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
public class LocalClientHandlerConnecting extends LocalClientHandler { public class LocalClientHandlerConnecting extends LocalClientHandler {
@@ -30,12 +34,19 @@ public class LocalClientHandlerConnecting extends LocalClientHandler {
private byte[] randomBytes; private byte[] randomBytes;
private byte[] alphaBytes; private byte[] alphaBytes;
/** The last Init1 we sent; resent until the server answers it. */
private PacketBody8Init1 pendingInit1;
/** The highest Init1 step the server has answered with; anything up to it again is a duplicate. */
private int serverStep;
private ScheduledExecutorService init1Resender;
public LocalClientHandlerConnecting(LocalTeamspeakClientSocket client) { public LocalClientHandlerConnecting(LocalTeamspeakClientSocket client) {
super(client); super(client);
} }
@Override @Override
public void onAssigned() throws IOException, TimeoutException { public void onAssigned() throws IOException, TimeoutException {
serverStep = 0;
PacketBody8Init1 packet = new PacketBody8Init1(ProtocolRole.CLIENT); PacketBody8Init1 packet = new PacketBody8Init1(ProtocolRole.CLIENT);
// Initialize connection // Initialize connection
@@ -53,10 +64,53 @@ public class LocalClientHandlerConnecting extends LocalClientHandler {
//getClient().writePacket(new PacketBody2Command(ProtocolRole.CLIENT, createInitIv())); //getClient().writePacket(new PacketBody2Command(ProtocolRole.CLIENT, createInitIv()));
} }
@Override
public void onUnassigning() {
stopResendingInit1();
}
/**
* Sends an Init1 and keeps resending the same packet until the server answers: Init1 has no
* acknowledgements, so without this one lost datagram stalls the handshake for good.
*/
private void sendInit1(PacketBody8Init1 packet) throws IOException, TimeoutException { private void sendInit1(PacketBody8Init1 packet) throws IOException, TimeoutException {
packet.setVersion(INIT1_VERSION); packet.setVersion(INIT1_VERSION);
synchronized (this) {
pendingInit1 = packet;
if (init1Resender == null) {
init1Resender = Executors.newSingleThreadScheduledExecutor(r -> {
Thread thread = new Thread(r, "TS3J/Init1Resend");
thread.setDaemon(true);
return thread;
});
}
}
getClient().writePacket(packet); getClient().writePacket(packet);
scheduleInit1Resend(packet, 0);
}
private synchronized void scheduleInit1Resend(PacketBody8Init1 packet, int resends) {
if (pendingInit1 != packet || init1Resender == null) return;
init1Resender.schedule(() -> {
synchronized (this) {
if (pendingInit1 != packet) return;
}
try {
getClient().writePacket(packet);
} catch (Exception e) {
Ts3Debugging.debug("Problem resending Init1", e);
}
scheduleInit1Resend(packet, resends + 1);
}, getClient().getResendTimeout(resends), TimeUnit.MILLISECONDS);
}
private synchronized void stopResendingInit1() {
pendingInit1 = null;
if (init1Resender != null) {
init1Resender.shutdownNow();
init1Resender = null;
}
} }
@Override @Override
@@ -65,6 +119,10 @@ public class LocalClientHandlerConnecting extends LocalClientHandler {
PacketBody8Init1 init1 = (PacketBody8Init1) packet.getBody(); PacketBody8Init1 init1 = (PacketBody8Init1) packet.getBody();
Ts3Debugging.debug("Handle Init1 step " + init1.getStep().getNumber()); Ts3Debugging.debug("Handle Init1 step " + init1.getStep().getNumber());
// Answering a duplicate would redo the handshake step, and a second clientinitiv would
// come with a new alpha, leaving us with a different key than the server.
if (init1.getStep().getNumber() <= serverStep) return;
serverStep = init1.getStep().getNumber();
PacketBody8Init1.Step step; PacketBody8Init1.Step step;
switch (init1.getStep().getNumber()) { switch (init1.getStep().getNumber()) {
@@ -101,16 +159,7 @@ public class LocalClientHandlerConnecting extends LocalClientHandler {
BigInteger x = new BigInteger(1, serverReplyStep3.getX()); BigInteger x = new BigInteger(1, serverReplyStep3.getX());
BigInteger n = new BigInteger(1, serverReplyStep3.getN()); BigInteger n = new BigInteger(1, serverReplyStep3.getN());
byte[] y = new byte[64]; byte[] y = unsigned64(x.modPow(BigInteger.valueOf(2L).pow(serverReplyStep3.getLevel()), n));
byte[] solution =
x.modPow(BigInteger.valueOf(2L).pow(serverReplyStep3.getLevel()), n).toByteArray();
System.arraycopy(
solution, Math.abs(solution.length - 64),
y, solution.length < 64 ? 64 - solution.length : 0,
solution.length < 64 ? solution.length : 64
);
// Build response // Build response
PacketBody8Init1.Step4 step4 = new PacketBody8Init1.Step4(); PacketBody8Init1.Step4 step4 = new PacketBody8Init1.Step4();
@@ -138,6 +187,7 @@ public class LocalClientHandlerConnecting extends LocalClientHandler {
sendInit1(new PacketBody8Init1(getClient().getRole().getOut(), step)); sendInit1(new PacketBody8Init1(getClient().getRole().getOut(), step));
} else if (packet.getBody() instanceof PacketBody2Command) { } else if (packet.getBody() instanceof PacketBody2Command) {
stopResendingInit1();
SingleCommand command = ((PacketBody2Command) packet.getBody()).parse().simplifyOne(); SingleCommand command = ((PacketBody2Command) packet.getBody()).parse().simplifyOne();
Ts3Debugging.debug(command.build()); Ts3Debugging.debug(command.build());
@@ -146,6 +196,7 @@ public class LocalClientHandlerConnecting extends LocalClientHandler {
byte[] alpha = Base64.getDecoder().decode(command.get("alpha").getValue()); // alpha byte[] alpha = Base64.getDecoder().decode(command.get("alpha").getValue()); // alpha
byte[] beta = Base64.getDecoder().decode(command.get("beta").getValue()); // beta byte[] beta = Base64.getDecoder().decode(command.get("beta").getValue()); // beta
byte[] omega = Base64.getDecoder().decode(command.get("omega").getValue()); // omega byte[] omega = Base64.getDecoder().decode(command.get("omega").getValue()); // omega
getClient().setServerPublicKey(command.get("omega").getValue());
getClient().setSecureParameters(Ts3Crypt.cryptoInit(alpha, beta, omega, getClient().getIdentity())); getClient().setSecureParameters(Ts3Crypt.cryptoInit(alpha, beta, omega, getClient().getIdentity()));
@@ -166,6 +217,7 @@ public class LocalClientHandlerConnecting extends LocalClientHandler {
byte[] beta = Base64.getDecoder().decode(command.get("beta").getValue()); // beta byte[] beta = Base64.getDecoder().decode(command.get("beta").getValue()); // beta
byte[] omega = Base64.getDecoder().decode(command.get("omega").getValue()); // omega byte[] omega = Base64.getDecoder().decode(command.get("omega").getValue()); // omega
getClient().setServerPublicKey(command.get("omega").getValue());
byte[] proof = Base64.getDecoder().decode(command.get("proof").getValue()); byte[] proof = Base64.getDecoder().decode(command.get("proof").getValue());
Pair<byte[], byte[]> keyPair = Ts3Crypt.generateKeypair(); Pair<byte[], byte[]> keyPair = Ts3Crypt.generateKeypair();
@@ -185,7 +237,9 @@ public class LocalClientHandlerConnecting extends LocalClientHandler {
getClient().getIdentity() getClient().getIdentity()
); );
getClient().writePacket(new PacketBody2Command( // Don't wait for the ACK: the server ignores a resent clientek, so a lost ACK would stall us, and
// it can't decrypt clientinit before processing clientek anyway, so the two stay in order.
getClient().writePacketAsync(new PacketBody2Command(
ProtocolRole.CLIENT, ProtocolRole.CLIENT,
new SingleCommand( new SingleCommand(
"clientek", ProtocolRole.CLIENT, "clientek", ProtocolRole.CLIENT,
@@ -203,15 +257,28 @@ public class LocalClientHandlerConnecting extends LocalClientHandler {
getClient().setCommandProcessor(getClient()); getClient().setCommandProcessor(getClient());
getClient().setState(ClientConnectionState.RETRIEVING_DATA); getClient().setState(ClientConnectionState.RETRIEVING_DATA);
} else if (command.getName().equals("error")) { } else if (command.getName().equals("error")) {
getClient().setState(ClientConnectionState.DISCONNECTED); CommandException refusal = refusal(command);
getClient().refuse(refusal);
throw new IOException(command.get("msg").getValue()); throw new IOException(refusal.getMessage(), refusal);
} else { } else {
throw new IOException("Unknown Init command: " + command.getName()); throw new IOException("Unknown Init command: " + command.getName());
} }
} }
} }
/** The server's answer to a handshake command it refused, as an exception carrying its error id. */
static CommandException refusal(SingleCommand error) {
String message = error.has("msg") ? error.get("msg").getValue() : "connection refused";
int id;
try {
id = error.has("id") ? Integer.parseInt(error.get("id").getValue()) : -1;
} catch (NumberFormatException e) {
id = -1;
}
return new CommandException(message, id);
}
private SingleCommand createInitIv() { private SingleCommand createInitIv() {
alphaBytes = new byte[10]; alphaBytes = new byte[10];
new Random().nextBytes(alphaBytes); new Random().nextBytes(alphaBytes);
@@ -279,8 +346,22 @@ public class LocalClientHandlerConnecting extends LocalClientHandler {
) )
); );
Ts3Debugging.debug(clientinit.build()); getClient().addMyTeamSpeakParameters(clientinit);
Ts3Debugging.debug("Sending clientinit");
getClient().writePacket(new PacketBody2Command(ProtocolRole.CLIENT, clientinit)); getClient().writePacket(new PacketBody2Command(ProtocolRole.CLIENT, clientinit));
} }
/**
* The puzzle's answer as 64 unsigned big-endian bytes. {@link BigInteger#toByteArray()}
* adds a sign byte when the top bit is set and drops leading zero bytes, so it can be
* 65 bytes or fewer than 64.
*/
static byte[] unsigned64(BigInteger value) {
byte[] bytes = value.toByteArray();
byte[] y = new byte[64];
int length = Math.min(bytes.length, 64);
System.arraycopy(bytes, bytes.length - length, y, 64 - length, length);
return y;
}
} }
@@ -1,9 +1,9 @@
package com.github.manevolent.ts3j.protocol.packet.handler.client; package com.github.manevolent.ts3j.protocol.packet.handler.client;
import com.github.manevolent.ts3j.command.CommandException;
import com.github.manevolent.ts3j.command.CommandProcessException; import com.github.manevolent.ts3j.command.CommandProcessException;
import com.github.manevolent.ts3j.command.CommandProcessor; import com.github.manevolent.ts3j.command.CommandProcessor;
import com.github.manevolent.ts3j.command.MultiCommand; import com.github.manevolent.ts3j.command.MultiCommand;
import com.github.manevolent.ts3j.protocol.client.ClientConnectionState;
import com.github.manevolent.ts3j.protocol.socket.client.LocalTeamspeakClientSocket; import com.github.manevolent.ts3j.protocol.socket.client.LocalTeamspeakClientSocket;
@@ -15,13 +15,14 @@ public class LocalClientHandlerRetrievingData extends LocalClientHandlerFull {
@Override @Override
protected void handleCommand(MultiCommand command) throws CommandProcessException { protected void handleCommand(MultiCommand command) throws CommandProcessException {
if (command.getName().equalsIgnoreCase("error")) { if (command.getName().equalsIgnoreCase("error")) {
// clientinit was refused, e.g. for a nickname in use or a wrong server password.
CommandException refusal = LocalClientHandlerConnecting.refusal(command.simplifyOne());
try { try {
getClient().setState(ClientConnectionState.DISCONNECTED); getClient().refuse(refusal);
} catch (Exception e) { } catch (Exception e) {
getClient().getExceptionHandler().accept(e); getClient().getExceptionHandler().accept(e);
} }
throw new CommandProcessException(refusal.getMessage());
throw new CommandProcessException(command.simplifyOne().get("msg").getValue());
} }
CommandProcessor processor = getClient().getCommandProcessor(); CommandProcessor processor = getClient().getCommandProcessor();
@@ -61,7 +61,7 @@ public class PacketStatistics {
} }
public int getSentPacketsLastMinute() { public int getSentPacketsLastMinute() {
long now = System.nanoTime() - 1_000_000_000L; long now = System.nanoTime() - 60_000_000_000L;
synchronized (sentPacketList) { synchronized (sentPacketList) {
return (int) sentPacketList.stream() return (int) sentPacketList.stream()
@@ -124,6 +124,16 @@ public class PacketStatistics {
} }
} }
/** Average bytes per second sent over the last minute, as TeamSpeak reports a minute's bandwidth. */
public int getSentBandwidthLastMinute() {
return getSentBytesLastMinute() / 60;
}
/** Average bytes per second received over the last minute. */
public int getReceivedBandwidthLastMinute() {
return getReceivedBytesLastMinute() / 60;
}
public int getReceivedBytesLastMinute() { public int getReceivedBytesLastMinute() {
long now = System.nanoTime() - 60_000_000_000L; long now = System.nanoTime() - 60_000_000_000L;
@@ -24,7 +24,7 @@ public class PacketTransformation {
public PacketTransformation(byte[] ivStruct, byte[] fakeMac) { public PacketTransformation(byte[] ivStruct, byte[] fakeMac) {
this.ivStruct = ivStruct; this.ivStruct = ivStruct;
this.cipher = new EAXBlockCipher(new AESEngine()); this.cipher = new EAXBlockCipher(AESEngine.newInstance());
this.fakeMac = fakeMac; this.fakeMac = fakeMac;
} }
@@ -32,6 +32,12 @@ public class PacketTransformation {
return fakeMac; return fakeMac;
} }
/** Connection binding used by myTeamSpeak, in the AES-128/SHA-256 protocol mode. */
public byte[] getMyTeamSpeakChallenge() {
return Ts3Crypt.hash256(ByteBuffer.allocate(6 + ivStruct.length)
.put(new byte[] {0x30, 8, 0, 0, 0, 0}).put(ivStruct).array());
}
public Pair<byte[], byte[]> computeParameters(PacketHeader header) { public Pair<byte[], byte[]> computeParameters(PacketHeader header) {
ByteBuffer temporaryByteBuffer = ByteBuffer ByteBuffer temporaryByteBuffer = ByteBuffer
.allocate(ivStruct.length == 20 ? 26 : 70) .allocate(ivStruct.length == 20 ? 26 : 70)
@@ -86,20 +92,18 @@ public class PacketTransformation {
int dataLen = packet.getBody().getSize(); int dataLen = packet.getBody().getSize();
ByteBuffer packetBuffer = packet.writeBody(ByteBuffer.allocate(dataLen).order(ByteOrder.BIG_ENDIAN)); ByteBuffer packetBuffer = packet.writeBody(ByteBuffer.allocate(dataLen).order(ByteOrder.BIG_ENDIAN));
byte[] result; // TS3 derives key and nonce from the packet id, so a resend encrypts under the same pair
int len; // again. BouncyCastle refuses that on a cipher that has seen it, hence one per packet.
EAXBlockCipher cipher = new EAXBlockCipher(AESEngine.newInstance());
cipher.init(true, cipherParameters);
synchronized (cipher) { byte[] result = new byte[cipher.getOutputSize(dataLen)];
cipher.init(true, cipherParameters); int len = cipher.processBytes(packetBuffer.array(), 0, dataLen, result, 0);
result = new byte[cipher.getOutputSize(dataLen)]; try {
len = cipher.processBytes(packetBuffer.array(), 0, dataLen, result, 0); len += cipher.doFinal(result, len);
} catch (InvalidCipherTextException e) {
try { throw new RuntimeException(e);
len += cipher.doFinal(result, len);
} catch (InvalidCipherTextException e) {
throw new RuntimeException(e);
}
} }
ByteBuffer outputBuffer = ByteBuffer.allocate(MAC_LEN + headerWithoutMac.length + (len - MAC_LEN)); ByteBuffer outputBuffer = ByteBuffer.allocate(MAC_LEN + headerWithoutMac.length + (len - MAC_LEN));
@@ -1,6 +1,9 @@
package com.github.manevolent.ts3j.protocol.socket.client; package com.github.manevolent.ts3j.protocol.socket.client;
import com.github.manevolent.ts3j.command.CommandException;
import com.github.manevolent.ts3j.command.*; import com.github.manevolent.ts3j.command.*;
import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter;
import com.github.manevolent.ts3j.identity.Identity; import com.github.manevolent.ts3j.identity.Identity;
import com.github.manevolent.ts3j.protocol.NetworkPacket; import com.github.manevolent.ts3j.protocol.NetworkPacket;
import com.github.manevolent.ts3j.protocol.Packet; import com.github.manevolent.ts3j.protocol.Packet;
@@ -34,6 +37,7 @@ import java.nio.*;
import java.util.*; import java.util.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Function;
/** /**
* Server/client common abstract client socket, used to interact with the UDP connection. Provides most of the protocol * Server/client common abstract client socket, used to interact with the UDP connection. Provides most of the protocol
@@ -52,6 +56,8 @@ public abstract class AbstractTeamspeakClientSocket
private final Map<String, Object> clientOptions = new ConcurrentHashMap<>(); private final Map<String, Object> clientOptions = new ConcurrentHashMap<>();
private final Object connectionStateLock = new Object(); private final Object connectionStateLock = new Object();
/** Why the server turned the connection down while it was being set up; null otherwise. */
private volatile CommandException refusal;
private final LinkedBlockingDeque<Packet> readQueue = new LinkedBlockingDeque<>(65536); private final LinkedBlockingDeque<Packet> readQueue = new LinkedBlockingDeque<>(65536);
@@ -75,7 +81,8 @@ public abstract class AbstractTeamspeakClientSocket
private Identity identity = null; private Identity identity = null;
private ClientConnectionState connectionState = null; private ClientConnectionState connectionState = null;
private PacketTransformation transformation = new InitPacketTransformation(); private final PacketTransformation initTransformation = new InitPacketTransformation();
private PacketTransformation transformation = initTransformation;
private PacketHandler handler; private PacketHandler handler;
private int clientId = 0; private int clientId = 0;
@@ -83,13 +90,7 @@ public abstract class AbstractTeamspeakClientSocket
private long lastResponse; private long lastResponse;
private long lastPing; private long lastPing;
// RTT private final ResendTiming resendTiming = new ResendTiming();
private static final double alphaSmooth = 0.125D;
private static final double betaSmooth = 0.25D;
private double smoothedRtt;
private double smoothedRttVar;
private double currentRto;
//
// Ping // Ping
private List<Double> pings = new LinkedList<>(); private List<Double> pings = new LinkedList<>();
@@ -166,6 +167,21 @@ public abstract class AbstractTeamspeakClientSocket
setTransformation(new PacketTransformation(parameters.getIvStruct(), parameters.getFakeSignature())); setTransformation(new PacketTransformation(parameters.getIvStruct(), parameters.getFakeSignature()));
} }
private volatile Function<byte[], Map<String, String>> myTeamSpeakAuthenticator;
/** Set before connecting; invoked after the handshake with this connection's challenge. */
public void setMyTeamSpeakAuthenticator(Function<byte[], Map<String, String>> authenticator) {
myTeamSpeakAuthenticator = authenticator;
}
public void addMyTeamSpeakParameters(Command command) {
Function<byte[], Map<String, String>> authenticator = myTeamSpeakAuthenticator;
if (authenticator == null) return;
Map<String, String> parameters = authenticator.apply(transformation.getMyTeamSpeakChallenge());
for (Map.Entry<String, String> entry : parameters.entrySet())
command.add(new CommandSingleParameter(entry.getKey(), entry.getValue()));
}
protected abstract NetworkPacket readNetworkPacket(int timeout) throws IOException; protected abstract NetworkPacket readNetworkPacket(int timeout) throws IOException;
protected abstract void writeNetworkPacket(NetworkPacket packet) throws IOException; protected abstract void writeNetworkPacket(NetworkPacket packet) throws IOException;
@@ -177,8 +193,10 @@ public abstract class AbstractTeamspeakClientSocket
boolean initialState = this.connectionState == null; boolean initialState = this.connectionState == null;
if (state == ClientConnectionState.CONNECTING) if (state == ClientConnectionState.CONNECTING) {
refusal = null;
setReading(true); setReading(true);
}
this.connectionState = state; this.connectionState = state;
@@ -250,20 +268,40 @@ public abstract class AbstractTeamspeakClientSocket
return connectionState; return connectionState;
} }
/**
* Waits for the connection to reach a state.
*
* @throws IOException if the connection is closed before it gets there
*/
public void waitForState(ClientConnectionState state, long wait) public void waitForState(ClientConnectionState state, long wait)
throws InterruptedException, TimeoutException { throws InterruptedException, TimeoutException, IOException {
synchronized (connectionStateLock) { synchronized (connectionStateLock) {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
while (connectionState != state && System.currentTimeMillis() - start < wait) { while (connectionState != state && connectionState != ClientConnectionState.DISCONNECTED
&& System.currentTimeMillis() - start < wait) {
connectionStateLock.wait(Math.max(0L, wait - (System.currentTimeMillis() - start))); connectionStateLock.wait(Math.max(0L, wait - (System.currentTimeMillis() - start)));
} }
if (connectionState != state && connectionState == ClientConnectionState.DISCONNECTED) {
CommandException refused = refusal;
if (refused != null) throw new IOException(refused.getMessage(), refused);
throw new IOException("disconnected while waiting for " + state.name() + " state");
}
if (connectionState != state) if (connectionState != state)
throw new TimeoutException("timeout waiting for " + state.name() + " state"); throw new TimeoutException("timeout waiting for " + state.name() + " state");
} }
} }
/**
* Records the error the server answered a handshake command with, and leaves the connection:
* {@link #waitForState} then fails with it rather than with a bare disconnect.
*/
public void refuse(CommandException error) throws IOException, TimeoutException {
refusal = error;
setState(ClientConnectionState.DISCONNECTED);
}
public boolean isConnected() { public boolean isConnected() {
return connectionState == ClientConnectionState.CONNECTED; return connectionState == ClientConnectionState.CONNECTED;
} }
@@ -282,6 +320,41 @@ public abstract class AbstractTeamspeakClientSocket
@Override @Override
public void writePacket(PacketBody body) throws IOException, TimeoutException { public void writePacket(PacketBody body) throws IOException, TimeoutException {
writePacket(newOutgoingPacket(body));
}
/**
* Sends a packet body without waiting for its acknowledgement. It is numbered and encrypted before this
* returns, so packets written afterwards follow it; resends until it is acknowledged continue in the background.
*
* @return completes once the packet is acknowledged, or exceptionally if it never is
*/
public CompletableFuture<Void> writePacketAsync(PacketBody body) throws IOException, TimeoutException {
Packet packet = newOutgoingPacket(body);
List<PacketResponse> responses = new ArrayList<>();
synchronized (sendLocks.get(packet.getHeader().getType())) {
for (Packet piece : split(packet))
responses.add(sendPacketIntl(piece));
}
CompletableFuture<Void> acknowledged = new CompletableFuture<>();
Thread thread = new Thread(() -> {
try {
for (PacketResponse response : responses)
awaitAcknowledgement(response);
acknowledged.complete(null);
} catch (Throwable e) {
acknowledged.completeExceptionally(e);
}
}, "TS3J/Resend");
thread.setDaemon(true);
thread.start();
return acknowledged;
}
private Packet newOutgoingPacket(PacketBody body) {
// Construct a packet object // Construct a packet object
Packet packet = new Packet(body.getRole()); Packet packet = new Packet(body.getRole());
@@ -317,12 +390,32 @@ public abstract class AbstractTeamspeakClientSocket
// Assign header pointer // Assign header pointer
packet.setHeader(header); packet.setHeader(header);
// Lower-level write; helper is done return packet;
writePacket(packet);
} }
@Override @Override
public void writePacket(Packet packet) throws IOException, TimeoutException { public void writePacket(Packet packet) throws IOException, TimeoutException {
List<Packet> pieces = split(packet);
if (packet.getHeader().getType().isSplittable()) {
// Note, it's very important we send these packets synchronously.
// we allow the split to happen multi-thread, but we block until all
// chunks are sent synchronously. So, all chunks of packets are synchronous.
// this happens because we care that the packet IDs are contiguous.
synchronized (sendLocks.get(packet.getHeader().getType())) {
for (Packet piece : pieces)
awaitAcknowledgement(sendPacketIntl(piece)); // Write the individual piece, incrementing its packet
}
} else {
// Don't lock here, for the slight performance benefit.
awaitAcknowledgement(sendPacketIntl(packet));
}
}
/**
* Checks an outgoing packet and splits it into the pieces to send.
*/
private List<Packet> split(Packet packet) throws IOException {
// Sanity checks. People are insane! // Sanity checks. People are insane!
if (packet.getHeader() == null) if (packet.getHeader() == null)
throw new NullPointerException("header"); throw new NullPointerException("header");
@@ -338,28 +431,23 @@ public abstract class AbstractTeamspeakClientSocket
// it's better to do this all at once instead of sending them as they are split, // it's better to do this all at once instead of sending them as they are split,
// because we might get halfway through splitting them then throw an exception and // because we might get halfway through splitting them then throw an exception and
// we can't write the rest. // we can't write the rest.
List<Packet> packets = Fragments.split(packet); return Fragments.split(packet);
// Note, it's very important we send these packets synchronously.
// we allow the split to happen multi-thread, but we block until all
// chunks are sent synchronously. So, all chunks of packets are synchronous.
// this happens because we care that the packet IDs are contiguous.
synchronized (sendLocks.get(packet.getHeader().getType())) {
for (Packet piece : packets)
writePacketIntl(piece); // Write the individual piece, incrementing its packet
}
} else {
// Ensure the outbound packet's maximum size isn't too large if it can't be split (which it can't here)
if (packet.getSize() > Fragments.MAXIMUM_PACKET_SIZE)
throw new IllegalArgumentException("packet too large: " + packet.getSize() + "; " +
packet.getHeader().getType().name() + " cannot split");
// Don't lock here, for the slight performance benefit.
writePacketIntl(packet);
} }
// Ensure the outbound packet's maximum size isn't too large if it can't be split (which it can't here)
if (packet.getSize() > Fragments.MAXIMUM_PACKET_SIZE)
throw new IllegalArgumentException("packet too large: " + packet.getSize() + "; " +
packet.getHeader().getType().name() + " cannot split");
return Collections.singletonList(packet);
} }
private void writePacketIntl(Packet packet) throws IOException, TimeoutException { /**
* Numbers, encrypts and sends a single packet.
*
* @return the pending acknowledgement to wait for, or null if none is expected
*/
private PacketResponse sendPacketIntl(Packet packet) throws IOException {
PacketHeader header = packet.getHeader(); PacketHeader header = packet.getHeader();
// Count packet // Count packet
@@ -407,6 +495,8 @@ public abstract class AbstractTeamspeakClientSocket
// > X is a ushort in H2N order of an own audio packet counter // > X is a ushort in H2N order of an own audio packet counter
// it seems it can be the same as the packet counter so we will let the packethandler do it. // it seems it can be the same as the packet counter so we will let the packethandler do it.
((PacketBody0Voice)packet.getBody()).setPacketId(header.getPacketId()); ((PacketBody0Voice)packet.getBody()).setPacketId(header.getPacketId());
} else if (header.getType() == PacketBodyType.VOICE_WHISPER) {
((PacketBody1VoiceWhisper)packet.getBody()).setPacketId(header.getPacketId());
} }
// Flush to a buffer // Flush to a buffer
@@ -467,7 +557,7 @@ public abstract class AbstractTeamspeakClientSocket
response = new PacketResponse( response = new PacketResponse(
networkPacket, networkPacket,
responsibleQueue, responsibleQueue,
networkPacket.getHeader().getType().canResend() ? 30 : 0 networkPacket.getHeader().getType().canResend()
) )
); );
} else } else
@@ -485,31 +575,40 @@ public abstract class AbstractTeamspeakClientSocket
.get(kind) .get(kind)
.processOutgoing(packet); .processOutgoing(packet);
// If necessary, fulfill promise for the packet acknowledgement or throw TimeoutException return willWaitForAck ? response : null;
if (response != null && willWaitForAck) { }
while (response.getRetries() < response.getMaxTries() &&
getState() != ClientConnectionState.DISCONNECTED) {
try {
if (getState() == ClientConnectionState.DISCONNECTED)
throw new IllegalStateException("no longer connected");
// Wait one cycle for an ACK /** How long to wait for an answer to a packet that has been resent the given number of times. */
response.waitForAcknowledgement(1000L); public long getResendTimeout(int resends) {
return resendTiming.timeoutMs(resends);
}
/**
* Waits for a packet's acknowledgement, resending it until it arrives.
*/
private void awaitAcknowledgement(PacketResponse response) throws IOException, TimeoutException {
if (response != null) {
while (getState() != ClientConnectionState.DISCONNECTED) {
try {
response.waitForAcknowledgement(resendTiming.timeoutMs(response.getResends()));
break; break;
} catch (TimeoutException e) { } catch (TimeoutException e) {
if (response.willResend()) if (!response.willResend() || response.getResends() >= ResendTiming.MAX_RESENDS
response.resend(); || System.nanoTime() - response.getFirstSent()
else >= TimeUnit.MILLISECONDS.toNanos(ResendTiming.GIVE_UP_MS)) {
throw e; // Commands are handled in order: the server holds back everything sent after this one
// until it arrives, so giving up on it loses the connection, as in the official client.
if (getState() == ClientConnectionState.CONNECTED)
setState(ClientConnectionState.DISCONNECTED);
throw new TimeoutException("send");
}
response.resend();
} catch (CancellationException e) { } catch (CancellationException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
if (response.getRetries() >= response.getMaxTries())
throw new TimeoutException("send");
} }
} }
@@ -543,24 +642,18 @@ public abstract class AbstractTeamspeakClientSocket
+ " generation=" + networkPacket.getHeader().getGeneration()); + " generation=" + networkPacket.getHeader().getGeneration());
PacketTransformation transformation = getTransformation(); PacketTransformation transformation = getTransformation();
int dataLen = networkPacket.getDatagram().getLength() - networkPacket.getHeader().getSize();
try { try {
packetBuffer = ByteBuffer.wrap( packetBuffer = ByteBuffer.wrap(
transformation.decrypt( decrypt(transformation, networkPacket.getHeader(), packetBuffer, dataLen)
networkPacket.getHeader(),
packetBuffer,
networkPacket.getDatagram().getLength() -
networkPacket.getHeader().getSize()
)
).order(ByteOrder.BIG_ENDIAN); ).order(ByteOrder.BIG_ENDIAN);
} catch (InvalidCipherTextException e) { } catch (InvalidCipherTextException e) {
throw new IOException( throw new IOException(
"failed to decrypt " + networkPacket.getHeader().getType().name() "failed to decrypt " + networkPacket.getHeader().getType().name()
+ " (" + + " id=" + packet.getHeader().getPacketId()
"transformation=" + transformation.getClass() + + " generation=" + networkPacket.getHeader().getGeneration()
", state=" + getState() + + " (" + transformation.getClass().getSimpleName() + ", " + getState() + ")",
", id=" + packet.getHeader().getPacketId() +
", generation=" + networkPacket.getHeader().getGeneration(),
e e
); );
} }
@@ -604,6 +697,20 @@ public abstract class AbstractTeamspeakClientSocket
return packet; return packet;
} }
/**
* Decrypts with the session key, falling back to the handshake key: the server encrypts initivexpand2 with
* the latter, so its retransmits (sent when our ACK was lost) still arrive under it after the key switch.
*/
private byte[] decrypt(PacketTransformation transformation, PacketHeader header, ByteBuffer buffer, int dataLen)
throws InvalidCipherTextException {
try {
return transformation.decrypt(header, buffer, dataLen);
} catch (InvalidCipherTextException e) {
if (transformation instanceof InitPacketTransformation || header.getGeneration() != 0) throw e;
return initTransformation.decrypt(header, buffer, dataLen);
}
}
@Override @Override
public Packet readPacket() throws public Packet readPacket() throws
IOException, IOException,
@@ -746,13 +853,9 @@ public abstract class AbstractTeamspeakClientSocket
} }
} }
if (smoothedRtt < 0) // An acknowledgement of a resent packet can't tell which copy it answers.
smoothedRtt = sampleRtt; if (response.getResends() == 0)
else resendTiming.addSample(TimeUnit.NANOSECONDS.toMillis(rttNano));
smoothedRtt = (long)((1 - alphaSmooth) * smoothedRtt + alphaSmooth * sampleRtt);
smoothedRttVar = (long)((1 - betaSmooth) * smoothedRttVar + betaSmooth * Math.abs(sampleRtt - smoothedRtt));
currentRto = smoothedRtt + Math.max(0D, 4 * smoothedRttVar);
} }
if (response != null) if (response != null)
@@ -923,22 +1026,25 @@ public abstract class AbstractTeamspeakClientSocket
private class NetworkHandler implements Runnable { private class NetworkHandler implements Runnable {
@Override @Override
public void run() { public void run() {
try { while (isReading()) {
while (isReading()) { Packet packet;
try { try {
Packet packet = readQueue.take(); packet = readQueue.take();
} catch (InterruptedException e) {
// separate these so we getHandler at proper runtime instant rather than get it and let it change break;
// on us }
getHandler().handlePacket(packet); // One bad packet must not end this thread: everything received after it would queue up unhandled
} catch (InterruptedException e) { // while ACKs and pings, answered by the reader, keep the connection looking alive.
break; try {
} // separate these so we getHandler at proper runtime instant rather than get it and let it change
// on us
getHandler().handlePacket(packet);
} catch (Throwable e) {
Ts3Debugging.debug("Problem handling packet", e);
// A disconnect interrupts whatever the handler was waiting on; that is not an error.
if (isReading()) getExceptionHandler().accept(e);
} }
} catch (Throwable e) {
Ts3Debugging.debug("Problem reading packet", e);
getExceptionHandler().accept(e);
} }
} }
} }
@@ -970,18 +1076,17 @@ public abstract class AbstractTeamspeakClientSocket
private final NetworkPacket sentPacket; private final NetworkPacket sentPacket;
private final CompletableFuture<Packet> future = new CompletableFuture<>(); private final CompletableFuture<Packet> future = new CompletableFuture<>();
private final Map<Integer, PacketResponse> responsibleQueue; private final Map<Integer, PacketResponse> responsibleQueue;
private long lastSent = 0L; private final long firstSent = System.nanoTime();
private int tries = 1, maxTries; private long lastSent = firstSent;
private boolean willResend; private int resends;
private final boolean willResend;
public PacketResponse(NetworkPacket sentPacket, public PacketResponse(NetworkPacket sentPacket,
Map<Integer, PacketResponse> responsibleQueue, Map<Integer, PacketResponse> responsibleQueue,
int maxTries) { boolean willResend) {
this.sentPacket = sentPacket; this.sentPacket = sentPacket;
this.responsibleQueue = responsibleQueue; this.responsibleQueue = responsibleQueue;
this.maxTries = maxTries; this.willResend = willResend;
this.lastSent = System.nanoTime();
this.willResend = maxTries > 0;
} }
public NetworkPacket getPacket() { public NetworkPacket getPacket() {
@@ -990,17 +1095,8 @@ public abstract class AbstractTeamspeakClientSocket
public void resend() throws IOException { public void resend() throws IOException {
AbstractTeamspeakClientSocket.this.writeNetworkPacket(sentPacket); AbstractTeamspeakClientSocket.this.writeNetworkPacket(sentPacket);
setLastSent(System.nanoTime());
long t = System.nanoTime(); resends++;
long before = lastSent;
long elapsed = t - before;
setLastSent(t);
double elapsedSeconds = elapsed / 1_000_000_000D;
currentRto += elapsedSeconds;
tries ++;
} }
/** /**
@@ -1033,12 +1129,12 @@ public abstract class AbstractTeamspeakClientSocket
return willResend; return willResend;
} }
public int getMaxTries() { public int getResends() {
return maxTries; return resends;
} }
public int getRetries() { public long getFirstSent() {
return tries; return firstSent;
} }
public long getLastSent() { public long getLastSent() {
@@ -16,8 +16,12 @@ import com.github.manevolent.ts3j.identity.Uid;
import com.github.manevolent.ts3j.protocol.*; import com.github.manevolent.ts3j.protocol.*;
import com.github.manevolent.ts3j.protocol.client.ClientConnectionState; import com.github.manevolent.ts3j.protocol.client.ClientConnectionState;
import com.github.manevolent.ts3j.protocol.header.PacketHeader; import com.github.manevolent.ts3j.protocol.header.PacketHeader;
import com.github.manevolent.ts3j.enums.CodecType;
import com.github.manevolent.ts3j.protocol.packet.PacketBody;
import com.github.manevolent.ts3j.protocol.packet.PacketBody0Voice; import com.github.manevolent.ts3j.protocol.packet.PacketBody0Voice;
import com.github.manevolent.ts3j.protocol.packet.PacketBody1VoiceWhisper;
import com.github.manevolent.ts3j.protocol.packet.PacketBody2Command; import com.github.manevolent.ts3j.protocol.packet.PacketBody2Command;
import com.github.manevolent.ts3j.protocol.packet.PacketBodyType;
import com.github.manevolent.ts3j.protocol.packet.handler.PacketHandler; import com.github.manevolent.ts3j.protocol.packet.handler.PacketHandler;
import com.github.manevolent.ts3j.protocol.packet.handler.client.LocalClientHandlerConnected; import com.github.manevolent.ts3j.protocol.packet.handler.client.LocalClientHandlerConnected;
import com.github.manevolent.ts3j.protocol.packet.handler.client.LocalClientHandlerConnecting; import com.github.manevolent.ts3j.protocol.packet.handler.client.LocalClientHandlerConnecting;
@@ -32,6 +36,9 @@ import java.io.IOException;
import java.net.*; import java.net.*;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*; import java.util.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.function.Function; import java.util.function.Function;
@@ -50,7 +57,13 @@ public class LocalTeamspeakClientSocket
private volatile InetSocketAddress remote; private volatile InetSocketAddress remote;
private Microphone microphone; private Microphone microphone;
private volatile PacketBody1VoiceWhisper.WhisperTarget whisperTarget;
private HighPrecisionTimer microphoneThread; private HighPrecisionTimer microphoneThread;
/** Voice packets still to be sent again, soonest first; see {@link Microphone#getRedundancyDelay}. */
private final Queue<VoiceCopy> voiceCopies =
new PriorityBlockingQueue<>(64, Comparator.comparingLong((VoiceCopy copy) -> copy.due));
private volatile long voiceCopyDelayNanos;
private volatile int voiceCopyCount;
private List<TS3Listener> listeners = new LinkedList<>(); private List<TS3Listener> listeners = new LinkedList<>();
@@ -59,6 +72,9 @@ public class LocalTeamspeakClientSocket
/** The virtual server's properties as announced by <b>initserver</b>. */ /** The virtual server's properties as announced by <b>initserver</b>. */
private volatile Map<String, String> serverProperties = Collections.emptyMap(); private volatile Map<String, String> serverProperties = Collections.emptyMap();
/** The public key the server identified itself with in the handshake, base64 as sent. */
private volatile String serverPublicKey;
/** /**
* The internal command buffer * The internal command buffer
* <p> * <p>
@@ -66,6 +82,9 @@ public class LocalTeamspeakClientSocket
* <p> * <p>
* get * get
*/ */
/** Whether losing the connection now would go unreported: connected, and neither side has said goodbye. */
private volatile boolean dropUnannounced;
private Map<Integer, ClientCommandResponse> awaitingCommands = new ConcurrentHashMap<>(); private Map<Integer, ClientCommandResponse> awaitingCommands = new ConcurrentHashMap<>();
public LocalTeamspeakClientSocket() { public LocalTeamspeakClientSocket() {
@@ -90,6 +109,7 @@ public class LocalTeamspeakClientSocket
throws CommandProcessException { throws CommandProcessException {
int clientId = Integer.parseInt(command.get("clid").getValue()); int clientId = Integer.parseInt(command.get("clid").getValue());
if (clientId == getClientId()) { if (clientId == getClientId()) {
dropUnannounced = false; // this is the announcement
try { try {
setState(ClientConnectionState.DISCONNECTED); setState(ClientConnectionState.DISCONNECTED);
} catch (Exception e) { } catch (Exception e) {
@@ -134,17 +154,17 @@ public class LocalTeamspeakClientSocket
response.add(new CommandSingleParameter("connection_bandwidth_sent_last_second_" + name, response.add(new CommandSingleParameter("connection_bandwidth_sent_last_second_" + name,
Integer.toString(stats.getSentBytesLastSecond()))); Integer.toString(stats.getSentBytesLastSecond())));
response.add(new CommandSingleParameter("connection_bandwidth_sent_last_minute_" + name, response.add(new CommandSingleParameter("connection_bandwidth_sent_last_minute_" + name,
Integer.toString(stats.getSentBytesLastMinute()))); Integer.toString(stats.getSentBandwidthLastMinute())));
response.add(new CommandSingleParameter("connection_bandwidth_received_last_second_" + name, response.add(new CommandSingleParameter("connection_bandwidth_received_last_second_" + name,
Integer.toString(stats.getReceivedBytesLastSecond()))); Integer.toString(stats.getReceivedBytesLastSecond())));
response.add(new CommandSingleParameter("connection_bandwidth_received_last_minute_" + name, response.add(new CommandSingleParameter("connection_bandwidth_received_last_minute_" + name,
Integer.toString(stats.getReceivedBytesLastMinute()))); Integer.toString(stats.getReceivedBandwidthLastMinute())));
} }
response.add(new CommandSingleParameter("connection_server2client_packetloss_total", Integer.toString(0))); response.add(new CommandSingleParameter("connection_server2client_packetloss_total", Integer.toString(0)));
try { try {
writePacket(new PacketBody2Command(getRole().getOut(), response)); writePacketAsync(new PacketBody2Command(getRole().getOut(), response));
} catch (Exception e) { } catch (Exception e) {
Ts3Debugging.debug("Problem sending setconnectioninfo", e); Ts3Debugging.debug("Problem sending setconnectioninfo", e);
} }
@@ -247,7 +267,7 @@ public class LocalTeamspeakClientSocket
); );
} }
throw new IOException("disconnected"); throw new EOFException("disconnected");
} }
@Override @Override
@@ -268,6 +288,40 @@ public class LocalTeamspeakClientSocket
packet.getDatagram().setSocketAddress(remote); packet.getDatagram().setSocketAddress(remote);
socket.send(packet.getDatagram()); socket.send(packet.getDatagram());
long copyDelay = voiceCopyDelayNanos;
PacketBodyType type = packet.getHeader().getType();
if (copyDelay > 0 && (type == PacketBodyType.VOICE || type == PacketBodyType.VOICE_WHISPER)) {
// Aim half a tick early, so each copy goes out on the tick nearest its time.
long sent = System.nanoTime() - TICK_MS * 1_000_000L / 2;
for (int i = 1, n = voiceCopyCount; i <= n; i++)
voiceCopies.add(new VoiceCopy(sent + i * copyDelay, packet.getDatagram()));
}
}
/** Sends the voice copies that are due; runs on the microphone timer. */
private void sendDueVoiceCopies() {
long now = System.nanoTime();
VoiceCopy copy;
while ((copy = voiceCopies.peek()) != null && now - copy.due >= 0) {
// Whatever poll() hands out is due no later than the one peeked at.
copy = voiceCopies.poll();
try {
socket.send(copy.datagram);
} catch (IOException e) {
getExceptionHandler().accept(e);
}
}
}
private static final class VoiceCopy {
final long due;
final DatagramPacket datagram;
VoiceCopy(long due, DatagramPacket datagram) {
this.due = due;
this.datagram = datagram;
}
} }
@@ -283,6 +337,7 @@ public class LocalTeamspeakClientSocket
@Override @Override
protected void onConnect() { protected void onConnect() {
super.onConnect(); super.onConnect();
dropUnannounced = true;
if (microphoneThread != null && !microphoneThread.isAlive()) if (microphoneThread != null && !microphoneThread.isAlive())
microphoneThread.start(); microphoneThread.start();
@@ -304,8 +359,23 @@ public class LocalTeamspeakClientSocket
awaitingCommands.clear(); awaitingCommands.clear();
} }
if (dropUnannounced) {
dropUnannounced = false;
// Timed out, or gave up on a command: nobody else tells the listeners.
Map<String, String> reason = new HashMap<>();
reason.put("reasonid", "3");
reason.put("reasonmsg", "connection lost");
DisconnectedEvent e = new DisconnectedEvent(reason);
try {
commandExecutionService.submit(() -> listeners.forEach(e::fire));
} catch (RejectedExecutionException ignored) {
// the listeners are gone already
}
}
serverId = null; serverId = null;
serverProperties = Collections.emptyMap(); serverProperties = Collections.emptyMap();
serverPublicKey = null;
remote = null; remote = null;
} }
@@ -380,6 +450,7 @@ public class LocalTeamspeakClientSocket
// Free stuff // Free stuff
serverId = null; serverId = null;
serverProperties = Collections.emptyMap(); serverProperties = Collections.emptyMap();
serverPublicKey = null;
synchronized (commandSendLock) { synchronized (commandSendLock) {
@@ -519,17 +590,31 @@ public class LocalTeamspeakClientSocket
return microphone; return microphone;
} }
/** Where the microphone's voice goes: null for our channel, else whisper packets to the target. */
public PacketBody1VoiceWhisper.WhisperTarget getWhisperTarget() {
return whisperTarget;
}
/**
* Sends the microphone's voice to {@code target} as whispers, or to our channel again with null.
* A voice session under way ends on its old route first.
*/
public void setWhisperTarget(PacketBody1VoiceWhisper.WhisperTarget target) {
this.whisperTarget = target;
}
public void setMicrophone(Microphone microphone) { public void setMicrophone(Microphone microphone) {
if (this.microphone != microphone) { if (this.microphone != microphone) {
this.microphone = microphone; this.microphone = microphone;
if (microphone != null && microphoneThread == null) { if (microphone != null && microphoneThread == null) {
microphoneThread = new HighPrecisionTimer( microphoneThread = new HighPrecisionTimer(
20, TICK_MS,
5F, // up to 100ms of drift/catchup 5F, // up to 100ms of drift/catchup
new MicrophoneTask() new MicrophoneTask()
); );
microphoneThread.setDaemon(true); microphoneThread.setDaemon(true);
microphoneThread.setPriority(Thread.MAX_PRIORITY);
if (getState() != ClientConnectionState.DISCONNECTED) if (getState() != ClientConnectionState.DISCONNECTED)
microphoneThread.start(); microphoneThread.start();
@@ -593,14 +678,24 @@ public class LocalTeamspeakClientSocket
} }
} }
private static final int TICK_MS = 20;
private class MicrophoneTask implements Runnable { private class MicrophoneTask implements Runnable {
private boolean wasSendingAudio = false; private boolean wasSendingAudio = false;
/** Where the voice session under way goes; null for the channel. */
private PacketBody1VoiceWhisper.WhisperTarget sendingTarget;
private byte sessionId = 1; private byte sessionId = 1;
private int flaggedPackets = 5; private int flaggedPackets = 5;
@Override @Override
public void run() { public void run() {
if (!isConnected()) return; if (!isConnected()) {
// Copies from a connection that is gone must not reach the next one.
voiceCopies.clear();
return;
}
sendDueVoiceCopies();
Microphone microphone; Microphone microphone;
@@ -609,54 +704,84 @@ public class LocalTeamspeakClientSocket
if ((microphone = LocalTeamspeakClientSocket.this.microphone) == null) if ((microphone = LocalTeamspeakClientSocket.this.microphone) == null)
return; return;
// Copies are sent from this tick, so the delay is best a whole number of ticks.
int copyDelay = microphone.getRedundancyDelay();
int copies = microphone.getRedundancyCopies();
voiceCopyCount = copies;
voiceCopyDelayNanos = copyDelay > 0 && copies > 0 ? copyDelay * 1_000_000L : 0;
PacketBody1VoiceWhisper.WhisperTarget target = whisperTarget;
if (wasSendingAudio && target != sendingTarget) {
// The listeners of the old route hear the end of what they were hearing.
if (!sendEnd(microphone)) return;
}
if (microphone.isMuted()) { if (microphone.isMuted()) {
// TODO // TODO
// Set a state and send a muted event // Set a state and send a muted event
} else if (microphone.isReady()) { } else if (microphone.isReady()) {
byte[] data = microphone.provide(); boolean live = microphone.isLiveCapture();
if (data.length <= 0) byte[] data;
return; do {
data = microphone.provide();
if (data.length <= 0) break;
PacketBody0Voice voice = new PacketBody0Voice(getRole().getOut()); try {
writePacket(voicePacket(target, microphone.getCodec(), data,
flaggedPackets > 0 && target == null ? sessionId : null));
voice.setCodecType(microphone.getCodec()); flaggedPackets--;
voice.setCodecData(data); wasSendingAudio = true;
if (flaggedPackets > 0) voice.setServerFlag0(sessionId); sendingTarget = target;
} catch (Exception e) {
try { // All we are really concerned about here is a disconnection event, in which case the loop
writePacket(voice); // will exit.
getExceptionHandler().accept(e);
flaggedPackets--; return;
wasSendingAudio = true; }
} catch (Exception e) { } while (live && microphone.isReady());
// All we are really concerned about here is a disconnection event, in which case the loop
// will exit.
getExceptionHandler().accept(e);
}
} else if (wasSendingAudio) { } else if (wasSendingAudio) {
PacketBody0Voice voice = new PacketBody0Voice(getRole().getOut()); sendEnd(microphone);
voice.setCodecType(microphone.getCodec());
voice.setCodecData(new byte[0]);
try {
writePacket(voice);
// reset decoder flag
flaggedPackets = 5;
sessionId++;
if (sessionId >= 8)
sessionId = 1;
wasSendingAudio = false;
} catch (Exception e) {
// All we are really concerned about here is a disconnection event, in which case the loop
// will exit.
getExceptionHandler().accept(e);
}
} }
} }
/** Ends the voice session on the route it went, which an empty packet does; false once disconnected. */
private boolean sendEnd(Microphone microphone) {
try {
writePacket(voicePacket(sendingTarget, microphone.getCodec(), new byte[0], null));
// reset decoder flag
flaggedPackets = 5;
sessionId++;
if (sessionId >= 8)
sessionId = 1;
wasSendingAudio = false;
return true;
} catch (Exception e) {
// All we are really concerned about here is a disconnection event, in which case the loop
// will exit.
getExceptionHandler().accept(e);
return false;
}
}
private PacketBody voicePacket(PacketBody1VoiceWhisper.WhisperTarget target, CodecType codec, byte[] data,
Byte flag) {
if (target == null) {
PacketBody0Voice voice = new PacketBody0Voice(getRole().getOut());
voice.setCodecType(codec);
voice.setCodecData(data);
if (flag != null) voice.setServerFlag0(flag);
return voice;
}
PacketBody1VoiceWhisper whisper = new PacketBody1VoiceWhisper(getRole().getOut());
whisper.setCodecType(codec);
whisper.setTarget(target);
whisper.setCodecData(data);
return whisper;
}
} }
private class ClientCommandResponse<T> private class ClientCommandResponse<T>
@@ -740,16 +865,39 @@ public class LocalTeamspeakClientSocket
return command; return command;
} }
public boolean ensureSent() /**
* Sends the command unless it already was. Its acknowledgement is awaited in the background: the reply
* proves delivery anyway, and this is often called from the packet handler thread, which must keep
* handling while resends go on. A command that never gets through fails and makes way for the next one.
*/
public void ensureSent()
throws IOException, TimeoutException { throws IOException, TimeoutException {
synchronized (sendLock) { synchronized (sendLock) {
if (!sent) { if (sent) return;
LocalTeamspeakClientSocket.this.writePacket(new PacketBody2Command(ProtocolRole.CLIENT, command)); sent = true;
sent = true; }
return true;
}
return false; CompletableFuture<Void> acknowledged;
try {
acknowledged = writePacketAsync(new PacketBody2Command(ProtocolRole.CLIENT, command));
} catch (IOException | TimeoutException | RuntimeException e) {
abandon(e);
throw e;
}
acknowledged.whenComplete((ignored, e) -> {
if (e != null) abandon(e);
});
}
private void abandon(Throwable cause) {
completeFailure(cause);
synchronized (commandSendLock) {
if (!awaitingCommands.remove(returnCode, this)) return; // answered after all
try {
sendNextCommand();
} catch (IOException | TimeoutException e) {
// that command failed as well, and made way in turn
}
} }
} }
} }
@@ -798,6 +946,25 @@ public class LocalTeamspeakClientSocket
return serverProperties; return serverProperties;
} }
public void setServerPublicKey(String serverPublicKey) {
this.serverPublicKey = serverPublicKey;
}
/**
* The virtual server's unique identifier, or null before the handshake. It is derived from
* the server's public key as a client's is from its own; the server tells a client no other
* way, as guests may not read it with <b>serverinfo</b>.
*/
public Uid getServerUid() {
String key = serverPublicKey;
if (key == null) return null;
try {
return new Uid(MessageDigest.getInstance("SHA-1").digest(key.getBytes(StandardCharsets.US_ASCII)));
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
/** The virtual server's name, or null if it was not announced. */ /** The virtual server's name, or null if it was not announced. */
public String getServerName() { public String getServerName() {
return serverProperties.get("virtualserver_name"); return serverProperties.get("virtualserver_name");
@@ -1291,34 +1458,34 @@ public class LocalTeamspeakClientSocket
disconnect(null); disconnect(null);
} }
private static PacketBody2Command clientDisconnect(String reason) {
SingleCommand command = new SingleCommand("clientdisconnect", ProtocolRole.CLIENT);
if (reason != null) {
command.add(new CommandSingleParameter("reasonid", "8"));
command.add(new CommandSingleParameter("reasonmsg", reason));
}
return new PacketBody2Command(ProtocolRole.CLIENT, command);
}
public void disconnect(String reason) public void disconnect(String reason)
throws throws
IOException, TimeoutException, IOException, TimeoutException,
ExecutionException, InterruptedException { ExecutionException, InterruptedException {
dropUnannounced = false;
try { try {
switch (getState()) { switch (getState()) {
case CONNECTING:
case RETRIEVING_DATA: case RETRIEVING_DATA:
waitForState(ClientConnectionState.CONNECTED, 10000L); // Still loading, possibly stuck: say goodbye, but don't wait on a server that may not answer.
writePacketAsync(clientDisconnect(reason));
break;
case CONNECTED: case CONNECTED:
if (reason == null) { // The server confirms by letting us go, and after that acknowledges nothing: if the
writePacket(new PacketBody2Command( // confirmation is lost, waiting for an ACK would only keep us resending until the give-up.
ProtocolRole.CLIENT, writePacketAsync(clientDisconnect(reason));
new SingleCommand("clientdisconnect", ProtocolRole.CLIENT)) try {
); waitForState(ClientConnectionState.DISCONNECTED, 5000L);
} else { } catch (TimeoutException ignored) {
writePacket(new PacketBody2Command(
ProtocolRole.CLIENT,
new SingleCommand(
"clientdisconnect", ProtocolRole.CLIENT,
new CommandSingleParameter("reasonid", "8"),
new CommandSingleParameter("reasonmsg", reason)
))
);
} }
waitForState(ClientConnectionState.DISCONNECTED, 30000L);
break; break;
} }
} finally { } finally {
@@ -0,0 +1,45 @@
package com.github.manevolent.ts3j.protocol.socket.client;
/**
* When to resend an unacknowledged packet and when to give up on it, as the official client
* (3.6.2) does it: the timeout is the mean round trip plus three standard deviations plus 50 ms
* over the last 20 samples (a flat 500 ms until there are 6), growing by 1.4x per resend.
*/
final class ResendTiming {
/** How long a packet may go unacknowledged before the connection counts as lost. */
static final long GIVE_UP_MS = 18_000L;
/** Resends after which the connection is dropped regardless of time. */
static final int MAX_RESENDS = 255;
private static final int WINDOW = 20;
private static final int MIN_SAMPLES = 6;
private static final int INITIAL_MS = 500;
private final long[] samples = new long[WINDOW];
private int count;
private int next;
/** Adds the round trip of a packet that was acknowledged without having been resent. */
synchronized void addSample(long rttMs) {
samples[next] = rttMs;
next = (next + 1) % WINDOW;
if (count < WINDOW) count++;
}
/** How long to wait for an acknowledgement after the given number of resends. */
synchronized long timeoutMs(int resends) {
double base = INITIAL_MS;
if (count >= MIN_SAMPLES) {
double sum = 0, sumSquares = 0;
for (int i = 0; i < count; i++) {
sum += samples[i];
sumSquares += (double) samples[i] * samples[i];
}
double mean = sum / count;
double deviation = Math.sqrt(Math.max(0, (sumSquares - mean * sum) / count));
base = (int) (mean + 3 * deviation + 50);
}
int timeout = (int) (base * Math.pow(1.4, resends));
return timeout < 15_001 ? timeout : 19_000;
}
}
@@ -64,8 +64,8 @@ public class HighPrecisionTimer extends Thread {
now = System.nanoTime(); now = System.nanoTime();
// Clamp the next target to the maximum "drift" allowed // After a stall, catch up at most the allowed number of ticks rather than all of them
if (nextTarget - now > maximumDriftInNanos) if (now - nextTarget > maximumDriftInNanos)
nextTarget = now - maximumDriftInNanos; nextTarget = now - maximumDriftInNanos;
if (sleepFor(nextTarget - now)) { if (sleepFor(nextTarget - now)) {
@@ -53,6 +53,10 @@ public class EncryptionTest extends TestCase {
byte[] packetBytes = transformation.encrypt(packet).array(); byte[] packetBytes = transformation.encrypt(packet).array();
transformation.decrypt(header, ByteBuffer.wrap(packetBytes), packet.getBody().getSize()); transformation.decrypt(header, ByteBuffer.wrap(packetBytes), packet.getBody().getSize());
// A resend encrypts the same packet again, under the same key and nonce.
byte[] resent = transformation.encrypt(packet).array();
assertTrue(java.util.Arrays.equals(packetBytes, resent));
} }
} }
@@ -0,0 +1,15 @@
package com.github.manevolent.ts3j;
import com.github.manevolent.ts3j.protocol.socket.client.LocalTeamspeakClientSocket;
import junit.framework.TestCase;
public class ServerUidTest extends TestCase {
/** A real server's handshake key, and the unique id the official client files its chat logs under. */
public void testDerivedFromTheHandshakeKey() {
LocalTeamspeakClientSocket client = new LocalTeamspeakClientSocket();
assertNull(client.getServerUid());
client.setServerPublicKey("MEwDAgcAAgEgAiEAtg1UQ4UpfiyTjrYPQcWV7Pa04/HTWr/viRhqEOg7+MQCIH/FqUKJDpBJDn/v01KOR+snSWlcoxOsfb2R8C02T3/z");
assertEquals("+Tyg2JtxE8vRNZp+JiUBnmBh0MY=", client.getServerUid().toBase64());
}
}
@@ -1,27 +1,47 @@
package com.github.manevolent.ts3j; package com.github.manevolent.ts3j;
import com.github.manevolent.ts3j.protocol.TS3DNS; import com.github.manevolent.ts3j.protocol.TS3DNS;
import com.github.manevolent.ts3j.util.Ts3Debugging;
import junit.framework.TestCase; import junit.framework.TestCase;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.SocketAddress; import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List; import java.util.List;
/** SRV answers are stubbed: the test must not depend on what the network resolves today. */
public class TS3DNSTest extends TestCase { public class TS3DNSTest extends TestCase {
public static void main(String[] args) throws Exception { @Override
new TS3DNSTest().testParser(); protected void tearDown() {
TS3DNS.setSrvLookup(null);
} }
public void testParser() throws Exception { public void testOrdersRecordsByPriorityThenWeight() throws Exception {
Ts3Debugging.setEnabled(true); TS3DNS.setSrvLookup(name -> {
assertEquals("_ts3._udp.voice.example.com", name);
return Arrays.asList("20 0 9989 backup.example.com.", "10 5 9988 b.example.com.",
"10 1 9987 a.example.com.");
});
List<InetSocketAddress> soaddr = TS3DNS.lookup("voice.teamspeak.com"); List<InetSocketAddress> addresses = TS3DNS.lookup("voice.example.com");
assertTrue(soaddr.size() > 0); assertEquals(3, addresses.size());
assertEquals("a.example.com", addresses.get(0).getHostString());
assertEquals(9987, addresses.get(0).getPort());
assertEquals("b.example.com", addresses.get(1).getHostString());
assertEquals("backup.example.com", addresses.get(2).getHostString());
}
for (SocketAddress socketAddress : soaddr) public void testNoRecordMeansTheHostIsNotFound() {
Ts3Debugging.debug(socketAddress); TS3DNS.setSrvLookup(name -> Collections.emptyList());
try {
TS3DNS.lookup("voice.example.com");
fail("expected UnknownHostException");
} catch (UnknownHostException expected) {
// the caller then connects to the address itself
} catch (Exception e) {
fail("unexpected " + e);
}
} }
} }
@@ -0,0 +1,41 @@
package com.github.manevolent.ts3j;
import com.github.manevolent.ts3j.enums.CodecType;
import com.github.manevolent.ts3j.protocol.ProtocolRole;
import com.github.manevolent.ts3j.protocol.header.ClientPacketHeader;
import com.github.manevolent.ts3j.protocol.packet.PacketBody1VoiceWhisper;
import junit.framework.TestCase;
import java.nio.ByteBuffer;
import java.util.Arrays;
/** A whisper a client sends: codec, then the channel and client counts and ids, then the voice. */
public class WhisperPacketTest extends TestCase {
public void testClientWhisperRoundTrip() {
PacketBody1VoiceWhisper.WhisperTargetMultiple target = new PacketBody1VoiceWhisper.WhisperTargetMultiple();
target.setChannelIds(new int[]{7, 9});
target.setClientIds(new int[]{3});
PacketBody1VoiceWhisper sent = new PacketBody1VoiceWhisper(ProtocolRole.CLIENT);
sent.setPacketId(42);
sent.setCodecType(CodecType.OPUS_VOICE);
sent.setTarget(target);
sent.setCodecData(new byte[]{1, 2, 3});
ByteBuffer buffer = ByteBuffer.allocate(sent.getSize());
sent.write(buffer);
assertEquals("the size covers exactly what is written", buffer.capacity(), buffer.position());
assertEquals(2 + 1 + 1 + 1 + 2 * 8 + 2 + 3, buffer.capacity());
buffer.flip();
PacketBody1VoiceWhisper read = new PacketBody1VoiceWhisper(ProtocolRole.CLIENT);
read.read(new ClientPacketHeader(), buffer);
PacketBody1VoiceWhisper.WhisperTargetMultiple readTarget =
(PacketBody1VoiceWhisper.WhisperTargetMultiple) read.getTarget();
assertEquals(42, read.getPacketId());
assertEquals(CodecType.OPUS_VOICE, read.getCodecType());
assertTrue(Arrays.equals(new int[]{7, 9}, readTarget.getChannelIds()));
assertTrue(Arrays.equals(new int[]{3}, readTarget.getClientIds()));
assertTrue(Arrays.equals(new byte[]{1, 2, 3}, read.getCodecData()));
}
}
@@ -0,0 +1,33 @@
package com.github.manevolent.ts3j.protocol.packet.handler.client;
import junit.framework.TestCase;
import java.math.BigInteger;
import java.util.Arrays;
public class PuzzleAnswerTest extends TestCase {
private static byte[] bytes(int length, int first) {
byte[] b = new byte[length];
Arrays.fill(b, (byte) 0x11);
b[0] = (byte) first;
return b;
}
/** Top bit set: toByteArray() gives 65 bytes, the first a sign byte. */
public void testDropsTheSignByte() {
byte[] answer = bytes(64, 0x80);
assertTrue(Arrays.equals(answer, LocalClientHandlerConnecting.unsigned64(new BigInteger(1, answer))));
}
public void testKeepsSixtyFourBytes() {
byte[] answer = bytes(64, 0x7f);
assertTrue(Arrays.equals(answer, LocalClientHandlerConnecting.unsigned64(new BigInteger(1, answer))));
}
/** A leading zero byte: toByteArray() gives 63 bytes, which used to fail the connect. */
public void testPadsAShortAnswerWithZeros() {
byte[] answer = bytes(64, 0x00);
answer[1] = 0x42;
assertTrue(Arrays.equals(answer, LocalClientHandlerConnecting.unsigned64(new BigInteger(1, answer))));
}
}