Compare commits
10
Commits
b335c2c511
...
4cc27db0e8
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4cc27db0e8 | ||
|
|
d89a02957a | ||
|
|
c47bbdf96c | ||
|
|
8273a27160 | ||
|
|
4aa9341ec4 | ||
|
|
5a5fb6baaf | ||
|
|
3625cc24cf | ||
|
|
2018c1c593 | ||
|
|
45cb8fd559 | ||
|
|
765bfb25fd |
+1
-1
@@ -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
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -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);
|
||||||
}
|
}
|
||||||
|
|||||||
+79
-3
@@ -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()) {
|
||||||
@@ -138,6 +196,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 +205,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 +226,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 +246,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 +266,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);
|
||||||
|
|||||||
+5
-4
@@ -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();
|
||||||
|
|||||||
+11
-13
@@ -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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,20 +86,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));
|
||||||
|
|||||||
+181
-104
@@ -1,5 +1,7 @@
|
|||||||
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.identity.Identity;
|
import com.github.manevolent.ts3j.identity.Identity;
|
||||||
import com.github.manevolent.ts3j.protocol.NetworkPacket;
|
import com.github.manevolent.ts3j.protocol.NetworkPacket;
|
||||||
@@ -52,6 +54,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 +79,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 +88,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<>();
|
||||||
@@ -177,8 +176,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 +251,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 +303,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 +373,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 +414,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
|
||||||
@@ -467,7 +538,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 +556,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 +623,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 +678,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 +834,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 +1007,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 +1057,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 +1076,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 +1110,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() {
|
||||||
|
|||||||
+97
-28
@@ -32,6 +32,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;
|
||||||
@@ -59,6 +62,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 +72,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 +99,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) {
|
||||||
@@ -144,7 +154,7 @@ public class LocalTeamspeakClientSocket
|
|||||||
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 +257,7 @@ public class LocalTeamspeakClientSocket
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new IOException("disconnected");
|
throw new EOFException("disconnected");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -283,6 +293,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 +315,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 +406,7 @@ public class LocalTeamspeakClientSocket
|
|||||||
// Free stuff
|
// Free stuff
|
||||||
serverId = null;
|
serverId = null;
|
||||||
serverProperties = Collections.emptyMap();
|
serverProperties = Collections.emptyMap();
|
||||||
|
serverPublicKey = null;
|
||||||
|
|
||||||
|
|
||||||
synchronized (commandSendLock) {
|
synchronized (commandSendLock) {
|
||||||
@@ -740,16 +767,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 +848,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 +1360,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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user