Archive incari-client (client, 26.3, clean)

This commit is contained in:
2026-11-28 00:54:38 -06:00
parent 7a6174687f
commit 12838e838c
2383 changed files with 280266 additions and 0 deletions
+13
View File
@@ -0,0 +1,13 @@
# net
- Only `platform-api`, Netty and the JDK. Never game types (`BoundaryTest`): the client's adapters
(`incari.client.net`) hand it what it needs.
- Compiled into the browser build: no reflection, no blocking waits, no JDK APIs TeaVM lacks
(that's why `WebSocketUrl` parses by hand instead of using `java.net.URI`).
- Keep the game's pipeline handler names ("splitter", "prepender", "decoder", "encoder"...)
working: the game, Via (`:via`) and the Eagler stage place handlers relative to them.
- Eagler (`incari.net.eagler`): written from the wire protocol. Never copy EaglerXServer's code
(it's "All Rights Reserved"); reading it to learn the protocol is fine. A format change must
still match its converters byte for byte (ADR 0016 says how that was checked).
- Networking changes need a human reviewer (`.github/CODEOWNERS`).
- Test: `./gradlew :net:check`; end to end, `./gradlew :app-desktop:smokeServer` (README).
+68
View File
@@ -0,0 +1,68 @@
# net: the transport under the game's pipeline
How the game's Netty pipeline reaches a server (ADR 0009): TCP on the desktop, or WebSocket, the
only way out of a browser. The game's own protocol code runs unchanged on top. Every WebSocket
server is treated as an Eagler server, so Eagler's client side lives here too (ADR 0016, 0019).
Version translation is `:via`'s job.
## Code map
| Where | What |
| --- | --- |
| `NetConnectionChannel` | A Netty channel over a platform connection. A connect that neither opens nor fails gives up after `CONNECT_TIMEOUT_MILLIS` (30 s by default, as Netty's socket channels) |
| `WebSocketUrl`, `WebSocketAddress` | `ws://`/`wss://` addresses, parsed as a browser reads them |
| `ConnectionReport` | How a channel's connection went (timing, traffic, who closed it, the platform's `details()`), for Connection Details on the disconnection screen |
| `MessageFraming` | One packet per WebSocket message, replacing length-prefix framing under the same handler names |
| `eagler.EaglerHandshake` | The Eagler stage: protocol V5, then answers the game's login in the server's place, then passes packets |
| `eagler.EaglerLogin`, `EaglerMessages`, `EaglerTextures` | Login contents; Eagler's own messages; skin and cape formats |
| `eagler.EaglerQuery` | The MOTD query the server list uses |
| `eagler.EaglerPassword` | Auth plugins' password methods |
| `relay.*` | Joining a world shared through an Eagler relay, over a WebRTC data channel |
| `wisp.WispConnection`, `WispAddress` | A Java server's TCP port through a Wisp proxy (Wispcraft, ADR 0065), with its SRV lookup |
| `tls.TlsConnection`, `Transport` | TLS 1.2/1.3 (Bouncy Castle, non-blocking) over a socket or a Wisp stream, for sign-in (ADR 0070) |
| `tls.CertificateChain`, `TrustAnchors` | The server's chain against four pinned roots: host name, dates, CA rules, signatures |
| `https.HttpsClient`, `HttpRequest`, `ResponseParser` | One HTTPS/1.1 request per connection, to an allow-list of hosts, sizes capped |
| `msa.MicrosoftSignIn` | Microsoft sign-in as the launcher: device code, Xbox Live, XSTS, Minecraft token and profile; session joins; chat keys. A `SignInException` is `temporary()` when the request didn't get through or the service answered 5xx/429: the screen keeps polling, and a failed refresh keeps the account |
| `msa.MicrosoftAccount`, `MicrosoftEndpoints` | The signed-in account (tokens never printed); the client id, URLs and allowed hosts |
## Invariants
- **No game types**, only `platform-api` and Netty (`BoundaryTest`). `client`'s `incari.client.net`
is the game-facing half.
- **The game's handler names survive**, so everything added relative to "splitter" and
"prepender" works on both transports.
- **Bytes reach the pipeline only on its event loop.**
- **The Eagler stage speaks the server's version.** It sits below framing and Via.
- **Nothing of EaglerXServer's code** (it's All Rights Reserved). The client side is written from
the wire protocol.
- **Sign-in never logs a token** and reaches only `MicrosoftEndpoints.HOSTS`, over pinned TLS.
## How to test
```sh
./gradlew :net:check
INCARI_LIVE=1 ./gradlew :net:test --tests '*LiveEndpointsTest' # the real hosts' TLS; signs nobody in
```
`TlsConnectionTest` runs real handshakes against the JDK's TLS server on localhost. A whole
sign-in needs a Microsoft account that owns the game: Edit Profile → Microsoft Sign-In, then an
online-mode server (`online-mode=true`) directly or through `wisp-js-server` (below).
End to end against a local vanilla server behind `tools/wsbridge` (a stand-in Eagler proxy):
```sh
java -jar server.jar nogui # server-port=25581, online-mode=false, player opped
./gradlew :tools:wsbridge:run --args="--listen 8816 --target 127.0.0.1:25581"
./gradlew :app-desktop:smokeServer -Pincari.server=ws://127.0.0.1:8816
```
The report (`run/smoke-server/incari-smoke/report.txt`) covers ping, join, chat, the Nether and
back, and reconnecting. Against a real EaglerXServer, use its address; `smokeSkinA` with
`smokeSkinB` checks skins both ways (setup in ADR 0016). In the browser: `server-join.steps`.
The same server through a Wisp proxy (ADR 0065), with `@mercuryworkshop/wisp-js` from npm:
```sh
wisp-js-server --port 6001 -O '{"allow_private_ips":true,"allow_loopback_ips":true}'
./gradlew :app-desktop:smokeServer -Pincari.server=127.0.0.1:25581 -Pincari.wisp=ws://127.0.0.1:6001/
```
+36
View File
@@ -0,0 +1,36 @@
plugins {
`java-library`
}
// The game's network transport under its Netty pipeline (ADR 0009): the Netty channel over the
// platform's connections, WebSocket addresses, and message framing. No game types.
dependencies {
api(project(":platform-api"))
// Compile against the Netty version the game ships (libs.versions.toml). At run time the game's
// own copies are on the classpath, so these are compile-only.
compileOnly(libs.netty.buffer)
compileOnly(libs.netty.transport)
compileOnly(libs.netty.codec.base)
// TLS for Microsoft sign-in (incari.net.tls, ADR 0070): Bouncy Castle's lightweight TLS client,
// which runs over any NetConnection, a Wisp stream included. Ships in both builds.
implementation(libs.bctls)
implementation(libs.bcutil)
implementation(libs.bcprov)
// Microsoft's, Xbox's and Mojang's JSON through Gson's tree API (no reflection). The game ships
// Gson, so this is compile-only, as in :online.
compileOnly(libs.gson)
testImplementation(libs.gson)
testImplementation(libs.bcpkix)
testImplementation(libs.netty.buffer)
testImplementation(libs.netty.transport)
testImplementation(libs.netty.codec.base)
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testImplementation(libs.assertj)
testImplementation(libs.archunit)
testRuntimeOnly(libs.junit.launcher)
}
@@ -0,0 +1,212 @@
package incari.net;
import incari.net.wisp.WispAddress;
import incari.platform.api.net.NetConnection;
import java.net.InetSocketAddress;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.jspecify.annotations.Nullable;
/**
* How one {@link NetConnectionChannel} went: when it opened and closed, which side closed it, the
* traffic each way and the longest wait for the server, plus what the platform knows ({@link
* NetConnection#details}). The disconnect screen shows it, so a player can report a dropped
* connection with more than its last error.
*
* <p>Written on the channel's event loop only (one writer); read from any thread. Times are {@link
* System#nanoTime} values, passed in so tests choose them.
*/
public final class ConnectionReport {
/** One row: a label, its value, and what it means for a player. */
public record Line(String label, String value, String help) {}
private enum ClosedBy {
CLIENT,
REMOTE
}
private final String server;
private final String transport;
private final boolean messages;
private volatile @Nullable NetConnection connection;
private volatile long connectedAt = -1;
private volatile long closedAt = -1;
private volatile long closedAtMillis;
private volatile @Nullable ClosedBy closedBy;
private volatile @Nullable String error;
private volatile long lastIn = -1;
private volatile long lastOut = -1;
private volatile long longestWaitIn;
private volatile long countIn;
private volatile long bytesIn;
private volatile long countOut;
private volatile long bytesOut;
ConnectionReport(InetSocketAddress address) {
if (address instanceof WebSocketAddress webSocket) {
this.server = webSocket.url().toString();
this.transport = "WebSocket";
this.messages = true;
} else if (address instanceof WispAddress wisp) {
this.server = wisp.getHostString() + ":" + wisp.getPort();
this.transport = "Wisp proxy " + wisp.proxy();
this.messages = true;
} else {
this.server = address.getHostString() + ":" + address.getPort();
this.transport = address.getClass() == InetSocketAddress.class ? "TCP" : "Other";
this.messages = false;
}
}
void opening(NetConnection connection) {
this.connection = connection;
}
void connected(long now) {
connectedAt = now;
}
@SuppressWarnings("NonAtomicVolatileUpdate") // one writer: the channel's event loop
void received(long now, int bytes) {
long previous = lastIn >= 0 ? lastIn : connectedAt;
if (previous >= 0) {
longestWaitIn = Math.max(longestWaitIn, now - previous);
}
lastIn = now;
countIn++;
bytesIn += bytes;
}
@SuppressWarnings("NonAtomicVolatileUpdate") // one writer: the channel's event loop
void sent(long now, int bytes) {
lastOut = now;
countOut++;
bytesOut += bytes;
}
/** This client closed the channel; nothing if the other side already had. */
void closing(long now) {
end(now, ClosedBy.CLIENT, null);
}
/** The platform says the connection closed, from the far side or the network. */
void closedRemotely(long now, @Nullable Throwable cause) {
end(now, ClosedBy.REMOTE, cause);
}
private void end(long now, ClosedBy by, @Nullable Throwable cause) {
if (closedBy != null) {
return;
}
closedAt = now;
closedAtMillis = System.currentTimeMillis();
if (cause != null) {
String message = cause.getMessage();
error = cause.getClass().getSimpleName() + (message == null ? "" : ": " + message);
}
closedBy = by;
}
/** The rows, as of {@code now} if the connection is still open. */
public List<Line> lines(long now) {
List<Line> lines = new ArrayList<>();
long end = closedAt >= 0 ? closedAt : now;
boolean closed = closedBy != null;
lines.add(new Line("Server", server, "The address this connection went to."));
lines.add(new Line("Connection", transport, "How the game reached the server."));
lines.add(new Line(
"Closed at",
closed ? Instant.ofEpochMilli(closedAtMillis).truncatedTo(ChronoUnit.SECONDS) + " (UTC)" : "Still open",
"Match this against the server's logs."));
lines.add(new Line(
"Connected for",
connectedAt >= 0 ? duration(end - connectedAt) : "Never connected",
"From the connection opening to it closing."));
ClosedBy by = closedBy;
lines.add(new Line(
"Closed by",
by == null ? "Still open" : by == ClosedBy.CLIENT ? "This game" : "The server or the network",
"Which side ended the connection. \"The server or the network\" covers anything between you"
+ " and the server: a proxy, a filter, Wi-Fi."));
String failure = error;
lines.add(new Line(
"Error", failure != null ? failure : "None", "What the browser or system said when it closed."));
lines.add(new Line(
"Last received",
ago(lastIn, end, closed),
"How long before the close the server last sent something. Long means it went quiet first."));
lines.add(new Line(
"Last sent", ago(lastOut, end, closed), "How long before the close this game last sent something."));
lines.add(new Line(
"Longest wait",
countIn > 0 ? duration(longestWaitIn) : "None",
"The longest gap between two things from the server. Several seconds means lag spikes or"
+ " the game freezing."));
lines.add(new Line("Received", traffic(bytesIn, countIn), "Everything the server sent."));
lines.add(new Line("Sent", traffic(bytesOut, countOut), "Everything this game sent."));
NetConnection current = connection;
if (current != null) {
for (Map.Entry<String, String> detail : current.details().entrySet()) {
lines.add(new Line(detail.getKey(), detail.getValue(), ""));
}
}
return lines;
}
/** The rows as text to paste into a report. */
public String asText(long now) {
StringBuilder text = new StringBuilder();
for (Line line : lines(now)) {
text.append(line.label()).append(": ").append(line.value()).append('\n');
}
return text.toString();
}
private static String ago(long at, long end, boolean closed) {
if (at < 0) {
return "Never";
}
return duration(end - at) + (closed ? " before it closed" : " ago");
}
private String traffic(long bytes, long count) {
return messages ? bytes(bytes) + " in " + count + (count == 1 ? " message" : " messages") : bytes(bytes);
}
static String duration(long nanos) {
long millis = TimeUnit.NANOSECONDS.toMillis(Math.max(0, nanos));
if (millis < 1000) {
return millis + " ms";
}
if (millis < 60_000) {
return (millis / 1000) + "." + (millis % 1000 / 100) + " s";
}
long seconds = millis / 1000;
if (seconds < 3600) {
return (seconds / 60) + " min " + (seconds % 60) + " s";
}
return (seconds / 3600) + " h " + (seconds % 3600 / 60) + " min";
}
static String bytes(long bytes) {
if (bytes < 1024) {
return bytes + " B";
}
double kib = bytes / 1024.0;
if (kib < 1024) {
return oneDecimal(kib) + " KB";
}
return oneDecimal(kib / 1024) + " MB";
}
private static String oneDecimal(double value) {
long tenths = Math.round(value * 10);
return (tenths / 10) + "." + (tenths % 10);
}
}
@@ -0,0 +1,77 @@
package incari.net;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.CorruptedFrameException;
import io.netty.handler.codec.TooLongFrameException;
import java.util.function.IntConsumer;
import org.jspecify.annotations.Nullable;
/**
* Packet framing for a WebSocket: one packet per binary message, as Eagler servers expect. Over
* TCP the game prefixes each packet with its length (a VarInt) and splits the byte stream on those
* lengths; a WebSocket already delivers whole messages, so both steps go away.
*
* <p>{@link #install} swaps the stream framing handlers for these, keeping their names. The game
* places later handlers (compression, encryption) relative to those names, so they keep working,
* and so will the Eagler handshake and the Via bridge when they join the pipeline.
*/
public final class MessageFraming {
/** The largest packet the game's own framing allows: a length that fits a 21-bit VarInt. */
public static final int MAX_PACKET_BYTES = (1 << 21) - 1;
private MessageFraming() {}
/**
* Replaces the handlers named {@code splitterName} (the length-prefix decoder) and {@code
* prependerName} (the length-prefix encoder) with message framing, under the same names.
*
* @param received told each packet's size in bytes, for the game's bandwidth chart; may be null
*/
public static void install(
ChannelPipeline pipeline, String splitterName, String prependerName, @Nullable IntConsumer received) {
pipeline.replace(splitterName, splitterName, new Decoder(received));
pipeline.replace(prependerName, prependerName, new Encoder());
}
/** Passes each message on as one packet, after checking its size. */
static final class Decoder extends ChannelInboundHandlerAdapter {
private final @Nullable IntConsumer received;
Decoder(@Nullable IntConsumer received) {
this.received = received;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object message) {
if (message instanceof ByteBuf packet) {
int size = packet.readableBytes();
if (size == 0) {
packet.release();
throw new CorruptedFrameException("Empty WebSocket message");
}
if (size > MAX_PACKET_BYTES) {
packet.release();
throw new TooLongFrameException("A packet of " + size + " bytes is over the game's limit");
}
if (received != null) {
received.accept(size);
}
}
ctx.fireChannelRead(message);
}
}
/**
* Writes each packet as it is: the channel sends every buffer as one message. It exists so the
* handlers the game places before or after the prepender find it.
*/
@ChannelHandler.Sharable
static final class Encoder extends ChannelOutboundHandlerAdapter {}
}
@@ -0,0 +1,451 @@
package incari.net;
import incari.net.wisp.WispAddress;
import incari.net.wisp.WispConnection;
import incari.platform.api.net.NetConnection;
import incari.platform.api.net.PlatformNetwork;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.AbstractChannel;
import io.netty.channel.ChannelConfig;
import io.netty.channel.ChannelId;
import io.netty.channel.ChannelMetadata;
import io.netty.channel.ChannelOutboundBuffer;
import io.netty.channel.ChannelPromise;
import io.netty.channel.ConnectTimeoutException;
import io.netty.channel.DefaultChannelConfig;
import io.netty.channel.EventLoop;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.jspecify.annotations.Nullable;
/**
* A Netty client channel over one of the platform's connections ({@code PlatformNetwork}), so the
* game's own pipeline (compression, packets) runs unchanged over a TCP socket on the desktop or a
* WebSocket anywhere. Connecting to a {@link WebSocketAddress} opens a WebSocket; each buffer the
* pipeline writes is then one message, and each message arrives as one buffer.
*
* <p>It registers no I/O with its event loop: the platform delivers bytes on its own thread, and
* the channel hops onto the event loop before touching the pipeline. So it runs on any event loop.
*/
public abstract class NetConnectionChannel extends AbstractChannel {
private static final ChannelMetadata METADATA = new ChannelMetadata(false);
/** The connection opened (an {@link #inbox} entry). */
private static final Object CONNECTED = new Object();
private static final AtomicLong NEXT_ID = new AtomicLong();
private enum State {
OPEN,
CONNECTING,
ACTIVE,
CLOSED
}
private final ChannelConfig config = new DefaultChannelConfig(this);
/** Bytes that arrived while the pipeline wasn't reading (auto-read off). Event loop only. */
private final Queue<ByteBuf> unread = new ArrayDeque<>();
/**
* What the platform reported, in order, for the event loop to take in one task: a {@link ByteBuf},
* {@link #CONNECTED} or a {@link Closed}. The browser hands over a frame's messages at once, and a
* task each cost a wake-up of the loop and a read-complete through the pipeline per message.
*/
private final Queue<Object> inbox = new ConcurrentLinkedQueue<>();
/** Whether a task to drain {@link #inbox} is queued on the event loop and hasn't started yet. */
private final AtomicBoolean drainQueued = new AtomicBoolean();
private volatile State state = State.OPEN;
private volatile @Nullable NetConnection connection;
private volatile @Nullable InetSocketAddress remoteAddress;
private @Nullable ChannelPromise connectPromise;
/**
* Gives up on a connect that neither opens nor fails ({@code CONNECT_TIMEOUT_MILLIS}, 30 s by
* default, as Netty's socket channels do): a server behind a firewall that drops packets would
* otherwise leave "Connecting to the server" up for as long as the browser waits. Event loop only.
*/
private @Nullable ScheduledFuture<?> connectTimeout;
/** Whether the pipeline asked for data (Netty's read()); event loop only. */
private boolean readRequested;
/** How this connection went, from its connect on; written on the event loop. */
private volatile @Nullable ConnectionReport report;
// The config only keeps a reference to the channel; it reads nothing from it while constructed.
@SuppressWarnings("this-escape")
protected NetConnectionChannel() {
super(null);
}
/**
* Opens the platform connection to {@code remote}, usually with {@link #openOn}. Called once, on
* the event loop; must return at once.
*/
protected abstract NetConnection open(InetSocketAddress remote, NetConnection.Listener listener);
/**
* {@link #open} on a platform: a WebSocket for a {@link WebSocketAddress}, a stream through a Wisp
* proxy for a {@link WispAddress}, a TCP socket otherwise.
*/
protected static NetConnection openOn(
final PlatformNetwork network, final InetSocketAddress remote, final NetConnection.Listener listener) {
if (remote instanceof WebSocketAddress webSocket) {
return network.openWebSocket(webSocket.url().toString(), listener);
}
if (remote instanceof WispAddress wisp) {
return WispConnection.open(network, wisp, listener);
}
return network.connect(remote.getHostString(), remote.getPort(), listener);
}
/**
* A plain counter: Netty's default id is built from the machine's MAC address and process id,
* which a page can't read (its lookup would fail in the browser build).
*/
@Override
protected ChannelId newId() {
return new ConnectionId(NEXT_ID.incrementAndGet());
}
/** How this connection went (for the disconnect screen); null before it starts connecting. */
public @Nullable ConnectionReport report() {
return this.report;
}
@Override
public ChannelConfig config() {
return this.config;
}
@Override
public boolean isOpen() {
return this.state != State.CLOSED;
}
@Override
public boolean isActive() {
return this.state == State.ACTIVE;
}
@Override
public ChannelMetadata metadata() {
return METADATA;
}
@Override
protected AbstractUnsafe newUnsafe() {
return new ConnectionUnsafe();
}
@Override
protected boolean isCompatible(final EventLoop loop) {
return true;
}
@Override
protected @Nullable SocketAddress localAddress0() {
return null;
}
@Override
protected @Nullable SocketAddress remoteAddress0() {
return this.remoteAddress;
}
@Override
protected void doBind(final SocketAddress localAddress) {
throw new UnsupportedOperationException("Platform connections can't choose a local address");
}
@Override
protected void doDisconnect() {
this.doClose();
}
/** The connect took too long: fails it and closes the connection still opening. Event loop only. */
private void onConnectTimeout(final ChannelPromise promise, final int millis) {
this.connectTimeout = null;
// A channel connects once: if this connect is still pending, the promise is this one.
if (this.connectPromise == null || this.state != State.CONNECTING) {
return;
}
this.connectPromise = null;
promise.tryFailure(new ConnectTimeoutException(
"Connection timed out after " + (millis / 1000) + " seconds: " + this.remoteAddress));
if (this.isOpen()) {
this.unsafe().close(this.unsafe().voidPromise());
}
}
private void cancelConnectTimeout() {
ScheduledFuture<?> timeout = this.connectTimeout;
this.connectTimeout = null;
if (timeout != null) {
timeout.cancel(false);
}
}
@Override
protected void doClose() {
this.cancelConnectTimeout();
ConnectionReport stats = this.report;
if (stats != null) {
stats.closing(System.nanoTime());
}
this.state = State.CLOSED;
NetConnection current = this.connection;
if (current != null) {
current.close();
}
ByteBuf pending;
while ((pending = this.unread.poll()) != null) {
pending.release();
}
}
@Override
protected void doBeginRead() {
this.readRequested = true;
this.deliverUnread();
}
@Override
protected void doWrite(final ChannelOutboundBuffer outbound) {
NetConnection current = this.connection;
while (true) {
Object message = outbound.current();
if (message == null) {
if (current != null) {
current.flush();
}
return;
}
if (message instanceof ByteBuf buffer && current != null) {
// The platform keeps the bytes it's given; copy them out of Netty's pooled buffer.
// One buffer is one WebSocket message: the framing handlers write whole packets.
ByteBuffer copy = ByteBuffer.allocate(buffer.readableBytes());
buffer.getBytes(buffer.readerIndex(), copy);
copy.flip();
ConnectionReport stats = this.report;
if (stats != null) {
stats.sent(System.nanoTime(), copy.remaining());
}
current.send(copy);
outbound.remove();
} else {
outbound.remove(
new UnsupportedOperationException("Can't write " + message + " to a platform connection"));
}
}
}
private void deliverUnread() {
boolean delivered = false;
while (this.readRequested && !this.unread.isEmpty()) {
ByteBuf data = this.unread.remove();
this.pipeline().fireChannelRead(data);
delivered = true;
if (!this.config.isAutoRead()) {
// Without auto-read, each read() asks for one batch.
this.readRequested = false;
}
}
if (delivered) {
this.pipeline().fireChannelReadComplete();
}
}
private final class ConnectionUnsafe extends AbstractUnsafe {
@Override
public void connect(
final SocketAddress remote, final @Nullable SocketAddress local, final ChannelPromise promise) {
if (!promise.setUncancellable() || !this.ensureOpen(promise)) {
return;
}
if (NetConnectionChannel.this.state != State.OPEN) {
promise.setFailure(new IllegalStateException("Already connecting or connected"));
return;
}
if (!(remote instanceof InetSocketAddress address)) {
promise.setFailure(new UnsupportedOperationException("Can't connect to " + remote));
return;
}
NetConnectionChannel.this.state = State.CONNECTING;
NetConnectionChannel.this.remoteAddress = address;
NetConnectionChannel.this.connectPromise = promise;
ConnectionReport stats = new ConnectionReport(address);
NetConnectionChannel.this.report = stats;
int millis = NetConnectionChannel.this.config.getConnectTimeoutMillis();
if (millis > 0) {
NetConnectionChannel.this.connectTimeout = NetConnectionChannel.this
.eventLoop()
.schedule(
() -> NetConnectionChannel.this.onConnectTimeout(promise, millis),
millis,
TimeUnit.MILLISECONDS);
}
NetConnection opened = NetConnectionChannel.this.open(address, new EventLoopListener());
stats.opening(opened);
NetConnectionChannel.this.connection = opened;
}
}
/** A channel's id: its number among this process's platform connections. */
private record ConnectionId(long number) implements ChannelId {
private static final long serialVersionUID = 1L;
@Override
public String asShortText() {
return Long.toHexString(number);
}
@Override
public String asLongText() {
return "incari-" + asShortText();
}
@Override
public int compareTo(final ChannelId other) {
if (other instanceof ConnectionId that) {
return Long.compare(number, that.number);
}
return asLongText().compareTo(other.asLongText());
}
@Override
public String toString() {
return asShortText();
}
}
/** Moves the platform's callbacks onto the channel's event loop, where Netty expects them. */
private final class EventLoopListener implements NetConnection.Listener {
@Override
public void connected() {
NetConnectionChannel.this.post(CONNECTED);
}
@Override
public void received(final ByteBuffer data) {
NetConnectionChannel.this.post(Unpooled.wrappedBuffer(data));
}
@Override
public void closed(final @Nullable Throwable cause) {
NetConnectionChannel.this.post(new Closed(cause));
}
}
/** How the connection closed (an {@link #inbox} entry). */
private record Closed(@Nullable Throwable cause) {}
/** Queues a platform event; the first since the last drain asks the event loop for one. Any thread. */
private void post(final Object event) {
this.inbox.add(event);
if (this.drainQueued.compareAndSet(false, true)) {
this.eventLoop().execute(this::drainInbox);
}
}
/**
* Takes in everything the platform reported, in order: reads go to the pipeline together, with
* one read-complete for each run of them. Event loop only.
*/
private void drainInbox() {
// Cleared first: an event posted from now on either is taken below or queues another drain.
this.drainQueued.set(false);
boolean reading = false;
Object event;
while ((event = this.inbox.poll()) != null) {
if (event instanceof ByteBuf data) {
reading |= this.onReceived(data);
continue;
}
if (reading) {
this.deliverUnread();
reading = false;
}
if (event == CONNECTED) {
this.onConnected();
} else if (event instanceof Closed closed) {
this.onClosed(closed.cause());
}
}
if (reading) {
this.deliverUnread();
}
}
private void onConnected() {
this.cancelConnectTimeout();
ChannelPromise promise = this.connectPromise;
this.connectPromise = null;
if (this.state != State.CONNECTING || promise == null) {
return;
}
this.state = State.ACTIVE;
ConnectionReport stats = this.report;
if (stats != null) {
stats.connected(System.nanoTime());
}
if (promise.trySuccess()) {
this.pipeline().fireChannelActive();
} else {
// The connect was given up on (timed out, cancelled) while it was opening.
this.unsafe().close(this.unsafe().voidPromise());
}
}
/** Holds the bytes for the pipeline; true if they're to be delivered (the channel is active). */
private boolean onReceived(final ByteBuf data) {
if (this.state != State.ACTIVE) {
data.release();
return false;
}
ConnectionReport stats = this.report;
if (stats != null) {
stats.received(System.nanoTime(), data.readableBytes());
}
this.unread.add(data);
if (this.config.isAutoRead()) {
this.readRequested = true;
}
return true;
}
private void onClosed(final @Nullable Throwable cause) {
this.cancelConnectTimeout();
ConnectionReport stats = this.report;
if (stats != null) {
// Before the pipeline hears of it: the game closes the channel in answer, which isn't
// this game closing it.
stats.closedRemotely(System.nanoTime(), cause);
}
ChannelPromise promise = this.connectPromise;
this.connectPromise = null;
if (promise != null) {
InetSocketAddress address = this.remoteAddress;
ConnectException failure = new ConnectException("Couldn't connect to " + address);
if (cause != null) {
failure.initCause(cause);
}
promise.tryFailure(failure);
} else if (cause != null && this.state == State.ACTIVE) {
this.pipeline().fireExceptionCaught(cause);
}
if (this.isOpen()) {
this.unsafe().close(this.unsafe().voidPromise());
}
}
}
@@ -0,0 +1,46 @@
package incari.net;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
/**
* A server reached through a WebSocket, as the socket address the game's connection code passes
* around. The game treats it like any other {@link InetSocketAddress} (its host name goes into the
* handshake packet), while {@link NetConnectionChannel} sees the URL it stands for and opens a
* WebSocket instead of a TCP socket.
*
* <p>No DNS lookup ever happens here: the platform's WebSocket resolves the host itself. The
* {@link #getAddress() address} is a placeholder (0.0.0.0) carrying the host name, since an
* unresolved {@code InetSocketAddress} can't be subclassed. Never connect to it as an IP.
*/
public final class WebSocketAddress extends InetSocketAddress {
private static final long serialVersionUID = 1L;
private final WebSocketUrl url;
public WebSocketAddress(WebSocketUrl url) {
super(placeholder(url.host()), url.port());
this.url = url;
}
/** The URL the WebSocket connects to. */
public WebSocketUrl url() {
return url;
}
@Override
public String toString() {
return url.toString();
}
private static InetAddress placeholder(String host) {
try {
// Only checks the array's length; resolves nothing.
return InetAddress.getByAddress(host, new byte[4]);
} catch (UnknownHostException e) {
throw new IllegalStateException(e);
}
}
}
@@ -0,0 +1,202 @@
package incari.net;
import java.io.Serializable;
import java.util.Locale;
import org.jspecify.annotations.Nullable;
/**
* A server address written as a WebSocket URL, {@code ws://host[:port][/path]} or {@code wss://...}:
* how players name a server the browser can reach. Parsed by hand rather than with {@link
* java.net.URI}, so that it behaves the same in the browser build, and so that what it accepts is
* exactly what a browser's {@code WebSocket} constructor will: no user info, no fragment.
*
* @param secure whether it's {@code wss://} (TLS)
* @param host a host name, IPv4 literal or IPv6 literal (without brackets)
* @param port the TCP port, the scheme's default (80 or 443) if the URL gives none
* @param path the path and query, at least {@code "/"}
*/
public record WebSocketUrl(boolean secure, String host, int port, String path) implements Serializable {
private static final long serialVersionUID = 1L;
private static final String WS = "ws://";
private static final String WSS = "wss://";
public WebSocketUrl {
if (host.isEmpty()) {
throw new IllegalArgumentException("A WebSocket URL needs a host");
}
if (port < 1 || port > 65535) {
throw new IllegalArgumentException("Port out of range: " + port);
}
if (!path.startsWith("/")) {
throw new IllegalArgumentException("A path starts with /: " + path);
}
}
/** Whether {@code text} is meant as a WebSocket URL (by its scheme), valid or not. */
public static boolean isWebSocketUrl(@Nullable String text) {
if (text == null) {
return false;
}
String lower = text.strip().toLowerCase(Locale.ROOT);
return lower.startsWith(WS) || lower.startsWith(WSS);
}
/** Parses {@code text}, or returns null if it isn't a valid WebSocket URL. */
public static @Nullable WebSocketUrl tryParse(@Nullable String text) {
if (text == null || !isWebSocketUrl(text)) {
return null;
}
try {
return parse(text);
} catch (IllegalArgumentException e) {
return null;
}
}
/**
* Parses a WebSocket URL.
*
* @throws IllegalArgumentException if it isn't one, with the reason
*/
public static WebSocketUrl parse(String text) {
String url = text.strip();
String lower = url.toLowerCase(Locale.ROOT);
boolean secure;
String rest;
if (lower.startsWith(WSS)) {
secure = true;
rest = url.substring(WSS.length());
} else if (lower.startsWith(WS)) {
secure = false;
rest = url.substring(WS.length());
} else {
throw new IllegalArgumentException("Not a ws:// or wss:// URL: " + text);
}
int authorityEnd = firstOf(rest, "/?#");
String authority = rest.substring(0, authorityEnd);
String path = pathOf(rest.substring(authorityEnd));
if (authority.indexOf('@') >= 0) {
throw new IllegalArgumentException("User names and passwords aren't allowed in a server address");
}
String host;
String portText = null;
if (authority.startsWith("[")) {
int close = authority.indexOf(']');
if (close < 0) {
throw new IllegalArgumentException("Unclosed [ in " + text);
}
host = authority.substring(1, close);
String after = authority.substring(close + 1);
if (!after.isEmpty()) {
if (!after.startsWith(":")) {
throw new IllegalArgumentException("Unexpected text after ] in " + text);
}
portText = after.substring(1);
}
checkIpv6(host);
} else {
int colon = authority.indexOf(':');
if (colon >= 0 && authority.indexOf(':', colon + 1) >= 0) {
throw new IllegalArgumentException("An IPv6 address must be in brackets: " + text);
}
host = colon < 0 ? authority : authority.substring(0, colon);
portText = colon < 0 ? null : authority.substring(colon + 1);
checkHostName(host);
}
int port = portText == null ? (secure ? 443 : 80) : parsePort(portText);
return new WebSocketUrl(secure, host, port, path);
}
/** Whether the port is the scheme's default, so the URL needn't spell it out. */
public boolean hasDefaultPort() {
return port == (secure ? 443 : 80);
}
/** The URL in canonical form: lower-case scheme, bracketed IPv6, no default port. */
@Override
public String toString() {
StringBuilder out = new StringBuilder(secure ? WSS : WS);
if (host.indexOf(':') >= 0) {
out.append('[').append(host).append(']');
} else {
out.append(host);
}
if (!hasDefaultPort()) {
out.append(':').append(port);
}
return out.append(path).toString();
}
private static int firstOf(String text, String characters) {
for (int i = 0; i < text.length(); i++) {
if (characters.indexOf(text.charAt(i)) >= 0) {
return i;
}
}
return text.length();
}
/** The path and query of what follows the authority; a fragment means nothing to a WebSocket. */
private static String pathOf(String afterAuthority) {
int fragment = afterAuthority.indexOf('#');
String path = fragment < 0 ? afterAuthority : afterAuthority.substring(0, fragment);
for (int i = 0; i < path.length(); i++) {
char c = path.charAt(i);
if (c <= ' ' || c == 0x7F) {
throw new IllegalArgumentException("Spaces and control characters aren't allowed in the path");
}
}
if (path.isEmpty() || path.startsWith("?")) {
return "/" + path;
}
return path;
}
private static int parsePort(String text) {
if (text.isEmpty() || text.length() > 5) {
throw new IllegalArgumentException("Not a port: '" + text + "'");
}
int port = 0;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c < '0' || c > '9') {
throw new IllegalArgumentException("Not a port: '" + text + "'");
}
port = port * 10 + (c - '0');
}
if (port < 1 || port > 65535) {
throw new IllegalArgumentException("Port out of range: " + port);
}
return port;
}
private static void checkHostName(String host) {
if (host.isEmpty()) {
throw new IllegalArgumentException("A WebSocket URL needs a host");
}
for (int i = 0; i < host.length(); i++) {
char c = host.charAt(i);
// Letters beyond ASCII are fine: the browser and the JDK both apply IDNA.
boolean allowed = Character.isLetterOrDigit(c) || c == '-' || c == '.' || c == '_';
if (!allowed) {
throw new IllegalArgumentException("'" + c + "' isn't allowed in a host name");
}
}
}
private static void checkIpv6(String host) {
if (host.isEmpty() || host.indexOf(':') < 0) {
throw new IllegalArgumentException("Not an IPv6 address: [" + host + "]");
}
for (int i = 0; i < host.length(); i++) {
char c = host.charAt(i);
boolean allowed = c == ':' || c == '.' || Character.digit(c, 16) >= 0;
if (!allowed) {
throw new IllegalArgumentException("Not an IPv6 address: [" + host + "]");
}
}
}
}
@@ -0,0 +1,459 @@
package incari.net.eagler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.DecoderException;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.UUID;
import org.jspecify.annotations.Nullable;
/**
* The client side of the EaglercraftX V5 handshake, the first stage of the game's pipeline (ADR
* 0016). Eagler servers start their own login on a WebSocket's first binary message, log the player
* in to their backend themselves, then carry vanilla packets, one per message. So this stage:
*
* <ol>
* <li>runs Eagler's exchange when the channel opens: client version, login request, profile data
* (the skin and cape), finish;
* <li>swallows what the game sends meanwhile (its handshake and Login Start), since the proxy
* already sent its own to the backend;
* <li>answers the game's login in the server's place, with a Login Success for the name and UUID
* the server granted (or a Login Disconnect carrying the server's refusal);
* <li>then passes vanilla packets both ways, keeping Eagler's own messages ({@code 0xEE}) for
* the {@link EaglerSession}.
* </ol>
*
* <p>Packets are the Minecraft protocol of {@link EaglerLogin#minecraftProtocol()}: the game's own,
* or the server's when Via translates between them above this stage.
*/
// Handshake packets go out with the void promise: a failed write fails the channel, which the
// game reports as a lost connection.
@SuppressWarnings("FutureReturnValueIgnored")
public final class EaglerHandshake extends ChannelDuplexHandler {
/** The name this stage has in the pipeline. */
public static final String NAME = "eagler";
/** The handshake protocol this client speaks. */
static final int EAGLER_PROTOCOL = 5;
// Handshake packet ids (Eagler's, not Minecraft's).
static final int CLIENT_VERSION = 0x01;
static final int SERVER_VERSION = 0x02;
static final int VERSION_MISMATCH = 0x03;
static final int CLIENT_REQUEST_LOGIN = 0x04;
static final int SERVER_ALLOW_LOGIN = 0x05;
static final int SERVER_DENY_LOGIN = 0x06;
static final int CLIENT_PROFILE_DATA = 0x07;
static final int CLIENT_FINISH_LOGIN = 0x08;
static final int SERVER_FINISH_LOGIN = 0x09;
static final int SERVER_REDIRECT_TO = 0x0A;
static final int SERVER_ERROR = 0xFF;
/** The error code of a server that wants a password the client didn't offer. */
static final int ERROR_AUTHENTICATION_REQUIRED = 0x09;
/** How that error's message starts: "Authentication Required: [method] message". */
private static final String AUTHENTICATION_REQUIRED = "Authentication Required:";
private enum State {
/** Not yet active. */
IDLE,
/** Sent our versions; waiting for the server's choice. */
SENT_VERSION,
/** Asked to log in; waiting for the server to allow or deny it. */
SENT_LOGIN,
/** Sent profile data and finished; waiting for the server's finish. */
SENT_FINISH,
/** The server finished; waiting for the game's Login Start before answering it. */
LOGGED_IN,
/** Answered the game's login; waiting for its Login Acknowledged (1.20.2 and later). */
AWAITING_ACKNOWLEDGEMENT,
/** Vanilla packets pass both ways. */
PLAY,
/** Refused or broken; everything is dropped until the channel closes. */
FAILED
}
private final EaglerLogin login;
private final EaglerSession session;
/** Vanilla packets from the server held until the game is ready for them. Event loop only. */
private final Queue<ByteBuf> held = new ArrayDeque<>();
private State state = State.IDLE;
/** Serverbound packets the game sent before play: its handshake, then Login Start. */
private int swallowed;
private boolean loginStartSeen;
private @Nullable String grantedName;
private @Nullable UUID grantedUuid;
/** A refusal to show once the game can take a Login Disconnect. */
private @Nullable String pendingDisconnect;
/** The password method the server named, once it has; {@link EaglerPassword#NONE} before. */
private int authMethod = EaglerPassword.NONE;
/** Whether the login request carried a password, so a refusal may mean a wrong one. */
private boolean sentPassword;
/** Set when the server closed the connection mid-login without saying why. */
private volatile boolean droppedDuringLogin;
public EaglerHandshake(EaglerLogin login, EaglerSession session) {
this.login = login;
this.session = session;
}
/** Adds the stage at the head of {@code pipeline}, below framing, and returns it. */
public static EaglerHandshake install(ChannelPipeline pipeline, EaglerLogin login, EaglerSession session) {
EaglerHandshake stage = new EaglerHandshake(login, session);
pipeline.addFirst(NAME, stage);
return stage;
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
sendClientVersion(ctx);
state = State.SENT_VERSION;
ctx.fireChannelActive();
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
if (state == State.SENT_VERSION || state == State.SENT_LOGIN || state == State.SENT_FINISH) {
droppedDuringLogin = true;
}
releaseHeld();
session.closed();
ctx.fireChannelInactive();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object message) {
if (!(message instanceof ByteBuf buffer)) {
ctx.fireChannelRead(message);
return;
}
switch (state) {
case PLAY, LOGGED_IN, AWAITING_ACKNOWLEDGEMENT -> readPlay(ctx, buffer);
case FAILED, IDLE -> buffer.release();
default -> {
try {
readHandshake(ctx, buffer);
} catch (IndexOutOfBoundsException | DecoderException e) {
fail(ctx, "The server sent a malformed Eagler handshake packet");
} finally {
buffer.release();
}
}
}
}
@Override
public void write(ChannelHandlerContext ctx, Object message, ChannelPromise promise) {
if (state == State.PLAY || !(message instanceof ByteBuf buffer)) {
ctx.write(message, promise);
return;
}
int id = Wire.peekVarInt(buffer);
boolean acknowledgement = state == State.AWAITING_ACKNOWLEDGEMENT
&& id == VanillaLogin.LOGIN_ACKNOWLEDGED_ID
&& buffer.readableBytes() == 1;
// Nothing the game sends before play reaches the server: the proxy did the vanilla login.
buffer.release();
promise.trySuccess();
swallowed++;
if (acknowledgement) {
enterPlay(ctx);
} else if (!loginStartSeen && swallowed >= 2 && id == VanillaLogin.LOGIN_START_ID) {
loginStartSeen = true;
answerLogin(ctx);
}
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
releaseHeld();
}
/**
* Whether the server silently closed the connection during Eagler's login. EaglerXServer does
* that when its proxy can't speak the client's protocol (a BungeeCord older than the client),
* so "Auto" takes it as a hint to try another version (ADR 0018).
*/
public boolean droppedDuringLogin() {
return droppedDuringLogin;
}
// --- The Eagler exchange ---------------------------------------------------------------
private void sendClientVersion(ChannelHandlerContext ctx) {
ByteBuf out = ctx.alloc().buffer();
out.writeByte(CLIENT_VERSION);
out.writeByte(0x02); // the V2+ handshake family
out.writeShort(1);
out.writeShort(EAGLER_PROTOCOL);
out.writeShort(1);
out.writeShort(login.minecraftProtocol());
Wire.writeByteAscii(out, login.brand());
Wire.writeByteAscii(out, login.version());
// Offering a password makes an auth plugin send its method and salt instead of refusing.
out.writeBoolean(login.password() != null);
Wire.writeByteAscii(out, login.username());
ctx.writeAndFlush(out, ctx.voidPromise());
}
private void readHandshake(ChannelHandlerContext ctx, ByteBuf in) {
int id = in.readUnsignedByte();
switch (id) {
case SERVER_VERSION -> {
if (state != State.SENT_VERSION) {
fail(ctx, "The server sent its version twice");
return;
}
readServerVersion(ctx, in);
}
case SERVER_ALLOW_LOGIN -> {
if (state != State.SENT_LOGIN) {
fail(ctx, "The server allowed a login it wasn't asked for");
return;
}
readAllowLogin(ctx, in);
}
case SERVER_FINISH_LOGIN -> {
if (state != State.SENT_FINISH) {
fail(ctx, "The server finished a login too early");
return;
}
state = State.LOGGED_IN;
if (loginStartSeen) {
answerLogin(ctx);
}
}
case VERSION_MISMATCH -> fail(ctx, versionMismatch(in));
case SERVER_DENY_LOGIN -> {
String reason = Wire.readShortUtf8(in);
if (sentPassword) {
// An auth plugin's refusal of the password sent: ask for it again.
session.authenticationRequired(authMethod, reason);
}
fail(ctx, reason);
}
case SERVER_REDIRECT_TO -> {
String address = Wire.readShortUtf8(in);
session.redirected(address);
fail(ctx, "The server redirected this client to " + address);
}
case SERVER_ERROR -> readServerError(ctx, in);
default -> fail(ctx, "The server sent an unknown Eagler handshake packet (" + id + ")");
}
}
private void readServerVersion(ChannelHandlerContext ctx, ByteBuf in) {
int eaglerProtocol = in.readUnsignedShort();
int minecraftProtocol = in.readUnsignedShort();
Wire.readByteAscii(in); // server brand
Wire.readByteAscii(in); // server version
int method = in.readUnsignedByte();
byte[] salt = new byte[in.readUnsignedShort()];
in.readBytes(salt);
// V5 then says whether the player may pick a name other than the one offered; the name
// offered is the one wanted, so there's nothing to do with it.
if (eaglerProtocol != EAGLER_PROTOCOL) {
fail(ctx, "The server chose Eagler protocol " + eaglerProtocol + "; this client speaks " + EAGLER_PROTOCOL);
return;
}
if (minecraftProtocol != login.minecraftProtocol()) {
fail(
ctx,
"The server chose Minecraft protocol " + minecraftProtocol + ", not " + login.minecraftProtocol());
return;
}
authMethod = method;
byte[] answer = new byte[0];
EaglerPassword password = login.password();
if (method != EaglerPassword.NONE && password != null) {
byte[] hashed = password.answer(method, salt);
if (hashed == null) {
if (method == EaglerPassword.PLAINTEXT) {
session.authenticationRequired(method, "");
fail(ctx, "This server wants your password as plain text, and you haven't allowed that");
} else {
fail(ctx, "This server uses a login method Incari doesn't support (method " + method + ")");
}
return;
}
answer = hashed;
}
// With a method but no password, the server takes a cookie instead or says it wants one.
sentPassword = answer.length > 0;
EaglerLogin.Cookie cookie = login.cookie();
byte[] cookieData = cookie != null ? cookie.data() : new byte[0];
ByteBuf out = ctx.alloc().buffer();
out.writeByte(CLIENT_REQUEST_LOGIN);
Wire.writeByteAscii(out, login.username());
Wire.writeByteAscii(out, login.requestedServer());
out.writeByte(answer.length);
out.writeBytes(answer);
boolean cookies = (login.capabilities() & EaglerLogin.COOKIE) != 0;
out.writeBoolean(cookies);
out.writeByte(cookies ? cookieData.length : 0);
if (cookies) {
out.writeBytes(cookieData);
}
int capabilities = login.capabilities();
Wire.writeVarInt(out, capabilities);
for (int i = 0; i < Integer.bitCount(capabilities); i++) {
Wire.writeVarInt(out, 1); // each at version 0 (bit 0 of its versions)
}
out.writeByte(0); // no extended capabilities
ctx.writeAndFlush(out, ctx.voidPromise());
state = State.SENT_LOGIN;
}
private void readAllowLogin(ChannelHandlerContext ctx, ByteBuf in) {
String name = Wire.readByteAscii(in);
UUID uuid = new UUID(in.readLong(), in.readLong());
int accepted = 0;
if (in.isReadable()) {
accepted = Wire.readVarInt(in);
in.skipBytes(Integer.bitCount(accepted)); // the version of each, only ever 0 here
// Extended capabilities follow; none were asked for.
}
session.capabilities(accepted & login.capabilities());
grantedName = name;
grantedUuid = uuid;
if (!login.profileData().isEmpty()) {
ByteBuf out = ctx.alloc().buffer();
out.writeByte(CLIENT_PROFILE_DATA);
out.writeByte(login.profileData().size());
for (EaglerLogin.ProfileData data : login.profileData()) {
Wire.writeByteAscii(out, data.type());
out.writeShort(data.data().length);
out.writeBytes(data.data());
}
ctx.write(out, ctx.voidPromise());
}
ByteBuf finish = ctx.alloc().buffer(1);
finish.writeByte(CLIENT_FINISH_LOGIN);
ctx.writeAndFlush(finish, ctx.voidPromise());
state = State.SENT_FINISH;
}
private static String versionMismatch(ByteBuf in) {
in.skipBytes(in.readUnsignedShort() * 2); // Eagler protocols the server speaks
int ranges = in.readUnsignedShort();
int min = ranges >= 2 ? in.readUnsignedShort() : -1;
int max = ranges >= 2 ? in.readUnsignedShort() : -1;
in.skipBytes(Math.max(0, ranges - 2) * 2);
String reason = in.isReadable() ? Wire.readByteAscii(in) : "Unsupported client version";
return reason + (min >= 0 ? " (the server takes Minecraft protocols " + min + " to " + max + ")" : "");
}
private void readServerError(ChannelHandlerContext ctx, ByteBuf in) {
int code = in.readUnsignedByte();
// A short-prefixed message, or a byte-prefixed one when the server answers before it has
// chosen the protocol (an auth plugin's first refusal comes that early).
String message = in.readableBytes() >= 2 && in.getUnsignedShort(in.readerIndex()) == in.readableBytes() - 2
? Wire.readShortUtf8(in)
: Wire.readByteAscii(in);
if (code == ERROR_AUTHENTICATION_REQUIRED && message.startsWith(AUTHENTICATION_REQUIRED)) {
// "Authentication Required: [1] Log in with your password"
String rest = message.substring(AUTHENTICATION_REQUIRED.length()).trim();
int method = EaglerPassword.NONE;
int close = rest.indexOf(']');
if (rest.startsWith("[") && close > 0) {
try {
method = Integer.parseInt(rest.substring(1, close));
} catch (NumberFormatException e) {
// Left at NONE: the screen asks for a password all the same.
}
rest = rest.substring(close + 1).trim();
}
session.authenticationRequired(method, rest);
fail(ctx, rest.isEmpty() ? "This server needs a password" : rest);
return;
}
fail(ctx, message);
}
// --- Standing in for the vanilla login ------------------------------------------------
/** Once the server finished and the game is waiting for its login: Login Success. */
private void answerLogin(ChannelHandlerContext ctx) {
if (pendingDisconnect != null) {
String reason = pendingDisconnect;
pendingDisconnect = null;
ctx.fireChannelRead(VanillaLogin.loginDisconnect(ctx.alloc(), reason));
return;
}
String name = grantedName;
UUID uuid = grantedUuid;
if (state != State.LOGGED_IN || name == null || uuid == null) {
return;
}
session.loggedIn(name, uuid, EaglerMessages.on(ctx));
boolean acknowledges = VanillaLogin.acknowledgesLogin(login.minecraftProtocol());
state = acknowledges ? State.AWAITING_ACKNOWLEDGEMENT : State.PLAY;
ctx.fireChannelRead(VanillaLogin.loginSuccess(ctx.alloc(), login.minecraftProtocol(), name, uuid));
if (!acknowledges) {
flushHeld(ctx);
}
}
private void enterPlay(ChannelHandlerContext ctx) {
state = State.PLAY;
flushHeld(ctx);
}
private void readPlay(ChannelHandlerContext ctx, ByteBuf buffer) {
if (buffer.isReadable() && buffer.getUnsignedByte(buffer.readerIndex()) == EaglerMessages.PREFIX) {
try {
buffer.skipBytes(1);
EaglerMessages.dispatch(buffer, session);
} catch (IndexOutOfBoundsException | DecoderException e) {
// A malformed extra (a skin) mustn't end the game's connection.
ctx.fireExceptionCaught(new DecoderException("Malformed Eagler message", e));
} finally {
buffer.release();
}
return;
}
if (state == State.PLAY) {
ctx.fireChannelRead(buffer);
} else {
// The server sends the backend's packets as soon as it finishes; the game isn't ready
// for them until it has taken the login (and, from 1.20.2, acknowledged it).
held.add(buffer);
}
}
private void flushHeld(ChannelHandlerContext ctx) {
while (!held.isEmpty() && state == State.PLAY) {
ctx.fireChannelRead(held.remove());
}
}
private void releaseHeld() {
while (!held.isEmpty()) {
held.remove().release();
}
}
/**
* Ends the login with {@code reason} shown to the player: as a Login Disconnect once the game is
* waiting for its login (it shows the reason as a kick), then the connection closes.
*/
private void fail(ChannelHandlerContext ctx, String reason) {
state = State.FAILED;
releaseHeld();
if (loginStartSeen) {
ctx.fireChannelRead(VanillaLogin.loginDisconnect(ctx.alloc(), reason));
} else {
// Delivered when the game's Login Start comes through write(). The game sends it the
// moment the channel opens, long before any answer can arrive, so this is rare.
pendingDisconnect = reason;
}
}
}
@@ -0,0 +1,110 @@
package incari.net.eagler;
import java.util.List;
import org.jspecify.annotations.Nullable;
/**
* What the client tells an Eagler server when it logs in.
*
* @param username the name to ask for; the server may assign another
* @param minecraftProtocol the Minecraft protocol the game (or Via above it) will speak, which the
* proxy passes on to its backend; must fit 16 bits
* @param brand the client's name, shown in the server's logs
* @param version the client's version string
* @param requestedServer the backend to join, or empty for the proxy's default
* @param profileData up to eight named blobs sent after login: the skin ({@code skin_v2}), the cape
* ({@code cape_v1}) and so on ({@link EaglerTextures})
* @param password the password to answer an auth plugin with, or null to offer none (ADR 0019)
* @param cookie the cookie this server set earlier, sent back with the login, or null for none
* @param capabilities the standard capabilities to ask for ({@link #VOICE}, {@link #COOKIE}...)
*/
public record EaglerLogin(
String username,
int minecraftProtocol,
String brand,
String version,
String requestedServer,
List<ProfileData> profileData,
@Nullable EaglerPassword password,
@Nullable Cookie cookie,
int capabilities) {
/** Eagler's handshake allows eight profile data entries. */
public static final int MAX_PROFILE_DATA = 8;
// Standard capabilities, as bits of the login request's mask (each asked for at version 0).
/** WebRTC voice signalling. */
public static final int VOICE = 1 << 1;
/** Redirects to another server, during login and during play. */
public static final int REDIRECT = 1 << 2;
/** The server's pause menu buttons and their icons ({@link EaglerPauseMenu}). */
public static final int PAUSE_MENU = 1 << 4;
/** Server cookies: the server may store up to 255 bytes, sent back on the next login. */
public static final int COOKIE = 1 << 6;
/** A login without a password, a cookie or capabilities, as the first handshake sent. */
public EaglerLogin(
String username,
int minecraftProtocol,
String brand,
String version,
String requestedServer,
List<ProfileData> profileData) {
this(username, minecraftProtocol, brand, version, requestedServer, profileData, null, null, 0);
}
public EaglerLogin {
if (minecraftProtocol < 0 || minecraftProtocol > 0xFFFF) {
throw new IllegalArgumentException("The Eagler handshake can't carry protocol " + minecraftProtocol);
}
if (profileData.size() > MAX_PROFILE_DATA) {
throw new IllegalArgumentException("At most " + MAX_PROFILE_DATA + " profile data entries");
}
profileData = List.copyOf(profileData);
}
/** A cookie to send back: the bytes the server set, at most 255. */
public static final class Cookie {
private final byte[] data;
public Cookie(byte[] data) {
if (data.length > 255) {
throw new IllegalArgumentException("A cookie is at most 255 bytes, not " + data.length);
}
this.data = data.clone();
}
byte[] data() {
return data;
}
}
/** One named blob of profile data; the data must fit an unsigned short length. */
public static final class ProfileData {
private final String type;
private final byte[] data;
public ProfileData(String type, byte[] data) {
if (data.length > 0xFFFF) {
throw new IllegalArgumentException(type + " is " + data.length + " bytes, over 65535");
}
this.type = type;
this.data = data.clone();
}
public String type() {
return type;
}
/** The blob itself; don't change it. */
byte[] data() {
return data;
}
public int size() {
return data.length;
}
}
}
@@ -0,0 +1,160 @@
package incari.net.eagler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.DecoderException;
import java.nio.charset.StandardCharsets;
import java.util.function.Consumer;
/**
* Eagler's own messages in protocol V5: WebSocket messages that start with {@code 0xEE}, then the
* message id and its body, travelling beside the game's packets (no packet id starts with that
* byte: it would be a VarInt over 127). {@code 0xEE 0xFF} bundles several: a VarInt count, then
* each message as a VarInt length and its id and body (no prefix of its own).
*
* <p>Sends go straight to the socket from the Eagler stage, past the game's pipeline.
*/
public final class EaglerMessages {
static final int PREFIX = 0xEE;
static final int BUNDLE = 0xFF;
// Client to server (V5).
public static final int C_GET_OTHER_SKIN = 0x01;
public static final int C_GET_OTHER_CAPE = 0x02;
public static final int C_GET_OTHER_TEXTURES = 0x03;
public static final int C_VOICE_REQUEST = 0x06;
public static final int C_VOICE_CONNECT = 0x07;
public static final int C_VOICE_DISCONNECT = 0x08;
public static final int C_VOICE_DISCONNECT_PEER = 0x09;
public static final int C_VOICE_ICE = 0x0A;
public static final int C_VOICE_DESCRIPTION = 0x0B;
// Server to client (V5).
public static final int S_OTHER_SKIN_PRESET = 0x01;
public static final int S_OTHER_SKIN_CUSTOM = 0x02;
public static final int S_OTHER_CAPE_PRESET = 0x03;
public static final int S_OTHER_CAPE_CUSTOM = 0x04;
public static final int S_OTHER_TEXTURES = 0x05;
public static final int S_VOICE_ALLOWED = 0x06;
public static final int S_VOICE_CONNECT = 0x07;
public static final int S_VOICE_CONNECT_ANNOUNCE = 0x08;
public static final int S_VOICE_DISCONNECT_PEER = 0x09;
public static final int S_VOICE_ICE = 0x0A;
public static final int S_VOICE_DESCRIPTION = 0x0B;
public static final int S_VOICE_GLOBAL = 0x0C;
public static final int S_FORCE_SKIN_PRESET = 0x0F;
public static final int S_FORCE_SKIN_CUSTOM = 0x10;
public static final int S_FORCE_CAPE_PRESET = 0x14;
public static final int S_FORCE_CAPE_CUSTOM = 0x15;
public static final int S_SET_COOKIE = 0x11;
public static final int S_REDIRECT = 0x12;
public static final int S_INVALIDATE_PLAYER = 0x16;
public static final int S_CUSTOMIZE_PAUSE_MENU = 0x18;
/** Where messages go: the socket, or a test's list. */
interface Sink {
ByteBuf allocate();
void write(ByteBuf message);
}
private final Sink sink;
EaglerMessages(Sink sink) {
this.sink = sink;
}
/** Messages written from the Eagler stage's context, straight to the socket. */
// Written with the void promise: a failed write fails the channel, which the game reports.
@SuppressWarnings("FutureReturnValueIgnored")
static EaglerMessages on(ChannelHandlerContext context) {
return new EaglerMessages(new Sink() {
@Override
public ByteBuf allocate() {
return context.alloc().buffer();
}
@Override
public void write(ByteBuf message) {
Channel channel = context.channel();
if (!channel.isActive()) {
message.release();
} else if (context.executor().inEventLoop()) {
context.writeAndFlush(message, context.voidPromise());
} else {
context.executor().execute(() -> context.writeAndFlush(message, context.voidPromise()));
}
}
});
}
/** Sends message {@code id} with the body {@code body} writes. Any thread. */
public void send(int id, Consumer<ByteBuf> body) {
ByteBuf message = sink.allocate();
message.writeByte(PREFIX);
message.writeByte(id);
body.accept(message);
sink.write(message);
}
/** Writes a VarInt, for message bodies. */
public static void writeVarInt(ByteBuf out, int value) {
Wire.writeVarInt(out, value);
}
/** Reads a VarInt, for message bodies. */
public static int readVarInt(ByteBuf in) {
return Wire.readVarInt(in);
}
/** Reads a VarLong (a cookie's lifetime). */
public static long readVarLong(ByteBuf in) {
long value = 0;
for (int shift = 0; shift < 70; shift += 7) {
int b = in.readUnsignedByte();
value |= (long) (b & 0x7F) << shift;
if ((b & 0x80) == 0) {
return value;
}
}
throw new DecoderException("VarLong too long");
}
/** Reads a game string: VarInt length, UTF-8 (voice servers' addresses, player names). */
public static String readString(ByteBuf in) {
return Wire.readString(in);
}
/** Reads a short-length ASCII string (a redirect's address). */
public static String readShortAscii(ByteBuf in) {
int length = in.readUnsignedShort();
String value = in.toString(in.readerIndex(), length, StandardCharsets.US_ASCII);
in.skipBytes(length);
return value;
}
/**
* Splits a {@code 0xEE} message (the prefix already read) into its messages and hands each to
* {@code session}.
*/
static void dispatch(ByteBuf message, EaglerSession session) {
if (!message.isReadable()) {
return;
}
if (message.getUnsignedByte(message.readerIndex()) != BUNDLE) {
int id = message.readUnsignedByte();
session.received(id, message);
return;
}
message.skipBytes(1);
int count = Wire.readVarInt(message);
for (int i = 0; i < count && message.isReadable(); i++) {
ByteBuf entry = message.readSlice(Wire.readVarInt(message));
if (entry.isReadable()) {
session.received(entry.readUnsignedByte(), entry);
}
}
}
}
@@ -0,0 +1,131 @@
package incari.net.eagler;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import org.jspecify.annotations.Nullable;
/**
* A password for an Eagler server that asks for one (ADR 0019), and the forms it's sent in.
* EaglerXServer leaves checking to an auth plugin, which names one of three methods in the
* handshake along with a salt; the client answers in that method's form:
*
* <ul>
* <li>{@link #EAGLER_SHA256}: SHA-256 of the password (as UTF-16 with a length prefix) and a fixed
* salt, then twice more with each half of the server's 64-byte salt and a second fixed salt;
* <li>{@link #AUTHME_SHA256}: AuthMe's hash, {@code hex(sha256(hex(sha256(password)) + salt))},
* which is what AuthMe stores after its {@code $SHA$salt$};
* <li>{@link #PLAINTEXT}: the password itself, as UTF-16, which the player must agree to first.
* </ul>
*
* @param text the password as typed
* @param plaintextAllowed whether the player agreed to send it unhashed if the server asks so
*/
public record EaglerPassword(String text, boolean plaintextAllowed) {
public static final int NONE = 0x00;
public static final int EAGLER_SHA256 = 0x01;
public static final int AUTHME_SHA256 = 0x02;
public static final int PLAINTEXT = 0xFF;
// Protocol constants: every Eagler client and auth plugin uses these two salts.
private static final byte[] SALT_BASE = bytes(
117, 43, 1, 112, 75, 3, 188, 61, 121, 31, 34, 181, 234, 31, 247, 72, 12, 168, 138, 45, 143, 77, 118, 245,
187, 242, 188, 219, 160, 235, 235, 68);
private static final byte[] SALT_SAVE = bytes(
49, 25, 39, 38, 253, 85, 70, 245, 71, 150, 253, 206, 4, 26, 198, 249, 145, 251, 232, 174, 186, 98, 27, 232,
55, 144, 83, 21, 36, 55, 170, 118);
private static final byte[] HEX = "0123456789abcdef".getBytes(StandardCharsets.US_ASCII);
/** Whether this client can answer {@code method} at all. */
public static boolean supports(int method) {
return method == EAGLER_SHA256 || method == AUTHME_SHA256 || method == PLAINTEXT;
}
/**
* What goes in the login request's password field for {@code method} and the server's {@code
* salt}, or null if it can't be sent: an unknown method, a short salt, or plain text the player
* hasn't agreed to.
*/
byte @Nullable [] answer(int method, byte[] salt) {
return switch (method) {
case EAGLER_SHA256 -> salt.length < 64 ? null : eaglerSha256(text, salt);
case AUTHME_SHA256 -> authMeSha256(text, salt);
case PLAINTEXT -> plaintextAllowed && text.length() <= 127 ? utf16(text) : null;
default -> null;
};
}
static byte[] eaglerSha256(String password, byte[] salt) {
MessageDigest digest = sha256();
digest.update((byte) (password.length() >>> 8));
digest.update((byte) password.length());
digest.update(utf16(password));
digest.update(SALT_SAVE);
byte[] hash = digest.digest();
digest.update(hash);
digest.update(salt, 0, 32);
digest.update(SALT_BASE);
hash = digest.digest();
digest.update(hash);
digest.update(salt, 32, 32);
digest.update(SALT_BASE);
return digest.digest();
}
static byte[] authMeSha256(String password, byte[] salt) {
MessageDigest digest = sha256();
byte[] inner = hex(digest.digest(password.getBytes(StandardCharsets.UTF_8)));
digest.update(inner);
digest.update(salt);
return hex(digest.digest());
}
private static byte[] utf16(String text) {
return text.getBytes(StandardCharsets.UTF_16BE);
}
private static byte[] hex(byte[] bytes) {
byte[] out = new byte[bytes.length * 2];
for (int i = 0; i < bytes.length; i++) {
out[i * 2] = HEX[(bytes[i] >> 4) & 0xF];
out[i * 2 + 1] = HEX[bytes[i] & 0xF];
}
return out;
}
private static MessageDigest sha256() {
try {
return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Every Java platform has SHA-256", e);
}
}
private static byte[] bytes(int... values) {
byte[] out = new byte[values.length];
for (int i = 0; i < values.length; i++) {
out[i] = (byte) values[i];
}
return out;
}
// A record's generated toString would print the password into logs.
@Override
public String toString() {
return "EaglerPassword[" + text.length() + " characters]";
}
@Override
public boolean equals(@Nullable Object other) {
return other instanceof EaglerPassword password
&& password.text.equals(text)
&& password.plaintextAllowed == plaintextAllowed;
}
@Override
public int hashCode() {
return Arrays.hashCode(new Object[] {text, plaintextAllowed});
}
}
@@ -0,0 +1,144 @@
package incari.net.eagler;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.DecoderException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jspecify.annotations.Nullable;
/**
* An EaglerXServer's pause menu (message {@link EaglerMessages#S_CUSTOMIZE_PAUSE_MENU}, sent to
* clients that ask for {@link EaglerLogin#PAUSE_MENU}): a "server info" button, a Discord button,
* and small images for the menu's buttons and title, each named by a key such as {@code
* icon_discord_L} (left of the Discord button's text) or {@code icon_title_R}.
*
* @param serverInfo the server info button, or null for none
* @param discord the Discord button, or null for none
* @param icons each icon key's image
*/
public record EaglerPauseMenu(
@Nullable Button serverInfo, @Nullable Button discord, Map<String, Image> icons) {
/** Opens {@code url} in a new tab. */
public static final int MODE_EXTERNAL_URL = 1;
/** Shows {@code url} in an embedded web view; the page has none, so it opens in a new tab. */
public static final int MODE_EMBED_URL = 2;
/** Shows markup downloaded from the server in an embedded web view; {@code url} is null. */
public static final int MODE_EMBED_DOWNLOAD = 3;
/** The largest icon side EaglerXServer sends. */
private static final int MAX_ICON_SIZE = 64;
/**
* A button: its text, how it acts ({@link #MODE_EXTERNAL_URL} and the other modes; always the
* first for Discord), and the address it opens if it has one.
*/
public record Button(String text, int mode, @Nullable String url) {}
/** An image, {@code width × height} pixels of ARGB, row by row; fully transparent or opaque. */
public static final class Image {
private final int width;
private final int height;
private final int[] argb;
Image(int width, int height, int[] argb) {
this.width = width;
this.height = height;
this.argb = argb;
}
public int width() {
return width;
}
public int height() {
return height;
}
/** The pixel at ({@code x}, {@code y}). */
public int pixel(int x, int y) {
return argb[y * width + x];
}
}
/** Reads the message's body (the id already read). */
public static EaglerPauseMenu read(ByteBuf in) {
int flags = in.readUnsignedByte();
int serverInfoMode = flags & 0x0F;
int discordMode = (flags >> 4) & 0x0F;
Button serverInfo = null;
switch (serverInfoMode) {
case MODE_EXTERNAL_URL -> serverInfo = new Button(Wire.readString(in), MODE_EXTERNAL_URL, shortAscii(in));
case MODE_EMBED_URL -> {
String text = Wire.readString(in);
String url = shortAscii(in);
in.skipBytes(1); // the web view's permissions
Wire.readString(in); // the web view screen's title
serverInfo = new Button(text, MODE_EMBED_URL, url);
}
case MODE_EMBED_DOWNLOAD -> {
String text = Wire.readString(in);
in.skipBytes(1); // permissions
Wire.readString(in); // title
in.skipBytes(20); // the markup's SHA-1, which asks for it
serverInfo = new Button(text, MODE_EMBED_DOWNLOAD, null);
}
default -> {}
}
Button discord = null;
if (discordMode == MODE_EXTERNAL_URL) {
discord = new Button(Wire.readString(in), MODE_EXTERNAL_URL, shortAscii(in));
}
Map<String, Image> icons = new HashMap<>();
int mappings = Wire.readVarInt(in);
if (mappings > 0) {
Map<String, Integer> indices = new HashMap<>();
for (int i = 0; i < mappings; i++) {
String key = Wire.readByteAscii(in);
indices.put(key, Wire.readVarInt(in));
}
int count = Wire.readVarInt(in);
List<Image> images = new ArrayList<>();
for (int i = 0; i < count; i++) {
images.add(readImage(in));
}
indices.forEach((key, index) -> {
if (index >= 0 && index < images.size()) {
icons.put(key, images.get(index));
}
});
}
return new EaglerPauseMenu(serverInfo, discord, Map.copyOf(icons));
}
/** An unsigned short length, then one byte a character. */
private static String shortAscii(ByteBuf in) {
return EaglerMessages.readShortAscii(in);
}
/**
* Eagler's 16-bit image: a byte each for width and height, then a short a pixel, RGB 5:6:5 with
* blue counted from 1, and 0 for transparent.
*/
private static Image readImage(ByteBuf in) {
int width = in.readUnsignedByte();
int height = in.readUnsignedByte();
if (width < 1 || height < 1 || width > MAX_ICON_SIZE || height > MAX_ICON_SIZE) {
throw new DecoderException("Bad pause menu icon size " + width + "x" + height);
}
int[] argb = new int[width * height];
for (int i = 0; i < argb.length; i++) {
int pixel = in.readUnsignedShort();
if (pixel == 0) {
continue;
}
int red = (pixel >>> 11) & 0x1F;
int green = (pixel >>> 5) & 0x3F;
int blue = Math.max(0, (pixel & 0x1F) - 1);
argb[i] = 0xFF000000 | (red * 255 / 31) << 16 | (green * 255 / 63) << 8 | blue * 255 / 30;
}
return new Image(width, height, argb);
}
}
@@ -0,0 +1,161 @@
package incari.net.eagler;
import incari.platform.api.net.NetConnection;
import incari.platform.api.net.PlatformNetwork;
import java.nio.ByteBuffer;
import org.jspecify.annotations.Nullable;
/**
* An Eagler server's MOTD, the server list's ping for a WebSocket server. Eagler servers don't
* answer the vanilla status ping; a WebSocket whose first message is the text {@code Accept: motd}
* gets a JSON answer in text (the MOTD lines, player counts, a sample of names), then the server's
* icon as a binary message if it has one: 64x64 pixels, four bytes each (red, green, blue, alpha).
*/
public final class EaglerQuery implements NetConnection.Listener {
/** The icon's size in bytes. */
public static final int ICON_BYTES = 64 * 64 * 4;
/** Hears how a query ended. Calls come on a platform thread; exactly one of them, once. */
public interface Callback {
/**
* The server answered.
*
* @param json the answer as the server sent it (its {@code data} object holds the MOTD)
* @param icon the icon's RGBA bytes, or null if the server has none
* @param latencyMillis from the socket opening to the answer
*/
void answered(String json, byte @Nullable [] icon, long latencyMillis);
/** The query failed: the server refused it, closed, or isn't an Eagler server. */
void failed(String reason);
}
private final Callback callback;
private final Clock clock;
private final Object lock = new Object();
private @Nullable NetConnection connection;
private @Nullable String json;
private long openedAt;
private long latency;
private boolean expectingIcon;
private boolean done;
/** A monotonic clock in milliseconds. */
public interface Clock {
long millis();
}
private EaglerQuery(Callback callback, Clock clock) {
this.callback = callback;
this.clock = clock;
}
/** Opens a WebSocket to {@code url} and asks for the MOTD. Returns at once. */
public static EaglerQuery motd(PlatformNetwork network, String url, Clock clock, Callback callback) {
EaglerQuery query = new EaglerQuery(callback, clock);
NetConnection opened = network.openWebSocket(url, query);
synchronized (query.lock) {
query.connection = opened;
}
// Queued by the platform until the socket opens.
opened.sendText("Accept: motd");
return query;
}
/** Gives up on the query (the server list closed); the callback isn't called. */
public void cancel() {
NetConnection current;
synchronized (lock) {
done = true;
current = connection;
}
if (current != null) {
current.close();
}
}
@Override
public void connected() {
synchronized (lock) {
openedAt = clock.millis();
}
}
@Override
public void receivedText(String text) {
boolean finished;
synchronized (lock) {
if (done || json != null) {
return;
}
json = text;
latency = clock.millis() - openedAt;
// Whether an icon follows is in the answer; a quick look saves parsing JSON here.
expectingIcon = text.contains("\"icon\":true");
finished = !expectingIcon;
}
if (finished) {
finish(text, null);
}
}
@Override
public void received(ByteBuffer data) {
String answer;
synchronized (lock) {
if (done || json == null || !expectingIcon) {
return;
}
answer = json;
}
byte[] icon = null;
if (data.remaining() == ICON_BYTES) {
icon = new byte[ICON_BYTES];
data.get(icon);
}
finish(answer, icon);
}
@Override
public void closed(@Nullable Throwable cause) {
String answer;
synchronized (lock) {
if (done) {
return;
}
answer = json;
}
if (answer != null) {
// Answered, but the icon never came: the MOTD alone will do.
finish(answer, null);
return;
}
synchronized (lock) {
done = true;
}
callback.failed(
cause != null && cause.getMessage() != null
? cause.getMessage()
: "The server closed the connection without answering");
}
private void finish(String answer, byte @Nullable [] icon) {
NetConnection current;
long took;
synchronized (lock) {
if (done) {
return;
}
done = true;
current = connection;
took = latency;
}
if (current != null) {
current.close();
}
callback.answered(answer, icon, took);
}
}
@@ -0,0 +1,43 @@
package incari.net.eagler;
import io.netty.buffer.ByteBuf;
import java.util.UUID;
/**
* Hears one Eagler connection after its handshake: the login the server granted, and Eagler's own
* messages (skins, capes; voice and the rest later), which travel beside the game's packets. Calls
* come on the channel's event loop.
*/
public interface EaglerSession {
/**
* The server logged the player in, as {@code name} with {@code uuid} (offline-mode UUIDs unless
* an auth plugin chose others). {@code messages} sends Eagler messages from now on.
*/
default void loggedIn(String name, UUID uuid, EaglerMessages messages) {}
/**
* One Eagler message from the server: its id and body (V5 numbering, {@link EaglerMessages}).
* The buffer is only valid during the call.
*/
default void received(int id, ByteBuf body) {}
/**
* The standard capabilities the server accepted of those asked for ({@link EaglerLogin#VOICE}
* and so on), before {@link #loggedIn}.
*/
default void capabilities(int accepted) {}
/**
* The server wants a password: none was offered, the one sent was refused, or it must go
* unhashed and the player hasn't agreed. {@code method} is the server's ({@link
* EaglerPassword}), {@code message} its words for the player. The login then fails.
*/
default void authenticationRequired(int method, String message) {}
/** The server sent the player on to {@code address} instead of logging in. The login then fails. */
default void redirected(String address) {}
/** The connection closed. */
default void closed() {}
}
@@ -0,0 +1,418 @@
package incari.net.eagler;
import io.netty.buffer.ByteBuf;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.jspecify.annotations.Nullable;
/**
* Eagler skins and capes: this client's own, sent as profile data at login, and other players',
* asked of the server by UUID. Converts between Eagler's compact formats and the ARGB pixels the
* game's textures are built from (one int per pixel, {@code 0xAARRGGBB}, rows top to bottom).
*
* <ul>
* <li>A skin is 64x64 pixels at three bytes each: blue, green, then red's top seven bits with
* alpha as a single bit (12288 bytes), plus a model id (0 wide, 1 slim).
* <li>A cape is the 22x17 region the cape model uses plus one more column of 11 pixels, at three
* bytes each (blue, green, red; 1173 bytes), of a 64x32 cape texture.
* <li>Either may instead be a preset: a number naming one of Eagler's built-in textures.
* </ul>
*/
public final class EaglerTextures {
public static final int SKIN_WIDTH = 64;
public static final int SKIN_HEIGHT = 64;
public static final int CAPE_WIDTH = 64;
public static final int CAPE_HEIGHT = 32;
static final int SKIN_BYTES = SKIN_WIDTH * SKIN_HEIGHT * 3;
static final int CAPE_BYTES = 23 * 17 * 3;
/** Profile data names, as the handshake sends them. */
public static final String SKIN_PROFILE_DATA = "skin_v2";
public static final String CAPE_PROFILE_DATA = "cape_v1";
private static final int PRESET = 1;
private static final int CUSTOM = 2;
/** Eagler's preset skins 0 and 1 are the default Steve and Alex; the rest are its own art. */
public static final int PRESET_STEVE = 0;
public static final int PRESET_ALEX = 1;
/** Preset cape 0 is no cape. */
public static final int PRESET_NO_CAPE = 0;
/** A player's skin: a preset number, or custom pixels (64x64 ARGB, not to be changed). */
public static final class Skin {
private final int preset;
private final int @Nullable [] pixels;
private final boolean slim;
private Skin(int preset, int @Nullable [] pixels, boolean slim) {
this.preset = preset;
this.pixels = pixels;
this.slim = slim;
}
public static Skin preset(int preset) {
// Eagler's odd presets are its slim ("Alex") variants.
return new Skin(preset, null, (preset & 1) != 0);
}
public static Skin custom(int[] pixels, boolean slim) {
return new Skin(-1, pixels, slim);
}
/** The preset's number, or -1 for a custom skin. */
public int preset() {
return preset;
}
public int @Nullable [] pixels() {
return pixels;
}
public boolean slim() {
return slim;
}
}
/** A player's cape: a preset number (0: none), or custom pixels (64x32 ARGB, not to be changed). */
public static final class Cape {
public static final Cape NONE = new Cape(PRESET_NO_CAPE, null);
private final int preset;
private final int @Nullable [] pixels;
private Cape(int preset, int @Nullable [] pixels) {
this.preset = preset;
this.pixels = pixels;
}
public static Cape preset(int preset) {
return preset == PRESET_NO_CAPE ? NONE : new Cape(preset, null);
}
public static Cape custom(int[] pixels) {
return new Cape(-1, pixels);
}
/** The preset's number, or -1 for a custom cape. */
public int preset() {
return preset;
}
public int @Nullable [] pixels() {
return pixels;
}
}
/** Hears textures arriving and changing. Calls come on the connection's event loop. */
public interface Listener {
/** The server answered a {@link #request} for {@code player}. */
void received(UUID player, Skin skin, Cape cape);
/** The server says {@code player}'s textures changed; ask again if they're still needed. */
default void invalidated(UUID player) {}
/** The server replaced this client's own skin (or cape) with {@code skin} ({@code cape}). */
default void forced(@Nullable Skin skin, @Nullable Cape cape) {}
}
private final Listener listener;
private final Map<Integer, UUID> requests = new HashMap<>();
private @Nullable EaglerMessages messages;
private int nextRequest = 1;
public EaglerTextures(Listener listener) {
this.listener = listener;
}
/** Starts sending requests over {@code messages}; call from {@link EaglerSession#loggedIn}. */
public synchronized void attach(EaglerMessages messages) {
this.messages = messages;
}
/** Asks the server for {@code player}'s skin and cape. Any thread; nothing before login. */
public void request(UUID player) {
EaglerMessages current;
int id;
synchronized (this) {
current = messages;
if (current == null) {
return;
}
id = nextRequest++;
requests.put(id, player);
}
current.send(EaglerMessages.C_GET_OTHER_TEXTURES, out -> {
Wire.writeVarInt(out, id);
out.writeLong(player.getMostSignificantBits());
out.writeLong(player.getLeastSignificantBits());
});
}
/**
* Handles an Eagler message if it's about textures; returns whether it was. Called from {@link
* EaglerSession#received}.
*/
public boolean handle(int id, ByteBuf in) {
switch (id) {
case EaglerMessages.S_OTHER_TEXTURES -> {
UUID player = answered(Wire.readVarInt(in));
int skinId = Wire.readVarInt(in);
int capeId = Wire.readVarInt(in);
Skin skin = skinId >= 0 ? Skin.preset(skinId) : readCustomSkin(in, -skinId - 1);
Cape cape = capeId >= 0 ? Cape.preset(capeId) : Cape.custom(readCape(in));
if (player != null) {
listener.received(player, skin, cape);
}
}
case EaglerMessages.S_OTHER_SKIN_PRESET,
EaglerMessages.S_OTHER_SKIN_CUSTOM,
EaglerMessages.S_OTHER_CAPE_PRESET,
EaglerMessages.S_OTHER_CAPE_CUSTOM -> {
// Answers to the skin-only and cape-only requests, which this client doesn't send.
}
case EaglerMessages.S_FORCE_SKIN_PRESET -> listener.forced(Skin.preset(in.readInt()), null);
case EaglerMessages.S_FORCE_SKIN_CUSTOM -> listener.forced(readCustomSkin(in, in.readUnsignedByte()), null);
case EaglerMessages.S_FORCE_CAPE_PRESET -> listener.forced(null, Cape.preset(in.readInt()));
case EaglerMessages.S_FORCE_CAPE_CUSTOM -> listener.forced(null, Cape.custom(readCape(in)));
case EaglerMessages.S_INVALIDATE_PLAYER -> {
int count = Wire.readVarInt(in);
for (int i = 0; i < count; i++) {
in.readUnsignedByte(); // which of skin and cape changed: both are asked for again
listener.invalidated(new UUID(in.readLong(), in.readLong()));
}
}
default -> {
return false;
}
}
return true;
}
private synchronized @Nullable UUID answered(int request) {
return requests.remove(request);
}
private static Skin readCustomSkin(ByteBuf in, int rawModel) {
byte[] data = new byte[SKIN_BYTES];
in.readBytes(data);
// The top bit marks skins converted from older formats; the rest is the model.
return Skin.custom(decodeSkin(data), (rawModel & 0x7F) == 1);
}
private static int[] readCape(ByteBuf in) {
byte[] data = new byte[CAPE_BYTES];
in.readBytes(data);
return decodeCape(data);
}
// --- Formats -----------------------------------------------------------------------------
/** Eagler's 12288-byte skin as 64x64 ARGB pixels. */
public static int[] decodeSkin(byte[] data) {
if (data.length != SKIN_BYTES) {
throw new IllegalArgumentException("A skin is " + SKIN_BYTES + " bytes, not " + data.length);
}
int[] pixels = new int[SKIN_WIDTH * SKIN_HEIGHT];
for (int i = 0; i < pixels.length; i++) {
int blue = data[i * 3] & 0xFF;
int green = data[i * 3 + 1] & 0xFF;
int redAlpha = data[i * 3 + 2] & 0xFF;
// Seven bits of red, restored the way Eagler's own clients do, so colours match theirs.
int red = (redAlpha & 0x7F) << 1;
int alpha = (redAlpha & 0x80) != 0 ? 0xFF : 0;
pixels[i] = (alpha << 24) | (red << 16) | (green << 8) | blue;
}
return pixels;
}
/** 64x64 ARGB pixels in Eagler's 12288-byte skin format (alpha kept as one bit). */
public static byte[] encodeSkin(int[] pixels) {
if (pixels.length != SKIN_WIDTH * SKIN_HEIGHT) {
throw new IllegalArgumentException("A skin is 64x64 pixels");
}
byte[] data = new byte[SKIN_BYTES];
for (int i = 0; i < pixels.length; i++) {
int argb = pixels[i];
data[i * 3] = (byte) argb;
data[i * 3 + 1] = (byte) (argb >>> 8);
data[i * 3 + 2] = (byte) (((argb >>> 17) & 0x7F) | ((argb >>> 24) & 0x80));
}
return data;
}
/** Eagler's 1173-byte cape as 64x32 ARGB pixels; what it doesn't carry is transparent. */
public static int[] decodeCape(byte[] data) {
if (data.length != CAPE_BYTES) {
throw new IllegalArgumentException("A cape is " + CAPE_BYTES + " bytes, not " + data.length);
}
int[] pixels = new int[CAPE_WIDTH * CAPE_HEIGHT];
for (int y = 0; y < 17; y++) {
for (int x = 0; x < 22; x++) {
pixels[y * CAPE_WIDTH + x] = capePixel(data, (y * 23 + x) * 3);
}
}
// The 23rd column's lower 11 rows hold the cape's column 22, rows 11 to 21.
for (int y = 0; y < 11; y++) {
pixels[(y + 11) * CAPE_WIDTH + 22] = capePixel(data, ((y + 6) * 23 + 22) * 3);
}
return pixels;
}
/** 64x32 ARGB cape pixels in Eagler's 1173-byte format. */
public static byte[] encodeCape(int[] pixels) {
if (pixels.length != CAPE_WIDTH * CAPE_HEIGHT) {
throw new IllegalArgumentException("A cape is 64x32 pixels");
}
byte[] data = new byte[CAPE_BYTES];
for (int y = 0; y < 17; y++) {
for (int x = 0; x < 22; x++) {
putCapePixel(data, (y * 23 + x) * 3, pixels[y * CAPE_WIDTH + x]);
}
}
for (int y = 0; y < 11; y++) {
putCapePixel(data, ((y + 6) * 23 + 22) * 3, pixels[(y + 11) * CAPE_WIDTH + 22]);
}
return data;
}
private static int capePixel(byte[] data, int offset) {
return 0xFF000000
| ((data[offset + 2] & 0xFF) << 16)
| ((data[offset + 1] & 0xFF) << 8)
| (data[offset] & 0xFF);
}
private static void putCapePixel(byte[] data, int offset, int argb) {
data[offset] = (byte) argb;
data[offset + 1] = (byte) (argb >>> 8);
data[offset + 2] = (byte) (argb >>> 16);
}
/**
* A 64x32 skin (from before 1.8) as a 64x64 one: the lower half gets the left arm and leg, which
* old skins share with the right ones, mirrored face by face; the second layers stay empty.
*/
public static int[] legacySkinToModern(int[] pixels) {
if (pixels.length != SKIN_WIDTH * 32) {
throw new IllegalArgumentException("A legacy skin is 64x32 pixels");
}
int[] modern = new int[SKIN_WIDTH * SKIN_HEIGHT];
System.arraycopy(pixels, 0, modern, 0, pixels.length);
mirrorLimb(modern, 0, 16, 16, 48); // right leg to left leg
mirrorLimb(modern, 40, 16, 32, 48); // right arm to left arm
return modern;
}
/**
* Copies a 16x16 limb layout (top and bottom 4x4 faces above four 4x12 sides) from ({@code
* fromX}, {@code fromY}) to ({@code toX}, {@code toY}) as its mirror image: every face flipped
* left to right, and the outer and inner sides swapped.
*/
private static void mirrorLimb(int[] skin, int fromX, int fromY, int toX, int toY) {
copyFlipped(skin, fromX + 4, fromY, toX + 4, toY, 4, 4); // top
copyFlipped(skin, fromX + 8, fromY, toX + 8, toY, 4, 4); // bottom
copyFlipped(skin, fromX + 8, fromY + 4, toX, toY + 4, 4, 12); // inner side becomes outer
copyFlipped(skin, fromX + 4, fromY + 4, toX + 4, toY + 4, 4, 12); // front
copyFlipped(skin, fromX, fromY + 4, toX + 8, toY + 4, 4, 12); // outer side becomes inner
copyFlipped(skin, fromX + 12, fromY + 4, toX + 12, toY + 4, 4, 12); // back
}
private static void copyFlipped(int[] skin, int fromX, int fromY, int toX, int toY, int width, int height) {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
skin[(toY + y) * SKIN_WIDTH + toX + width - 1 - x] = skin[(fromY + y) * SKIN_WIDTH + fromX + x];
}
}
}
/**
* Makes the skin's first layer opaque, as the game does for downloaded skins: the base head,
* body and limbs have no see-through pixels, whatever the file says. The second layer (hat,
* jacket, sleeves, trousers) keeps its transparency.
*/
public static void makeBaseLayerOpaque(int[] skin) {
opaque(skin, 0, 0, 32, 16); // head
opaque(skin, 0, 16, 64, 32); // right leg, body, right arm
opaque(skin, 16, 48, 48, 64); // left leg, left arm
}
private static void opaque(int[] skin, int x0, int y0, int x1, int y1) {
for (int y = y0; y < y1; y++) {
for (int x = x0; x < x1; x++) {
skin[y * SKIN_WIDTH + x] |= 0xFF000000;
}
}
}
/** The {@link #SKIN_PROFILE_DATA} entry for a custom skin. */
public static EaglerLogin.ProfileData skinProfileData(int[] pixels, boolean slim) {
byte[] data = new byte[2 + SKIN_BYTES];
data[0] = CUSTOM;
data[1] = (byte) (slim ? 1 : 0);
System.arraycopy(encodeSkin(pixels), 0, data, 2, SKIN_BYTES);
return new EaglerLogin.ProfileData(SKIN_PROFILE_DATA, data);
}
/** The {@link #SKIN_PROFILE_DATA} entry for a preset skin. */
public static EaglerLogin.ProfileData presetSkinProfileData(int preset) {
return new EaglerLogin.ProfileData(SKIN_PROFILE_DATA, presetData(preset));
}
/** The {@link #CAPE_PROFILE_DATA} entry for a custom cape. */
public static EaglerLogin.ProfileData capeProfileData(int[] pixels) {
byte[] data = new byte[1 + CAPE_BYTES];
data[0] = CUSTOM;
System.arraycopy(encodeCape(pixels), 0, data, 1, CAPE_BYTES);
return new EaglerLogin.ProfileData(CAPE_PROFILE_DATA, data);
}
/**
* A skin as Eagler's shared-world hosts take it in their login (the V3 layout): a preset, or
* the model and the 64x64 pixels as alpha, blue, green, red bytes.
*/
public static byte[] legacySkinPacket(Skin skin) {
int[] pixels = skin.pixels();
if (pixels == null) {
return presetData(skin.preset());
}
byte[] data = new byte[2 + SKIN_WIDTH * SKIN_HEIGHT * 4];
data[0] = CUSTOM;
data[1] = (byte) (skin.slim() ? 1 : 0);
for (int i = 0; i < SKIN_WIDTH * SKIN_HEIGHT; i++) {
int argb = pixels[i];
data[2 + i * 4] = (byte) (argb >>> 24);
data[3 + i * 4] = (byte) argb;
data[4 + i * 4] = (byte) (argb >>> 8);
data[5 + i * 4] = (byte) (argb >>> 16);
}
return data;
}
/** A cape in the layout of {@link #CAPE_PROFILE_DATA}: a preset, or the custom cape's pixels. */
public static byte[] capePacket(Cape cape) {
int[] pixels = cape.pixels();
if (pixels == null) {
return presetData(cape.preset());
}
byte[] data = new byte[1 + CAPE_BYTES];
data[0] = CUSTOM;
System.arraycopy(encodeCape(pixels), 0, data, 1, CAPE_BYTES);
return data;
}
private static byte[] presetData(int preset) {
return new byte[] {
PRESET, (byte) ((preset >>> 24) & 0x7F), (byte) (preset >>> 16), (byte) (preset >>> 8), (byte) preset
};
}
}
@@ -0,0 +1,102 @@
package incari.net.eagler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import java.util.UUID;
/**
* The vanilla login packets the Eagler stage writes to the game in the server's place. An Eagler
* proxy logs the player in to its backend itself; the client only sees Eagler's own exchange. So
* the stage answers the game's login with the packets a server would have sent, in the protocol
* version the proxy was told (the connection's Minecraft protocol, which is the server's version
* when Via translates above this stage).
*/
final class VanillaLogin {
/** 1.16: the player's UUID is written as two longs instead of a string. */
static final int BINARY_UUID = 735;
/** 1.19: Login Success carries the profile's properties. */
static final int PROFILE_PROPERTIES = 759;
/** 1.20.2: login ends with the client's Login Acknowledged and a configuration phase. */
static final int LOGIN_ACKNOWLEDGED = 764;
/** 1.20.5 to 1.21.1: Login Success ends with a "strict error handling" flag. */
static final int STRICT_ERRORS_FROM = 766;
static final int STRICT_ERRORS_UNTIL = 767;
/** 26.2: Login Success ends with a session id. */
static final int SESSION_ID = 776;
/** Clientbound login packet ids, the same in every version. */
static final int LOGIN_DISCONNECT_ID = 0x00;
static final int LOGIN_SUCCESS_ID = 0x02;
/** Serverbound: the handshake (in its own state) and Login Start both have id 0. */
static final int HANDSHAKE_ID = 0x00;
static final int LOGIN_START_ID = 0x00;
static final int LOGIN_ACKNOWLEDGED_ID = 0x03;
private VanillaLogin() {}
/** Whether a server of this protocol expects Login Acknowledged before configuration. */
static boolean acknowledgesLogin(int protocol) {
return protocol >= LOGIN_ACKNOWLEDGED;
}
/** Login Success for {@code name} and {@code uuid}, in the layout {@code protocol} uses. */
static ByteBuf loginSuccess(ByteBufAllocator alloc, int protocol, String name, UUID uuid) {
ByteBuf out = alloc.buffer();
Wire.writeVarInt(out, LOGIN_SUCCESS_ID);
if (protocol >= BINARY_UUID) {
out.writeLong(uuid.getMostSignificantBits());
out.writeLong(uuid.getLeastSignificantBits());
} else {
Wire.writeString(out, uuid.toString());
}
Wire.writeString(out, name);
if (protocol >= PROFILE_PROPERTIES) {
Wire.writeVarInt(out, 0); // no properties: offline profile
}
if (protocol >= STRICT_ERRORS_FROM && protocol <= STRICT_ERRORS_UNTIL) {
out.writeBoolean(false);
}
if (protocol >= SESSION_ID) {
// Fresh per login: the proxy chose none, and the game only uses it to tell sessions apart.
UUID session = UUID.randomUUID();
out.writeLong(session.getMostSignificantBits());
out.writeLong(session.getLeastSignificantBits());
}
return out;
}
/**
* A login-state disconnect showing {@code message}: a JSON text component (every version's
* login disconnect is JSON), or plain text, which is wrapped in one.
*/
static ByteBuf loginDisconnect(ByteBufAllocator alloc, String message) {
ByteBuf out = alloc.buffer();
Wire.writeVarInt(out, LOGIN_DISCONNECT_ID);
Wire.writeString(out, message.startsWith("{") ? message : jsonText(message));
return out;
}
static String jsonText(String text) {
StringBuilder json = new StringBuilder(text.length() + 12).append("{\"text\":\"");
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
switch (c) {
case '"' -> json.append("\\\"");
case '\\' -> json.append("\\\\");
case '\n' -> json.append("\\n");
default -> {
if (c < 0x20) {
json.append(c < 0x10 ? "\\u000" : "\\u00").append(Integer.toHexString(c));
} else {
json.append(c);
}
}
}
}
return json.append("\"}").toString();
}
}
@@ -0,0 +1,97 @@
package incari.net.eagler;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.DecoderException;
import java.nio.charset.StandardCharsets;
/**
* The few Minecraft and Eagler wire types this package reads and writes: VarInts, the game's
* length-prefixed UTF-8 strings, and Eagler's byte- or short-prefixed ASCII strings.
*/
final class Wire {
private Wire() {}
static void writeVarInt(ByteBuf out, int value) {
while ((value & ~0x7F) != 0) {
out.writeByte((value & 0x7F) | 0x80);
value >>>= 7;
}
out.writeByte(value);
}
static int readVarInt(ByteBuf in) {
int value = 0;
for (int shift = 0; shift < 35; shift += 7) {
byte next = in.readByte();
value |= (next & 0x7F) << shift;
if ((next & 0x80) == 0) {
return value;
}
}
throw new DecoderException("VarInt too long");
}
/** The first VarInt of a packet (its id) without moving the reader, or -1 if it's cut short. */
static int peekVarInt(ByteBuf in) {
int value = 0;
int index = in.readerIndex();
for (int shift = 0; shift < 35 && index < in.writerIndex(); shift += 7) {
byte next = in.getByte(index++);
value |= (next & 0x7F) << shift;
if ((next & 0x80) == 0) {
return value;
}
}
return -1;
}
/** A game string: VarInt byte length, then UTF-8. */
static void writeString(ByteBuf out, String value) {
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
writeVarInt(out, bytes.length);
out.writeBytes(bytes);
}
static String readString(ByteBuf in) {
int length = readVarInt(in);
if (length < 0 || length > in.readableBytes()) {
throw new DecoderException("Bad string length " + length);
}
String value = in.toString(in.readerIndex(), length, StandardCharsets.UTF_8);
in.skipBytes(length);
return value;
}
/** An Eagler handshake string: an unsigned byte length, then ASCII, cut to 255 characters. */
static void writeByteAscii(ByteBuf out, String value) {
byte[] bytes = ascii(value, 255);
out.writeByte(bytes.length);
out.writeBytes(bytes);
}
static String readByteAscii(ByteBuf in) {
int length = in.readUnsignedByte();
String value = in.toString(in.readerIndex(), length, StandardCharsets.US_ASCII);
in.skipBytes(length);
return value;
}
/** An unsigned short length, then UTF-8 (Eagler's error and deny messages). */
static String readShortUtf8(ByteBuf in) {
int length = in.readUnsignedShort();
String value = in.toString(in.readerIndex(), length, StandardCharsets.UTF_8);
in.skipBytes(length);
return value;
}
static byte[] ascii(String value, int maxLength) {
int length = Math.min(value.length(), maxLength);
byte[] bytes = new byte[length];
for (int i = 0; i < length; i++) {
char c = value.charAt(i);
bytes[i] = (byte) (c < 0x80 ? c : '?');
}
return bytes;
}
}
@@ -0,0 +1,10 @@
/**
* The client side of Eagler's protocol (ADR 0016): the V5 handshake that opens every connection to
* an Eagler server, Eagler's own messages beside the game's packets (skins and capes), and the MOTD
* query the server list uses. Written from the protocol as EaglerXServer speaks it; no code of
* EaglerXServer's is used. No game types.
*/
@NullMarked
package incari.net.eagler;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,163 @@
package incari.net.https;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* One HTTPS request: method, host ({@code host}, lower case), path and query, headers and body. Built from an {@code https://} URL;
* other schemes and ports are refused, since sign-in only ever talks to HTTPS hosts on 443.
* {@code Host}, {@code Content-Length} and {@code Connection: close} are added on the wire.
*/
public final class HttpRequest {
private final String method;
private final String host;
private final String path;
private final Map<String, String> headers;
private final byte[] body;
public HttpRequest(String method, String host, String path, Map<String, String> headers, byte[] body) {
this.method = method;
this.host = host;
this.path = path;
this.headers = Map.copyOf(headers);
this.body = body.clone();
checkToken(method);
checkHost(host);
if (!path.startsWith("/") || hasControl(path) || path.indexOf(' ') >= 0) {
throw new IllegalArgumentException("Not a request path: " + path);
}
for (Map.Entry<String, String> header : this.headers.entrySet()) {
checkToken(header.getKey());
if (hasControl(header.getValue())) {
throw new IllegalArgumentException("Header " + header.getKey() + " has a control character");
}
}
}
public String method() {
return method;
}
public String host() {
return host;
}
public String path() {
return path;
}
public Map<String, String> headers() {
return headers;
}
public byte[] body() {
return body.clone();
}
/** A GET of {@code url}. */
public static HttpRequest get(String url, Map<String, String> headers) {
Target target = Target.parse(url);
return new HttpRequest("GET", target.host(), target.path(), headers, new byte[0]);
}
/** A POST of {@code body} as {@code contentType} to {@code url}. */
public static HttpRequest post(String url, String contentType, String body, Map<String, String> headers) {
Target target = Target.parse(url);
Map<String, String> all = new LinkedHashMap<>(headers);
all.put("Content-Type", contentType);
return new HttpRequest("POST", target.host(), target.path(), all, body.getBytes(StandardCharsets.UTF_8));
}
/** The request as it goes on the wire: HTTP/1.1, one request, then the connection closes. */
byte[] encode() {
StringBuilder head = new StringBuilder();
head.append(method).append(' ').append(path).append(" HTTP/1.1\r\n");
head.append("Host: ").append(host).append("\r\n");
head.append("Connection: close\r\n");
head.append("Accept-Encoding: identity\r\n");
if (body.length > 0 || method.equals("POST")) {
head.append("Content-Length: ").append(body.length).append("\r\n");
}
List<String> names = new ArrayList<>(headers.keySet());
names.sort(String.CASE_INSENSITIVE_ORDER);
for (String name : names) {
head.append(name).append(": ").append(headers.get(name)).append("\r\n");
}
head.append("\r\n");
byte[] start = head.toString().getBytes(StandardCharsets.UTF_8);
byte[] all = new byte[start.length + body.length];
System.arraycopy(start, 0, all, 0, start.length);
System.arraycopy(body, 0, all, start.length, body.length);
return all;
}
@Override
public String toString() {
// Never the body or headers: they carry tokens.
return method + " https://" + host + pathWithoutQuery();
}
private String pathWithoutQuery() {
int query = path.indexOf('?');
return query < 0 ? path : path.substring(0, query);
}
private static void checkToken(String token) {
if (token.isEmpty()) {
throw new IllegalArgumentException("Empty HTTP token");
}
for (int i = 0; i < token.length(); i++) {
char c = token.charAt(i);
boolean ok =
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || "-_.".indexOf(c) >= 0;
if (!ok) {
throw new IllegalArgumentException("Not an HTTP token: " + token);
}
}
}
private static void checkHost(String host) {
if (host.isEmpty() || !host.equals(host.toLowerCase(java.util.Locale.ROOT))) {
throw new IllegalArgumentException("Not a lower-case host: " + host);
}
for (int i = 0; i < host.length(); i++) {
char c = host.charAt(i);
if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '.')) {
throw new IllegalArgumentException("Not a host name: " + host);
}
}
}
private static boolean hasControl(String text) {
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c < 0x20 || c == 0x7F) {
return true;
}
}
return false;
}
/** An {@code https://host/path} URL, split by hand (the browser build has no {@code java.net.URI}). */
record Target(String host, String path) {
static Target parse(String url) {
String prefix = "https://";
if (!url.startsWith(prefix)) {
throw new IllegalArgumentException("Not an https URL: " + url);
}
String rest = url.substring(prefix.length());
int slash = rest.indexOf('/');
String authority = slash < 0 ? rest : rest.substring(0, slash);
String path = slash < 0 ? "/" : rest.substring(slash);
if (authority.indexOf('@') >= 0 || authority.indexOf(':') >= 0) {
throw new IllegalArgumentException("Only a plain host on port 443: " + url);
}
return new Target(authority.toLowerCase(java.util.Locale.ROOT), path);
}
}
}
@@ -0,0 +1,55 @@
package incari.net.https;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import org.jspecify.annotations.Nullable;
/**
* A whole HTTP response: the status, the headers (names in lower case; a repeated header keeps its
* last value) and the body (decoded from chunks if it was chunked).
*/
public final class HttpResponse {
private final int status;
private final Map<String, String> headers;
private final byte[] body;
public HttpResponse(int status, Map<String, String> headers, byte[] body) {
this.status = status;
this.headers = Map.copyOf(headers);
this.body = body.clone();
}
public int status() {
return status;
}
public Map<String, String> headers() {
return headers;
}
public byte[] body() {
return body.clone();
}
/** The body as UTF-8 text. */
public String text() {
return new String(body, StandardCharsets.UTF_8);
}
/** A header's value, by name in any case. */
public @Nullable String header(String name) {
return headers.get(name.toLowerCase(java.util.Locale.ROOT));
}
/** Whether the status is 2xx. */
public boolean ok() {
return status >= 200 && status < 300;
}
@Override
public String toString() {
// Never the body: it can carry tokens.
return "HTTP " + status + " (" + body.length + " bytes)";
}
}
@@ -0,0 +1,11 @@
package incari.net.https;
import java.util.concurrent.CompletableFuture;
/** Sends HTTPS requests: {@link HttpsClient}, or a fake in tests. */
@FunctionalInterface
public interface Https {
/** Sends {@code request}; the future fails with an {@link java.io.IOException} on any failure. */
CompletableFuture<HttpResponse> send(HttpRequest request);
}
@@ -0,0 +1,153 @@
package incari.net.https;
import incari.net.tls.CertificateChain;
import incari.net.tls.TlsConnection;
import incari.net.tls.Transport;
import incari.platform.api.net.NetConnection;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.LongSupplier;
import org.jspecify.annotations.Nullable;
/**
* HTTPS requests over {@link TlsConnection}: one connection per request, HTTP/1.1, closed after
* the response. Only the hosts it's built with can be reached, so nothing that reaches it can
* point it, and the tokens it carries, anywhere else.
*
* <p>Nothing blocks: {@link #send} returns a future completed on the transport's thread (the
* browser's main thread, the desktop's reader thread). Callers that touch the game hop back to it.
*/
public final class HttpsClient implements Https {
/** How long a request may take, from connecting to the response's last byte. */
static final long TIMEOUT_SECONDS = 30;
private static final int PORT = 443;
private final Transport transport;
private final Set<String> hosts;
private final CertificateChain certificates;
private final LongSupplier clock;
/**
* @param hosts the only hosts requests may go to
* @param clock the time certificates are checked against, in epoch milliseconds
*/
public HttpsClient(Transport transport, Set<String> hosts, CertificateChain certificates, LongSupplier clock) {
this.transport = transport;
this.hosts = Set.copyOf(hosts);
this.certificates = certificates;
this.clock = clock;
}
/** Pinned roots and the system clock. */
public static HttpsClient pinned(Transport transport, Set<String> hosts) {
return new HttpsClient(transport, hosts, CertificateChain.pinned(), System::currentTimeMillis);
}
/**
* Sends {@code request}. The future fails with an {@link IOException} if the host isn't allowed,
* the connection or TLS fails, the response is malformed, or it takes too long.
*/
@Override
public CompletableFuture<HttpResponse> send(HttpRequest request) {
CompletableFuture<HttpResponse> result = new CompletableFuture<>();
if (!hosts.contains(request.host())) {
result.completeExceptionally(new IOException("Incari doesn't send sign-in requests to " + request.host()));
return result;
}
Exchange exchange = new Exchange(request, result);
NetConnection connection = TlsConnection.open(transport, request.host(), PORT, certificates, clock, exchange);
exchange.attach(connection);
// The connection closes once the response is in, fails or times out.
return result.orTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.whenComplete((response, failure) -> connection.close());
}
/** One request and its response, as the connection's listener. */
private static final class Exchange implements NetConnection.Listener {
private final HttpRequest request;
private final CompletableFuture<HttpResponse> result;
private final ResponseParser parser;
// Guarded by this: the connection can say it's connected before open() has returned it.
private @Nullable NetConnection connection;
private boolean connectedEarly;
Exchange(HttpRequest request, CompletableFuture<HttpResponse> result) {
this.request = request;
this.result = result;
this.parser = new ResponseParser(request.method().equals("HEAD"));
}
void attach(NetConnection opened) {
boolean sendNow;
synchronized (this) {
connection = opened;
sendNow = connectedEarly;
}
if (sendNow) {
sendRequest(opened);
}
}
@Override
public void connected() {
NetConnection current;
synchronized (this) {
current = connection;
connectedEarly = current == null;
}
if (current != null) {
sendRequest(current);
}
}
private void sendRequest(NetConnection current) {
current.send(ByteBuffer.wrap(request.encode()));
current.flush();
}
@Override
public void received(ByteBuffer data) {
if (result.isDone()) {
return;
}
byte[] bytes = new byte[data.remaining()];
data.get(bytes);
try {
synchronized (parser) {
HttpResponse response = parser.feed(bytes, 0, bytes.length);
if (response != null) {
result.complete(response);
}
}
} catch (IOException | RuntimeException e) {
result.completeExceptionally(e instanceof IOException ? e : new IOException(e));
}
}
@Override
public void closed(@Nullable Throwable cause) {
if (result.isDone()) {
return;
}
try {
synchronized (parser) {
result.complete(parser.finish(cause == null));
}
} catch (IOException e) {
IOException failure = cause != null ? new IOException(failureText(cause), cause) : e;
result.completeExceptionally(failure);
}
}
private String failureText(Throwable cause) {
String message = cause.getMessage();
return "Couldn't reach " + request.host() + (message != null ? ": " + message : "");
}
}
}
@@ -0,0 +1,251 @@
package incari.net.https;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.jspecify.annotations.Nullable;
/**
* Reads one HTTP/1.1 response as its bytes arrive: the status line and headers, then a body framed
* by {@code Content-Length}, by chunks, or (with neither) by the connection's end. Sizes are capped,
* since a hostile proxy can't forge a response but a hostile or broken server could send any.
*
* <p>Interim 1xx responses are skipped. Not thread-safe; its connection feeds it in order.
*/
final class ResponseParser {
static final int MAX_HEAD = 32 * 1024;
static final int MAX_BODY = 1024 * 1024;
/** CR LF CR LF as four bytes of an int. */
private static final int BLANK_LINE = 0x0D0A0D0A;
private enum State {
HEAD,
BODY_LENGTH,
CHUNK_SIZE,
CHUNK_DATA,
CHUNK_END,
TRAILERS,
UNTIL_CLOSE,
DONE
}
private final boolean head;
private State state = State.HEAD;
private final ByteArrayOutputStream line = new ByteArrayOutputStream();
private final ByteArrayOutputStream headBytes = new ByteArrayOutputStream();
private final ByteArrayOutputStream body = new ByteArrayOutputStream();
private int status;
private Map<String, String> headers = new HashMap<>();
private long remaining;
/** The last four bytes of the head, to spot the blank line that ends it. */
private int headTail;
/** The byte before the current one in a line, to spot its CRLF. */
private byte lastLineByte;
/** @param head whether the request was a HEAD (or otherwise expects no body) */
ResponseParser(boolean head) {
this.head = head;
}
/**
* Takes more of the stream.
*
* @return the whole response once it's complete, else null
* @throws IOException if the response is malformed or too big
*/
@Nullable
HttpResponse feed(byte[] data, int offset, int length) throws IOException {
int i = offset;
int end = offset + length;
while (i < end && state != State.DONE) {
switch (state) {
case HEAD -> {
byte b = data[i++];
headBytes.write(b);
if (headBytes.size() > MAX_HEAD) {
throw new IOException("The response's headers are too long");
}
headTail = (headTail << 8) | (b & 0xFF);
if (headTail == BLANK_LINE) {
headTail = 0;
parseHead();
}
}
case BODY_LENGTH -> {
int n = (int) Math.min(remaining, end - i);
writeBody(data, i, n);
i += n;
remaining -= n;
if (remaining == 0) {
state = State.DONE;
}
}
case CHUNK_SIZE -> {
if (readLine(data[i++])) {
remaining = chunkSize(takeLine());
state = remaining == 0 ? State.TRAILERS : State.CHUNK_DATA;
}
}
case CHUNK_DATA -> {
int n = (int) Math.min(remaining, end - i);
writeBody(data, i, n);
i += n;
remaining -= n;
if (remaining == 0) {
state = State.CHUNK_END;
}
}
case CHUNK_END -> {
if (readLine(data[i++])) {
if (!takeLine().isEmpty()) {
throw new IOException("A chunk of the response runs over its size");
}
state = State.CHUNK_SIZE;
}
}
case TRAILERS -> {
if (readLine(data[i++]) && takeLine().isEmpty()) {
state = State.DONE;
}
}
case UNTIL_CLOSE -> {
writeBody(data, i, end - i);
i = end;
}
case DONE -> throw new IllegalStateException();
}
}
return state == State.DONE ? response() : null;
}
/**
* The connection ended. A body framed by the connection's end is whole only if the end was a
* proper TLS close ({@code cleanClose}); anything else still waiting is truncated.
*/
HttpResponse finish(boolean cleanClose) throws IOException {
if (state == State.DONE || (state == State.UNTIL_CLOSE && cleanClose)) {
return response();
}
throw new IOException("The response was cut off");
}
private HttpResponse response() {
state = State.DONE;
return new HttpResponse(status, headers, body.toByteArray());
}
private void parseHead() throws IOException {
String text = headBytes.toString(StandardCharsets.ISO_8859_1);
headBytes.reset();
String[] lines = text.split("\r\n", -1);
String[] statusLine = lines[0].split(" ", 3);
if (statusLine.length < 2 || !statusLine[0].startsWith("HTTP/1.")) {
throw new IOException("Not an HTTP/1.x response");
}
try {
status = Integer.parseInt(statusLine[1]);
} catch (NumberFormatException e) {
throw new IOException("Not an HTTP status: " + statusLine[1], e);
}
if (status < 100 || status > 999) {
throw new IOException("Not an HTTP status: " + status);
}
Map<String, String> parsed = new HashMap<>();
for (int i = 1; i < lines.length; i++) {
String header = lines[i];
if (header.isEmpty()) {
continue;
}
int colon = header.indexOf(':');
if (colon <= 0) {
throw new IOException("A malformed response header");
}
String name = header.substring(0, colon).strip().toLowerCase(Locale.ROOT);
String value = header.substring(colon + 1).strip();
if (name.equals("content-length")
&& parsed.containsKey(name)
&& !parsed.get(name).equals(value)) {
throw new IOException("Two different response lengths");
}
parsed.put(name, value);
}
if (status < 200) {
// An interim response (100 Continue): the real one follows.
return;
}
headers = parsed;
if (head || status == 204 || status == 304) {
state = State.DONE;
return;
}
String transfer = parsed.get("transfer-encoding");
if (transfer != null) {
if (!transfer.equalsIgnoreCase("chunked")) {
throw new IOException("An unsupported transfer encoding: " + transfer);
}
state = State.CHUNK_SIZE;
return;
}
String length = parsed.get("content-length");
if (length != null) {
try {
remaining = Long.parseLong(length);
} catch (NumberFormatException e) {
throw new IOException("Not a response length: " + length, e);
}
if (remaining < 0 || remaining > MAX_BODY) {
throw new IOException("The response is too big");
}
state = remaining == 0 ? State.DONE : State.BODY_LENGTH;
return;
}
state = State.UNTIL_CLOSE;
}
private void writeBody(byte[] data, int offset, int length) throws IOException {
if (body.size() + (long) length > MAX_BODY) {
throw new IOException("The response is too big");
}
body.write(data, offset, length);
}
/** Adds a byte to the current line; true once the line has ended (CRLF). */
private boolean readLine(byte b) throws IOException {
line.write(b);
if (line.size() > 1024) {
throw new IOException("A line of the response is too long");
}
boolean ended = lastLineByte == '\r' && b == '\n';
lastLineByte = ended ? 0 : b;
return ended;
}
private String takeLine() {
String text = line.toString(StandardCharsets.ISO_8859_1);
line.reset();
return text.substring(0, text.length() - 2);
}
private long chunkSize(String text) throws IOException {
int semicolon = text.indexOf(';');
String hex = (semicolon < 0 ? text : text.substring(0, semicolon)).strip();
if (hex.isEmpty() || hex.length() > 8) {
throw new IOException("Not a chunk size: " + hex);
}
long size;
try {
size = Long.parseLong(hex, 16);
} catch (NumberFormatException e) {
throw new IOException("Not a chunk size: " + hex, e);
}
if (size < 0 || body.size() + size > MAX_BODY) {
throw new IOException("The response is too big");
}
return size;
}
}
@@ -0,0 +1,9 @@
/**
* A small HTTPS/1.1 client over {@link incari.net.tls.TlsConnection}, for sign-in's handful of
* JSON requests (ADR 0070): one request per connection, an allow-list of hosts, capped sizes and
* a time limit. No game types, no blocking.
*/
@NullMarked
package incari.net.https;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,25 @@
package incari.net.msa;
/**
* A device-code sign-in under way: the player opens {@link #pageUrl} on any device and types
* {@link #userCode}, while the client asks every {@link #intervalSeconds} whether they have.
*
* @param userCode the short code the player types
* @param deviceCode the code the client polls with; secret, never shown or logged
* @param pageUrl Microsoft's page for the code, checked to be on {@code microsoft.com}
* @param expiresAtMillis when the code stops working, in epoch milliseconds
* @param intervalSeconds how often to poll
*/
public record DeviceCode(
String userCode, String deviceCode, String pageUrl, long expiresAtMillis, int intervalSeconds) {
/** The page with the code filled in, for a link or a QR code. */
public String pageWithCode() {
return pageUrl + (pageUrl.indexOf('?') < 0 ? "?" : "&") + "otc=" + userCode;
}
@Override
public String toString() {
return "DeviceCode[" + userCode + ", " + pageUrl + "]";
}
}
@@ -0,0 +1,15 @@
package incari.net.msa;
/** What {@code sessionserver} said to a join: the server then checks it said yes. */
public enum JoinResult {
/** Joined: the server will find this account in the session server. */
OK,
/** The Minecraft token was refused: sign in again. */
INVALID_SESSION,
/** The account may not play online (a child account, or multiplayer turned off). */
INSUFFICIENT_PRIVILEGES,
/** The account is banned from multiplayer. */
BANNED,
/** The session server couldn't be reached or answered something else. */
UNAVAILABLE
}
@@ -0,0 +1,109 @@
package incari.net.msa;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import org.jspecify.annotations.Nullable;
/**
* A signed-in Minecraft account: who it is, the Minecraft token servers check, and the Microsoft
* refresh token that gets a new one. The tokens are secrets: {@link #toString} leaves them out,
* and nothing logs them.
*
* @param name the player's name
* @param id the profile id, 32 hex digits without dashes, as Mojang's services write it
* @param minecraftToken the token {@code sessionserver} checks on a join
* @param minecraftExpiresAtMillis when it stops working, in epoch milliseconds
* @param refreshToken Microsoft's refresh token, for a new Minecraft token without signing in again
*/
public record MicrosoftAccount(
String name, String id, String minecraftToken, long minecraftExpiresAtMillis, String refreshToken) {
public MicrosoftAccount {
if (!isPlayerName(name)) {
throw new IllegalArgumentException("Not a player name");
}
if (!isProfileId(id)) {
throw new IllegalArgumentException("Not a profile id");
}
if (minecraftToken.isEmpty() || refreshToken.isEmpty()) {
throw new IllegalArgumentException("Missing token");
}
}
/** The profile id with dashes, as {@code java.util.UUID} reads it. */
public String dashedId() {
return id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20)
+ "-" + id.substring(20);
}
/** Whether the Minecraft token is still good for at least {@code marginMillis} at {@code nowMillis}. */
public boolean fresh(long nowMillis, long marginMillis) {
return nowMillis + marginMillis < minecraftExpiresAtMillis;
}
/** The account as JSON, for its file. Holds the tokens: only ever written to the player's own storage. */
public String toJson() {
JsonObject json = new JsonObject();
json.addProperty("version", 1);
json.addProperty("name", name);
json.addProperty("id", id);
json.addProperty("minecraftToken", minecraftToken);
json.addProperty("minecraftExpiresAt", minecraftExpiresAtMillis);
json.addProperty("refreshToken", refreshToken);
return json.toString();
}
/** The account {@link #toJson} wrote, or null if the text isn't one. */
public static @Nullable MicrosoftAccount fromJson(String text) {
try {
JsonObject json = JsonParser.parseString(text).getAsJsonObject();
if (json.get("version").getAsInt() != 1) {
return null;
}
return new MicrosoftAccount(
json.get("name").getAsString(),
json.get("id").getAsString(),
json.get("minecraftToken").getAsString(),
json.get("minecraftExpiresAt").getAsLong(),
json.get("refreshToken").getAsString());
} catch (JsonParseException
| IllegalStateException
| IllegalArgumentException
| NullPointerException
| UnsupportedOperationException e) {
return null;
}
}
static boolean isPlayerName(String name) {
if (name.isEmpty() || name.length() > 16) {
return false;
}
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_')) {
return false;
}
}
return true;
}
static boolean isProfileId(String id) {
if (id.length() != 32) {
return false;
}
for (int i = 0; i < id.length(); i++) {
char c = id.charAt(i);
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) {
return false;
}
}
return true;
}
@Override
public String toString() {
return "MicrosoftAccount[" + name + ", " + dashedId() + "]";
}
}
@@ -0,0 +1,42 @@
package incari.net.msa;
import java.util.Set;
/**
* Where Microsoft sign-in goes, and as whom (ADR 0070). Every URL here is HTTPS on a host in
* {@link #HOSTS}, the only hosts the sign-in client will connect to.
*/
public final class MicrosoftEndpoints {
/**
* The OAuth client sign-in asks Microsoft for tokens as: the official Minecraft launcher's. An
* app of Incari's own would need Mojang's approval to reach {@code login_with_xbox}. Swapping it
* is this one line plus {@link #SCOPE} (an Azure app uses {@code login.microsoftonline.com}).
*/
public static final String CLIENT_ID = "00000000402b5328";
/** The scope the launcher's client asks for: an Xbox Live ticket. */
public static final String SCOPE = "service::user.auth.xboxlive.com::MBI_SSL";
static final String DEVICE_CODE = "https://login.live.com/oauth20_connect.srf";
static final String TOKEN = "https://login.live.com/oauth20_token.srf";
static final String XBOX_USER = "https://user.auth.xboxlive.com/user/authenticate";
static final String XSTS = "https://xsts.auth.xboxlive.com/xsts/authorize";
static final String LOGIN_WITH_XBOX = "https://api.minecraftservices.com/authentication/login_with_xbox";
static final String PROFILE = "https://api.minecraftservices.com/minecraft/profile";
static final String CERTIFICATES = "https://api.minecraftservices.com/player/certificates";
static final String JOIN = "https://sessionserver.mojang.com/session/minecraft/join";
/** The only hosts sign-in may reach. */
public static final Set<String> HOSTS = Set.of(
"login.live.com",
"user.auth.xboxlive.com",
"xsts.auth.xboxlive.com",
"api.minecraftservices.com",
"sessionserver.mojang.com");
/** Where the player types the code; the device-code answer must name a page on this host. */
static final Set<String> CODE_PAGE_HOSTS = Set.of("www.microsoft.com", "microsoft.com");
private MicrosoftEndpoints() {}
}
@@ -0,0 +1,498 @@
package incari.net.msa;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import incari.net.https.HttpRequest;
import incari.net.https.HttpResponse;
import incari.net.https.Https;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.function.LongSupplier;
import org.jspecify.annotations.Nullable;
/**
* Microsoft sign-in as the Minecraft launcher does it, written from the services' public behaviour
* (ADR 0070): a device code from {@code login.live.com}, the player approving it on any device, an
* Xbox Live token and an XSTS token for Minecraft, then {@code login_with_xbox} for the Minecraft
* token and the profile it belongs to. Also a session-server join and the chat-signing key pair.
*
* <p>Every call returns at once; the futures complete on the transport's thread. Failures are
* {@link SignInException}s with a message for the player. No token is ever logged.
*/
public final class MicrosoftSignIn {
/** Renew a Minecraft token with less than this left, so a join never races its expiry. */
public static final long RENEW_MARGIN_MILLIS = 10 * 60 * 1000L;
private static final String JSON = "application/json";
private static final String FORM = "application/x-www-form-urlencoded";
private final Https https;
private final LongSupplier clock;
/**
* @param https a client allowed {@link MicrosoftEndpoints#HOSTS} (an {@link incari.net.https.HttpsClient})
* @param clock epoch milliseconds, for expiry times
*/
public MicrosoftSignIn(Https https, LongSupplier clock) {
this.https = https;
this.clock = clock;
}
// --- Device code ---------------------------------------------------------------------------
/** Asks for a code for the player to type at Microsoft's page. */
public CompletableFuture<DeviceCode> requestCode() {
Map<String, String> form = new LinkedHashMap<>();
form.put("client_id", MicrosoftEndpoints.CLIENT_ID);
form.put("scope", MicrosoftEndpoints.SCOPE);
form.put("response_type", "device_code");
return post(MicrosoftEndpoints.DEVICE_CODE, FORM, form(form), Map.of()).thenApply(response -> {
JsonObject json = json(response, "Microsoft");
if (!response.ok()) {
throw failure("Microsoft didn't give a sign-in code (" + errorCode(json, response) + ")");
}
String userCode = string(json, "user_code");
String page = string(json, "verification_uri");
if (!isCodePage(page) || !isPlainCode(userCode)) {
throw failure("Microsoft's sign-in answer looked wrong");
}
long expiresIn = number(json, "expires_in");
long interval = json.has("interval") ? number(json, "interval") : 5;
return new DeviceCode(
userCode,
string(json, "device_code"),
page,
clock.getAsLong() + Math.max(0, expiresIn) * 1000,
(int) Math.max(1, Math.min(interval, 60)));
});
}
/** What one poll found. */
public enum PollState {
/** The player hasn't typed the code yet: poll again after the interval. */
WAITING,
/** Microsoft asks for slower polling: add five seconds to the interval. */
SLOW_DOWN,
/** Signed in: {@link Poll#tokens} holds Microsoft's tokens. */
DONE
}
/** A poll's answer; {@code tokens} is set when {@code state} is {@link PollState#DONE}. */
public record Poll(PollState state, @Nullable MicrosoftTokens tokens) {}
/** Microsoft's tokens: the access token for Xbox Live, and the refresh token to keep. */
public record MicrosoftTokens(String accessToken, String refreshToken) {
@Override
public String toString() {
return "MicrosoftTokens[…]";
}
}
/** Asks whether the player has typed {@code code}'s code yet. */
public CompletableFuture<Poll> poll(DeviceCode code) {
if (clock.getAsLong() >= code.expiresAtMillis()) {
return CompletableFuture.failedFuture(new SignInException("The sign-in code expired. Start again."));
}
Map<String, String> form = new LinkedHashMap<>();
form.put("client_id", MicrosoftEndpoints.CLIENT_ID);
form.put("grant_type", "urn:ietf:params:oauth:grant-type:device_code");
form.put("device_code", code.deviceCode());
return post(MicrosoftEndpoints.TOKEN, FORM, form(form), Map.of()).thenApply(response -> {
JsonObject json = json(response, "Microsoft");
if (response.ok()) {
return new Poll(PollState.DONE, tokens(json));
}
String error = errorCode(json, response);
return switch (error) {
case "authorization_pending" -> new Poll(PollState.WAITING, null);
case "slow_down" -> new Poll(PollState.SLOW_DOWN, null);
case "expired_token" -> throw failure("The sign-in code expired. Start again.");
case "authorization_declined", "access_denied" -> throw failure("Sign-in was cancelled.");
default ->
// Microsoft's own trouble passes; anything else it said is its answer.
throw serviceTrouble(response)
? temporaryFailure("Microsoft's sign-in isn't answering right now (" + error + ")")
: failure("Microsoft refused the sign-in (" + error + ")");
};
});
}
/** Swaps a refresh token for new tokens. */
public CompletableFuture<MicrosoftTokens> refresh(String refreshToken) {
Map<String, String> form = new LinkedHashMap<>();
form.put("client_id", MicrosoftEndpoints.CLIENT_ID);
form.put("scope", MicrosoftEndpoints.SCOPE);
form.put("grant_type", "refresh_token");
form.put("refresh_token", refreshToken);
return post(MicrosoftEndpoints.TOKEN, FORM, form(form), Map.of()).thenApply(response -> {
JsonObject json = json(response, "Microsoft");
if (!response.ok()) {
if (serviceTrouble(response)) {
// Not the sign-in's fault: it's still good, and the next try may get through.
throw temporaryFailure("Microsoft's sign-in isn't answering right now. Try again in a moment.");
}
// invalid_grant and the like: the refresh token expired or was revoked.
throw failure("The Microsoft sign-in has expired. Sign in again.");
}
return tokens(json);
});
}
private static MicrosoftTokens tokens(JsonObject json) {
return new MicrosoftTokens(string(json, "access_token"), string(json, "refresh_token"));
}
// --- Xbox Live and Minecraft ---------------------------------------------------------------
/** Signs in to Minecraft with Microsoft's tokens: Xbox Live, XSTS, the Minecraft token, the profile. */
public CompletableFuture<MicrosoftAccount> signIn(MicrosoftTokens tokens) {
return xboxUser(tokens.accessToken(), "t=")
.thenCompose(this::xsts)
.thenCompose(this::minecraftToken)
.thenCompose(login -> profile(login, tokens.refreshToken()));
}
/**
* {@code account} with a Minecraft token good for at least {@link #RENEW_MARGIN_MILLIS}: itself
* if it has one, else renewed through its refresh token.
*/
public CompletableFuture<MicrosoftAccount> renew(MicrosoftAccount account) {
if (account.fresh(clock.getAsLong(), RENEW_MARGIN_MILLIS)) {
return CompletableFuture.completedFuture(account);
}
return refresh(account.refreshToken()).thenCompose(this::signIn);
}
private CompletableFuture<String> xboxUser(String microsoftToken, String ticketPrefix) {
JsonObject properties = new JsonObject();
properties.addProperty("AuthMethod", "RPS");
properties.addProperty("SiteName", "user.auth.xboxlive.com");
properties.addProperty("RpsTicket", ticketPrefix + microsoftToken);
JsonObject body = new JsonObject();
body.add("Properties", properties);
body.addProperty("RelyingParty", "http://auth.xboxlive.com");
body.addProperty("TokenType", "JWT");
return post(MicrosoftEndpoints.XBOX_USER, JSON, body.toString(), Map.of("x-xbl-contract-version", "1"))
.thenCompose(response -> {
// Tickets from login.live.com go as "t="; an Azure app's tokens as "d=". Xbox
// answers 400 to the wrong one, so try the other once.
if (response.status() == 400 && ticketPrefix.equals("t=")) {
return xboxUser(microsoftToken, "d=");
}
JsonObject json = json(response, "Xbox Live");
if (!response.ok()) {
throw failure("Xbox Live refused the sign-in (HTTP " + response.status() + ")");
}
return CompletableFuture.completedFuture(string(json, "Token"));
});
}
private record XstsToken(String token, String userHash) {}
private CompletableFuture<XstsToken> xsts(String xboxToken) {
JsonArray userTokens = new JsonArray();
userTokens.add(xboxToken);
JsonObject properties = new JsonObject();
properties.addProperty("SandboxId", "RETAIL");
properties.add("UserTokens", userTokens);
JsonObject body = new JsonObject();
body.add("Properties", properties);
body.addProperty("RelyingParty", "rp://api.minecraftservices.com/");
body.addProperty("TokenType", "JWT");
return post(MicrosoftEndpoints.XSTS, JSON, body.toString(), Map.of("x-xbl-contract-version", "1"))
.thenApply(response -> {
JsonObject json = json(response, "Xbox Live");
if (response.status() == 401 && json.has("XErr")) {
throw failure(xboxError(json.get("XErr").getAsLong()));
}
if (!response.ok()) {
throw failure("Xbox Live refused the sign-in (HTTP " + response.status() + ")");
}
String userHash;
try {
userHash = json.getAsJsonObject("DisplayClaims")
.getAsJsonArray("xui")
.get(0)
.getAsJsonObject()
.get("uhs")
.getAsString();
} catch (RuntimeException e) {
throw failure("Xbox Live's answer looked wrong");
}
return new XstsToken(string(json, "Token"), userHash);
});
}
/** Why XSTS refused, by Xbox's documented error codes. */
static String xboxError(long code) {
if (code == 2148916227L) {
return "This Xbox account is banned.";
}
if (code == 2148916233L) {
return "This Microsoft account has no Xbox profile. Sign in once at minecraft.net, then try again.";
}
if (code == 2148916235L) {
return "Xbox Live isn't available in this account's country.";
}
if (code == 2148916236L || code == 2148916237L) {
return "This account needs adult verification on xbox.com first.";
}
if (code == 2148916238L) {
return "This is a child account: an adult has to add it to a Microsoft family first.";
}
return "Xbox Live refused the sign-in (error " + code + ").";
}
private record MinecraftLogin(String token, long expiresAtMillis) {}
private CompletableFuture<MinecraftLogin> minecraftToken(XstsToken xsts) {
JsonObject body = new JsonObject();
body.addProperty("identityToken", "XBL3.0 x=" + xsts.userHash() + ";" + xsts.token());
return post(MicrosoftEndpoints.LOGIN_WITH_XBOX, JSON, body.toString(), Map.of())
.thenApply(response -> {
JsonObject json = json(response, "Minecraft");
if (!response.ok()) {
throw failure("Minecraft refused the sign-in (HTTP " + response.status() + ")");
}
long expiresIn = json.has("expires_in") ? number(json, "expires_in") : 3600;
return new MinecraftLogin(
string(json, "access_token"), clock.getAsLong() + Math.max(0, expiresIn) * 1000);
});
}
private CompletableFuture<MicrosoftAccount> profile(MinecraftLogin login, String refreshToken) {
return get(MicrosoftEndpoints.PROFILE, login.token()).thenApply(response -> {
if (response.status() == 404) {
throw failure("This Microsoft account doesn't own Minecraft: Java Edition.");
}
JsonObject json = json(response, "Minecraft");
if (!response.ok()) {
throw failure("Minecraft didn't give the profile (HTTP " + response.status() + ")");
}
String name = string(json, "name");
String id = string(json, "id");
if (!MicrosoftAccount.isPlayerName(name) || !MicrosoftAccount.isProfileId(id)) {
throw failure("Minecraft's profile looked wrong");
}
return new MicrosoftAccount(name, id, login.token(), login.expiresAtMillis(), refreshToken);
});
}
// --- Using the account ---------------------------------------------------------------------
/**
* Tells the session server {@code account} is joining the server whose hash is
* {@code serverHash} (the game's {@code digestData}, as signed hex). The server then asks the
* session server whether this account joined.
*/
public CompletableFuture<JoinResult> join(MicrosoftAccount account, String serverHash) {
JsonObject body = new JsonObject();
body.addProperty("accessToken", account.minecraftToken());
body.addProperty("selectedProfile", account.id());
body.addProperty("serverId", serverHash);
return post(MicrosoftEndpoints.JOIN, JSON, body.toString(), Map.of())
.thenApply(response -> {
if (response.ok()) {
return JoinResult.OK;
}
String error = "";
try {
JsonElement parsed = JsonParser.parseString(response.text());
if (parsed.isJsonObject() && parsed.getAsJsonObject().has("error")) {
error = parsed.getAsJsonObject().get("error").getAsString();
}
} catch (JsonParseException | IllegalStateException | UnsupportedOperationException ignored) {
// No reason given.
}
if (error.endsWith("InsufficientPrivilegesException")) {
return JoinResult.INSUFFICIENT_PRIVILEGES;
}
if (error.endsWith("UserBannedException")) {
return JoinResult.BANNED;
}
if (response.status() == 401 || response.status() == 403) {
return JoinResult.INVALID_SESSION;
}
return JoinResult.UNAVAILABLE;
})
.exceptionally(failure -> JoinResult.UNAVAILABLE);
}
/** Fetches the account's chat-signing key pair. */
public CompletableFuture<ProfileCertificates> certificates(MicrosoftAccount account) {
Map<String, String> headers = Map.of("Authorization", "Bearer " + account.minecraftToken());
return post(MicrosoftEndpoints.CERTIFICATES, JSON, "", headers).thenApply(response -> {
JsonObject json = json(response, "Minecraft");
if (!response.ok()) {
throw failure("Minecraft didn't give a chat key (HTTP " + response.status() + ")");
}
try {
JsonObject keyPair = json.getAsJsonObject("keyPair");
byte[] signature = Base64.getDecoder().decode(string(json, "publicKeySignatureV2"));
return new ProfileCertificates(
string(keyPair, "privateKey"),
string(keyPair, "publicKey"),
signature,
string(json, "expiresAt"),
string(json, "refreshedAfter"));
} catch (IllegalArgumentException | ClassCastException | NullPointerException e) {
throw failure("Minecraft's chat key looked wrong");
}
});
}
// --- HTTP and JSON -------------------------------------------------------------------------
private CompletableFuture<HttpResponse> post(String url, String type, String body, Map<String, String> headers) {
Map<String, String> all = new LinkedHashMap<>(headers);
all.put("Accept", JSON);
all.put("User-Agent", "Incari");
return https.send(HttpRequest.post(url, type, body, all)).exceptionally(MicrosoftSignIn::unreachable);
}
private CompletableFuture<HttpResponse> get(String url, String bearer) {
Map<String, String> headers = new LinkedHashMap<>();
headers.put("Accept", JSON);
headers.put("User-Agent", "Incari");
headers.put("Authorization", "Bearer " + bearer);
return https.send(HttpRequest.get(url, headers)).exceptionally(MicrosoftSignIn::unreachable);
}
private static HttpResponse unreachable(Throwable failure) {
Throwable cause =
failure instanceof CompletionException && failure.getCause() != null ? failure.getCause() : failure;
String message = cause.getMessage();
throw new CompletionException(new SignInException(
"Couldn't reach Microsoft's sign-in" + (message != null ? ": " + message : ".") + " Try again.",
cause,
true));
}
/** Whether a refusal is the service's own trouble (a 5xx, or too many requests), not an answer. */
static boolean serviceTrouble(HttpResponse response) {
return response.status() >= 500 || response.status() == 429;
}
/** The body as a JSON object; an empty object for an empty or non-JSON error body. */
private static JsonObject json(HttpResponse response, String service) {
String text = response.text();
if (text.isBlank()) {
if (response.ok()) {
throw failure(service + " sent an empty answer");
}
return new JsonObject();
}
try {
JsonElement parsed = JsonParser.parseString(text);
if (parsed.isJsonObject()) {
return parsed.getAsJsonObject();
}
} catch (JsonParseException e) {
// Falls through.
}
if (response.ok()) {
throw failure(service + " sent an answer that isn't JSON");
}
return new JsonObject();
}
private static String errorCode(JsonObject json, HttpResponse response) {
JsonElement error = json.get("error");
if (error != null && error.isJsonPrimitive()) {
String code = error.getAsString();
// Shown to the player: keep it to a plain code.
if (code.length() <= 40 && code.chars().allMatch(c -> c == '_' || Character.isLetterOrDigit(c))) {
return code;
}
}
return "HTTP " + response.status();
}
private static String string(JsonObject json, String name) {
JsonElement value = json.get(name);
if (value == null || !value.isJsonPrimitive() || value.getAsString().isEmpty()) {
throw failure("A sign-in answer was missing " + name);
}
return value.getAsString();
}
private static long number(JsonObject json, String name) {
JsonElement value = json.get(name);
try {
if (value != null && value.isJsonPrimitive()) {
return value.getAsLong();
}
} catch (NumberFormatException e) {
// Falls through.
}
throw failure("A sign-in answer was missing " + name);
}
static boolean isCodePage(String url) {
String prefix = "https://";
if (!url.startsWith(prefix)) {
return false;
}
String rest = url.substring(prefix.length());
int slash = rest.indexOf('/');
String host = slash < 0 ? rest : rest.substring(0, slash);
return MicrosoftEndpoints.CODE_PAGE_HOSTS.contains(host) && url.chars().allMatch(c -> c > 0x20 && c < 0x7F);
}
private static boolean isPlainCode(String code) {
return !code.isEmpty()
&& code.length() <= 16
&& code.chars().allMatch(c -> (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'));
}
/** {@code application/x-www-form-urlencoded}, by hand (the browser build has no URLEncoder). */
static String form(Map<String, String> fields) {
StringBuilder out = new StringBuilder();
for (Map.Entry<String, String> field : fields.entrySet()) {
if (out.length() > 0) {
out.append('&');
}
encode(field.getKey(), out);
out.append('=');
encode(field.getValue(), out);
}
return out.toString();
}
private static void encode(String text, StringBuilder out) {
for (byte b : text.getBytes(StandardCharsets.UTF_8)) {
int c = b & 0xFF;
if ((c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9')
|| c == '-'
|| c == '.'
|| c == '_'
|| c == '*') {
out.append((char) c);
} else if (c == ' ') {
out.append('+');
} else {
out.append('%')
.append(Character.toUpperCase(Character.forDigit(c >> 4, 16)))
.append(Character.toUpperCase(Character.forDigit(c & 0xF, 16)));
}
}
}
private static CompletionException failure(String message) {
return new CompletionException(new SignInException(message));
}
private static CompletionException temporaryFailure(String message) {
return new CompletionException(new SignInException(message, true));
}
}
@@ -0,0 +1,59 @@
package incari.net.msa;
/**
* The key pair Mojang issues an account for signing chat, with Mojang's signature over its public
* half. Servers that enforce secure chat refuse players without one.
*/
public final class ProfileCertificates {
private final String privateKeyPem;
private final String publicKeyPem;
private final byte[] publicKeySignature;
private final String expiresAt;
private final String refreshedAfter;
/**
* @param privateKeyPem the private key, PEM ({@code -----BEGIN RSA PRIVATE KEY-----}); secret
* @param publicKeyPem the public key, PEM ({@code -----BEGIN RSA PUBLIC KEY-----})
* @param publicKeySignature Mojang's signature over the public key and profile id (v2)
* @param expiresAt when the key stops being accepted, ISO-8601
* @param refreshedAfter when to fetch a new one, ISO-8601
*/
public ProfileCertificates(
String privateKeyPem,
String publicKeyPem,
byte[] publicKeySignature,
String expiresAt,
String refreshedAfter) {
this.privateKeyPem = privateKeyPem;
this.publicKeyPem = publicKeyPem;
this.publicKeySignature = publicKeySignature.clone();
this.expiresAt = expiresAt;
this.refreshedAfter = refreshedAfter;
}
public String privateKeyPem() {
return privateKeyPem;
}
public String publicKeyPem() {
return publicKeyPem;
}
public byte[] publicKeySignature() {
return publicKeySignature.clone();
}
public String expiresAt() {
return expiresAt;
}
public String refreshedAfter() {
return refreshedAfter;
}
@Override
public String toString() {
return "ProfileCertificates[expires " + expiresAt + "]";
}
}
@@ -0,0 +1,38 @@
package incari.net.msa;
import java.io.IOException;
/**
* Sign-in, a refresh or a join failed. The message is plain words for the player's screen, and
* never holds a token. A {@linkplain #temporary temporary} one (the network, or a service's own
* trouble) is worth trying again; any other is Microsoft's or Xbox's answer, final for this try.
*/
public final class SignInException extends IOException {
private static final long serialVersionUID = 1L;
private final boolean temporary;
public SignInException(String message) {
this(message, false);
}
public SignInException(String message, Throwable cause) {
this(message, cause, false);
}
public SignInException(String message, boolean temporary) {
super(message);
this.temporary = temporary;
}
public SignInException(String message, Throwable cause, boolean temporary) {
super(message, cause);
this.temporary = temporary;
}
/** Whether trying the same again may work: the request didn't get through, or the service was down. */
public boolean temporary() {
return temporary;
}
}
@@ -0,0 +1,10 @@
/**
* Microsoft account sign-in for online-mode servers (ADR 0070): the device-code flow with the
* Minecraft launcher's client id, Xbox Live and XSTS, the Minecraft token and profile, session
* joins and chat-signing keys, all over {@link incari.net.https.HttpsClient}. No game types, no
* blocking, and never a token in a log or an exception message.
*/
@NullMarked
package incari.net.msa;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,9 @@
/**
* The transport under the game's Netty pipeline: a channel over the platform's connections,
* WebSocket server addresses, and one-packet-per-message framing (ADR 0009). No game types; later
* the Eagler handshake and the Via bridge join it as pipeline stages.
*/
@NullMarked
package incari.net;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,43 @@
package incari.net.relay;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
/**
* What an Incari host says first on a guest's data channel (ADR 0062), so an Incari guest knows the
* world is today's game and joins it as it is, without Via and Eagler's 1.8 login. Eagler's hosts
* never speak first: their guest does. One message: a kind byte none of {@link LanFraming}'s
* (0x49), "INCARI", then the game's protocol number as four bytes, big-endian.
*/
public final class HostHello {
private static final byte KIND = 0x49;
private static final byte[] MAGIC = "INCARI".getBytes(StandardCharsets.US_ASCII);
private static final int LENGTH = 1 + 6 + 4;
/** How long a guest waits for it after the channel opens, before taking the host for Eagler's. */
public static final long WAIT_MILLIS = 1_500;
private HostHello() {}
/** The hello for a host playing the game's {@code protocol}. */
public static ByteBuffer write(int protocol) {
ByteBuffer out = ByteBuffer.allocate(LENGTH);
out.put(KIND).put(MAGIC).putInt(protocol).flip();
return out;
}
/** The protocol {@code message} names, if it's a hello; -1 if it isn't one. */
public static int read(ByteBuffer message) {
ByteBuffer in = message.duplicate();
if (in.remaining() != LENGTH || in.get() != KIND) {
return -1;
}
for (byte b : MAGIC) {
if (in.get() != b) {
return -1;
}
}
return in.getInt();
}
}
@@ -0,0 +1,164 @@
package incari.net.relay;
import java.util.ArrayList;
import java.util.List;
import org.jspecify.annotations.Nullable;
/**
* ICE candidates in the JSON Eagler's peers exchange through a relay: an array of objects with
* {@code candidate} and {@code sdpMLineIndex}, the index written as a string. Small enough to
* write and read by hand; the net module has no JSON library.
*/
final class IceJson {
/** One candidate. */
record Candidate(String candidate, int sdpMLineIndex) {}
private IceJson() {}
static String write(List<Candidate> candidates) {
StringBuilder json = new StringBuilder("[");
for (Candidate c : candidates) {
if (json.length() > 1) {
json.append(',');
}
json.append("{\"sdpMLineIndex\":\"").append(c.sdpMLineIndex()).append("\",\"candidate\":");
quote(json, c.candidate());
json.append('}');
}
return json.append(']').toString();
}
/** The candidates in {@code json}: an array of them, or a single one. */
static List<Candidate> read(String json) {
List<Candidate> out = new ArrayList<>();
int at = 0;
while (true) {
int open = json.indexOf('{', at);
if (open < 0) {
return out;
}
int close = closing(json, open);
String object = json.substring(open, close + 1);
String candidate = field(object, "candidate");
String index = field(object, "sdpMLineIndex");
if (candidate != null) {
int line = 0;
if (index != null) {
try {
line = Integer.parseInt(index.trim());
} catch (NumberFormatException e) {
// Left at 0: a single-stream connection has only line 0 anyway.
}
}
out.add(new Candidate(candidate, line));
}
at = close + 1;
}
}
/** The end of the object at {@code open}, skipping braces inside strings. */
private static int closing(String json, int open) {
boolean inString = false;
for (int i = open; i < json.length(); i++) {
char c = json.charAt(i);
if (inString) {
if (c == '\\') {
i++;
} else if (c == '"') {
inString = false;
}
} else if (c == '"') {
inString = true;
} else if (c == '}') {
return i;
}
}
return json.length() - 1;
}
/** A field's value, string or number, unescaped; null if absent. */
private static @Nullable String field(String object, String name) {
int key = object.indexOf('"' + name + '"');
if (key < 0) {
return null;
}
int colon = object.indexOf(':', key + name.length() + 2);
if (colon < 0) {
return null;
}
int i = colon + 1;
while (i < object.length() && Character.isWhitespace(object.charAt(i))) {
i++;
}
if (i >= object.length()) {
return null;
}
if (object.charAt(i) != '"') {
int end = i;
while (end < object.length() && ",}".indexOf(object.charAt(end)) < 0) {
end++;
}
return object.substring(i, end).trim();
}
StringBuilder value = new StringBuilder();
for (int j = i + 1; j < object.length(); j++) {
char c = object.charAt(j);
if (c == '"') {
return value.toString();
}
if (c == '\\' && j + 1 < object.length()) {
char next = object.charAt(++j);
switch (next) {
case 'n' -> value.append('\n');
case 'r' -> value.append('\r');
case 't' -> value.append('\t');
case 'u' -> {
int code = hex4(object, j + 1);
if (code >= 0) {
value.append((char) code);
j += 4;
}
// A broken escape is left out: the text comes from a stranger's peer, and
// a candidate it spoils just won't connect.
}
default -> value.append(next);
}
} else {
value.append(c);
}
}
return value.toString();
}
/** The four hex digits at {@code at} as a number, or -1 if there aren't four there. */
private static int hex4(String text, int at) {
if (at + 4 > text.length()) {
return -1;
}
int code = 0;
for (int i = at; i < at + 4; i++) {
int digit = Character.digit(text.charAt(i), 16);
if (digit < 0) {
return -1;
}
code = code * 16 + digit;
}
return code;
}
private static void quote(StringBuilder out, String text) {
out.append('"');
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
switch (c) {
case '"' -> out.append("\\\"");
case '\\' -> out.append("\\\\");
case '\n' -> out.append("\\n");
case '\r' -> out.append("\\r");
default -> out.append(c);
}
}
out.append('"');
}
}
@@ -0,0 +1,136 @@
package incari.net.relay;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.DecoderException;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;
/**
* How a shared world's host frames packets on the data channel: one packet per message, after a
* byte that says what the message is. 0: a whole packet. 1: a piece of a packet, more follows. 2:
* a whole packet, compressed, as a four-byte length and zlib data. A packet ends at a 0 or 2; the
* pieces before it are its start. Packets this client sends go whole, or in pieces of at most
* {@link #FRAGMENT} bytes.
*
* <p>This stage sits at the pipeline's head, below the message framing, so the rest sees one
* whole packet per message, as over a WebSocket.
*/
// Writes go out with the channel's promises; a failed write fails the channel.
@SuppressWarnings("FutureReturnValueIgnored")
public final class LanFraming extends ChannelDuplexHandler {
public static final String NAME = "lan-framing";
/** The largest message either side sends, header included. */
static final int FRAGMENT = 0xFF00;
/** The largest packet a host's compressed message may unpack to. */
private static final int MAX_PACKET = 8 * 1024 * 1024;
private static final int WHOLE = 0;
private static final int PIECE = 1;
private static final int COMPRESSED = 2;
/** The pieces of the packet being received. */
private final ByteBuf pieces = Unpooled.buffer();
/** Adds the stage at the head of {@code pipeline}. */
public static void install(ChannelPipeline pipeline) {
pipeline.addFirst(NAME, new LanFraming());
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
pieces.release();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object message) {
if (!(message instanceof ByteBuf in)) {
ctx.fireChannelRead(message);
return;
}
try {
if (!in.isReadable()) {
return;
}
int kind = in.readUnsignedByte();
switch (kind) {
case PIECE -> pieces.writeBytes(in);
case WHOLE -> {
ByteBuf packet = ctx.alloc().buffer(pieces.readableBytes() + in.readableBytes());
packet.writeBytes(pieces).writeBytes(in);
pieces.clear();
ctx.fireChannelRead(packet);
}
case COMPRESSED -> {
pieces.writeBytes(in);
ByteBuf packet = inflate(ctx, pieces);
pieces.clear();
ctx.fireChannelRead(packet);
}
default -> throw new DecoderException("Unknown shared-world message kind " + kind);
}
} finally {
in.release();
}
}
@Override
public void write(ChannelHandlerContext ctx, Object message, ChannelPromise promise) {
if (!(message instanceof ByteBuf packet)) {
ctx.write(message, promise);
return;
}
try {
int max = FRAGMENT - 1;
if (packet.readableBytes() <= max) {
ByteBuf out = ctx.alloc().buffer(packet.readableBytes() + 1);
out.writeByte(WHOLE).writeBytes(packet);
ctx.write(out, promise);
return;
}
while (packet.readableBytes() > 0) {
int length = Math.min(max, packet.readableBytes());
ByteBuf out = ctx.alloc().buffer(length + 1);
out.writeByte(packet.readableBytes() > length ? PIECE : WHOLE);
out.writeBytes(packet, length);
boolean last = !packet.isReadable();
ctx.write(out, last ? promise : ctx.voidPromise());
}
} finally {
packet.release();
}
}
private static ByteBuf inflate(ChannelHandlerContext ctx, ByteBuf data) {
int size = data.readInt();
if (size < 0 || size > MAX_PACKET) {
throw new DecoderException("A shared-world packet of " + size + " bytes");
}
byte[] compressed = new byte[data.readableBytes()];
data.readBytes(compressed);
byte[] packet = new byte[size];
Inflater inflater = new Inflater();
try {
inflater.setInput(compressed);
int done = 0;
while (done < size && !inflater.finished()) {
int n = inflater.inflate(packet, done, size - done);
if (n == 0 && (inflater.needsInput() || inflater.needsDictionary())) {
break;
}
done += n;
}
return ctx.alloc().buffer(done).writeBytes(packet, 0, done);
} catch (DataFormatException e) {
throw new DecoderException("A shared-world packet that doesn't inflate", e);
} finally {
inflater.end();
}
}
}
@@ -0,0 +1,160 @@
package incari.net.relay;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.DecoderException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
/**
* A shared world's host speaks 1.8 with Eagler's changes to its login, which Via (translating the
* game's packets to 1.8 above this stage) doesn't know:
*
* <ul>
* <li>there's no handshake: the host starts in the login state, so the game's is dropped;
* <li>Login Start carries, after the name, the player's skin and cape (Eagler's formats), the
* Eagler protocols the client speaks, and the client's brand UUID;
* <li>Login Success may end with the Eagler protocol the host chose, which Via would pass on to
* the game as bytes it can't read, so it's cut off here.
* </ul>
*
* Everything else is plain 1.8. Eagler's own messages (skins, voice) travel as plugin messages,
* which the game ignores.
*/
// Writes go out with the channel's promises; a failed write fails the channel.
@SuppressWarnings("FutureReturnValueIgnored")
public final class LanLogin extends ChannelDuplexHandler {
public static final String NAME = "lan-login";
/** The Eagler protocols this client lists: 3 and 4, the ones hosts choose between. */
private static final int[] EAGLER_PROTOCOLS = {3, 4};
/** 1.8's login packets: serverbound Login Start and clientbound Login Success are 0 and 2. */
private static final int LOGIN_START = 0x00;
private static final int LOGIN_SUCCESS = 0x02;
private final byte[] skin;
private final byte[] cape;
private final UUID brand;
/** Packets the game has sent so far, while logging in: the handshake, then Login Start. */
private int sent;
private boolean loggedIn;
public LanLogin(byte[] skin, byte[] cape, UUID brand) {
this.skin = skin.clone();
this.cape = cape.clone();
this.brand = brand;
}
/** Adds the stage at the head of {@code pipeline}, above {@link LanFraming} if that's there. */
public static void install(ChannelPipeline pipeline, LanLogin stage) {
if (pipeline.get(LanFraming.NAME) != null) {
pipeline.addAfter(LanFraming.NAME, NAME, stage);
} else {
pipeline.addFirst(NAME, stage);
}
}
@Override
public void write(ChannelHandlerContext ctx, Object message, ChannelPromise promise) {
if (loggedIn || !(message instanceof ByteBuf packet)) {
ctx.write(message, promise);
return;
}
sent++;
if (sent == 1) {
// The handshake: the host has no handshake state.
packet.release();
promise.trySuccess();
return;
}
if (sent == 2 && readVarInt(packet.duplicate()) == LOGIN_START) {
ByteBuf out = ctx.alloc().buffer(packet.readableBytes() + skin.length + cape.length + 64);
out.writeBytes(packet);
packet.release();
writeByteArray(out, skin);
writeByteArray(out, cape);
byte[] protocols = new byte[2 + EAGLER_PROTOCOLS.length * 2];
protocols[1] = (byte) EAGLER_PROTOCOLS.length;
for (int i = 0; i < EAGLER_PROTOCOLS.length; i++) {
protocols[3 + i * 2] = (byte) EAGLER_PROTOCOLS[i];
}
writeByteArray(out, protocols);
out.writeLong(brand.getMostSignificantBits());
out.writeLong(brand.getLeastSignificantBits());
ctx.write(out, promise);
return;
}
ctx.write(packet, promise);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object message) {
if (loggedIn || !(message instanceof ByteBuf packet)) {
ctx.fireChannelRead(message);
return;
}
ByteBuf peek = packet.duplicate();
if (readVarInt(peek) != LOGIN_SUCCESS) {
// A kick while logging in: passes as it is.
ctx.fireChannelRead(packet);
return;
}
loggedIn = true;
String uuid = readString(peek);
String name = readString(peek);
// Whatever follows (the chosen Eagler protocol) is cut: Via expects the name to end it.
ByteBuf success = ctx.alloc().buffer();
writeVarInt(success, LOGIN_SUCCESS);
writeString(success, uuid);
writeString(success, name);
packet.release();
ctx.fireChannelRead(success);
}
private static void writeByteArray(ByteBuf out, byte[] bytes) {
writeVarInt(out, bytes.length);
out.writeBytes(bytes);
}
private static int readVarInt(ByteBuf in) {
int value = 0;
for (int shift = 0; shift < 35; shift += 7) {
if (!in.isReadable()) {
throw new DecoderException("Truncated VarInt");
}
int b = in.readUnsignedByte();
value |= (b & 0x7F) << shift;
if ((b & 0x80) == 0) {
return value;
}
}
throw new DecoderException("VarInt too long");
}
private static void writeVarInt(ByteBuf out, int value) {
while ((value & ~0x7F) != 0) {
out.writeByte((value & 0x7F) | 0x80);
value >>>= 7;
}
out.writeByte(value);
}
private static String readString(ByteBuf in) {
int length = readVarInt(in);
String text = in.toString(in.readerIndex(), length, StandardCharsets.UTF_8);
in.skipBytes(length);
return text;
}
private static void writeString(ByteBuf out, String text) {
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
writeVarInt(out, bytes.length);
out.writeBytes(bytes);
}
}
@@ -0,0 +1,400 @@
package incari.net.relay;
import incari.platform.api.net.NetConnection;
import incari.platform.api.net.PlatformNetwork;
import incari.platform.api.rtc.IceServer;
import incari.platform.api.rtc.PlatformRtc;
import incari.platform.api.rtc.RtcPeer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.DecoderException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.LongSupplier;
import org.jspecify.annotations.Nullable;
/**
* Shares a world through an Eagler relay (ADR 0062): the host's side of {@link RelayJoin}, as
* Eagler's own hosts do it.
*
* <ol>
* <li>The host says hello with the world's name; the relay answers with a join code.
* <li>The relay announces each client that uses the code. The host answers its offer, sends ICE
* candidates once it has the client's, and takes the "lan" data channel the client opens.
* <li>On that channel the host sends {@link HostHello}, then hands the channel to the world
* ({@link Listener#guest}).
* </ol>
*
* <p>The relay's WebSocket stays open while the world is shared, so more can join. Game thread;
* {@link #tick} (once a frame) runs the timers.
*/
public final class RelayHost implements NetConnection.Listener {
/** Hears how sharing goes. Game thread. */
public interface Listener {
/** The relay gave the world {@code code}: what guests type to join. */
void shared(String code);
/**
* A guest's data channel opened (after the host's hello). Returns who hears it from now on:
* the world's connection for the guest.
*/
NetConnection.Listener guest(String clientId, NetConnection channel);
/** A guest couldn't connect; for the host's log. */
default void guestFailed(String clientId, String reason) {}
/** A step of sharing, for the host's log. */
default void trace(String step) {}
/** Sharing stopped (the relay closed, or refused); the reason is for the player. */
void stopped(String reason);
}
/** How long the relay may take to give a code, and a client to finish connecting. */
private static final long STEP_MILLIS = 15_000;
/** How long after the client's candidates this side sends its own, if gathering isn't done. */
private static final long GATHER_MILLIS = 2_000;
/** At most this many guests connecting at once: a relay is public, and each costs a peer. */
private static final int MAX_CONNECTING = 8;
private final PlatformNetwork network;
private final PlatformRtc rtc;
private final String relay;
private final String worldName;
private final int protocol;
private final Listener listener;
private final LongSupplier clock;
private final Map<String, Guest> connecting = new LinkedHashMap<>();
private @Nullable NetConnection socket;
private List<IceServer> iceServers = List.of();
private @Nullable String code;
private long deadline;
private boolean stopped;
/**
* @param protocol the game's protocol number, for the hello Incari guests read
*/
public RelayHost(
PlatformNetwork network,
PlatformRtc rtc,
String relay,
String worldName,
int protocol,
Listener listener,
LongSupplier clock) {
this.network = network;
this.rtc = rtc;
this.relay = relay;
this.worldName = worldName;
this.protocol = protocol;
this.listener = listener;
this.clock = clock;
}
/** Opens the relay's WebSocket. */
public void start() {
deadline = clock.getAsLong() + STEP_MILLIS;
socket = network.openWebSocket(relay, this);
}
/** The join code, once the relay has given one. */
public @Nullable String code() {
return code;
}
/** The relay's address. */
public String relay() {
return relay;
}
/** Runs the deadlines; call once a frame. */
public void tick() {
if (stopped) {
return;
}
long now = clock.getAsLong();
if (code == null && now > deadline) {
stop("The relay didn't give the world a code");
return;
}
for (Guest guest : new ArrayList<>(connecting.values())) {
guest.tick(now);
}
}
/** Stops sharing: no one new can join. Guests already in stay, on their own channels. */
public void close() {
if (stopped) {
return;
}
stopped = true;
for (Guest guest : new ArrayList<>(connecting.values())) {
guest.fail("The host stopped sharing");
}
closeSocket();
}
// --- The relay's WebSocket ---------------------------------------------------------------
@Override
public void connected() {
listener.trace("connected to " + relay + "; saying hello");
send(RelayPackets.hostHandshake(worldName, false));
}
@Override
public void received(ByteBuffer data) {
if (stopped) {
return;
}
ByteBuf in = Unpooled.wrappedBuffer(data);
RelayPackets.Message message;
try {
message = RelayPackets.read(in);
} catch (IndexOutOfBoundsException | DecoderException e) {
stop("The relay sent something unreadable");
return;
}
listener.trace("heard " + message.getClass().getSimpleName());
// An instanceof chain, not a pattern switch: the browser build's compiler (TeaVM) can't
// link the switch's type bootstrap.
if (message instanceof RelayPackets.Handshake hello) {
if (code == null) {
code = hello.code();
listener.shared(hello.code());
}
} else if (message instanceof RelayPackets.IceServers servers) {
iceServers = servers.servers();
} else if (message instanceof RelayPackets.NewClient client) {
newGuest(client.clientId());
} else if (message instanceof RelayPackets.Signal signal) {
Guest guest = connecting.get(signal.peerId());
if (guest != null) {
guest.signal(signal);
}
} else if (message instanceof RelayPackets.ClientDone done) {
Guest guest = connecting.get(done.clientId());
if (guest != null && !done.success()) {
guest.fail("The guest's side failed");
}
} else if (message instanceof RelayPackets.Refusal refusal) {
stop(
refusal.code() == 0x01
? "The relay runs a different version (" + refusal.message() + ")"
: "The relay refused: " + refusal.message());
}
}
@Override
public void closed(@Nullable Throwable cause) {
listener.trace("the relay's connection closed" + (cause == null ? "" : ": " + cause.getMessage()));
if (!stopped) {
stop(cause == null ? "The relay closed the connection" : "Couldn't reach the relay: " + cause.getMessage());
}
}
private void newGuest(String clientId) {
if (connecting.size() >= MAX_CONNECTING || connecting.containsKey(clientId)) {
return;
}
Guest guest = new Guest(clientId);
connecting.put(clientId, guest);
guest.peer = rtc.createPeer(iceServers, guest);
guest.deadline = clock.getAsLong() + STEP_MILLIS;
}
private void stop(String reason) {
if (stopped) {
return;
}
listener.trace("stopping: " + reason);
close();
listener.stopped(reason);
}
private void send(ByteBuffer message) {
NetConnection current = socket;
if (current != null) {
current.send(message);
}
}
private void closeSocket() {
NetConnection current = socket;
socket = null;
if (current != null) {
current.close();
}
}
// --- One guest connecting ----------------------------------------------------------------
private final class Guest implements RtcPeer.Listener {
private final String id;
private final List<IceJson.Candidate> candidates = new ArrayList<>();
private @Nullable RtcPeer peer;
private long deadline;
private boolean gathered;
/** When the client's candidates came; 0 before. */
private long theirsAt;
private boolean sentOurs;
Guest(String id) {
this.id = id;
}
void tick(long now) {
if (theirsAt > 0 && !sentOurs && (gathered || now - theirsAt > GATHER_MILLIS)) {
sendCandidates();
}
if (now > deadline) {
fail("Timed out connecting");
}
}
void signal(RelayPackets.Signal signal) {
RtcPeer current = peer;
if (current == null) {
return;
}
try {
if (signal.id() == RelayPackets.DESCRIPTION) {
current.setRemoteDescription(signal.text());
} else if (signal.id() == RelayPackets.ICE_CANDIDATE) {
for (IceJson.Candidate candidate : IceJson.read(signal.text())) {
current.addIceCandidate(candidate.candidate(), candidate.sdpMLineIndex());
}
theirsAt = clock.getAsLong();
}
} catch (RuntimeException e) {
// A guest's text that can't be read fails that guest only, never the world's
// sharing (or the frame it arrived in: this runs in the platform's event poll).
fail("The guest sent something unreadable");
}
}
@Override
public void localDescription(String json) {
send(RelayPackets.description(id, json));
}
@Override
public void iceCandidate(String candidate, int sdpMLineIndex) {
candidates.add(new IceJson.Candidate(candidate, sdpMLineIndex));
}
@Override
public void iceGatheringComplete() {
gathered = true;
}
@Override
public void stateChanged(String state) {
if ("failed".equals(state) && connecting.containsKey(id)) {
fail("Couldn't connect the host and the guest");
}
}
@Override
public void dataChannel(String label, RtcPeer.IncomingChannel incoming) {
if (!label.equals(RelayJoin.CHANNEL) || !connecting.containsKey(id)) {
return;
}
Forward forward = new Forward();
NetConnection channel = incoming.accept(forward);
forward.channel = channel;
forward.guestId = id;
forward.peer = peer;
if (channel.isOpen()) {
forward.connected();
}
}
private void sendCandidates() {
sentOurs = true;
send(RelayPackets.iceCandidates(id, IceJson.write(candidates)));
}
/** The channel opened: the guest is the world's now, and this side leaves it. */
void joined() {
connecting.remove(id);
}
void fail(String reason) {
if (connecting.remove(id) == null) {
return;
}
RtcPeer current = peer;
if (current != null) {
current.close();
}
listener.guestFailed(id, reason);
}
}
/**
* A guest's data channel: says the host's hello when it opens, then hands everything to the
* world's connection for the guest.
*/
private final class Forward implements NetConnection.Listener {
private @Nullable NetConnection channel;
/** The guest's peer connection, closed with the channel: it carries nothing else. */
private @Nullable RtcPeer peer;
private String guestId = "";
private NetConnection.@Nullable Listener target;
private boolean opened;
@Override
public void connected() {
NetConnection current = channel;
if (opened || current == null) {
return;
}
opened = true;
current.send(HostHello.write(protocol));
Guest guest = connecting.get(guestId);
if (guest != null) {
guest.joined();
}
NetConnection.Listener world = listener.guest(guestId, current);
target = world;
world.connected();
}
@Override
public void received(ByteBuffer data) {
NetConnection.Listener world = target;
if (world != null) {
world.received(data);
}
}
@Override
public void closed(@Nullable Throwable cause) {
NetConnection.Listener world = target;
if (world != null) {
RtcPeer current = peer;
peer = null;
if (current != null) {
current.close();
}
world.closed(cause);
} else {
Guest guest = connecting.get(guestId);
if (guest != null) {
guest.fail("The guest's channel closed");
}
}
}
}
}
@@ -0,0 +1,350 @@
package incari.net.relay;
import incari.platform.api.net.NetConnection;
import incari.platform.api.net.PlatformNetwork;
import incari.platform.api.rtc.PlatformRtc;
import incari.platform.api.rtc.RtcPeer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.DecoderException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.function.LongSupplier;
import org.jspecify.annotations.Nullable;
/**
* Joining a shared world through an Eagler relay (ADR 0019), up to an open data channel to
* its host. The relay is a WebSocket server that knows each shared world by a code and passes
* WebRTC signalling between the world's host and whoever joins:
*
* <ol>
* <li>the client says hello with the code; the relay answers hello, then its STUN and TURN
* servers;
* <li>the client makes a peer connection with a data channel ("lan") and sends its offer; the
* host answers;
* <li>the client sends all its ICE candidates at once, when it has them; the host sends its own;
* <li>once the data channel opens, the client tells the relay it succeeded and leaves;
* <li>an Incari host then says so first on the channel ({@link HostHello}, ADR 0062); a moment
* without it means one of Eagler's.
* </ol>
*
* Every step has a deadline. The platform's calls come on the game's thread; {@link #tick} (once a
* frame) runs the timers.
*/
public final class RelayJoin implements NetConnection.Listener, RtcPeer.Listener {
/** Hears how a join ends. Game thread. */
public interface Listener {
/** What the join is doing, for the player. */
default void progress(String status) {}
/** The data channel is open; the game connects to {@code address}. */
void joined(RelayWorldAddress address);
/** The join failed; the reason is for the player. */
void failed(String reason);
}
/** How long each step may take. */
private static final long STEP_MILLIS = 10_000;
/** How long after its last new ICE candidate this side is taken to have them all. */
private static final long GATHER_QUIET_MILLIS = 2_000;
/** The data channel's label, as the hosts expect. */
static final String CHANNEL = "lan";
private enum State {
CONNECTING,
HELLO,
ICE_SERVERS,
OFFERING,
AWAITING_ANSWER,
GATHERING,
AWAITING_HOST_CANDIDATES,
OPENING,
/** The channel is open: a moment for an Incari host's hello (ADR 0062). */
HEARING_HOST,
JOINED,
FAILED
}
private final PlatformNetwork network;
private final PlatformRtc rtc;
private final String relay;
private final String code;
private final Listener listener;
private final LongSupplier clock;
private final List<IceJson.Candidate> candidates = new ArrayList<>();
private State state = State.CONNECTING;
private long deadline;
private long lastCandidate;
private boolean gatheringComplete;
private String hostPeer = "";
private @Nullable NetConnection socket;
private @Nullable RtcPeer peer;
private @Nullable NetConnection channel;
private final RelayWorldAddress.Buffered buffered = new RelayWorldAddress.Buffered(this::channelOpened);
public RelayJoin(
PlatformNetwork network,
PlatformRtc rtc,
String relay,
String code,
Listener listener,
LongSupplier clock) {
this.network = network;
this.rtc = rtc;
this.relay = relay;
this.code = code;
this.listener = listener;
this.clock = clock;
}
/** Opens the relay's WebSocket. */
public void start() {
deadline = clock.getAsLong() + STEP_MILLIS;
listener.progress("Connecting to " + relay);
socket = network.openWebSocket(relay, this);
}
/** Runs the deadlines; call once a frame. */
public void tick() {
if (state == State.JOINED || state == State.FAILED) {
return;
}
long now = clock.getAsLong();
if (state == State.HEARING_HOST) {
if (buffered.heard || now > deadline) {
join();
}
return;
}
if (state == State.GATHERING
&& (gatheringComplete || (!candidates.isEmpty() && now - lastCandidate > GATHER_QUIET_MILLIS))) {
sendCandidates();
return;
}
if (now > deadline) {
fail(
switch (state) {
case CONNECTING, HELLO -> "The relay didn't answer";
case ICE_SERVERS -> "The relay didn't send connection details";
case AWAITING_ANSWER -> "The world's host didn't answer (is the code right?)";
case GATHERING -> "Couldn't find a way to connect to the host";
case AWAITING_HOST_CANDIDATES -> "The host couldn't find a way to connect";
default -> "Couldn't reach the world's host";
});
}
}
/** Gives up, closing whatever is open. */
public void cancel() {
fail("Cancelled");
}
// --- The relay's WebSocket ---------------------------------------------------------------
@Override
public void connected() {
if (state != State.CONNECTING) {
return;
}
state = State.HELLO;
send(RelayPackets.handshake(code));
}
@Override
public void received(ByteBuffer data) {
if (state == State.JOINED || state == State.FAILED) {
return;
}
ByteBuf in = Unpooled.wrappedBuffer(data);
RelayPackets.Message message;
try {
message = RelayPackets.read(in);
} catch (IndexOutOfBoundsException | DecoderException e) {
fail("The relay sent something unreadable");
return;
}
if (message instanceof RelayPackets.Refusal error) {
fail(errorText(error));
} else if (message instanceof RelayPackets.Handshake && state == State.HELLO) {
state = State.ICE_SERVERS;
deadline = clock.getAsLong() + STEP_MILLIS;
listener.progress("Finding the world " + code);
} else if (message instanceof RelayPackets.IceServers servers && state == State.ICE_SERVERS) {
RtcPeer created = rtc.createPeer(servers.servers(), this);
peer = created;
channel = created.openDataChannel(CHANNEL, buffered);
state = State.OFFERING;
deadline = clock.getAsLong() + STEP_MILLIS;
created.createOffer();
listener.progress("Asking the world's host to connect");
} else if (message instanceof RelayPackets.Signal signal) {
signal(signal);
} else if (!(message instanceof RelayPackets.Ignored)) {
fail("The relay sent a message out of turn");
}
}
@Override
public void closed(@Nullable Throwable cause) {
if (state != State.JOINED && state != State.FAILED && state != State.OPENING && state != State.HEARING_HOST) {
fail(cause == null ? "The relay closed the connection" : "Couldn't reach the relay: " + cause.getMessage());
}
}
private void signal(RelayPackets.Signal signal) {
RtcPeer current = peer;
if (current == null) {
fail("The relay sent a message out of turn");
return;
}
if (signal.id() == RelayPackets.DESCRIPTION && state == State.AWAITING_ANSWER) {
current.setRemoteDescription(signal.text());
state = State.GATHERING;
deadline = clock.getAsLong() + STEP_MILLIS;
} else if (signal.id() == RelayPackets.ICE_CANDIDATE && state == State.AWAITING_HOST_CANDIDATES) {
hostPeer = signal.peerId();
try {
for (IceJson.Candidate candidate : IceJson.read(signal.text())) {
current.addIceCandidate(candidate.candidate(), candidate.sdpMLineIndex());
}
} catch (RuntimeException e) {
// Runs in the platform's event poll: a host's unreadable text fails the join only.
fail("The world's host sent something unreadable");
return;
}
state = State.OPENING;
deadline = clock.getAsLong() + STEP_MILLIS;
listener.progress("Opening the connection");
if (buffered.isOpen()) {
channelOpened();
}
} else {
fail("The relay sent a message out of turn");
}
}
// --- The peer connection -----------------------------------------------------------------
@Override
public void localDescription(String json) {
if (state == State.OFFERING) {
send(RelayPackets.description(json));
state = State.AWAITING_ANSWER;
deadline = clock.getAsLong() + STEP_MILLIS;
}
}
@Override
public void iceCandidate(String candidate, int sdpMLineIndex) {
candidates.add(new IceJson.Candidate(candidate, sdpMLineIndex));
lastCandidate = clock.getAsLong();
}
@Override
public void iceGatheringComplete() {
gatheringComplete = true;
}
@Override
public void stateChanged(String connectionState) {
if ("failed".equals(connectionState) && state != State.JOINED) {
fail("Couldn't connect to the world's host (the network between you may block it)");
}
}
private void sendCandidates() {
send(RelayPackets.iceCandidates(IceJson.write(candidates)));
state = State.AWAITING_HOST_CANDIDATES;
deadline = clock.getAsLong() + STEP_MILLIS;
}
private void channelOpened() {
if (state != State.OPENING) {
// Opened before the host's candidates arrived (a direct route): finished when they do.
return;
}
if (channel == null) {
return;
}
// An Incari host speaks first (HostHello); Eagler's never do, so the wait ends at the
// first message or after a moment.
state = State.HEARING_HOST;
deadline = clock.getAsLong() + HostHello.WAIT_MILLIS;
send(RelayPackets.clientSuccess(hostPeer));
closeSocket();
if (buffered.heard) {
join();
}
}
private void join() {
NetConnection opened = channel;
if (opened == null || state != State.HEARING_HOST) {
return;
}
state = State.JOINED;
listener.joined(new RelayWorldAddress(code, opened, buffered));
}
// --- Endings -----------------------------------------------------------------------------
private void fail(String reason) {
if (state == State.JOINED || state == State.FAILED) {
return;
}
if (state == State.HEARING_HOST) {
// The channel opened and the relay was told: what's left is the channel.
state = State.FAILED;
NetConnection opened = channel;
if (opened != null) {
opened.close();
}
RtcPeer current = peer;
if (current != null) {
current.close();
}
listener.failed(reason);
return;
}
boolean told = state == State.OPENING;
state = State.FAILED;
if (told) {
send(RelayPackets.clientFailure(hostPeer));
}
RtcPeer current = peer;
if (current != null) {
current.close();
}
closeSocket();
listener.failed(reason);
}
private void send(ByteBuffer message) {
NetConnection current = socket;
if (current != null) {
current.send(message);
}
}
private void closeSocket() {
NetConnection current = socket;
socket = null;
if (current != null) {
current.close();
}
}
private String errorText(RelayPackets.Refusal error) {
return switch (error.code()) {
case 0x01 -> "The relay runs a different version (" + error.message() + ")";
case 0x04, 0x05 -> "No world is shared with the code " + code;
case 0x06 -> "The world's host left";
default -> "The relay refused: " + error.message();
};
}
}
@@ -0,0 +1,207 @@
package incari.net.relay;
import incari.platform.api.rtc.IceServer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.DecoderException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/**
* The messages of Eagler's shared-world relay (protocol version 1): one binary WebSocket message
* each, an id byte, then big-endian fields. Strings are ASCII with a one- or two-byte length.
* Written from the protocol; only the ones a joining client sends or reads are here.
*/
final class RelayPackets {
static final int HANDSHAKE = 0x00;
static final int ICE_SERVERS = 0x01;
static final int NEW_CLIENT = 0x02;
static final int ICE_CANDIDATE = 0x03;
static final int DESCRIPTION = 0x04;
static final int CLIENT_SUCCESS = 0x05;
static final int CLIENT_FAILURE = 0x06;
static final int PONG = 0x69;
static final int SPECIAL_UPDATE = 0x70;
static final int DISCONNECT_CLIENT = 0xFE;
static final int ERROR = 0xFF;
/** The relay protocol this client speaks. */
static final int VERSION = 1;
/** A handshake's connection type: a client joining a world by its code. */
static final int TYPE_CLIENT = 0x02;
/** A handshake's connection type: a host sharing a world, which the relay gives a code. */
static final int TYPE_SERVER = 0x01;
private RelayPackets() {}
static ByteBuffer handshake(String code) {
ByteBuf out = Unpooled.buffer();
out.writeByte(HANDSHAKE);
out.writeByte(TYPE_CLIENT);
out.writeByte(VERSION);
writeAscii8(out, code);
return nio(out);
}
/**
* A host's hello (ADR 0062): the world's name and whether it's hidden from the relay's world
* list, as "name;0" or "name;1", as Eagler's hosts write it.
*/
static ByteBuffer hostHandshake(String worldName, boolean hidden) {
ByteBuf out = Unpooled.buffer();
out.writeByte(HANDSHAKE);
out.writeByte(TYPE_SERVER);
out.writeByte(VERSION);
String name = worldName.replace(';', ' ');
// The relay reads it as one ASCII string of at most 255 bytes.
StringBuilder ascii = new StringBuilder();
for (int i = 0; i < name.length() && ascii.length() < 200; i++) {
char c = name.charAt(i);
ascii.append(c >= 0x20 && c < 0x7F ? c : '?');
}
writeAscii8(out, ascii + (hidden ? ";1" : ";0"));
return nio(out);
}
/** A host's answer to the client {@code peerId}. */
static ByteBuffer description(String peerId, String json) {
ByteBuf out = Unpooled.buffer();
out.writeByte(DESCRIPTION);
writeAscii8(out, peerId);
writeBytes16(out, json.getBytes(StandardCharsets.ISO_8859_1));
return nio(out);
}
/** A host's ICE candidates for the client {@code peerId}, all at once. */
static ByteBuffer iceCandidates(String peerId, String jsonArray) {
ByteBuf out = Unpooled.buffer();
out.writeByte(ICE_CANDIDATE);
writeAscii8(out, peerId);
writeBytes16(out, jsonArray.getBytes(StandardCharsets.ISO_8859_1));
return nio(out);
}
/** This client's offer; the host is the only peer, so the peer id is empty. */
static ByteBuffer description(String json) {
ByteBuf out = Unpooled.buffer();
out.writeByte(DESCRIPTION);
writeAscii8(out, "");
writeBytes16(out, json.getBytes(StandardCharsets.ISO_8859_1));
return nio(out);
}
/** This client's ICE candidates, all at once, as a JSON array. */
static ByteBuffer iceCandidates(String jsonArray) {
ByteBuf out = Unpooled.buffer();
out.writeByte(ICE_CANDIDATE);
writeAscii8(out, "");
writeBytes16(out, jsonArray.getBytes(StandardCharsets.ISO_8859_1));
return nio(out);
}
static ByteBuffer clientSuccess(String peerId) {
ByteBuf out = Unpooled.buffer();
out.writeByte(CLIENT_SUCCESS);
writeAscii8(out, peerId);
return nio(out);
}
static ByteBuffer clientFailure(String peerId) {
ByteBuf out = Unpooled.buffer();
out.writeByte(CLIENT_FAILURE);
writeAscii8(out, peerId);
return nio(out);
}
/** A message from the relay, read. */
sealed interface Message {}
record Handshake(int type, int version, String code) implements Message {}
record IceServers(List<IceServer> servers) implements Message {}
/** The host's candidates ({@link #ICE_CANDIDATE}) or description ({@link #DESCRIPTION}). */
record Signal(int id, String peerId, String text) implements Message {}
record Refusal(int code, String message) implements Message {}
/** To a host: a client asks to join ({@link #NEW_CLIENT}). */
record NewClient(String clientId) implements Message {}
/** To a host: a client says its connection worked or not ({@link #CLIENT_SUCCESS}, {@link #CLIENT_FAILURE}). */
record ClientDone(String clientId, boolean success) implements Message {}
/** Anything this client has no use for (pongs, update certificates). */
record Ignored(int id) implements Message {}
static Message read(ByteBuf in) {
int id = in.readUnsignedByte();
return switch (id) {
case HANDSHAKE -> new Handshake(in.readUnsignedByte(), in.readUnsignedByte(), readAscii8(in));
case ICE_SERVERS -> {
int count = in.readUnsignedShort();
List<IceServer> servers = new ArrayList<>();
for (int i = 0; i < count; i++) {
int type = in.readUnsignedByte();
String url = readAscii16(in);
String user = readAscii8(in);
String password = readAscii8(in);
if (type == 'T') {
servers.add(new IceServer(url, user, password));
} else if (type == 'S') {
servers.add(new IceServer(url, null, null));
} else {
throw new DecoderException("Unknown relay ICE server type " + type);
}
}
yield new IceServers(servers);
}
case ICE_CANDIDATE, DESCRIPTION -> {
String peer = readAscii8(in);
int length = in.readUnsignedShort();
String text = in.toString(in.readerIndex(), length, StandardCharsets.ISO_8859_1);
in.skipBytes(length);
yield new Signal(id, peer, text);
}
case ERROR -> new Refusal(in.readUnsignedByte(), readAscii16(in));
case NEW_CLIENT -> new NewClient(readAscii8(in));
case CLIENT_SUCCESS, CLIENT_FAILURE -> new ClientDone(readAscii8(in), id == CLIENT_SUCCESS);
default -> new Ignored(id);
};
}
private static void writeAscii8(ByteBuf out, String text) {
byte[] bytes = text.getBytes(StandardCharsets.ISO_8859_1);
out.writeByte(bytes.length);
out.writeBytes(bytes);
}
private static void writeBytes16(ByteBuf out, byte[] bytes) {
out.writeShort(bytes.length);
out.writeBytes(bytes);
}
private static String readAscii8(ByteBuf in) {
int length = in.readUnsignedByte();
String text = in.toString(in.readerIndex(), length, StandardCharsets.ISO_8859_1);
in.skipBytes(length);
return text;
}
private static String readAscii16(ByteBuf in) {
int length = in.readUnsignedShort();
String text = in.toString(in.readerIndex(), length, StandardCharsets.ISO_8859_1);
in.skipBytes(length);
return text;
}
private static ByteBuffer nio(ByteBuf out) {
byte[] bytes = new byte[out.readableBytes()];
out.readBytes(bytes);
out.release();
return ByteBuffer.wrap(bytes);
}
}
@@ -0,0 +1,149 @@
package incari.net.relay;
import incari.platform.api.net.NetConnection;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import org.jspecify.annotations.Nullable;
/**
* A shared world's address once {@link RelayJoin} has opened a data channel to its host: the
* game's connection "connects" to it by taking over that channel. Messages that arrive before
* then are kept for it.
*/
public final class RelayWorldAddress extends InetSocketAddress {
private static final long serialVersionUID = 1L;
private final transient Buffered buffered;
private final String code;
RelayWorldAddress(String code, NetConnection channel, Buffered buffered) {
super(placeholder(), 0);
this.code = code;
this.buffered = buffered;
buffered.channel = channel;
}
/** 0.0.0.0 named "shared-world": resolves nothing, as for WebSocketAddress. */
private static InetAddress placeholder() {
try {
return InetAddress.getByAddress("shared-world", new byte[4]);
} catch (UnknownHostException e) {
throw new IllegalStateException(e);
}
}
/** The world's join code. */
public String code() {
return code;
}
/**
* The game's protocol the host plays if it's an Incari host ({@link HostHello}, ADR 0062): the
* guest joins it as it is. -1 for Eagler's hosts, which play 1.8 with Eagler's login.
*/
public int incariProtocol() {
return buffered.incariProtocol;
}
/**
* The data channel, now {@code listener}'s: it hears that the channel is open at once, then
* whatever came before, then everything as it comes.
*/
public NetConnection open(NetConnection.Listener listener) {
return buffered.attach(listener);
}
@Override
public String toString() {
return "shared world " + code;
}
/** Hears the data channel from its creation, until the game's connection takes it over. */
static final class Buffered implements NetConnection.Listener {
private final List<ByteBuffer> early = new ArrayList<>();
/** The protocol an Incari host's hello named; -1 before one, or for Eagler's hosts. */
int incariProtocol = -1;
/** Whether anything came on the channel yet: a hello comes first or not at all. */
boolean heard;
private @Nullable NetConnection channel;
private NetConnection.@Nullable Listener target;
private boolean open;
private boolean closed;
private @Nullable Throwable closeCause;
/** The join, told when the channel opens or closes before the game takes it. */
private final Runnable onOpen;
Buffered(Runnable onOpen) {
this.onOpen = onOpen;
}
boolean isOpen() {
return open && !closed;
}
NetConnection attach(NetConnection.Listener listener) {
NetConnection current = channel;
if (current == null) {
throw new IllegalStateException("No data channel yet");
}
target = listener;
if (closed) {
listener.closed(closeCause);
return current;
}
listener.connected();
for (ByteBuffer message : early) {
listener.received(message);
}
early.clear();
return current;
}
@Override
public void connected() {
open = true;
NetConnection.Listener listener = target;
if (listener == null) {
onOpen.run();
}
}
@Override
public void received(ByteBuffer data) {
if (!heard) {
heard = true;
int protocol = HostHello.read(data);
if (protocol >= 0) {
// The host's hello is for the join, not the game's connection.
incariProtocol = protocol;
return;
}
}
NetConnection.Listener listener = target;
if (listener != null) {
listener.received(data);
} else {
early.add(data);
}
}
@Override
public void closed(@Nullable Throwable cause) {
closed = true;
closeCause = cause;
NetConnection.Listener listener = target;
if (listener != null) {
listener.closed(cause);
}
}
}
}
@@ -0,0 +1,9 @@
/**
* Joining a world an Eagler player shares through a relay (ADR 0019): the relay protocol
* that pairs the client with the world's host over WebRTC, and the host's variant of the 1.8
* protocol carried over the data channel.
*/
@NullMarked
package incari.net.relay;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,442 @@
package incari.net.tls;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import org.bouncycastle.asn1.ASN1Encoding;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1String;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.RSAPublicKey;
import org.bouncycastle.asn1.sec.SECObjectIdentifiers;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.Certificate;
import org.bouncycastle.asn1.x509.ExtendedKeyUsage;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.Extensions;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.KeyPurposeId;
import org.bouncycastle.asn1.x509.KeyUsage;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x509.Time;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.Signer;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.digests.SHA384Digest;
import org.bouncycastle.crypto.digests.SHA512Digest;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.signers.DSADigestSigner;
import org.bouncycastle.crypto.signers.ECDSASigner;
import org.bouncycastle.crypto.signers.RSADigestSigner;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import org.jspecify.annotations.Nullable;
/**
* Checks a server's certificate chain the way RFC 5280 path validation would for the few hosts
* Microsoft sign-in talks to: the leaf names the host and is for server authentication, every
* certificate is in date, each one is signed by the next with a key that's a CA's, and the chain
* ends in a certificate signed by one of the pinned roots ({@link TrustAnchors}).
*
* <p>Deliberately narrow, since it only has to accept Microsoft's and Mojang's chains: RSA (2048
* bits or more) and ECDSA on P-256 or P-384, with SHA-256, -384 or -512. No SHA-1, no RSA-PSS
* certificate signatures, no name constraints (a critical one fails the chain), no revocation
* checks (browsers soft-fail those too). Chains are taken in the order the server sends them.
*/
public final class CertificateChain {
/** Longer chains than this aren't what these hosts send; refusing them bounds the work. */
static final int MAX_LENGTH = 6;
private static final int MIN_RSA_BITS = 2048;
/**
* The largest RSA modulus checked, and the largest public exponent (bits). Keys are read before
* anything is authenticated, and reading one tests its modulus for primality and a signature
* check raises to its exponent: a hostile proxy's 16384-bit key with a huge exponent costs
* seconds of CPU per certificate. Real CAs use 2048 to 4096 bits and 65537.
*/
static final int MAX_RSA_BITS = 4096;
static final int MAX_RSA_EXPONENT_BITS = 32;
/** Critical extensions this check understands; any other critical one fails the chain. */
private static final Set<ASN1ObjectIdentifier> UNDERSTOOD = Set.of(
Extension.basicConstraints,
Extension.keyUsage,
Extension.extendedKeyUsage,
Extension.subjectAlternativeName);
private final List<Certificate> anchors;
CertificateChain(List<Certificate> anchors) {
this.anchors = List.copyOf(anchors);
}
/** A check against the pinned roots. */
public static CertificateChain pinned() {
return new CertificateChain(TrustAnchors.roots());
}
/**
* Checks {@code chain} (DER certificates, leaf first, as the server sent them) for {@code host}
* at {@code nowMillis}.
*
* @throws UntrustedCertificateException saying what's wrong
*/
public void check(String host, List<byte[]> chain, long nowMillis) throws UntrustedCertificateException {
if (chain.isEmpty()) {
throw new UntrustedCertificateException("The server sent no certificate");
}
if (chain.size() > MAX_LENGTH) {
throw new UntrustedCertificateException("The server's certificate chain is too long");
}
List<Certificate> certificates = new ArrayList<>(chain.size());
for (byte[] encoded : chain) {
certificates.add(parse(encoded));
}
Certificate leaf = certificates.get(0);
if (!namesHost(leaf, host)) {
throw new UntrustedCertificateException("The server's certificate isn't for " + host);
}
// Every public TLS certificate names server authentication; one that doesn't isn't for this.
Extensions leafExtensions = leaf.getTBSCertificate().getExtensions();
ExtendedKeyUsage usage = leafExtensions == null ? null : ExtendedKeyUsage.fromExtensions(leafExtensions);
if (usage == null || !usage.hasKeyPurposeId(KeyPurposeId.id_kp_serverAuth)) {
throw new UntrustedCertificateException("The server's certificate isn't for servers");
}
for (int i = 0; i < certificates.size(); i++) {
Certificate certificate = certificates.get(i);
checkDates(certificate, nowMillis);
checkCriticalExtensions(certificate);
if (signedByAnchor(certificate)) {
return;
}
if (i + 1 == certificates.size()) {
break;
}
Certificate issuer = certificates.get(i + 1);
if (!certificate.getIssuer().equals(issuer.getSubject())) {
throw new UntrustedCertificateException("The server's certificate chain is out of order");
}
// i intermediates sit below the issuer at i + 1 (the leaf isn't counted).
checkIssuer(issuer, i);
if (!verifies(certificate, issuer.getSubjectPublicKeyInfo())) {
throw new UntrustedCertificateException("A signature in the server's certificate chain is wrong");
}
}
throw new UntrustedCertificateException("The server's certificate isn't issued by a trusted root");
}
private static Certificate parse(byte[] encoded) throws UntrustedCertificateException {
try {
return Certificate.getInstance(encoded);
} catch (RuntimeException e) {
throw new UntrustedCertificateException("The server's certificate can't be read", e);
}
}
// --- Names ---------------------------------------------------------------------------------
/**
* Whether a DNS name in the certificate's subject alternative names matches {@code host}. The
* common name isn't consulted (RFC 6125; public CAs always fill in the alternative names).
*/
static boolean namesHost(Certificate certificate, String host) {
Extensions extensions = certificate.getTBSCertificate().getExtensions();
if (extensions == null) {
return false;
}
GeneralNames names;
try {
names = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
} catch (RuntimeException e) {
return false;
}
if (names == null) {
return false;
}
String wanted = normalize(host);
for (GeneralName name : names.getNames()) {
if (name.getTagNo() == GeneralName.dNSName
&& name.getName() instanceof ASN1String dns
&& matches(normalize(dns.getString()), wanted)) {
return true;
}
}
return false;
}
/**
* Whether a certificate's DNS name matches a host: exactly, or as a wildcard for the whole
* leftmost label ({@code *.mojang.com} matches {@code sessionserver.mojang.com}, not
* {@code mojang.com} or {@code a.b.mojang.com}), and never a wildcard over fewer than two labels.
*/
static boolean matches(String pattern, String host) {
if (pattern.isEmpty() || host.isEmpty()) {
return false;
}
if (!pattern.startsWith("*.")) {
return pattern.indexOf('*') < 0 && pattern.equals(host);
}
String suffix = pattern.substring(1); // ".mojang.com"
if (suffix.indexOf('*') >= 0 || suffix.indexOf('.', 1) < 0) {
return false;
}
if (!host.endsWith(suffix)) {
return false;
}
String label = host.substring(0, host.length() - suffix.length());
return !label.isEmpty() && label.indexOf('.') < 0;
}
private static String normalize(String name) {
String lower = name.toLowerCase(Locale.ROOT);
return lower.endsWith(".") ? lower.substring(0, lower.length() - 1) : lower;
}
// --- Each certificate ----------------------------------------------------------------------
private static void checkDates(Certificate certificate, long nowMillis) throws UntrustedCertificateException {
long notBefore = epochMillis(certificate.getStartDate());
long notAfter = epochMillis(certificate.getEndDate());
if (nowMillis < notBefore || nowMillis > notAfter) {
throw new UntrustedCertificateException(
"A certificate in the server's chain is out of date (check this device's clock)");
}
}
/**
* A certificate time in epoch milliseconds, read from its DER form by hand: RFC 5280 allows only
* {@code YYMMDDHHMMSSZ} (UTCTime, years 1950 to 2049) and {@code YYYYMMDDHHMMSSZ}
* (GeneralizedTime), and Bouncy Castle's own conversion goes through {@code SimpleDateFormat},
* which the browser build lacks.
*/
static long epochMillis(Time time) throws UntrustedCertificateException {
byte[] encoded;
try {
encoded = time.toASN1Primitive().getEncoded(ASN1Encoding.DER);
} catch (IOException e) {
throw new UntrustedCertificateException("A certificate's date can't be read", e);
}
int tag = encoded.length > 2 ? encoded[0] & 0xFF : -1;
int length = encoded.length > 2 ? encoded[1] & 0xFF : -1;
String text = length == encoded.length - 2 ? new String(encoded, 2, length, StandardCharsets.US_ASCII) : "";
int year;
String rest;
if (tag == 0x17 && text.length() == 13) {
int yy = digits(text, 0, 2);
year = yy < 50 ? 2000 + yy : 1900 + yy;
rest = text.substring(2);
} else if (tag == 0x18 && text.length() == 15) {
year = digits(text, 0, 4);
rest = text.substring(4);
} else {
throw new UntrustedCertificateException("A certificate's date isn't in the standard form");
}
if (rest.charAt(10) != 'Z') {
throw new UntrustedCertificateException("A certificate's date isn't in UTC");
}
int month = digits(rest, 0, 2);
int day = digits(rest, 2, 4);
int hour = digits(rest, 4, 6);
int minute = digits(rest, 6, 8);
int second = digits(rest, 8, 10);
if (month < 1 || month > 12 || day < 1 || day > 31 || hour > 23 || minute > 59 || second > 60) {
throw new UntrustedCertificateException("A certificate's date isn't a real date");
}
long days = daysFromCivil(year, month, day);
return ((days * 24 + hour) * 60 + minute) * 60_000L + second * 1000L;
}
private static int digits(String text, int from, int to) throws UntrustedCertificateException {
int value = 0;
for (int i = from; i < to; i++) {
char c = text.charAt(i);
if (c < '0' || c > '9') {
throw new UntrustedCertificateException("A certificate's date isn't in the standard form");
}
value = value * 10 + (c - '0');
}
return value;
}
/** Days since 1970-01-01 in the proleptic Gregorian calendar (Howard Hinnant's algorithm). */
static long daysFromCivil(int year, int month, int day) {
int y = month <= 2 ? year - 1 : year;
int era = Math.floorDiv(y, 400);
int yearOfEra = y - era * 400;
int monthIndex = month > 2 ? month - 3 : month + 9;
int dayOfYear = (153 * monthIndex + 2) / 5 + day - 1;
int dayOfEra = yearOfEra * 365 + yearOfEra / 4 - yearOfEra / 100 + dayOfYear;
return era * 146097L + dayOfEra - 719468;
}
private static void checkCriticalExtensions(Certificate certificate) throws UntrustedCertificateException {
Extensions extensions = certificate.getTBSCertificate().getExtensions();
if (extensions == null) {
return;
}
for (ASN1ObjectIdentifier oid : extensions.getCriticalExtensionOIDs()) {
if (!UNDERSTOOD.contains(oid)) {
throw new UntrustedCertificateException(
"A certificate in the server's chain has an unknown critical part");
}
}
}
/** That {@code issuer} may sign certificates, with {@code below} intermediates under it. */
private static void checkIssuer(Certificate issuer, int below) throws UntrustedCertificateException {
Extensions extensions = issuer.getTBSCertificate().getExtensions();
BasicConstraints constraints = extensions == null ? null : BasicConstraints.fromExtensions(extensions);
if (constraints == null || !constraints.isCA()) {
throw new UntrustedCertificateException("A certificate in the server's chain was signed by a non-CA");
}
BigInteger pathLength = constraints.getPathLenConstraint();
if (pathLength != null && pathLength.compareTo(BigInteger.valueOf(below)) < 0) {
throw new UntrustedCertificateException("The server's certificate chain is longer than its CA allows");
}
KeyUsage keyUsage = KeyUsage.fromExtensions(extensions);
if (keyUsage != null && !keyUsage.hasUsages(KeyUsage.keyCertSign)) {
throw new UntrustedCertificateException(
"A certificate in the server's chain was signed by a key not for that");
}
// A CA limited to other purposes (code or document signing) can't vouch for a server.
ExtendedKeyUsage purposes = ExtendedKeyUsage.fromExtensions(extensions);
if (purposes != null
&& !purposes.hasKeyPurposeId(KeyPurposeId.id_kp_serverAuth)
&& !purposes.hasKeyPurposeId(KeyPurposeId.anyExtendedKeyUsage)) {
throw new UntrustedCertificateException("A CA in the server's chain isn't for servers");
}
}
/** Whether one of the pinned roots issued {@code certificate}: names match and its key verifies. */
private boolean signedByAnchor(Certificate certificate) throws UntrustedCertificateException {
for (Certificate anchor : anchors) {
if (certificate.getIssuer().equals(anchor.getSubject())
&& verifies(certificate, anchor.getSubjectPublicKeyInfo())) {
return true;
}
}
return false;
}
// --- Signatures ----------------------------------------------------------------------------
/** Whether {@code certificate}'s signature verifies with {@code issuerKey}. */
static boolean verifies(Certificate certificate, SubjectPublicKeyInfo issuerKey)
throws UntrustedCertificateException {
AlgorithmIdentifier algorithm = certificate.getSignatureAlgorithm();
if (!algorithm.equals(certificate.getTBSCertificate().getSignature())) {
throw new UntrustedCertificateException(
"A certificate in the server's chain names two signature algorithms");
}
Signer signer = signer(algorithm.getAlgorithm(), issuerKey);
try {
byte[] signed = certificate.getTBSCertificate().getEncoded(ASN1Encoding.DER);
signer.update(signed, 0, signed.length);
return signer.verifySignature(certificate.getSignature().getOctets());
} catch (IOException | RuntimeException e) {
return false;
}
}
private static Signer signer(ASN1ObjectIdentifier algorithm, SubjectPublicKeyInfo issuerKey)
throws UntrustedCertificateException {
Digest rsaDigest = rsaDigest(algorithm);
if (rsaDigest != null) {
Signer signer = new RSADigestSigner(rsaDigest);
signer.init(false, rsaKey(issuerKey));
return signer;
}
Digest ecDigest = ecdsaDigest(algorithm);
if (ecDigest != null) {
// The curve is checked before the key is read, so no explicit curve is ever parsed.
Object curve = issuerKey.getAlgorithm().getParameters();
boolean knownCurve =
X9ObjectIdentifiers.prime256v1.equals(curve) || SECObjectIdentifiers.secp384r1.equals(curve);
if (!X9ObjectIdentifiers.id_ecPublicKey.equals(
issuerKey.getAlgorithm().getAlgorithm())
|| !knownCurve) {
throw new UntrustedCertificateException(
"A key in the server's certificate chain is of an unknown kind");
}
AsymmetricKeyParameter key = readKey(issuerKey);
if (!(key instanceof ECPublicKeyParameters ec)) {
throw new UntrustedCertificateException(
"A key in the server's certificate chain is of an unknown kind");
}
Signer signer = new DSADigestSigner(new ECDSASigner(), ecDigest);
signer.init(false, ec);
return signer;
}
throw new UntrustedCertificateException("The server's certificate chain uses an unsupported signature");
}
/** An RSA key, its sizes checked from the raw numbers before Bouncy Castle reads it. */
private static RSAKeyParameters rsaKey(SubjectPublicKeyInfo issuerKey) throws UntrustedCertificateException {
if (!PKCSObjectIdentifiers.rsaEncryption.equals(issuerKey.getAlgorithm().getAlgorithm())) {
throw new UntrustedCertificateException("A key in the server's certificate chain is of an unknown kind");
}
RSAPublicKey numbers;
try {
numbers = RSAPublicKey.getInstance(issuerKey.parsePublicKey());
} catch (IOException | RuntimeException e) {
throw new UntrustedCertificateException("A key in the server's certificate chain can't be read", e);
}
int bits = numbers.getModulus().bitLength();
if (bits < MIN_RSA_BITS
|| bits > MAX_RSA_BITS
|| numbers.getPublicExponent().bitLength() > MAX_RSA_EXPONENT_BITS) {
throw new UntrustedCertificateException("A key in the server's certificate chain is too weak or too big");
}
if (!(readKey(issuerKey) instanceof RSAKeyParameters rsa) || rsa.isPrivate()) {
throw new UntrustedCertificateException("A key in the server's certificate chain can't be read");
}
return rsa;
}
private static AsymmetricKeyParameter readKey(SubjectPublicKeyInfo key) throws UntrustedCertificateException {
try {
return PublicKeyFactory.createKey(key);
} catch (IOException | RuntimeException e) {
throw new UntrustedCertificateException("A key in the server's certificate chain can't be read", e);
}
}
private static @Nullable Digest rsaDigest(ASN1ObjectIdentifier algorithm) {
if (PKCSObjectIdentifiers.sha256WithRSAEncryption.equals(algorithm)) {
return new SHA256Digest();
}
if (PKCSObjectIdentifiers.sha384WithRSAEncryption.equals(algorithm)) {
return new SHA384Digest();
}
if (PKCSObjectIdentifiers.sha512WithRSAEncryption.equals(algorithm)) {
return new SHA512Digest();
}
return null;
}
private static @Nullable Digest ecdsaDigest(ASN1ObjectIdentifier algorithm) {
if (X9ObjectIdentifiers.ecdsa_with_SHA256.equals(algorithm)) {
return new SHA256Digest();
}
if (X9ObjectIdentifiers.ecdsa_with_SHA384.equals(algorithm)) {
return new SHA384Digest();
}
if (X9ObjectIdentifiers.ecdsa_with_SHA512.equals(algorithm)) {
return new SHA512Digest();
}
return null;
}
}
@@ -0,0 +1,338 @@
package incari.net.tls;
import incari.platform.api.net.NetConnection;
import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.function.LongSupplier;
import org.bouncycastle.tls.AlertDescription;
import org.bouncycastle.tls.CertificateRequest;
import org.bouncycastle.tls.DefaultTlsClient;
import org.bouncycastle.tls.NameType;
import org.bouncycastle.tls.ProtocolName;
import org.bouncycastle.tls.ProtocolVersion;
import org.bouncycastle.tls.ServerName;
import org.bouncycastle.tls.TlsAuthentication;
import org.bouncycastle.tls.TlsClientProtocol;
import org.bouncycastle.tls.TlsCredentials;
import org.bouncycastle.tls.TlsFatalAlert;
import org.bouncycastle.tls.TlsServerCertificate;
import org.bouncycastle.tls.crypto.TlsCertificate;
import org.bouncycastle.tls.crypto.impl.bc.BcTlsCrypto;
import org.jspecify.annotations.Nullable;
/**
* A TLS 1.2 or 1.3 client connection over another connection's bytes ({@link Transport}): Bouncy
* Castle's protocol engine in its non-blocking mode, fed as bytes arrive, so nothing waits. What it
* hands its listener is the decrypted stream, and {@link Listener#connected} comes only once the
* handshake has finished and the server's certificate passed {@link CertificateChain}.
*
* <p>Encryption is end to end: a Wisp proxy in between carries only ciphertext, and can't read or
* change what's sent without the handshake or a record failing.
*
* <p>Closing: {@link Listener#closed} gets null only after the server's close_notify; a transport
* that ends without one gets an {@link EOFException}, so a reader framing by connection close
* can tell a truncated stream from a whole one.
*/
public final class TlsConnection implements NetConnection {
private final String host;
private final Listener listener;
private final CertificateChain certificates;
private final LongSupplier clock;
private final TlsClientProtocol protocol = new TlsClientProtocol();
private @Nullable NetConnection transport;
// Guarded by this.
private boolean handshaken;
private boolean closed;
/** What was sent before the handshake finished, sent once it has. */
private final List<byte[]> early = new ArrayList<>();
private TlsConnection(String host, Listener listener, CertificateChain certificates, LongSupplier clock) {
this.host = host;
this.listener = listener;
this.certificates = certificates;
this.clock = clock;
}
/**
* Connects to {@code host}:{@code port} over {@code transport} and starts the handshake.
* Returns at once.
*
* @param clock the time certificates are checked against, in epoch milliseconds
*/
public static NetConnection open(
Transport transport,
String host,
int port,
CertificateChain certificates,
LongSupplier clock,
Listener listener) {
TlsConnection connection = new TlsConnection(host, listener, certificates, clock);
synchronized (connection) {
// Held so the transport's first callbacks wait for the field.
connection.transport = transport.connect(host, port, connection.new TransportListener());
}
return connection;
}
@Override
public void send(ByteBuffer data) {
byte[] bytes = new byte[data.remaining()];
data.get(bytes);
@Nullable IOException failure = null;
synchronized (this) {
if (closed) {
return;
}
if (!handshaken) {
early.add(bytes);
return;
}
try {
protocol.writeApplicationData(bytes, 0, bytes.length);
drain();
} catch (IOException e) {
failure = e;
}
}
if (failure != null) {
fail(failure);
}
}
@Override
public void close() {
boolean tell;
synchronized (this) {
tell = !closed;
if (tell) {
try {
protocol.close();
drain();
} catch (IOException ignored) {
// Closing anyway.
}
}
finish();
}
if (tell) {
listener.closed(null);
}
}
@Override
public synchronized boolean isOpen() {
return handshaken && !closed;
}
@Override
public String remoteDescription() {
NetConnection current = transport;
return "TLS to " + host + (current != null ? " over " + current.remoteDescription() : "");
}
// --- Under the lock ------------------------------------------------------------------------
/** Sends whatever the protocol has written (handshake messages, records, alerts). */
private void drain() {
int available = protocol.getAvailableOutputBytes();
NetConnection current = transport;
if (available <= 0 || current == null) {
return;
}
byte[] out = new byte[available];
int read = protocol.readOutput(out, 0, available);
current.send(ByteBuffer.wrap(out, 0, read));
current.flush();
}
private void finish() {
closed = true;
early.clear();
NetConnection current = transport;
if (current != null) {
current.close();
}
}
private void fail(Throwable cause) {
boolean tell;
synchronized (this) {
tell = !closed;
if (tell) {
drain(); // A fatal alert, if the protocol wrote one.
}
finish();
}
if (tell) {
listener.closed(cause);
}
}
// --- Callbacks -----------------------------------------------------------------------------
private final class TransportListener implements Listener {
@Override
public void connected() {
@Nullable IOException failure = null;
synchronized (TlsConnection.this) {
if (closed) {
return;
}
try {
protocol.connect(new Client());
drain();
} catch (IOException e) {
failure = e;
}
}
if (failure != null) {
fail(failure);
}
}
@Override
public void received(ByteBuffer data) {
byte[] bytes = new byte[data.remaining()];
data.get(bytes);
boolean nowConnected = false;
byte @Nullable [] plain = null;
boolean peerClosed = false;
@Nullable Throwable failure = null;
synchronized (TlsConnection.this) {
if (closed) {
return;
}
try {
boolean wasHandshaken = handshaken;
protocol.offerInput(bytes);
if (!wasHandshaken && handshaken) {
nowConnected = true;
for (byte[] queued : early) {
protocol.writeApplicationData(queued, 0, queued.length);
}
early.clear();
}
drain();
int available = protocol.getAvailableInputBytes();
if (available > 0) {
plain = new byte[available];
protocol.readInput(plain, 0, available);
}
peerClosed = protocol.isClosed();
} catch (IOException | RuntimeException e) {
failure = e;
}
}
if (failure != null) {
fail(failure);
return;
}
if (nowConnected) {
listener.connected();
}
if (plain != null) {
listener.received(ByteBuffer.wrap(plain));
}
if (peerClosed) {
boolean tell;
synchronized (TlsConnection.this) {
tell = !closed;
finish();
}
if (tell) {
listener.closed(null);
}
}
}
@Override
public void closed(@Nullable Throwable cause) {
boolean tell;
boolean wasHandshaken;
synchronized (TlsConnection.this) {
tell = !closed;
wasHandshaken = handshaken;
closed = true;
early.clear();
}
if (tell) {
Throwable reason = cause != null
? cause
: new EOFException(
wasHandshaken
? "The connection to " + host + " ended without a TLS close"
: "The connection to " + host + " ended during the TLS handshake");
listener.closed(reason);
}
}
}
/** Bouncy Castle's client side: TLS 1.2 and 1.3, the host's name, and the pinned roots. */
private final class Client extends DefaultTlsClient {
Client() {
super(new BcTlsCrypto(new SecureRandom()));
}
@Override
protected ProtocolVersion[] getSupportedVersions() {
return ProtocolVersion.TLSv13.downTo(ProtocolVersion.TLSv12);
}
@Override
@SuppressWarnings({"JdkObsolete", "rawtypes", "unchecked"}) // Bouncy Castle's API takes a Vector.
protected Vector getSNIServerNames() {
Vector names = new Vector(1);
names.add(new ServerName(NameType.host_name, host.getBytes(StandardCharsets.US_ASCII)));
return names;
}
@Override
@SuppressWarnings({"JdkObsolete", "rawtypes", "unchecked"}) // Bouncy Castle's API takes a Vector.
protected Vector getProtocolNames() {
Vector names = new Vector(1);
names.add(ProtocolName.HTTP_1_1);
return names;
}
@Override
public TlsAuthentication getAuthentication() {
return new TlsAuthentication() {
@Override
public void notifyServerCertificate(TlsServerCertificate serverCertificate) throws IOException {
TlsCertificate[] chain = serverCertificate.getCertificate().getCertificateList();
List<byte[]> encoded = new ArrayList<>(chain.length);
for (TlsCertificate certificate : chain) {
encoded.add(certificate.getEncoded());
}
try {
certificates.check(host, encoded, clock.getAsLong());
} catch (UntrustedCertificateException e) {
throw new TlsFatalAlert(AlertDescription.bad_certificate, e.getMessage(), e);
}
}
@Override
public @Nullable TlsCredentials getClientCredentials(CertificateRequest request) {
return null;
}
};
}
@Override
public void notifyHandshakeComplete() throws IOException {
super.notifyHandshakeComplete();
// Called from inside offerInput, under the connection's lock.
handshaken = true;
}
}
}
@@ -0,0 +1,29 @@
package incari.net.tls;
import incari.net.WebSocketUrl;
import incari.net.wisp.WispAddress;
import incari.net.wisp.WispConnection;
import incari.platform.api.net.NetConnection;
import incari.platform.api.net.PlatformNetwork;
/**
* Where TLS's bytes go: a TCP connection to a host and port, however this platform makes one. The
* desktop opens a socket; a page, which has none, opens a stream through a Wisp proxy, which sees
* only the encrypted bytes.
*/
@FunctionalInterface
public interface Transport {
/** Starts a TCP connection and returns at once, as {@link PlatformNetwork#connect} does. */
NetConnection connect(String host, int port, NetConnection.Listener listener);
/** A socket of this machine's own (the desktop). */
static Transport direct(PlatformNetwork network) {
return network::connect;
}
/** A stream through the Wisp proxy at {@code proxy} (the browser). */
static Transport wisp(PlatformNetwork network, WebSocketUrl proxy) {
return (host, port, listener) -> WispConnection.open(network, new WispAddress(proxy, host, port), listener);
}
}
@@ -0,0 +1,116 @@
package incari.net.tls;
import java.util.Base64;
import java.util.List;
import org.bouncycastle.asn1.x509.Certificate;
/**
* The root certificates Incari trusts for Microsoft sign-in: only the roots Microsoft's and Mojang's
* sign-in hosts chain to, not a browser's whole store. Every host in {@code MicrosoftEndpoints}
* chained to DigiCert Global Root G2 when this was written (November 2026); the other three are the
* roots Microsoft names for its own services, so a move to them keeps sign-in working.
*
* <p>A host that moves to another root fails the handshake with "not issued by a trusted root" until
* this list is updated. Embedded as DER rather than read as a resource: the browser build's class
* path resources are the game's, mounted from its jar.
*/
final class TrustAnchors {
/**
* DigiCert Global Root G2 (RSA 2048, until 2038-01-15). SHA-256
* CB:3C:CB:B7:60:31:E5:E0:13:8F:8D:D3:9A:23:F9:DE:47:FF:C3:5E:43:C1:14:4C:EA:27:D4:6A:5A:B1:CB:5F.
*/
private static final String DIGICERT_GLOBAL_ROOT_G2 =
"MIIDjjCCAnagAwIBAgIQAzrx5qcRqaC7KGSxHQn65TANBgkqhkiG9w0BAQsFADBhMQswCQYDVQQGEwJVUzEVMBMGA1UEChMM"
+ "RGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBH"
+ "MjAeFw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMx"
+ "GTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEcyMIIBIjANBgkqhkiG"
+ "9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzfNNNx7a8myaJCtSnX/RrohCgiN9RlUyfuI2/Ou8jqJkTx65qsGGmvPrC3oXgkkRLpi"
+ "mn7Wo6h+4FR1IAWsULecYxpsMNzaHxmx1x7e/dfgy5SDN67sH0NO3Xss0r0upS/kqbitOtSZpLYl6ZtrAGCSYP9PIUkY92eQ"
+ "q2EGnI/yuum06ZIya7XzV+hdG82MHauVBJVJ8zUtluNJbd134/tJS7SsVQepj5WztCO7TG1F8PapspUwtP1MVYwnSlcUfIKd"
+ "zXOS0xZKBgyMUNGPHgm+F6HmIcr9g+UQvIOlCsRnKPZzFBQ9RnbDhxSJITRNrw9FDKZJobq7nMWxM4MphQIDAQABo0IwQDAP"
+ "BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUTiJUIBiV5uNu5g/6+rkS7QYXjzkwDQYJKoZIhvcN"
+ "AQELBQADggEBAGBnKJRvDkhj6zHd6mcY1Yl9PMWLSn/pvtsrF9+wX3N3KjITOYFnQoQj8kVnNeyIv/iPsGEMNKSuIEyExtv4"
+ "NeF22d+mQrvHRAiGfzZ0JFrabA0UWTW98kndth/Jsw1HKj2ZL7tcu7XUIOGZX1NGFdtom/DzMNU+MeKNhJ7jitralj41E6Vf"
+ "8PlwUHBHQRFXGU7Aj64GxJUTFy8bJZ918rGOmaFvE7FBcf6IKshPECBV1/MUReXgRPTqh5Uykw7+U0b6LJ3/iyK5S9kJRaTe"
+ "pLiaWN0bfVKfjllDiIGknibVb63dDcY3fe0Dkhvld1927jyNxF1WW6LZZm6zNTflMrY=";
/**
* DigiCert Global Root G3 (ECDSA P-384, until 2038-01-15). SHA-256
* 31:AD:66:48:F8:10:41:38:C7:38:F3:9E:A4:32:01:33:39:3E:3A:18:CC:02:29:6E:F9:7C:2A:C9:EF:67:31:D0.
*/
private static final String DIGICERT_GLOBAL_ROOT_G3 =
"MIICPzCCAcWgAwIBAgIQBVVWvPJepDU1w6QP1atFcjAKBggqhkjOPQQDAzBhMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGln"
+ "aUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBHMzAe"
+ "Fw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAX"
+ "BgNVBAsTEHd3dy5kaWdpY2VydC5jb20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEczMHYwEAYHKoZIzj0CAQYF"
+ "K4EEACIDYgAE3afZu4q4C/sLfyHS8L6+c/MzXRq8NOrexpu80JX28MzQC7phW1FGfp4tn+6OYwwX7Adw9c+ELkCDnOg/QW07"
+ "rdOkFFk2eJ0DQ+4QE2xy3q6Ip6FrtUPOZ9wj/wMco+I+o0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAd"
+ "BgNVHQ4EFgQUs9tIpPmhxdiuNkHMEWNpYim8S8YwCgYIKoZIzj0EAwMDaAAwZQIxAK288mw/EkrRLTnDCgmXc/SINoyIJ7vm"
+ "iI1Qhadj+Z4y3maTD/HMsQmP3Wyr+mt/oAIwOWZbwmSNuJ5Q3KjVSaLtx9zRSX8XAbjIho9OjIgrqJqpisXRAL34VOKa5Vt8"
+ "sycX";
/**
* Microsoft RSA Root Certificate Authority 2017 (RSA 4096, until 2042-07-18). SHA-256
* C7:41:F7:0F:4B:2A:8D:88:BF:2E:71:C1:41:22:EF:53:EF:10:EB:A0:CF:A5:E6:4C:FA:20:F4:18:85:30:73:E0.
*/
private static final String MICROSOFT_RSA_ROOT_2017 =
"MIIFqDCCA5CgAwIBAgIQHtOXCV/YtLNHcB6qvn9FszANBgkqhkiG9w0BAQwFADBlMQswCQYDVQQGEwJVUzEeMBwGA1UEChMV"
+ "TWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYDVQQDEy1NaWNyb3NvZnQgUlNBIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5"
+ "IDIwMTcwHhcNMTkxMjE4MjI1MTIyWhcNNDIwNzE4MjMwMDIzWjBlMQswCQYDVQQGEwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0"
+ "IENvcnBvcmF0aW9uMTYwNAYDVQQDEy1NaWNyb3NvZnQgUlNBIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIwMTcwggIi"
+ "MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKW76UM4wplZEWCpW9R2LBifOZNt9GkMml7Xhqb0eRaPgnZ1AzHaGm++Dl"
+ "Q6OEAlcBXZxIQIJTELy/xztokLaCLeX0ZdDMbRnMlfl7rEqUrQ7eS0MdhweSE5CAg2Q1OQT85elss7YfUJQ4ZVBcF0a5toW1"
+ "HLUX6NZFndiyJrDKxHBKrmCk3bPZ7Pw71VdyvD/IybLeS2v4I2wDwAW9lcfNcztmgGTjGqwu+UcF8ga2m3P1eDNbx6H7Jyqh"
+ "tJqRjJHTOoI+dkC0zVJhUXAoP8XFWvLJjEm7FFtNyP9nTUwSlq31/niol4fX/V4ggNyhSyL71Imtus5Hl0dVe49FyGcohJUc"
+ "aDDv70ngNXtk55iwlNpNhTs+VcQor1fznhPbRiefHqJeRIOkpcrVE7NLP8TjwuaGYaRSMLl6IE9vDzhTyzMMEyuP1pq9Ksgt"
+ "sRx9S1HKR9FIJ3Jdh+vVReZIZZ2vUpC6W6IYZVcSn2i51BVrlMRpIpj0M+Dt+VGOQVDJNE92kKz8OMHY4Xu54+OU4UZpyw4K"
+ "UGsTuqwPN1q3ErWQgR5WrlcihtnJ0tHXUeOrO8ZV/R4O03QK0dqq6mm4lyiPSMQH+FJDOvTKVTUssKZqwJz58oHhEmrARdln"
+ "s87/I6KJClTUFLkqqNfs+avNJVgyeY+QW5g5xAgGwax/Dj0ApQIDAQABo1QwUjAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/"
+ "BAUwAwEB/zAdBgNVHQ4EFgQUCctZf4aycI8awznjwNnpv7tNsiMwEAYJKwYBBAGCNxUBBAMCAQAwDQYJKoZIhvcNAQEMBQAD"
+ "ggIBAKyvPl3CEZaJjqPnktaXFbgToqZCLgLNFgVZJ8og6Lq46BrsTaiXVq5lQ7GPAJtSzVXNUzltYkyLDVt8LkS/gxCP81OC"
+ "gMNPOsduET/m4xaRhPtthH80dK2Jp86519efhGSSvpWhrQlTM93uCupKUY5vVau6tZRGrox/2KJQJWVggEbbMwSubLWYdFQl"
+ "3JPk+ONVFT24bcMKpBLBaYVu32TxU5nhSnUgnZUP5NbcA/FZGOhHibJXWpS2qdgXKxdJ5XbLwVaZOjex/2kskZGT4d9Mozd2"
+ "TaGf+G0eHdP67Pv0RR0Tbc/3WeUiJ3IrhvNXuzDtJE3cfVa7o7P4NHmJweDyAmH3pvwPuxwXC65B2Xy9J6P9LjrRk5Sxcx0k"
+ "i69bIImtt2dmefU6xqaWM/5TkshGsRGRxpl/j8nWZjEgQRCHLQzWwa80mMpkg/sTV9HB8Dx6jKXB/ZUhoHHBk2dxEuqPiApp"
+ "GWSZI1b7rCoucL5mxAyE7+WL85MB+GqQk2dLsmijtWKP6T+MejteD+eMuMZ87zf9dOLITzNy4ZQ5bb0Sr74MTnB8G2+NszKT"
+ "c0QWbej09+CVgI+WXTik9KveCjCHk9hNAHFiRSdLOkKEW39lt2c0Ui2cFmuqqNh7o0JMcccMyj6D5KbvtwEwXlGjefVwaaZB"
+ "RA+GsCyRxj3qrg+E";
/**
* Microsoft ECC Root Certificate Authority 2017 (ECDSA P-384, until 2042-07-18). SHA-256
* 35:8D:F3:9D:76:4A:F9:E1:B7:66:E9:C9:72:DF:35:2E:E1:5C:FA:C2:27:AF:6A:D1:D7:0E:8E:4A:6E:DC:BA:02.
*/
private static final String MICROSOFT_ECC_ROOT_2017 =
"MIICWTCCAd+gAwIBAgIQZvI9r4fei7FK6gxXMQHC7DAKBggqhkjOPQQDAzBlMQswCQYDVQQGEwJVUzEeMBwGA1UEChMVTWlj"
+ "cm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYDVQQDEy1NaWNyb3NvZnQgRUNDIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIw"
+ "MTcwHhcNMTkxMjE4MjMwNjQ1WhcNNDIwNzE4MjMxNjA0WjBlMQswCQYDVQQGEwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENv"
+ "cnBvcmF0aW9uMTYwNAYDVQQDEy1NaWNyb3NvZnQgRUNDIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIwMTcwdjAQBgcq"
+ "hkjOPQIBBgUrgQQAIgNiAATUvD0CQnVBEyPNgASGAlEvaqiBYgtlzPbKnR5vSmZRogPZnZH6thaxjG7efM3beaYvzrvOcS/l"
+ "paso7GMEZpn4+vKTEAXhgShC48Zo9OYbhGBKia/teQ87zvH2RPUBeMCjVDBSMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8E"
+ "BTADAQH/MB0GA1UdDgQWBBTIy5lycFIM+Oa+sgRXKSrPQhDtNTAQBgkrBgEEAYI3FQEEAwIBADAKBggqhkjOPQQDAwNoADBl"
+ "AjBY8k3qDPlfXu5gKcs68tvWMoQZP3zVL8KxzJOuULsJMsbG7X7JNpQS5GiFBqIb0C8CMQCZ6Ra0DvpWSNSkMBaReNtUjGUB"
+ "iudQZsIxtzm6uBoiB078a1QWIP8rtedMDE2mT3M=";
private static volatile List<Certificate> roots = List.of();
private TrustAnchors() {}
/** The pinned roots, parsed once. */
static List<Certificate> roots() {
List<Certificate> parsed = roots;
if (parsed.isEmpty()) {
parsed = List.of(
parse(DIGICERT_GLOBAL_ROOT_G2),
parse(DIGICERT_GLOBAL_ROOT_G3),
parse(MICROSOFT_RSA_ROOT_2017),
parse(MICROSOFT_ECC_ROOT_2017));
roots = parsed;
}
return parsed;
}
private static Certificate parse(String base64) {
return Certificate.getInstance(Base64.getDecoder().decode(base64));
}
}
@@ -0,0 +1,15 @@
package incari.net.tls;
/** A server's certificate chain failed {@link CertificateChain}'s checks; the message says why, in plain words. */
public final class UntrustedCertificateException extends Exception {
private static final long serialVersionUID = 1L;
public UntrustedCertificateException(String message) {
super(message);
}
public UntrustedCertificateException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,9 @@
/**
* TLS for Microsoft sign-in (ADR 0070): Bouncy Castle's non-blocking TLS client over any
* connection ({@link incari.net.tls.Transport}: a socket, or a Wisp stream in the browser), with
* the server's chain checked against a few pinned roots. No game types, no blocking.
*/
@NullMarked
package incari.net.tls;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,162 @@
package incari.net.wisp;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import org.jspecify.annotations.Nullable;
/**
* A server's {@code _minecraft._tcp} SRV record, asked of a public resolver over DNS-over-TCP through
* the Wisp proxy itself: a page can't look names up, and the proxy only opens sockets. The game
* does the same lookup for a host given without a port.
*/
final class SrvLookup {
/** Cloudflare's resolver, as Wispcraft uses (it asks over HTTPS; TCP needs no TLS here). */
static final String RESOLVER_HOST = "1.1.1.1";
static final int RESOLVER_PORT = 53;
private static final int TYPE_SRV = 33;
private static final int CLASS_IN = 1;
private static final int MAX_LABEL = 63;
/** Compression pointers followed per name; a loop in a bad reply stops here. */
private static final int MAX_JUMPS = 16;
/** Where an SRV record points. */
record Target(String host, int port) {}
private SrvLookup() {}
/** The record's name for {@code host}, or null if {@code host} can't be one (a label too long). */
static @Nullable String recordName(String host) {
String name = "_minecraft._tcp." + host;
for (String label : name.split("\\.", -1)) {
if (label.isEmpty() || label.length() > MAX_LABEL) {
return null;
}
}
return name;
}
/** A query for {@code name}'s SRV records, framed for TCP (a two-byte length first). */
static byte[] query(String name, int id) {
ByteArrayOutputStream message = new ByteArrayOutputStream();
writeShort(message, id);
writeShort(message, 0x0100); // a standard query, recursion desired
writeShort(message, 1); // one question
writeShort(message, 0);
writeShort(message, 0);
writeShort(message, 0);
for (String label : name.split("\\.", -1)) {
byte[] bytes = label.getBytes(StandardCharsets.US_ASCII);
message.write(bytes.length);
message.write(bytes, 0, bytes.length);
}
message.write(0);
writeShort(message, TYPE_SRV);
writeShort(message, CLASS_IN);
byte[] body = message.toByteArray();
ByteBuffer framed = ByteBuffer.allocate(2 + body.length);
framed.putShort((short) body.length).put(body);
return framed.array();
}
/**
* The length of the reply framed at the start of {@code received}, or -1 if its two-byte length
* hasn't all arrived.
*/
static int replyLength(byte[] received, int count) {
return count < 2 ? -1 : ((received[0] & 0xFF) << 8) | (received[1] & 0xFF);
}
/**
* The best target in a reply to query {@code id} (lowest priority, then highest weight), or null
* if there's none or the reply can't be read.
*/
static @Nullable Target parse(byte[] reply, int id) {
try {
ByteBuffer in = ByteBuffer.wrap(reply);
if ((in.getShort() & 0xFFFF) != id) {
return null;
}
int flags = in.getShort() & 0xFFFF;
if ((flags & 0x8000) == 0 || (flags & 0x000F) != 0) {
return null; // not a reply, or an error (no such name, refused)
}
int questions = in.getShort() & 0xFFFF;
int answers = in.getShort() & 0xFFFF;
in.getShort();
in.getShort();
for (int i = 0; i < questions; i++) {
readName(reply, in);
in.position(in.position() + 4);
}
Target best = null;
int bestPriority = Integer.MAX_VALUE;
int bestWeight = -1;
for (int i = 0; i < answers; i++) {
readName(reply, in);
int type = in.getShort() & 0xFFFF;
in.getShort();
in.getInt();
int length = in.getShort() & 0xFFFF;
int end = in.position() + length;
if (type == TYPE_SRV) {
int priority = in.getShort() & 0xFFFF;
int weight = in.getShort() & 0xFFFF;
int port = in.getShort() & 0xFFFF;
String host = readName(reply, in);
// "." names no service; port 0 can't be joined.
boolean better = priority < bestPriority || (priority == bestPriority && weight > bestWeight);
if (!host.isEmpty() && port != 0 && better) {
best = new Target(host, port);
bestPriority = priority;
bestWeight = weight;
}
}
in.position(end);
}
return best;
} catch (RuntimeException e) {
// A truncated or malformed reply: join the address as written.
return null;
}
}
/** Reads a name at {@code in}'s position, following compression pointers into {@code reply}. */
private static String readName(byte[] reply, ByteBuffer in) {
StringBuilder name = new StringBuilder();
int at = in.position();
int resume = -1;
for (int jumps = 0; ; ) {
int length = reply[at] & 0xFF;
if (length == 0) {
at++;
break;
}
if ((length & 0xC0) == 0xC0) {
if (++jumps > MAX_JUMPS) {
throw new IllegalArgumentException("Name compression loops");
}
if (resume < 0) {
resume = at + 2;
}
at = ((length & 0x3F) << 8) | (reply[at + 1] & 0xFF);
continue;
}
if (!name.isEmpty()) {
name.append('.');
}
name.append(new String(reply, at + 1, length, StandardCharsets.US_ASCII));
at += 1 + length;
}
in.position(resume >= 0 ? resume : at);
return name.toString();
}
private static void writeShort(ByteArrayOutputStream out, int value) {
out.write(value >>> 8);
out.write(value);
}
}
@@ -0,0 +1,76 @@
package incari.net.wisp;
import incari.net.WebSocketUrl;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
/**
* A Java server reached through a Wisp proxy, as the socket address the game's connection code
* passes around. The game sees the server's own host and port (they go into its handshake packet);
* {@code NetConnectionChannel} sees the proxy and opens a {@link WispConnection}.
*
* <p>No DNS lookup happens here: the proxy resolves the host. The {@link #getAddress() address} is a
* placeholder (0.0.0.0) carrying the host name, as in {@code WebSocketAddress}. Never connect to it
* as an IP.
*/
public final class WispAddress extends InetSocketAddress {
private static final long serialVersionUID = 1L;
/** The port a server address without one gets; only those look for an SRV record, as the game does. */
private static final int DEFAULT_PORT = 25565;
private final WebSocketUrl proxy;
private final boolean lookUpSrv;
/**
* @param proxy the Wisp proxy's WebSocket URL
* @param host the server's host name or IP literal
* @param port the server's port
*/
public WispAddress(WebSocketUrl proxy, String host, int port) {
super(placeholder(host), port);
this.proxy = proxy;
this.lookUpSrv = port == DEFAULT_PORT && !isIpLiteral(host);
}
/** The Wisp proxy's URL. */
public WebSocketUrl proxy() {
return proxy;
}
/**
* Whether to look for the server's {@code _minecraft._tcp} SRV record before connecting, as the
* game does for a host name given without a port.
*/
public boolean lookUpSrv() {
return lookUpSrv;
}
@Override
public String toString() {
return getHostString() + ":" + getPort() + " via " + proxy;
}
static boolean isIpLiteral(String host) {
if (host.indexOf(':') >= 0) {
return true;
}
for (int i = 0; i < host.length(); i++) {
char c = host.charAt(i);
if (c != '.' && (c < '0' || c > '9')) {
return false;
}
}
return true;
}
private static InetAddress placeholder(String host) {
try {
// Only checks the array's length; resolves nothing.
return InetAddress.getByAddress(host, new byte[4]);
} catch (UnknownHostException e) {
throw new IllegalStateException(e);
}
}
}
@@ -0,0 +1,349 @@
package incari.net.wisp;
import incari.platform.api.net.NetConnection;
import incari.platform.api.net.PlatformNetwork;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.jspecify.annotations.Nullable;
/**
* A TCP connection to a Java server through a Wisp proxy (protocol v1): one WebSocket to the proxy,
* one Wisp stream on it to the server, and the bytes of the stream passed up as a TCP connection's
* would be. First, for a host given without a port, a second stream asks a resolver for its SRV
* record ({@link SrvLookup}).
*
* <p>Every Wisp packet is one WebSocket message: a type byte, a stream id and its payload, little
* endian. The proxy grants a number of DATA packets per stream (CONTINUE) and grants more as it
* forwards them; what's sent beyond that waits. What the game sends between flushes goes as one
* DATA packet, so a tick's packets cost one message, not one each.
*
* <p>No Sec-WebSocket-Protocol header is sent, so a v2 proxy speaks v1 to it.
*/
public final class WispConnection implements NetConnection {
private static final byte CONNECT = 0x01;
private static final byte DATA = 0x02;
private static final byte CONTINUE = 0x03;
private static final byte CLOSE = 0x04;
private static final byte STREAM_TCP = 0x01;
private static final byte CLOSE_VOLUNTARY = 0x02;
private static final int HEADER = 5;
/** Stream ids are the client's choice; each connection has its own WebSocket, so fixed ones do. */
private static final int GAME_STREAM = 1;
private static final int SRV_STREAM = 2;
private static final int SRV_QUERY_ID = 0x1CA7;
private final WispAddress address;
private final Listener listener;
private @Nullable NetConnection socket;
// Guarded by this.
/** DATA packets each new stream may send before a CONTINUE: the proxy's first packet. -1 before. */
private int initialCredit = -1;
/** DATA packets the game stream may still send. */
private int credit;
private boolean gameOpen;
private boolean closed;
private final List<ByteBuffer> unsent = new ArrayList<>();
private int unsentBytes;
/** The SRV reply so far, while the lookup runs; null otherwise. */
private byte @Nullable [] srvReply;
private int srvReplyCount;
private WispConnection(WispAddress address, Listener listener) {
this.address = address;
this.listener = listener;
}
/** Opens a WebSocket to {@code address}'s proxy, and through it a stream to the server. Returns at once. */
public static NetConnection open(PlatformNetwork network, WispAddress address, Listener listener) {
WispConnection connection = new WispConnection(address, listener);
synchronized (connection) {
// Held so the socket's first callbacks wait for the field.
connection.socket = network.openWebSocket(address.proxy().toString(), connection.new SocketListener());
}
return connection;
}
@Override
public void send(ByteBuffer data) {
synchronized (this) {
if (closed) {
return;
}
unsent.add(data);
unsentBytes += data.remaining();
}
}
@Override
public void flush() {
synchronized (this) {
sendUnsent();
}
}
@Override
public void close() {
boolean tell;
synchronized (this) {
tell = !closed;
if (tell && gameOpen) {
sendPacket(CLOSE, GAME_STREAM, new byte[] {CLOSE_VOLUNTARY});
}
finish();
}
if (tell) {
listener.closed(null);
}
}
@Override
public synchronized boolean isOpen() {
return gameOpen && !closed;
}
@Override
public String remoteDescription() {
return address.toString();
}
/** The proxy's WebSocket's: the Wisp stream's own close reason is already in the error. */
@Override
public Map<String, String> details() {
NetConnection current;
synchronized (this) {
current = socket;
}
return current != null ? current.details() : Map.of();
}
// --- Under the lock ------------------------------------------------------------------------
/** Sends what the game queued as one DATA packet, if the proxy grants one. */
private void sendUnsent() {
if (!gameOpen || closed || unsent.isEmpty() || credit <= 0) {
return;
}
ByteBuffer packet = header(DATA, GAME_STREAM, unsentBytes);
for (ByteBuffer data : unsent) {
packet.put(data);
}
unsent.clear();
unsentBytes = 0;
credit--;
write(packet);
}
private void sendPacket(byte type, int stream, byte[] payload) {
ByteBuffer packet = header(type, stream, payload.length);
packet.put(payload);
write(packet);
}
private void write(ByteBuffer packet) {
NetConnection current = socket;
if (current != null) {
packet.flip();
current.send(packet);
}
}
private static ByteBuffer header(byte type, int stream, int payloadLength) {
ByteBuffer packet = ByteBuffer.allocate(HEADER + payloadLength).order(ByteOrder.LITTLE_ENDIAN);
return packet.put(type).putInt(stream);
}
private void connect(int stream, String host, int port) {
byte[] name = host.getBytes(StandardCharsets.UTF_8);
ByteBuffer packet = header(CONNECT, stream, 3 + name.length);
packet.put(STREAM_TCP).putShort((short) port).put(name);
write(packet);
}
/** Opens the game's stream; the caller then tells the listener it's connected. */
private void openGame(String host, int port) {
connect(GAME_STREAM, host, port);
gameOpen = true;
credit = initialCredit;
}
private void finish() {
closed = true;
unsent.clear();
unsentBytes = 0;
srvReply = null;
NetConnection current = socket;
if (current != null) {
current.close();
}
}
/** The proxy's reason for closing a stream, for the disconnect screen. */
static String reason(int code) {
return switch (code) {
case 0x41 -> "The Wisp proxy couldn't open the connection";
case 0x42 -> "The Wisp proxy couldn't reach the server";
case 0x43 -> "The Wisp proxy timed out connecting to the server";
case 0x44 -> "The server refused the Wisp proxy's connection";
case 0x47 -> "The connection through the Wisp proxy timed out";
case 0x48 -> "The Wisp proxy blocks this server";
case 0x49 -> "The Wisp proxy is limiting connections; try again soon";
case 0x03 -> "The Wisp proxy lost the connection";
default -> "The Wisp proxy closed the connection (reason " + code + ")";
};
}
/** Hears the proxy's WebSocket, one message (one Wisp packet) at a time. */
private final class SocketListener implements Listener {
@Override
public void connected() {
// Nothing goes out before the proxy's first CONTINUE says how much it buffers.
}
@Override
public void received(ByteBuffer message) {
ByteBuffer in = message.order(ByteOrder.LITTLE_ENDIAN);
if (in.remaining() < HEADER) {
return;
}
byte type = in.get();
int stream = in.getInt();
ByteBuffer payload = in.slice();
boolean connected = false;
@Nullable Throwable closedBy = null;
boolean close = false;
@Nullable ByteBuffer data = null;
synchronized (WispConnection.this) {
if (closed) {
return;
}
switch (type) {
case CONTINUE -> {
if (payload.remaining() < 4) {
return;
}
int granted = payload.order(ByteOrder.LITTLE_ENDIAN).getInt();
if (stream == 0 && initialCredit < 0) {
initialCredit = granted;
connected = start();
} else if (stream == GAME_STREAM) {
credit = granted;
sendUnsent();
}
}
case DATA -> {
if (stream == GAME_STREAM && gameOpen) {
data = payload;
} else if (stream == SRV_STREAM && srvReply != null) {
connected = srvData(payload);
}
}
case CLOSE -> {
int code = payload.hasRemaining() ? payload.get() & 0xFF : 0;
if (stream == GAME_STREAM && gameOpen) {
close = true;
closedBy = code == CLOSE_VOLUNTARY ? null : new IOException(reason(code));
finish();
} else if (stream == SRV_STREAM && srvReply != null) {
// No answer from the resolver: join the address as written.
srvReply = null;
openGame(address.getHostString(), address.getPort());
connected = true;
} else if (stream == 0) {
// The proxy turned the whole connection down.
close = true;
closedBy = new IOException(reason(code));
finish();
}
}
default -> {
// INFO and anything newer: v2's, which a v1 client ignores.
}
}
}
if (connected) {
listener.connected();
flush();
}
if (data != null) {
listener.received(data);
}
if (close) {
listener.closed(closedBy);
}
}
/** After the first CONTINUE: looks up the SRV record, or opens the game's stream at once. */
private boolean start() {
String record = address.lookUpSrv() ? SrvLookup.recordName(address.getHostString()) : null;
if (record == null) {
openGame(address.getHostString(), address.getPort());
return true;
}
srvReply = new byte[512];
srvReplyCount = 0;
connect(SRV_STREAM, SrvLookup.RESOLVER_HOST, SrvLookup.RESOLVER_PORT);
sendPacket(DATA, SRV_STREAM, SrvLookup.query(record, SRV_QUERY_ID));
return false;
}
/** More of the resolver's reply; once it's whole, opens the game's stream where it points. */
private boolean srvData(ByteBuffer payload) {
byte[] reply = srvReply;
if (reply == null) {
return false;
}
int needed = srvReplyCount + payload.remaining();
if (needed > reply.length) {
reply = Arrays.copyOf(reply, Math.max(needed, reply.length * 2));
}
payload.get(reply, srvReplyCount, payload.remaining());
srvReplyCount = needed;
srvReply = reply;
int length = SrvLookup.replyLength(reply, srvReplyCount);
if (length < 0 || srvReplyCount < 2 + length) {
return false;
}
SrvLookup.Target target = SrvLookup.parse(Arrays.copyOfRange(reply, 2, 2 + length), SRV_QUERY_ID);
srvReply = null;
sendPacket(CLOSE, SRV_STREAM, new byte[] {CLOSE_VOLUNTARY});
if (target != null) {
openGame(target.host(), target.port());
} else {
openGame(address.getHostString(), address.getPort());
}
return true;
}
@Override
public void closed(@Nullable Throwable cause) {
boolean tell;
boolean wasOpen;
synchronized (WispConnection.this) {
tell = !closed;
wasOpen = gameOpen;
closed = true;
unsent.clear();
srvReply = null;
}
if (tell) {
Throwable reason = cause != null || wasOpen
? cause
: new IOException("Couldn't reach the Wisp proxy " + address.proxy());
listener.closed(reason);
}
}
}
}
@@ -0,0 +1,9 @@
/**
* Wisp (Mercury Workshop's TCP-over-WebSocket protocol, as Wispcraft uses it): a page joins a Java
* server's TCP port through a Wisp proxy, and the game's own TCP pipeline (framing, encryption,
* compression) runs on top unchanged. Written from the protocol's spec. No game types.
*/
@NullMarked
package incari.net.wisp;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,32 @@
package incari.net;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
/**
* net sits between the game's pipeline and the platform: Netty and platform-api only. It never
* sees game types (the client's adapters hand it what it needs) or a platform implementation, and
* it's compiled into the browser build, so no JDK APIs beyond what TeaVM has.
*/
@AnalyzeClasses(packages = "incari.net", importOptions = ImportOption.DoNotIncludeTests.class)
class BoundaryTest {
@ArchTest
static final ArchRule onlyNettyAndPlatformApi = classes()
.should()
.onlyDependOnClassesThat()
.resideInAnyPackage(
"java..",
"org.jspecify..",
"io.netty..",
"incari.platform.api..",
"incari.net..",
// Sign-in's TLS and JSON (ADR 0070).
"org.bouncycastle..",
"com.google.gson..")
.allowEmptyShould(true);
}
@@ -0,0 +1,128 @@
package incari.net;
import static org.assertj.core.api.Assertions.assertThat;
import incari.platform.api.net.NetConnection;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
class ConnectionReportTest {
private static final long SECOND = TimeUnit.SECONDS.toNanos(1);
private static String value(List<ConnectionReport.Line> lines, String label) {
for (ConnectionReport.Line line : lines) {
if (line.label().equals(label)) {
return line.value();
}
}
throw new AssertionError("No line " + label + " in " + lines);
}
private static ConnectionReport webSocket() {
return new ConnectionReport(new WebSocketAddress(WebSocketUrl.parse("wss://mc.example.com/")));
}
@Test
void aDropFromTheFarSideSaysSoWithItsTiming() {
ConnectionReport report = webSocket();
report.connected(0);
report.received(2 * SECOND, 100);
report.sent(3 * SECOND, 40);
report.received(10 * SECOND, 924);
report.closedRemotely(12 * SECOND, new IOException("Connection to wss://mc.example.com/ closed (1006)"));
// The game closes the channel in answer: still the far side's close.
report.closing(13 * SECOND);
List<ConnectionReport.Line> lines = report.lines(99 * SECOND);
assertThat(value(lines, "Server")).isEqualTo("wss://mc.example.com/");
assertThat(value(lines, "Connection")).isEqualTo("WebSocket");
assertThat(value(lines, "Connected for")).isEqualTo("12.0 s");
assertThat(value(lines, "Closed by")).isEqualTo("The server or the network");
assertThat(value(lines, "Error")).isEqualTo("IOException: Connection to wss://mc.example.com/ closed (1006)");
assertThat(value(lines, "Last received")).isEqualTo("2.0 s before it closed");
assertThat(value(lines, "Last sent")).isEqualTo("9.0 s before it closed");
assertThat(value(lines, "Longest wait")).isEqualTo("8.0 s");
assertThat(value(lines, "Received")).isEqualTo("1.0 KB in 2 messages");
assertThat(value(lines, "Sent")).isEqualTo("40 B in 1 message");
assertThat(value(lines, "Closed at")).endsWith("Z (UTC)");
}
@Test
void aCloseByThisGameIsNotBlamedOnTheServer() {
ConnectionReport report = new ConnectionReport(InetSocketAddress.createUnresolved("127.0.0.1", 25565));
report.connected(0);
report.closing(SECOND);
report.closedRemotely(2 * SECOND, null);
List<ConnectionReport.Line> lines = report.lines(5 * SECOND);
assertThat(value(lines, "Closed by")).isEqualTo("This game");
assertThat(value(lines, "Error")).isEqualTo("None");
assertThat(value(lines, "Connection")).isEqualTo("TCP");
assertThat(value(lines, "Received")).isEqualTo("0 B");
assertThat(value(lines, "Last received")).isEqualTo("Never");
}
@Test
void aConnectionStillOpenCountsToNow() {
ConnectionReport report = webSocket();
report.connected(0);
report.received(SECOND, 1);
List<ConnectionReport.Line> lines = report.lines(75 * SECOND);
assertThat(value(lines, "Closed by")).isEqualTo("Still open");
assertThat(value(lines, "Connected for")).isEqualTo("1 min 15 s");
assertThat(value(lines, "Last received")).isEqualTo("1 min 14 s ago");
}
@Test
void theConnectionsOwnDetailsComeLast() {
ConnectionReport report = webSocket();
Map<String, String> details = new LinkedHashMap<>();
details.put("Close code", "1006 (dropped with no close message)");
report.opening(new Detailed(details));
List<ConnectionReport.Line> lines = report.lines(0);
assertThat(lines.getLast().label()).isEqualTo("Close code");
assertThat(report.asText(0)).contains("Close code: 1006 (dropped with no close message)\n");
assertThat(value(lines, "Connected for")).isEqualTo("Never connected");
}
@Test
void formatsSizesAndDurations() {
assertThat(ConnectionReport.duration(TimeUnit.MILLISECONDS.toNanos(340)))
.isEqualTo("340 ms");
assertThat(ConnectionReport.duration(TimeUnit.MINUTES.toNanos(61))).isEqualTo("1 h 1 min");
assertThat(ConnectionReport.bytes(1023)).isEqualTo("1023 B");
assertThat(ConnectionReport.bytes(5 * 1024 * 1024 + 300 * 1024)).isEqualTo("5.3 MB");
}
private record Detailed(Map<String, String> details) implements NetConnection {
@Override
public void send(ByteBuffer data) {}
@Override
public void close() {}
@Override
public boolean isOpen() {
return false;
}
@Override
public String remoteDescription() {
return "test";
}
}
}
@@ -0,0 +1,98 @@
package incari.net;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.CorruptedFrameException;
import io.netty.handler.codec.TooLongFrameException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
class MessageFramingTest {
private final List<Integer> sizes = new ArrayList<>();
/** A pipeline shaped like the game's: stream framing under the names the game uses. */
private EmbeddedChannel gameShapedChannel() {
EmbeddedChannel channel = new EmbeddedChannel();
channel.pipeline()
.addLast("splitter", new ChannelInboundHandlerAdapter())
.addLast("decoder", new ChannelInboundHandlerAdapter())
.addLast("prepender", new ChannelOutboundHandlerAdapter() {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
throw new AssertionError("the stream prepender must be gone");
}
})
.addLast("encoder", new ChannelOutboundHandlerAdapter());
MessageFraming.install(channel.pipeline(), "splitter", "prepender", sizes::add);
return channel;
}
@Test
void keepsTheHandlerNamesTheGamePlacesOthersBy() {
EmbeddedChannel channel = gameShapedChannel();
assertThat(channel.pipeline().names()).containsSubsequence("splitter", "decoder", "prepender", "encoder");
assertThat(channel.pipeline().get("splitter")).isInstanceOf(MessageFraming.Decoder.class);
assertThat(channel.pipeline().get("prepender")).isInstanceOf(MessageFraming.Encoder.class);
// What the game does when the server enables compression.
channel.pipeline().addAfter("splitter", "decompress", new ChannelInboundHandlerAdapter());
channel.pipeline().addAfter("prepender", "compress", new ChannelOutboundHandlerAdapter());
}
@Test
void eachMessageIsOnePacketAsItArrived() {
EmbeddedChannel channel = gameShapedChannel();
channel.writeInbound(text("first"), text("second packet"));
assertThat(readText(channel.readInbound())).isEqualTo("first");
assertThat(readText(channel.readInbound())).isEqualTo("second packet");
assertThat(sizes).containsExactly(5, 13);
}
@Test
void eachPacketIsWrittenWithoutALengthPrefix() {
EmbeddedChannel channel = gameShapedChannel();
channel.writeOutbound(text("packet"));
assertThat(readText(channel.readOutbound())).isEqualTo("packet");
}
@Test
void rejectsEmptyAndOversizedMessages() {
EmbeddedChannel channel = gameShapedChannel();
ByteBuf empty = Unpooled.buffer(0);
ByteBuf huge =
Unpooled.buffer(MessageFraming.MAX_PACKET_BYTES + 1).writerIndex(MessageFraming.MAX_PACKET_BYTES + 1);
assertThatThrownBy(() -> channel.writeInbound(empty)).isInstanceOf(CorruptedFrameException.class);
assertThatThrownBy(() -> channel.writeInbound(huge)).isInstanceOf(TooLongFrameException.class);
assertThat(empty.refCnt()).isZero();
assertThat(huge.refCnt()).isZero();
}
private static ByteBuf text(String text) {
return Unpooled.copiedBuffer(text, StandardCharsets.UTF_8);
}
private static String readText(Object message) {
ByteBuf buffer = (ByteBuf) message;
try {
return buffer.toString(StandardCharsets.UTF_8);
} finally {
buffer.release();
}
}
}
@@ -0,0 +1,317 @@
package incari.net;
import static org.assertj.core.api.Assertions.assertThat;
import incari.platform.api.net.NetConnection;
import incari.platform.api.net.PlatformNetwork;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ConnectTimeoutException;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.MultiThreadIoEventLoopGroup;
import io.netty.channel.local.LocalIoHandler;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
class NetConnectionChannelTest {
private final EchoNetwork network = new EchoNetwork();
private final EventLoopGroup loop = new MultiThreadIoEventLoopGroup(1, LocalIoHandler.newFactory());
@AfterEach
void cleanUp() throws InterruptedException {
loop.shutdownGracefully(0, 1, TimeUnit.SECONDS).await(5, TimeUnit.SECONDS);
}
@Test
void carriesBytesBothWaysOverTcp() throws Exception {
CompletableFuture<String> reply = new CompletableFuture<>();
ChannelFuture connect = bootstrap(reply).connect(InetSocketAddress.createUnresolved("127.0.0.1", 25565));
assertThat(connect.await(5, TimeUnit.SECONDS)).isTrue();
assertThat(connect.isSuccess()).isTrue();
Channel channel = connect.channel();
assertThat(channel.isActive()).isTrue();
assertThat(network.opened).containsExactly("tcp 127.0.0.1:25565");
channel.writeAndFlush(Unpooled.copiedBuffer("ping", StandardCharsets.UTF_8))
.sync();
assertThat(reply.get(5, TimeUnit.SECONDS)).isEqualTo("echo:ping");
}
@Test
void aWebSocketAddressOpensAWebSocket() throws Exception {
CompletableFuture<String> reply = new CompletableFuture<>();
WebSocketAddress address = new WebSocketAddress(WebSocketUrl.parse("wss://mc.example.com/play"));
ChannelFuture connect = bootstrap(reply).connect(address);
assertThat(connect.await(5, TimeUnit.SECONDS)).isTrue();
assertThat(connect.isSuccess()).isTrue();
assertThat(network.opened).containsExactly("ws wss://mc.example.com/play");
assertThat(connect.channel().remoteAddress()).isSameAs(address);
connect.channel()
.writeAndFlush(Unpooled.copiedBuffer("hi", StandardCharsets.UTF_8))
.sync();
assertThat(reply.get(5, TimeUnit.SECONDS)).isEqualTo("echo:hi");
}
@Test
void aClosedConnectionClosesTheChannel() throws Exception {
ChannelFuture connect =
bootstrap(new CompletableFuture<>()).connect(InetSocketAddress.createUnresolved("127.0.0.1", 1));
assertThat(connect.await(5, TimeUnit.SECONDS)).isTrue();
network.remoteClose();
assertThat(connect.channel().closeFuture().await(5, TimeUnit.SECONDS)).isTrue();
assertThat(connect.channel().isOpen()).isFalse();
}
@Test
void theReportCountsTrafficAndWhoClosed() throws Exception {
CompletableFuture<String> reply = new CompletableFuture<>();
ChannelFuture connect = bootstrap(reply).connect(InetSocketAddress.createUnresolved("127.0.0.1", 1));
assertThat(connect.await(5, TimeUnit.SECONDS)).isTrue();
NetConnectionChannel channel = (NetConnectionChannel) connect.channel();
channel.writeAndFlush(Unpooled.copiedBuffer("ping", StandardCharsets.UTF_8))
.sync();
reply.get(5, TimeUnit.SECONDS);
network.remoteClose();
assertThat(channel.closeFuture().await(5, TimeUnit.SECONDS)).isTrue();
ConnectionReport report = channel.report();
assertThat(report).isNotNull();
String text = report.asText(System.nanoTime());
assertThat(text)
.contains("Closed by: The server or the network\n")
.contains("Sent: 4 B\n")
.contains("Received: 9 B\n");
}
@Test
void closingTheChannelClosesTheConnection() throws Exception {
ChannelFuture connect =
bootstrap(new CompletableFuture<>()).connect(InetSocketAddress.createUnresolved("127.0.0.1", 1));
assertThat(connect.await(5, TimeUnit.SECONDS)).isTrue();
connect.channel().close().sync();
assertThat(network.closedByUs).isTrue();
}
@Test
void aFailedConnectFailsTheConnectFuture() throws Exception {
network.refuse = true;
ChannelFuture connect =
bootstrap(new CompletableFuture<>()).connect(InetSocketAddress.createUnresolved("127.0.0.1", 1));
assertThat(connect.await(5, TimeUnit.SECONDS)).isTrue();
assertThat(connect.cause()).isInstanceOf(ConnectException.class);
assertThat(connect.cause().getCause()).hasMessage("refused");
assertThat(connect.channel().closeFuture().await(5, TimeUnit.SECONDS)).isTrue();
}
@Test
void aConnectThatNeverAnswersTimesOut() throws Exception {
network.silent = true;
ChannelFuture connect = bootstrap(new CompletableFuture<>())
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 200)
.connect(InetSocketAddress.createUnresolved("127.0.0.1", 1));
assertThat(connect.await(5, TimeUnit.SECONDS)).isTrue();
assertThat(connect.cause()).isInstanceOf(ConnectTimeoutException.class);
assertThat(connect.channel().closeFuture().await(5, TimeUnit.SECONDS)).isTrue();
assertThat(network.closedByUs).isTrue();
}
@Test
void aConnectThatOpensInTimeStaysOpen() throws Exception {
ChannelFuture connect = bootstrap(new CompletableFuture<>())
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 200)
.connect(InetSocketAddress.createUnresolved("127.0.0.1", 1));
assertThat(connect.await(5, TimeUnit.SECONDS)).isTrue();
assertThat(connect.isSuccess()).isTrue();
Thread.sleep(400);
assertThat(connect.channel().isActive()).isTrue();
}
@Test
void aBurstReachesThePipelineInOrderAsOneReadThenTheClose() throws Exception {
List<String> seen = new CopyOnWriteArrayList<>();
java.util.concurrent.CountDownLatch inactive = new java.util.concurrent.CountDownLatch(1);
ChannelFuture connect = new Bootstrap()
.group(loop)
.channelFactory(() -> new TestChannel(network))
.handler(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object message) {
ByteBuf data = (ByteBuf) message;
seen.add(data.toString(StandardCharsets.UTF_8));
data.release();
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
seen.add("complete");
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
seen.add("inactive");
inactive.countDown();
}
})
.connect(InetSocketAddress.createUnresolved("127.0.0.1", 1));
assertThat(connect.await(5, TimeUnit.SECONDS)).isTrue();
NetConnection.Listener listener = network.listener;
assertThat(listener).isNotNull();
// As the browser hands over a frame's messages: all at once, while the loop is busy.
java.util.concurrent.CountDownLatch busy = new java.util.concurrent.CountDownLatch(1);
connect.channel().eventLoop().execute(() -> {
try {
busy.await(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
for (int i = 0; i < 50; i++) {
listener.received(ByteBuffer.wrap(("m" + i).getBytes(StandardCharsets.UTF_8)));
}
listener.closed(null);
busy.countDown();
// Netty reports the channel inactive just after its close future completes.
assertThat(inactive.await(5, TimeUnit.SECONDS)).isTrue();
List<String> expected = new java.util.ArrayList<>();
for (int i = 0; i < 50; i++) {
expected.add("m" + i);
}
expected.add("complete");
expected.add("inactive");
assertThat(seen).containsExactlyElementsOf(expected);
}
private Bootstrap bootstrap(CompletableFuture<String> reply) {
return new Bootstrap()
.group(loop)
.channelFactory(() -> new TestChannel(network))
.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object message) {
ByteBuf data = (ByteBuf) message;
reply.complete(data.toString(StandardCharsets.UTF_8));
data.release();
}
});
}
});
}
private static final class TestChannel extends NetConnectionChannel {
private final PlatformNetwork network;
TestChannel(PlatformNetwork network) {
this.network = network;
}
@Override
protected NetConnection open(InetSocketAddress remote, NetConnection.Listener listener) {
return openOn(network, remote, listener);
}
}
/** Answers every message with "echo:" and the message, from another thread, like a real transport. */
private static final class EchoNetwork implements PlatformNetwork {
final List<String> opened = new CopyOnWriteArrayList<>();
volatile boolean refuse;
/** Neither opens nor fails, like a server behind a firewall that drops packets. */
volatile boolean silent;
volatile boolean closedByUs;
volatile NetConnection.@Nullable Listener listener;
@Override
public NetConnection connect(String host, int port, NetConnection.Listener listener) {
opened.add("tcp " + host + ":" + port);
return start(listener);
}
@Override
public NetConnection openWebSocket(String url, NetConnection.Listener listener) {
opened.add("ws " + url);
return start(listener);
}
private NetConnection start(NetConnection.Listener listener) {
this.listener = listener;
Thread.ofVirtual().start(() -> {
if (silent) {
return;
}
if (refuse) {
listener.closed(new ConnectException("refused"));
} else {
listener.connected();
}
});
return new NetConnection() {
@Override
public void send(ByteBuffer data) {
String text = StandardCharsets.UTF_8.decode(data).toString();
Thread.ofVirtual()
.start(() -> listener.received(
ByteBuffer.wrap(("echo:" + text).getBytes(StandardCharsets.UTF_8))));
}
@Override
public void close() {
closedByUs = true;
}
@Override
public boolean isOpen() {
return true;
}
@Override
public String remoteDescription() {
return "test";
}
};
}
void remoteClose() {
NetConnection.Listener current = listener;
if (current != null) {
current.closed(null);
}
}
}
}
@@ -0,0 +1,98 @@
package incari.net;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
class WebSocketUrlTest {
@Test
void defaultsThePortAndPathByScheme() {
assertThat(WebSocketUrl.parse("ws://play.example.com"))
.isEqualTo(new WebSocketUrl(false, "play.example.com", 80, "/"));
assertThat(WebSocketUrl.parse("wss://play.example.com"))
.isEqualTo(new WebSocketUrl(true, "play.example.com", 443, "/"));
}
@Test
void keepsAnExplicitPortPathAndQuery() {
WebSocketUrl url = WebSocketUrl.parse(" WSS://Play.Example.com:8443/mc/ws?region=eu#ignored ");
assertThat(url).isEqualTo(new WebSocketUrl(true, "Play.Example.com", 8443, "/mc/ws?region=eu"));
assertThat(url.toString()).isEqualTo("wss://Play.Example.com:8443/mc/ws?region=eu");
}
@Test
void aQueryWithoutAPathGetsTheRootPath() {
assertThat(WebSocketUrl.parse("ws://localhost:8816?x=1").path()).isEqualTo("/?x=1");
}
@Test
void canonicalFormDropsTheDefaultPort() {
assertThat(WebSocketUrl.parse("ws://localhost:80/").toString()).isEqualTo("ws://localhost/");
assertThat(WebSocketUrl.parse("wss://localhost:443").toString()).isEqualTo("wss://localhost/");
assertThat(WebSocketUrl.parse("ws://localhost:8816").toString()).isEqualTo("ws://localhost:8816/");
}
@Test
void readsBracketedIpv6() {
WebSocketUrl url = WebSocketUrl.parse("ws://[::1]:8816/");
assertThat(url.host()).isEqualTo("::1");
assertThat(url.port()).isEqualTo(8816);
assertThat(url.toString()).isEqualTo("ws://[::1]:8816/");
}
@Test
void acceptsInternationalHostNames() {
assertThat(WebSocketUrl.parse("wss://bücher.example/").host()).isEqualTo("bücher.example");
}
@ParameterizedTest
@ValueSource(
strings = {
"ws://",
"ws://:8816",
"ws://host:0",
"ws://host:65536",
"ws://host:12a",
"ws://host:",
"ws://user:pass@host/",
"ws://::1/",
"ws://[::1/",
"ws://[::1]x/",
"ws://[host]/",
"ws://ho st/",
"ws://host/a b",
"http://host/",
"host:25565"
})
void rejects(String text) {
assertThatThrownBy(() -> WebSocketUrl.parse(text)).isInstanceOf(IllegalArgumentException.class);
assertThat(WebSocketUrl.tryParse(text)).isNull();
}
@Test
void recognisesTheSchemeBeforeParsing() {
assertThat(WebSocketUrl.isWebSocketUrl("ws://")).isTrue();
assertThat(WebSocketUrl.isWebSocketUrl(" WSS://x")).isTrue();
assertThat(WebSocketUrl.isWebSocketUrl("localhost:25565")).isFalse();
assertThat(WebSocketUrl.isWebSocketUrl("wsx://x")).isFalse();
assertThat(WebSocketUrl.isWebSocketUrl(null)).isFalse();
}
@Test
void anAddressStandsForItsUrlWithoutResolvingIt() {
WebSocketUrl url = WebSocketUrl.parse("wss://no-such-host.invalid:9443/mc");
WebSocketAddress address = new WebSocketAddress(url);
assertThat(address.url()).isEqualTo(url);
assertThat(address.getHostName()).isEqualTo("no-such-host.invalid");
assertThat(address.getHostString()).isEqualTo("no-such-host.invalid");
assertThat(address.getPort()).isEqualTo(9443);
assertThat(address.toString()).isEqualTo("wss://no-such-host.invalid:9443/mc");
}
}
@@ -0,0 +1,445 @@
package incari.net.eagler;
import static org.assertj.core.api.Assertions.assertThat;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.embedded.EmbeddedChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.Test;
/** The Eagler stage against a scripted server, with the channel's inbound end standing in for the game. */
class EaglerHandshakeTest {
private static final UUID GRANTED = UUID.fromString("0b6b1b5a-6c86-3b8c-9a63-2d5d2e3b0f11");
private final Session session = new Session();
private final List<ByteBuf> game = new ArrayList<>();
private EmbeddedChannel channel(int protocol, List<EaglerLogin.ProfileData> profile) {
return channel(new EaglerLogin("Steve", protocol, "Incari", "test", "", profile));
}
private static EaglerLogin login(
int protocol, @Nullable EaglerPassword password, byte @Nullable [] cookie, int capabilities) {
return new EaglerLogin(
"Steve",
protocol,
"Incari",
"test",
"",
List.of(),
password,
cookie == null ? null : new EaglerLogin.Cookie(cookie),
capabilities);
}
private EmbeddedChannel channel(EaglerLogin login) {
EmbeddedChannel channel = new EmbeddedChannel();
channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
game.add((ByteBuf) msg);
}
});
EaglerHandshake.install(channel.pipeline(), login, session);
channel.pipeline().fireChannelActive();
return channel;
}
@Test
void logsInAndStandsInForTheVanillaLogin() {
EaglerLogin.ProfileData skin = EaglerTextures.presetSkinProfileData(3);
EmbeddedChannel channel = channel(777, List.of(skin));
ByteBuf version = channel.readOutbound();
assertThat((int) version.readUnsignedByte()).isEqualTo(0x01);
assertThat((int) version.readUnsignedByte()).isEqualTo(0x02);
assertThat(version.readUnsignedShort()).isEqualTo(1);
assertThat(version.readUnsignedShort()).isEqualTo(5);
assertThat(version.readUnsignedShort()).isEqualTo(1);
assertThat(version.readUnsignedShort()).isEqualTo(777);
assertThat(Wire.readByteAscii(version)).isEqualTo("Incari");
assertThat(Wire.readByteAscii(version)).isEqualTo("test");
assertThat(version.readBoolean()).isFalse();
assertThat(Wire.readByteAscii(version)).isEqualTo("Steve");
assertThat(version.isReadable()).isFalse();
// The game's handshake and Login Start never reach the server.
channel.writeOutbound(packet(0x00, 777), packet(0x00, "Steve"));
assertThat(channel.outboundMessages()).isEmpty();
channel.writeInbound(serverVersion(5, 777, 0));
ByteBuf request = channel.readOutbound();
assertThat((int) request.readUnsignedByte()).isEqualTo(0x04);
assertThat(Wire.readByteAscii(request)).isEqualTo("Steve");
assertThat(Wire.readByteAscii(request)).isEmpty();
assertThat((int) request.readUnsignedByte()).isZero(); // password
assertThat(request.readBoolean()).isFalse(); // cookie
assertThat((int) request.readUnsignedByte()).isZero();
assertThat(Wire.readVarInt(request)).isZero(); // capabilities
assertThat((int) request.readUnsignedByte()).isZero();
assertThat(request.isReadable()).isFalse();
channel.writeInbound(allowLogin("Steve2", GRANTED));
ByteBuf profile = channel.readOutbound();
assertThat((int) profile.readUnsignedByte()).isEqualTo(0x07);
assertThat((int) profile.readUnsignedByte()).isEqualTo(1);
assertThat(Wire.readByteAscii(profile)).isEqualTo("skin_v2");
assertThat(profile.readUnsignedShort()).isEqualTo(5);
assertThat((int) profile.readUnsignedByte()).isEqualTo(1);
assertThat(profile.readInt()).isEqualTo(3);
ByteBuf finish = channel.readOutbound();
assertThat((int) finish.readUnsignedByte()).isEqualTo(0x08);
assertThat(game).isEmpty();
// The server finishes and sends the backend's first packets at once.
channel.writeInbound(bytes(0x09), packet(0x0E, "config"));
assertThat(session.name).isEqualTo("Steve2");
assertThat(game).hasSize(1);
ByteBuf success = game.get(0);
assertThat(Wire.readVarInt(success)).isEqualTo(0x02);
assertThat(new UUID(success.readLong(), success.readLong())).isEqualTo(GRANTED);
assertThat(Wire.readString(success)).isEqualTo("Steve2");
assertThat(Wire.readVarInt(success)).isZero(); // properties
success.skipBytes(16); // 26.2 and later: the session id
assertThat(success.isReadable()).isFalse();
// Held until the game acknowledges the login, which isn't passed on either.
channel.writeOutbound(packet(0x03));
assertThat(channel.outboundMessages()).isEmpty();
assertThat(game).hasSize(2);
assertThat(Wire.readVarInt(game.get(1))).isEqualTo(0x0E);
// Then packets pass both ways, and Eagler's own messages go to the session.
channel.writeOutbound(packet(0x02, "chat"));
ByteBuf out = channel.readOutbound();
assertThat(Wire.readVarInt(out)).isEqualTo(0x02);
channel.writeInbound(bytes(0xEE, 0x05, 0x01, 0x02));
assertThat(session.messages).containsExactly("5:0102");
assertThat(game).hasSize(2);
}
@Test
void anOlderServerNeedsNoAcknowledgement() {
EmbeddedChannel channel = channel(47, List.of());
channel.readOutbound();
channel.writeOutbound(packet(0x00, 47), packet(0x00, "Steve"));
channel.writeInbound(serverVersion(5, 47, 0));
channel.readOutbound();
channel.writeInbound(allowLogin("Steve", GRANTED));
ByteBuf finish = channel.readOutbound();
assertThat((int) finish.readUnsignedByte()).isEqualTo(0x08);
channel.writeInbound(bytes(0x09), packet(0x01, "join game"));
assertThat(game).hasSize(2);
ByteBuf success = game.get(0);
assertThat(Wire.readVarInt(success)).isEqualTo(0x02);
assertThat(Wire.readString(success)).isEqualTo(GRANTED.toString());
assertThat(Wire.readString(success)).isEqualTo("Steve");
assertThat(success.isReadable()).isFalse();
assertThat(Wire.readVarInt(game.get(1))).isEqualTo(0x01);
}
@Test
void waitsForTheGamesLoginStartBeforeAnswering() {
EmbeddedChannel channel = channel(47, List.of());
channel.readOutbound();
channel.writeInbound(serverVersion(5, 47, 0));
channel.readOutbound();
channel.writeInbound(allowLogin("Steve", GRANTED));
channel.readOutbound();
channel.readOutbound();
channel.writeInbound(bytes(0x09), packet(0x01, "join game"));
assertThat(game).isEmpty();
channel.writeOutbound(packet(0x00, 47), packet(0x00, "Steve"));
assertThat(game).hasSize(2);
}
@Test
void aRefusalBecomesALoginDisconnect() {
EmbeddedChannel channel = channel(777, List.of());
channel.readOutbound();
channel.writeOutbound(packet(0x00, 777), packet(0x00, "Steve"));
ByteBuf error = Unpooled.buffer();
error.writeByte(0xFF);
error.writeByte(0x08);
byte[] message = "You are \"banned\"".getBytes(StandardCharsets.UTF_8);
error.writeShort(message.length);
error.writeBytes(message);
channel.writeInbound(error);
assertThat(game).hasSize(1);
ByteBuf disconnect = game.get(0);
assertThat(Wire.readVarInt(disconnect)).isEqualTo(0x00);
assertThat(Wire.readString(disconnect)).isEqualTo("{\"text\":\"You are \\\"banned\\\"\"}");
}
@Test
void aPasswordServerWithoutAPasswordGetsAnEmptyOneAndTheCookie() {
// A server that names a method although none was offered takes a cookie instead.
EmbeddedChannel channel = channel(login(777, null, new byte[] {9, 8, 7}, EaglerLogin.COOKIE));
channel.readOutbound();
channel.writeOutbound(packet(0x00, 777), packet(0x00, "Steve"));
channel.writeInbound(serverVersion(5, 777, EaglerPassword.EAGLER_SHA256, new byte[64]));
ByteBuf request = channel.readOutbound();
request.skipBytes(1);
Wire.readByteAscii(request);
Wire.readByteAscii(request);
assertThat((int) request.readUnsignedByte()).isZero();
assertThat(request.readBoolean()).isTrue();
assertThat((int) request.readUnsignedByte()).isEqualTo(3);
assertThat(request.readByte()).isEqualTo((byte) 9);
request.skipBytes(2);
assertThat(Wire.readVarInt(request)).isEqualTo(EaglerLogin.COOKIE);
assertThat(Wire.readVarInt(request)).isEqualTo(1);
assertThat((int) request.readUnsignedByte()).isZero();
assertThat(request.isReadable()).isFalse();
}
@Test
void sendsThePasswordInTheServersForm() {
EaglerPassword password = new EaglerPassword("hunter2", false);
EmbeddedChannel channel = channel(login(47, password, null, 0));
ByteBuf version = channel.readOutbound();
version.skipBytes(1 + 1 + 2 + 2 + 2 + 2);
Wire.readByteAscii(version);
Wire.readByteAscii(version);
assertThat(version.readBoolean()).isTrue(); // a password is offered
byte[] salt = new byte[64];
for (int i = 0; i < 64; i++) {
salt[i] = (byte) i;
}
channel.writeInbound(serverVersion(5, 47, EaglerPassword.EAGLER_SHA256, salt));
ByteBuf request = channel.readOutbound();
request.skipBytes(1);
Wire.readByteAscii(request);
Wire.readByteAscii(request);
byte[] sent = new byte[request.readUnsignedByte()];
request.readBytes(sent);
// Computed independently (Python's hashlib) from the protocol's description.
assertThat(hex(sent)).isEqualTo("74333fa9174c0f16c2cdf3ac1e6b3376b71f1b93f32a7e4303b16867a4fab0cf");
}
@Test
void answersAuthMeWithItsOwnHash() {
byte[] answer = new EaglerPassword("hunter2", false)
.answer(EaglerPassword.AUTHME_SHA256, "0123456789abcdef".getBytes(StandardCharsets.US_ASCII));
// AuthMe stores "$SHA$0123456789abcdef$" and this hash for "hunter2".
assertThat(new String(answer, StandardCharsets.US_ASCII))
.isEqualTo("a8e5b4e6828c1d5c2dd411422a06f740b88a6267b74dd4cea0424c6e4c01c095");
}
@Test
void sendsPlainTextOnlyWithConsent() {
byte[] salt = new byte[0];
assertThat(new EaglerPassword("pw", false).answer(EaglerPassword.PLAINTEXT, salt))
.isNull();
assertThat(new EaglerPassword("pw", true).answer(EaglerPassword.PLAINTEXT, salt))
.containsExactly(0, 'p', 0, 'w');
EmbeddedChannel channel = channel(login(47, new EaglerPassword("pw", false), null, 0));
channel.readOutbound();
channel.writeOutbound(packet(0x00, 47), packet(0x00, "Steve"));
channel.writeInbound(serverVersion(5, 47, EaglerPassword.PLAINTEXT, salt));
assertThat(session.authRequired).isEqualTo(EaglerPassword.PLAINTEXT + ":");
assertThat(channel.outboundMessages()).isEmpty();
assertThat(game).hasSize(1); // the Login Disconnect
}
@Test
void aServerThatWantsAPasswordSaysSo() {
EmbeddedChannel channel = channel(777, List.of());
channel.readOutbound();
channel.writeOutbound(packet(0x00, 777), packet(0x00, "Steve"));
// Sent before the server has chosen a protocol: a byte-length message.
ByteBuf error = Unpooled.buffer();
error.writeByte(0xFF);
error.writeByte(0x09);
Wire.writeByteAscii(error, "Authentication Required: [2] Log in with /login");
channel.writeInbound(error);
assertThat(session.authRequired).isEqualTo("2:Log in with /login");
ByteBuf disconnect = game.get(0);
Wire.readVarInt(disconnect);
assertThat(Wire.readString(disconnect)).contains("Log in with /login");
}
@Test
void aRefusedPasswordAsksAgain() {
EmbeddedChannel channel = channel(login(47, new EaglerPassword("wrong", false), null, 0));
channel.readOutbound();
channel.writeOutbound(packet(0x00, 47), packet(0x00, "Steve"));
channel.writeInbound(serverVersion(5, 47, EaglerPassword.AUTHME_SHA256, new byte[16]));
channel.readOutbound();
ByteBuf deny = Unpooled.buffer();
deny.writeByte(0x06);
byte[] reason = "{\"text\":\"Wrong password\"}".getBytes(StandardCharsets.UTF_8);
deny.writeShort(reason.length);
deny.writeBytes(reason);
channel.writeInbound(deny);
assertThat(session.authRequired).isEqualTo("2:{\"text\":\"Wrong password\"}");
}
@Test
void asksForCapabilitiesAndHearsWhichWereAccepted() {
EmbeddedChannel channel = channel(login(47, null, null, EaglerLogin.VOICE | EaglerLogin.COOKIE));
channel.readOutbound();
channel.writeOutbound(packet(0x00, 47), packet(0x00, "Steve"));
channel.writeInbound(serverVersion(5, 47, 0));
ByteBuf request = channel.readOutbound();
request.skipBytes(1);
Wire.readByteAscii(request);
Wire.readByteAscii(request);
request.skipBytes(1);
assertThat(request.readBoolean()).isTrue(); // cookies allowed
assertThat((int) request.readUnsignedByte()).isZero(); // none stored yet
assertThat(Wire.readVarInt(request)).isEqualTo(EaglerLogin.VOICE | EaglerLogin.COOKIE);
assertThat(Wire.readVarInt(request)).isEqualTo(1);
assertThat(Wire.readVarInt(request)).isEqualTo(1);
ByteBuf allow = Unpooled.buffer();
allow.writeByte(0x05);
Wire.writeByteAscii(allow, "Steve");
allow.writeLong(GRANTED.getMostSignificantBits());
allow.writeLong(GRANTED.getLeastSignificantBits());
Wire.writeVarInt(allow, EaglerLogin.VOICE);
allow.writeByte(0);
allow.writeByte(0);
channel.writeInbound(allow);
assertThat(session.capabilities).isEqualTo(EaglerLogin.VOICE);
}
@Test
void bundledMessagesAreSplit() {
EmbeddedChannel channel = channel(47, List.of());
channel.readOutbound();
channel.writeOutbound(packet(0x00, 47), packet(0x00, "Steve"));
channel.writeInbound(serverVersion(5, 47, 0));
channel.readOutbound();
channel.writeInbound(allowLogin("Steve", GRANTED));
channel.readOutbound();
channel.readOutbound();
channel.writeInbound(bytes(0x09));
channel.writeInbound(bytes(0xEE, 0xFF, 0x02, 0x02, 0x16, 0x00, 0x03, 0x01, 0x07, 0x08));
assertThat(session.messages).containsExactly("22:00", "1:0708");
}
// --- The scripted server's packets ---------------------------------------------------
private static ByteBuf serverVersion(int eagler, int minecraft, int authMethod) {
return serverVersion(eagler, minecraft, authMethod, new byte[0]);
}
private static ByteBuf serverVersion(int eagler, int minecraft, int authMethod, byte[] salt) {
ByteBuf out = Unpooled.buffer();
out.writeByte(0x02);
out.writeShort(eagler);
out.writeShort(minecraft);
Wire.writeByteAscii(out, "EaglerXServer");
Wire.writeByteAscii(out, "1.1.1");
out.writeByte(authMethod);
out.writeShort(salt.length);
out.writeBytes(salt);
out.writeBoolean(false);
return out;
}
private static String hex(byte[] bytes) {
StringBuilder out = new StringBuilder();
for (byte b : bytes) {
out.append(Character.forDigit((b >> 4) & 15, 16)).append(Character.forDigit(b & 15, 16));
}
return out.toString();
}
private static ByteBuf allowLogin(String name, UUID uuid) {
ByteBuf out = Unpooled.buffer();
out.writeByte(0x05);
Wire.writeByteAscii(out, name);
out.writeLong(uuid.getMostSignificantBits());
out.writeLong(uuid.getLeastSignificantBits());
Wire.writeVarInt(out, 0);
out.writeByte(0);
return out;
}
/** A vanilla packet: its id, then an int or a string. */
private static ByteBuf packet(int id, Object... fields) {
ByteBuf out = Unpooled.buffer();
Wire.writeVarInt(out, id);
for (Object field : fields) {
if (field instanceof Integer number) {
Wire.writeVarInt(out, number);
} else {
Wire.writeString(out, (String) field);
}
}
return out;
}
private static ByteBuf bytes(int... values) {
ByteBuf out = Unpooled.buffer();
for (int value : values) {
out.writeByte(value);
}
return out;
}
private static final class Session implements EaglerSession {
@Nullable
String name;
final List<String> messages = new ArrayList<>();
@Nullable
String authRequired;
int capabilities = -1;
@Override
public void loggedIn(String name, UUID uuid, EaglerMessages messages) {
this.name = name;
}
@Override
public void capabilities(int accepted) {
capabilities = accepted;
}
@Override
public void authenticationRequired(int method, String message) {
authRequired = method + ":" + message;
}
@Override
public void received(int id, ByteBuf body) {
StringBuilder hex = new StringBuilder();
while (body.isReadable()) {
int b = body.readUnsignedByte();
hex.append(Character.forDigit(b >> 4, 16)).append(Character.forDigit(b & 15, 16));
}
messages.add(id + ":" + hex);
}
}
}
@@ -0,0 +1,74 @@
package incari.net.eagler;
import static org.assertj.core.api.Assertions.assertThat;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Test;
class EaglerPauseMenuTest {
@Test
void readsALinkButtonADiscordButtonAndTheirIcons() {
ByteBuf in = Unpooled.buffer();
in.writeByte(EaglerPauseMenu.MODE_EXTERNAL_URL | EaglerPauseMenu.MODE_EXTERNAL_URL << 4);
Wire.writeString(in, "Carrotcraft Store");
shortAscii(in, "https://store.example");
Wire.writeString(in, "Our Discord");
shortAscii(in, "https://discord.gg/example");
// Two keys share one image; a third names one that isn't there.
Wire.writeVarInt(in, 3);
Wire.writeByteAscii(in, "icon_serverInfo_L");
Wire.writeVarInt(in, 0);
Wire.writeByteAscii(in, "icon_discord_L");
Wire.writeVarInt(in, 0);
Wire.writeByteAscii(in, "icon_title_L");
Wire.writeVarInt(in, 5);
Wire.writeVarInt(in, 1);
// A 2x1 image: transparent, then white (the server writes white as 0xFFFF).
in.writeByte(2);
in.writeByte(1);
in.writeShort(0);
in.writeShort(0xFFFF);
EaglerPauseMenu menu = EaglerPauseMenu.read(in);
assertThat(menu.serverInfo())
.isEqualTo(new EaglerPauseMenu.Button(
"Carrotcraft Store", EaglerPauseMenu.MODE_EXTERNAL_URL, "https://store.example"));
assertThat(menu.discord()).isNotNull();
assertThat(menu.discord().url()).isEqualTo("https://discord.gg/example");
assertThat(menu.icons()).containsOnlyKeys("icon_serverInfo_L", "icon_discord_L");
EaglerPauseMenu.Image icon = menu.icons().get("icon_discord_L");
assertThat(icon.width()).isEqualTo(2);
assertThat(icon.pixel(0, 0)).isZero();
assertThat(icon.pixel(1, 0)).isEqualTo(0xFFFFFFFF);
assertThat(in.isReadable()).isFalse();
}
@Test
void readsAnEmbeddedServerInfoButtonAndNoIcons() {
ByteBuf in = Unpooled.buffer();
in.writeByte(EaglerPauseMenu.MODE_EMBED_DOWNLOAD);
Wire.writeString(in, "Server Info");
in.writeByte(0);
Wire.writeString(in, "Server Info");
in.writeZero(20);
// The server writes a single 0 byte for no icons.
in.writeByte(0);
EaglerPauseMenu menu = EaglerPauseMenu.read(in);
assertThat(menu.serverInfo())
.isEqualTo(new EaglerPauseMenu.Button("Server Info", EaglerPauseMenu.MODE_EMBED_DOWNLOAD, null));
assertThat(menu.discord()).isNull();
assertThat(menu.icons()).isEmpty();
assertThat(in.isReadable()).isFalse();
}
private static void shortAscii(ByteBuf out, String value) {
out.writeShort(value.length());
out.writeBytes(value.getBytes(StandardCharsets.US_ASCII));
}
}
@@ -0,0 +1,110 @@
package incari.net.eagler;
import static org.assertj.core.api.Assertions.assertThat;
import incari.platform.api.net.NetConnection;
import incari.platform.api.net.PlatformNetwork;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.Test;
class EaglerQueryTest {
private final FakeNetwork network = new FakeNetwork();
private final List<String> results = new ArrayList<>();
private final EaglerQuery.Callback callback = new EaglerQuery.Callback() {
@Override
public void answered(String json, byte @Nullable [] icon, long latencyMillis) {
results.add("answered " + json + " icon=" + (icon == null ? "none" : icon.length) + " " + latencyMillis);
}
@Override
public void failed(String reason) {
results.add("failed " + reason);
}
};
@Test
void asksForTheMotdAndTakesTheIconThatFollows() {
long[] now = {100};
EaglerQuery.motd(network, "ws://example/", () -> now[0], callback);
assertThat(network.texts).containsExactly("Accept: motd");
network.listener().connected();
now[0] = 142;
network.listener().receivedText("{\"type\":\"motd\",\"data\":{\"icon\":true}}");
assertThat(results).isEmpty();
network.listener().received(ByteBuffer.allocate(EaglerQuery.ICON_BYTES));
assertThat(results).containsExactly("answered {\"type\":\"motd\",\"data\":{\"icon\":true}} icon=16384 42");
assertThat(network.closed).isTrue();
}
@Test
void anAnswerWithoutAnIconIsDoneAtOnce() {
EaglerQuery.motd(network, "ws://example/", () -> 0, callback);
network.listener().connected();
network.listener().receivedText("{\"data\":{\"icon\":false}}");
assertThat(results).containsExactly("answered {\"data\":{\"icon\":false}} icon=none 0");
}
@Test
void aServerThatClosesWithoutAnsweringFails() {
EaglerQuery.motd(network, "ws://example/", () -> 0, callback);
network.listener().closed(null);
assertThat(results).containsExactly("failed The server closed the connection without answering");
}
/** One WebSocket, driven by the test. */
private static final class FakeNetwork implements PlatformNetwork {
final List<String> texts = new ArrayList<>();
NetConnection.@Nullable Listener listener;
boolean closed;
NetConnection.Listener listener() {
NetConnection.Listener current = listener;
assertThat(current).isNotNull();
return current;
}
@Override
public NetConnection connect(String host, int port, NetConnection.Listener listener) {
throw new UnsupportedOperationException();
}
@Override
public NetConnection openWebSocket(String url, NetConnection.Listener listener) {
this.listener = listener;
return new NetConnection() {
@Override
public void send(ByteBuffer data) {}
@Override
public void sendText(String text) {
texts.add(text);
}
@Override
public void close() {
closed = true;
}
@Override
public boolean isOpen() {
return !closed;
}
@Override
public String remoteDescription() {
return url;
}
};
}
}
}
@@ -0,0 +1,106 @@
package incari.net.eagler;
import static org.assertj.core.api.Assertions.assertThat;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.Test;
class EaglerTexturesTest {
@Test
void skinBytesMatchTheServersConversion() {
int[] pixels = new int[64 * 64];
pixels[0] = 0xFF123456;
pixels[1] = 0x00ABCDEF;
byte[] data = EaglerTextures.encodeSkin(pixels);
// EaglerXServer converts ARGB the same way: blue, green, red >> 1 with alpha's top bit.
assertThat(data[0]).isEqualTo((byte) 0x56);
assertThat(data[1]).isEqualTo((byte) 0x34);
assertThat(data[2]).isEqualTo((byte) ((0x12 >> 1) | 0x80));
assertThat(data[3]).isEqualTo((byte) 0xEF);
assertThat(data[4]).isEqualTo((byte) 0xCD);
assertThat(data[5]).isEqualTo((byte) (0xAB >> 1));
}
@Test
void skinsSurviveARoundTripWithinTheFormatsPrecision() {
int[] pixels = new int[64 * 64];
for (int i = 0; i < pixels.length; i++) {
pixels[i] = (i % 3 == 0 ? 0 : 0xFF000000) | ((i * 7919) & 0xFFFFFF);
}
int[] decoded = EaglerTextures.decodeSkin(EaglerTextures.encodeSkin(pixels));
for (int i = 0; i < pixels.length; i++) {
assertThat(decoded[i] >>> 24).isEqualTo(i % 3 == 0 ? 0 : 0xFF);
assertThat(decoded[i] & 0xFFFF).isEqualTo(pixels[i] & 0xFFFF);
assertThat((decoded[i] >>> 17) & 0x7F).isEqualTo((pixels[i] >>> 17) & 0x7F);
}
// Red loses its lowest bit, as it does between Eagler clients.
int[] red = new int[64 * 64];
Arrays.fill(red, 0xFFFF0000);
assertThat(EaglerTextures.decodeSkin(EaglerTextures.encodeSkin(red))[0]).isEqualTo(0xFFFE0000);
}
@Test
void capesCarryTheCapeRegionOnly() {
int[] pixels = new int[64 * 32];
pixels[0] = 0xFF010203;
pixels[16 * 64 + 21] = 0xFF0A0B0C; // the 22x17 region's last pixel
pixels[21 * 64 + 22] = 0xFF112233; // the extra column's last pixel
pixels[40] = 0xFFFFFFFF; // outside what Eagler sends
int[] decoded = EaglerTextures.decodeCape(EaglerTextures.encodeCape(pixels));
assertThat(decoded[0]).isEqualTo(0xFF010203);
assertThat(decoded[16 * 64 + 21]).isEqualTo(0xFF0A0B0C);
assertThat(decoded[21 * 64 + 22]).isEqualTo(0xFF112233);
assertThat(decoded[40]).isZero();
}
@Test
void theAnswerIsMatchedToItsRequest() {
List<String> seen = new ArrayList<>();
EaglerTextures textures = new EaglerTextures((player, skin, cape) -> seen.add(player + " " + skin.preset() + " "
+ skin.slim() + " " + (skin.pixels() != null) + " " + cape.preset()));
List<ByteBuf> sent = new ArrayList<>();
textures.attach(new EaglerMessages(new EaglerMessages.Sink() {
@Override
public ByteBuf allocate() {
return Unpooled.buffer();
}
@Override
public void write(ByteBuf message) {
sent.add(message);
}
}));
UUID player = UUID.randomUUID();
textures.request(player);
assertThat(sent).hasSize(1);
ByteBuf request = sent.get(0);
assertThat((int) request.readUnsignedByte()).isEqualTo(0xEE);
assertThat((int) request.readUnsignedByte()).isEqualTo(0x03);
int id = Wire.readVarInt(request);
assertThat(new UUID(request.readLong(), request.readLong())).isEqualTo(player);
ByteBuf answer = Unpooled.buffer();
Wire.writeVarInt(answer, id);
Wire.writeVarInt(answer, -1 - 1); // a custom skin on the slim model
Wire.writeVarInt(answer, 0); // no cape
answer.writeBytes(new byte[EaglerTextures.SKIN_BYTES]);
assertThat(textures.handle(0x05, answer)).isTrue();
assertThat(seen).containsExactly(player + " -1 true true 0");
assertThat(textures.handle(0x7F, Unpooled.buffer())).isFalse();
}
}
@@ -0,0 +1,54 @@
package incari.net.https;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import org.junit.jupiter.api.Test;
class HttpRequestTest {
@Test
void encodesAPost() {
HttpRequest request = HttpRequest.post(
"https://Login.Live.com/oauth20_token.srf",
"application/json",
"{}",
Map.of("Accept", "application/json"));
assertThat(request.host()).isEqualTo("login.live.com");
String wire = new String(request.encode(), StandardCharsets.UTF_8);
assertThat(wire)
.startsWith("POST /oauth20_token.srf HTTP/1.1\r\nHost: login.live.com\r\nConnection: close\r\n")
.contains("Content-Length: 2\r\n", "Content-Type: application/json\r\n")
.endsWith("\r\n\r\n{}");
}
@Test
void refusesAnythingButPlainHttps() {
assertThatThrownBy(() -> HttpRequest.get("http://login.live.com/", Map.of()))
.hasMessageContaining("https");
assertThatThrownBy(() -> HttpRequest.get("https://login.live.com:8443/", Map.of()))
.hasMessageContaining("443");
assertThatThrownBy(() -> HttpRequest.get("https://user@login.live.com/", Map.of()))
.hasMessageContaining("443");
}
@Test
void refusesHeaderInjection() {
assertThatThrownBy(() -> HttpRequest.get("https://login.live.com/", Map.of("X", "a\r\nEvil: 1")))
.hasMessageContaining("control character");
assertThatThrownBy(() -> HttpRequest.get("https://login.live.com/", Map.of("X: y", "a")))
.hasMessageContaining("Not an HTTP token");
assertThatThrownBy(() -> HttpRequest.get("https://login.live.com/a b", Map.of()))
.hasMessageContaining("Not a request path");
assertThatThrownBy(() -> HttpRequest.get("https://login.live.com/\r\nX", Map.of()))
.hasMessageContaining("Not a request path");
}
@Test
void neverPrintsTheQueryOrBody() {
HttpRequest request = HttpRequest.post("https://login.live.com/x?secret=1", "text/plain", "token", Map.of());
assertThat(request.toString()).isEqualTo("POST https://login.live.com/x");
}
}
@@ -0,0 +1,104 @@
package incari.net.https;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Test;
class ResponseParserTest {
@Test
void readsABodyByLength() throws IOException {
HttpResponse response =
whole("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 2\r\n\r\n{}");
assertThat(response.status()).isEqualTo(200);
assertThat(response.header("content-type")).isEqualTo("application/json");
assertThat(response.text()).isEqualTo("{}");
}
@Test
void readsABodyByteByByte() throws IOException {
byte[] bytes = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello".getBytes(StandardCharsets.US_ASCII);
ResponseParser parser = new ResponseParser(false);
HttpResponse response = null;
for (int i = 0; i < bytes.length; i++) {
assertThat(response).isNull();
response = parser.feed(bytes, i, 1);
}
assertThat(response).isNotNull();
assertThat(response.text()).isEqualTo("hello");
}
@Test
void readsChunks() throws IOException {
HttpResponse response = whole(String.join(
"\r\n",
"HTTP/1.1 200 OK",
"Transfer-Encoding: chunked",
"",
"4",
"Wiki",
"5;ext=1",
"pedia",
"0",
"Trailer: x",
"",
""));
assertThat(response.text()).isEqualTo("Wikipedia");
}
@Test
void skipsInterimResponses() throws IOException {
HttpResponse response = whole("HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 204 No Content\r\n\r\n");
assertThat(response.status()).isEqualTo(204);
assertThat(response.body()).isEmpty();
}
@Test
void readsUntilACleanCloseOnly() throws IOException {
ResponseParser parser = new ResponseParser(false);
byte[] bytes = "HTTP/1.1 200 OK\r\n\r\npartial".getBytes(StandardCharsets.US_ASCII);
assertThat(parser.feed(bytes, 0, bytes.length)).isNull();
assertThat(parser.finish(true).text()).isEqualTo("partial");
ResponseParser truncated = new ResponseParser(false);
truncated.feed(bytes, 0, bytes.length);
assertThatThrownBy(() -> truncated.finish(false)).hasMessageContaining("cut off");
}
@Test
void refusesAShortBody() throws IOException {
ResponseParser parser = new ResponseParser(false);
byte[] bytes = "HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc".getBytes(StandardCharsets.US_ASCII);
parser.feed(bytes, 0, bytes.length);
assertThatThrownBy(() -> parser.finish(true)).hasMessageContaining("cut off");
}
@Test
void refusesHugeAndMalformedResponses() {
assertThatThrownBy(() -> whole("HTTP/1.1 200 OK\r\nContent-Length: 99999999\r\n\r\n"))
.hasMessageContaining("too big");
assertThatThrownBy(() -> whole("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nFFFFFFF\r\n"))
.hasMessageContaining("too big");
assertThatThrownBy(() -> whole("SSH-2.0-OpenSSH\r\n\r\n")).hasMessageContaining("Not an HTTP");
assertThatThrownBy(() -> whole("HTTP/1.1 200 OK\r\nContent-Length: 1\r\nContent-Length: 2\r\n\r\n"))
.hasMessageContaining("Two different");
assertThatThrownBy(() -> whole("HTTP/1.1 200 OK\r\nTransfer-Encoding: gzip\r\n\r\n"))
.hasMessageContaining("unsupported transfer");
assertThatThrownBy(() -> whole("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nabcd\r\n"))
.hasMessageContaining("runs over");
String longHeader = "HTTP/1.1 200 OK\r\nX: " + "a".repeat(ResponseParser.MAX_HEAD) + "\r\n\r\n";
assertThatThrownBy(() -> whole(longHeader)).hasMessageContaining("too long");
}
private static HttpResponse whole(String text) throws IOException {
byte[] bytes = text.getBytes(StandardCharsets.US_ASCII);
HttpResponse response = new ResponseParser(false).feed(bytes, 0, bytes.length);
if (response == null) {
throw new IOException("incomplete");
}
return response;
}
}
@@ -0,0 +1,70 @@
package incari.net.msa;
import static org.assertj.core.api.Assertions.assertThat;
import incari.net.https.HttpRequest;
import incari.net.https.HttpResponse;
import incari.net.https.HttpsClient;
import incari.net.tls.SocketTransport;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
/**
* The real hosts, through the real TLS and certificate checks: off unless {@code INCARI_LIVE=1}, as
* it needs the network. Signs nobody in: it asks for a code and sends tokens that are refused.
*/
@EnabledIfEnvironmentVariable(named = "INCARI_LIVE", matches = "1")
class LiveEndpointsTest {
private final HttpsClient https = HttpsClient.pinned(new SocketTransport(), MicrosoftEndpoints.HOSTS);
private final MicrosoftSignIn signIn = new MicrosoftSignIn(https, System::currentTimeMillis);
@Test
void microsoftGivesADeviceCode() throws Exception {
DeviceCode code = signIn.requestCode().get(30, TimeUnit.SECONDS);
assertThat(code.userCode()).isNotEmpty();
assertThat(code.pageUrl()).startsWith("https://www.microsoft.com/");
MicrosoftSignIn.Poll poll = signIn.poll(code).get(30, TimeUnit.SECONDS);
assertThat(poll.state()).isEqualTo(MicrosoftSignIn.PollState.WAITING);
}
@Test
void everyHostPassesTheCertificateChecks() throws Exception {
for (String host : MicrosoftEndpoints.HOSTS) {
HttpResponse response = https.send(HttpRequest.get("https://" + host + "/", Map.of()))
.get(30, TimeUnit.SECONDS);
assertThat(response.status()).as(host).isBetween(200, 599);
}
}
@Test
void theSessionServerRefusesAMadeUpToken() throws Exception {
MicrosoftAccount account =
new MicrosoftAccount("Nobody", "0123456789abcdef0123456789abcdef", "not-a-token", Long.MAX_VALUE, "x");
assertThat(signIn.join(account, "-1234abcd").get(30, TimeUnit.SECONDS)).isEqualTo(JoinResult.INVALID_SESSION);
}
@Test
void aHostOffTheListIsRefusedWithoutConnecting() {
HttpsClient narrow = HttpsClient.pinned(new SocketTransport(), Set.of("login.live.com"));
assertThat(narrow.send(HttpRequest.get("https://example.com/", Map.of())))
.failsWithin(1, TimeUnit.SECONDS)
.withThrowableOfType(ExecutionException.class)
.withMessageContaining("example.com");
}
@Test
void anUntrustedChainFailsTheHandshake() {
// example.com chains to a root that isn't pinned.
HttpsClient other = HttpsClient.pinned(new SocketTransport(), Set.of("example.com"));
assertThat(other.send(HttpRequest.get("https://example.com/", Map.of())))
.failsWithin(30, TimeUnit.SECONDS)
.withThrowableOfType(ExecutionException.class)
.withMessageContaining("trusted root");
}
}
@@ -0,0 +1,353 @@
package incari.net.msa;
import static org.assertj.core.api.Assertions.assertThat;
import incari.net.https.HttpRequest;
import incari.net.https.HttpResponse;
import incari.net.https.Https;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
class MicrosoftSignInTest {
private static final long NOW = 1_800_000_000_000L;
private final FakeServer server = new FakeServer();
private final MicrosoftSignIn signIn = new MicrosoftSignIn(server, () -> NOW);
// --- Device code ---------------------------------------------------------------------------
@Test
void asksForACodeAsTheLauncher() throws Exception {
server.answer(
"login.live.com/oauth20_connect.srf",
200,
"{\"user_code\":\"ABCD1234\",\"device_code\":\"secret\",\"verification_uri\":\"https://www.microsoft.com/link\","
+ "\"interval\":5,\"expires_in\":900}");
DeviceCode code = signIn.requestCode().get();
assertThat(code.userCode()).isEqualTo("ABCD1234");
assertThat(code.pageWithCode()).isEqualTo("https://www.microsoft.com/link?otc=ABCD1234");
assertThat(code.expiresAtMillis()).isEqualTo(NOW + 900_000);
assertThat(code.toString()).doesNotContain("secret");
String form = server.bodies.getFirst();
assertThat(form)
.isEqualTo("client_id=00000000402b5328&scope=service%3A%3Auser.auth.xboxlive.com%3A%3AMBI_SSL"
+ "&response_type=device_code");
}
@Test
void refusesACodePageOffMicrosoft() {
server.answer(
"login.live.com/oauth20_connect.srf",
200,
"{\"user_code\":\"ABCD1234\",\"device_code\":\"secret\",\"verification_uri\":\"https://evil.example/link\","
+ "\"interval\":5,\"expires_in\":900}");
assertFails(signIn.requestCode(), "looked wrong");
}
@Test
void pollsUntilThePlayerHasTypedTheCode() throws Exception {
DeviceCode code = new DeviceCode("ABCD1234", "device", "https://www.microsoft.com/link", NOW + 1000, 5);
server.answer("login.live.com/oauth20_token.srf", 400, "{\"error\":\"authorization_pending\"}");
server.answer("login.live.com/oauth20_token.srf", 400, "{\"error\":\"slow_down\"}");
server.answer(
"login.live.com/oauth20_token.srf", 200, "{\"access_token\":\"ms\",\"refresh_token\":\"refresh\"}");
assertThat(signIn.poll(code).get().state()).isEqualTo(MicrosoftSignIn.PollState.WAITING);
assertThat(signIn.poll(code).get().state()).isEqualTo(MicrosoftSignIn.PollState.SLOW_DOWN);
MicrosoftSignIn.Poll done = signIn.poll(code).get();
assertThat(done.state()).isEqualTo(MicrosoftSignIn.PollState.DONE);
assertThat(done.tokens()).isEqualTo(new MicrosoftSignIn.MicrosoftTokens("ms", "refresh"));
assertThat(server.bodies.getFirst()).contains("device_code=device", "grant_type=urn%3Aietf%3Aparams");
}
@Test
void sayWhenTheCodeExpiredOrWasDeclined() {
DeviceCode code = new DeviceCode("ABCD1234", "device", "https://www.microsoft.com/link", NOW + 1000, 5);
server.answer("login.live.com/oauth20_token.srf", 400, "{\"error\":\"expired_token\"}");
assertFails(signIn.poll(code), "expired");
server.answer("login.live.com/oauth20_token.srf", 400, "{\"error\":\"authorization_declined\"}");
assertFails(signIn.poll(code), "cancelled");
DeviceCode old = new DeviceCode("ABCD1234", "device", "https://www.microsoft.com/link", NOW - 1, 5);
assertFails(signIn.poll(old), "expired");
}
// --- The token chain -----------------------------------------------------------------------
@Test
void signsInThroughXboxToMinecraft() throws Exception {
answerTheChain();
MicrosoftAccount account = signIn.signIn(new MicrosoftSignIn.MicrosoftTokens("ms", "refresh"))
.get();
assertThat(account.name()).isEqualTo("Steve");
assertThat(account.id()).isEqualTo("0123456789abcdef0123456789abcdef");
assertThat(account.minecraftToken()).isEqualTo("mc");
assertThat(account.minecraftExpiresAtMillis()).isEqualTo(NOW + 86_400_000L);
assertThat(account.refreshToken()).isEqualTo("refresh");
assertThat(server.bodies.get(0))
.contains("\"RpsTicket\":\"t=ms\"", "\"RelyingParty\":\"http://auth.xboxlive.com\"");
assertThat(server.bodies.get(1)).contains("\"UserTokens\":[\"xbl\"]", "rp://api.minecraftservices.com/");
assertThat(server.bodies.get(2)).isEqualTo("{\"identityToken\":\"XBL3.0 x=hash;xsts\"}");
assertThat(server.headers.get(3)).containsEntry("Authorization", "Bearer mc");
}
@Test
void triesTheOtherTicketFormOnce() throws Exception {
server.answer("user.auth.xboxlive.com/user/authenticate", 400, "");
answerTheChain();
signIn.signIn(new MicrosoftSignIn.MicrosoftTokens("ms", "refresh")).get();
assertThat(server.bodies.get(0)).contains("t=ms");
assertThat(server.bodies.get(1)).contains("d=ms");
}
@Test
void explainsXboxRefusals() {
server.answer("user.auth.xboxlive.com/user/authenticate", 200, "{\"Token\":\"xbl\"}");
server.answer("xsts.auth.xboxlive.com/xsts/authorize", 401, "{\"XErr\":2148916233}");
assertFails(signIn.signIn(new MicrosoftSignIn.MicrosoftTokens("ms", "r")), "no Xbox profile");
assertThat(MicrosoftSignIn.xboxError(2148916238L)).contains("child account");
}
@Test
void saysWhenTheAccountDoesNotOwnTheGame() {
server.answer("user.auth.xboxlive.com/user/authenticate", 200, "{\"Token\":\"xbl\"}");
server.answer(
"xsts.auth.xboxlive.com/xsts/authorize",
200,
"{\"Token\":\"xsts\",\"DisplayClaims\":{\"xui\":[{\"uhs\":\"hash\"}]}}");
server.answer(
"api.minecraftservices.com/authentication/login_with_xbox",
200,
"{\"access_token\":\"mc\",\"expires_in\":86400}");
server.answer("api.minecraftservices.com/minecraft/profile", 404, "{\"error\":\"NOT_FOUND\"}");
assertFails(signIn.signIn(new MicrosoftSignIn.MicrosoftTokens("ms", "r")), "doesn't own Minecraft");
}
@Test
void refusesAProfileThatLooksWrong() {
server.answer("user.auth.xboxlive.com/user/authenticate", 200, "{\"Token\":\"xbl\"}");
server.answer(
"xsts.auth.xboxlive.com/xsts/authorize",
200,
"{\"Token\":\"xsts\",\"DisplayClaims\":{\"xui\":[{\"uhs\":\"hash\"}]}}");
server.answer("api.minecraftservices.com/authentication/login_with_xbox", 200, "{\"access_token\":\"mc\"}");
server.answer(
"api.minecraftservices.com/minecraft/profile",
200,
"{\"id\":\"../../etc\",\"name\":\"\\u00a7cSteve\"}");
assertFails(signIn.signIn(new MicrosoftSignIn.MicrosoftTokens("ms", "r")), "looked wrong");
}
@Test
void renewsOnlyATokenAboutToExpire() throws Exception {
MicrosoftAccount fresh = account(NOW + MicrosoftSignIn.RENEW_MARGIN_MILLIS + 60_000);
assertThat(signIn.renew(fresh).get()).isSameAs(fresh);
assertThat(server.urls).isEmpty();
server.answer(
"login.live.com/oauth20_token.srf", 200, "{\"access_token\":\"ms2\",\"refresh_token\":\"refresh2\"}");
answerTheChain();
MicrosoftAccount renewed = signIn.renew(account(NOW + 1000)).get();
assertThat(renewed.refreshToken()).isEqualTo("refresh2");
assertThat(server.bodies.getFirst()).contains("grant_type=refresh_token", "refresh_token=old-refresh");
}
@Test
void anExpiredRefreshTokenAsksToSignInAgain() {
server.answer("login.live.com/oauth20_token.srf", 400, "{\"error\":\"invalid_grant\"}");
assertFails(signIn.renew(account(NOW)), "Sign in again");
assertThat(((SignInException) failureAfter(400, "invalid_grant")).temporary())
.isFalse();
}
@Test
void aServiceOutageOrNetworkFailureIsWorthTryingAgain() {
server.answer("login.live.com/oauth20_token.srf", 503, "");
Throwable outage = failure(signIn.renew(account(NOW)));
assertThat(outage.getMessage()).contains("Try again").doesNotContain("Sign in again");
assertThat(((SignInException) outage).temporary()).isTrue();
server.fail("login.live.com/oauth20_token.srf");
Throwable unreachable = failure(signIn.renew(account(NOW)));
assertThat(((SignInException) unreachable).temporary()).isTrue();
}
@Test
void aPollThatDoesntGetThroughIsTemporaryAndARefusalIsNot() {
DeviceCode code = new DeviceCode("ABCD1234", "device", "https://www.microsoft.com/link", NOW + 1000, 5);
server.fail("login.live.com/oauth20_token.srf");
assertThat(((SignInException) failure(signIn.poll(code))).temporary()).isTrue();
server.answer("login.live.com/oauth20_token.srf", 502, "<html>Bad gateway</html>");
assertThat(((SignInException) failure(signIn.poll(code))).temporary()).isTrue();
server.answer("login.live.com/oauth20_token.srf", 400, "{\"error\":\"expired_token\"}");
assertThat(((SignInException) failure(signIn.poll(code))).temporary()).isFalse();
server.answer("login.live.com/oauth20_token.srf", 400, "{\"error\":\"access_denied\"}");
assertThat(((SignInException) failure(signIn.poll(code))).temporary()).isFalse();
}
private Throwable failureAfter(int status, String error) {
server.answer("login.live.com/oauth20_token.srf", status, "{\"error\":\"" + error + "\"}");
return failure(signIn.renew(account(NOW)));
}
// --- Joins and keys ------------------------------------------------------------------------
@Test
void joinsAndReadsTheSessionServersAnswers() throws Exception {
server.answer("sessionserver.mojang.com/session/minecraft/join", 204, "");
assertThat(signIn.join(account(NOW + 1000), "-6b2c").get()).isEqualTo(JoinResult.OK);
assertThat(server.bodies.getFirst())
.isEqualTo(
"{\"accessToken\":\"mc\",\"selectedProfile\":\"0123456789abcdef0123456789abcdef\",\"serverId\":\"-6b2c\"}");
server.answer(
"sessionserver.mojang.com/session/minecraft/join", 403, "{\"error\":\"ForbiddenOperationException\"}");
assertThat(signIn.join(account(NOW), "x").get()).isEqualTo(JoinResult.INVALID_SESSION);
server.answer(
"sessionserver.mojang.com/session/minecraft/join",
403,
"{\"error\":\"InsufficientPrivilegesException\"}");
assertThat(signIn.join(account(NOW), "x").get()).isEqualTo(JoinResult.INSUFFICIENT_PRIVILEGES);
server.answer("sessionserver.mojang.com/session/minecraft/join", 403, "{\"error\":\"UserBannedException\"}");
assertThat(signIn.join(account(NOW), "x").get()).isEqualTo(JoinResult.BANNED);
server.answer("sessionserver.mojang.com/session/minecraft/join", 503, "");
assertThat(signIn.join(account(NOW), "x").get()).isEqualTo(JoinResult.UNAVAILABLE);
server.fail("sessionserver.mojang.com/session/minecraft/join");
assertThat(signIn.join(account(NOW), "x").get()).isEqualTo(JoinResult.UNAVAILABLE);
}
@Test
void fetchesTheChatKey() throws Exception {
server.answer(
"api.minecraftservices.com/player/certificates",
200,
"{\"keyPair\":{\"privateKey\":\"-----BEGIN RSA PRIVATE KEY-----\\nAAA\\n-----END RSA PRIVATE KEY-----\\n\","
+ "\"publicKey\":\"-----BEGIN RSA PUBLIC KEY-----\\nBBB\\n-----END RSA PUBLIC KEY-----\\n\"},"
+ "\"publicKeySignature\":\"AAEC\",\"publicKeySignatureV2\":\"AQID\","
+ "\"expiresAt\":\"2027-01-02T03:04:05.123Z\",\"refreshedAfter\":\"2027-01-01T00:00:00Z\"}");
ProfileCertificates keys = signIn.certificates(account(NOW + 1000)).get();
assertThat(keys.publicKeySignature()).containsExactly(1, 2, 3);
assertThat(keys.privateKeyPem()).startsWith("-----BEGIN RSA PRIVATE KEY-----");
assertThat(keys.expiresAt()).isEqualTo("2027-01-02T03:04:05.123Z");
assertThat(server.headers.getFirst()).containsEntry("Authorization", "Bearer mc");
assertThat(keys.toString()).doesNotContain("PRIVATE");
}
// --- Accounts ------------------------------------------------------------------------------
@Test
void anAccountRoundTripsAndNeverPrintsItsTokens() {
MicrosoftAccount account = account(NOW);
assertThat(MicrosoftAccount.fromJson(account.toJson())).isEqualTo(account);
assertThat(account.toString()).doesNotContain("mc", "old-refresh").contains("Steve");
assertThat(account.dashedId()).isEqualTo("01234567-89ab-cdef-0123-456789abcdef");
assertThat(MicrosoftAccount.fromJson("{\"version\":2}")).isNull();
assertThat(MicrosoftAccount.fromJson("not json")).isNull();
assertThat(MicrosoftAccount.fromJson("{\"version\":1,\"name\":\"a b\",\"id\":\"x\"}"))
.isNull();
}
@Test
void failuresNeverCarryTokens() {
server.fail("login.live.com/oauth20_token.srf");
Throwable thrown = failure(signIn.renew(account(NOW)));
for (Throwable t = thrown; t != null; t = t.getCause()) {
assertThat(String.valueOf(t.getMessage())).doesNotContain("old-refresh");
}
}
// --- Helpers -------------------------------------------------------------------------------
private void answerTheChain() {
server.answer("user.auth.xboxlive.com/user/authenticate", 200, "{\"Token\":\"xbl\"}");
server.answer(
"xsts.auth.xboxlive.com/xsts/authorize",
200,
"{\"Token\":\"xsts\",\"DisplayClaims\":{\"xui\":[{\"uhs\":\"hash\"}]}}");
server.answer(
"api.minecraftservices.com/authentication/login_with_xbox",
200,
"{\"access_token\":\"mc\",\"expires_in\":86400}");
server.answer(
"api.minecraftservices.com/minecraft/profile",
200,
"{\"id\":\"0123456789abcdef0123456789abcdef\",\"name\":\"Steve\"}");
}
private static MicrosoftAccount account(long expiresAt) {
return new MicrosoftAccount("Steve", "0123456789abcdef0123456789abcdef", "mc", expiresAt, "old-refresh");
}
private static void assertFails(CompletableFuture<?> future, String message) {
Throwable thrown = failure(future);
assertThat(thrown).isInstanceOf(SignInException.class);
assertThat(thrown.getMessage()).contains(message);
}
private static Throwable failure(CompletableFuture<?> future) {
try {
future.get(5, TimeUnit.SECONDS);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
while (cause instanceof java.util.concurrent.CompletionException && cause.getCause() != null) {
cause = cause.getCause();
}
return cause;
} catch (Exception e) {
throw new AssertionError(e);
}
throw new AssertionError("Didn't fail");
}
/** Answers by host and path, in the order answers were given for each. */
private static final class FakeServer implements Https {
private final Map<String, Deque<HttpResponse>> answers = new LinkedHashMap<>();
final List<String> urls = new ArrayList<>();
final List<String> bodies = new ArrayList<>();
final List<Map<String, String>> headers = new ArrayList<>();
void answer(String where, int status, String body) {
answers.computeIfAbsent(where, k -> new ArrayDeque<>())
.add(new HttpResponse(status, Map.of(), body.getBytes(StandardCharsets.UTF_8)));
}
void fail(String where) {
answers.computeIfAbsent(where, k -> new ArrayDeque<>()).add(new HttpResponse(-1, Map.of(), new byte[0]));
}
@Override
public CompletableFuture<HttpResponse> send(HttpRequest request) {
String where = request.host() + request.path();
urls.add(where);
bodies.add(new String(request.body(), StandardCharsets.UTF_8));
headers.add(request.headers());
Deque<HttpResponse> queue = answers.get(where);
HttpResponse response = queue == null ? null : queue.poll();
if (response == null) {
return CompletableFuture.failedFuture(new AssertionError("Unexpected request to " + where));
}
if (response.status() < 0) {
return CompletableFuture.failedFuture(new java.io.IOException("connection refused"));
}
return CompletableFuture.completedFuture(response);
}
}
}
@@ -0,0 +1,133 @@
package incari.net.relay;
import static org.assertj.core.api.Assertions.assertThat;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.zip.Deflater;
import org.junit.jupiter.api.Test;
/** The shared-world host's framing and login, as the game's side of the pipeline sees them. */
class LanStagesTest {
@Test
void joinsPiecesAndInflatesCompressedPackets() {
EmbeddedChannel channel = new EmbeddedChannel();
LanFraming.install(channel.pipeline());
channel.writeInbound(bytes(1, 10, 11), bytes(0, 12));
ByteBuf joined = channel.readInbound();
assertThat(array(joined)).containsExactly(10, 11, 12);
byte[] packet = new byte[5000];
for (int i = 0; i < packet.length; i++) {
packet[i] = (byte) (i % 7);
}
Deflater deflater = new Deflater();
deflater.setInput(packet);
deflater.finish();
ByteArrayOutputStream compressed = new ByteArrayOutputStream();
byte[] chunk = new byte[1024];
while (!deflater.finished()) {
compressed.write(chunk, 0, deflater.deflate(chunk));
}
ByteBuf message = Unpooled.buffer();
message.writeByte(2).writeInt(packet.length).writeBytes(compressed.toByteArray());
channel.writeInbound(message);
ByteBuf inflated = channel.readInbound();
assertThat(inflated.readableBytes()).isEqualTo(5000);
assertThat(inflated.getByte(4999)).isEqualTo(packet[4999]);
}
@Test
void sendsBigPacketsInPieces() {
EmbeddedChannel channel = new EmbeddedChannel();
LanFraming.install(channel.pipeline());
channel.writeOutbound(Unpooled.wrappedBuffer(new byte[100_000]));
int total = 0;
int pieces = 0;
ByteBuf out;
int last = -1;
while ((out = channel.readOutbound()) != null) {
assertThat(out.readableBytes()).isLessThanOrEqualTo(LanFraming.FRAGMENT);
last = out.readUnsignedByte();
total += out.readableBytes();
pieces++;
out.release();
}
assertThat(total).isEqualTo(100_000);
assertThat(pieces).isEqualTo(2);
assertThat(last).isZero();
}
@Test
void speaksTheHostsLogin() {
EmbeddedChannel channel = new EmbeddedChannel();
UUID brand = new UUID(1, 2);
LanLogin.install(
channel.pipeline(), new LanLogin(new byte[] {1, 0, 0, 0, 0}, new byte[] {1, 0, 0, 0, 0}, brand));
// Via's 1.8 handshake is dropped; Login Start gains Eagler's fields.
channel.writeOutbound(bytes(0x00, 47, 0), packet(0x00, "Steve"));
ByteBuf start = channel.readOutbound();
assertThat(channel.<Object>readOutbound()).isNull();
assertThat((int) start.readByte()).isZero();
assertThat(string(start)).isEqualTo("Steve");
assertThat((int) start.readByte()).isEqualTo(5);
start.skipBytes(5);
assertThat((int) start.readByte()).isEqualTo(5);
start.skipBytes(5);
assertThat((int) start.readByte()).isEqualTo(6);
assertThat(start.readShort()).isEqualTo((short) 2);
assertThat(start.readShort()).isEqualTo((short) 3);
assertThat(start.readShort()).isEqualTo((short) 4);
assertThat(new UUID(start.readLong(), start.readLong())).isEqualTo(brand);
assertThat(start.isReadable()).isFalse();
// The host's Login Success loses the Eagler protocol it ends with.
ByteBuf success = packet(0x02, "00000000-0000-0000-0000-000000000001", "Steve");
success.writeShort(4);
channel.writeInbound(success);
ByteBuf passed = channel.readInbound();
assertThat((int) passed.readByte()).isEqualTo(2);
string(passed);
assertThat(string(passed)).isEqualTo("Steve");
assertThat(passed.isReadable()).isFalse();
}
private static ByteBuf packet(int id, String... strings) {
ByteBuf out = Unpooled.buffer();
out.writeByte(id);
for (String s : strings) {
byte[] b = s.getBytes(StandardCharsets.UTF_8);
out.writeByte(b.length).writeBytes(b);
}
return out;
}
private static String string(ByteBuf in) {
int length = in.readByte();
return in.readCharSequence(length, StandardCharsets.UTF_8).toString();
}
private static ByteBuf bytes(int... values) {
ByteBuf out = Unpooled.buffer();
for (int v : values) {
out.writeByte(v);
}
return out;
}
private static int[] array(ByteBuf in) {
int[] out = new int[in.readableBytes()];
for (int i = 0; i < out.length; i++) {
out[i] = in.readUnsignedByte();
}
return out;
}
}
@@ -0,0 +1,324 @@
package incari.net.relay;
import static org.assertj.core.api.Assertions.assertThat;
import incari.platform.api.net.NetConnection;
import incari.platform.api.net.PlatformNetwork;
import incari.platform.api.rtc.IceServer;
import incari.platform.api.rtc.Microphone;
import incari.platform.api.rtc.PlatformRtc;
import incari.platform.api.rtc.RemoteVoice;
import incari.platform.api.rtc.RtcPeer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.Test;
/** Sharing a world against a scripted relay and a fake WebRTC peer (ADR 0062). */
class RelayHostTest {
private long now = 1000;
private final List<ByteBuffer> sentToRelay = new ArrayList<>();
private NetConnection.@Nullable Listener relay;
private final List<Peer> peers = new ArrayList<>();
private @Nullable String code;
private @Nullable String stopped;
private final List<String> guests = new ArrayList<>();
private final List<String> heardFromGuest = new ArrayList<>();
private final PlatformNetwork network = new PlatformNetwork() {
@Override
public NetConnection connect(String host, int port, NetConnection.Listener listener) {
throw new UnsupportedOperationException();
}
@Override
public NetConnection openWebSocket(String url, NetConnection.Listener listener) {
relay = listener;
return new Sent(sentToRelay);
}
};
private final PlatformRtc rtc = new PlatformRtc() {
@Override
public boolean supported() {
return true;
}
@Override
public Microphone microphone() {
throw new UnsupportedOperationException();
}
@Override
public RtcPeer createPeer(List<IceServer> iceServers, RtcPeer.Listener listener) {
Peer peer = new Peer(listener);
peers.add(peer);
return peer;
}
};
private final RelayHost host = new RelayHost(
network,
rtc,
"wss://relay.example",
"My World",
775,
new RelayHost.Listener() {
@Override
public void shared(String given) {
code = given;
}
@Override
public NetConnection.Listener guest(String clientId, NetConnection channel) {
guests.add(clientId);
return new NetConnection.Listener() {
@Override
public void connected() {
heardFromGuest.add("connected");
}
@Override
public void received(ByteBuffer data) {
heardFromGuest.add("bytes " + data.remaining());
}
@Override
public void closed(@Nullable Throwable cause) {
heardFromGuest.add("closed");
}
};
}
@Override
public void stopped(String reason) {
stopped = reason;
}
},
() -> now);
@Test
void sharesAnswersAGuestAndHandsItsChannelOver() {
host.start();
relay.connected();
ByteBuf hello = next();
assertThat((int) hello.readUnsignedByte()).isEqualTo(0x00);
assertThat((int) hello.readUnsignedByte()).isEqualTo(0x01);
assertThat((int) hello.readUnsignedByte()).isEqualTo(1);
assertThat(ascii8(hello)).isEqualTo("My World;0");
relay.received(message(0x00, 0x01, 0x01, 5, 'a', 'b', 'c', 'd', 'e'));
assertThat(code).isEqualTo("abcde");
relay.received(message(0x01, 0x00, 0x00));
relay.received(withAscii8(0x02, "client1"));
assertThat(peers).hasSize(1);
Peer peer = peers.get(0);
relay.received(signal(0x04, "client1", "{\"type\":\"offer\",\"sdp\":\"v=0\"}"));
assertThat(peer.remote).isEqualTo("{\"type\":\"offer\",\"sdp\":\"v=0\"}");
peer.listener.localDescription("{\"type\":\"answer\",\"sdp\":\"v=0 answer\"}");
ByteBuf answer = next();
assertThat((int) answer.readUnsignedByte()).isEqualTo(0x04);
assertThat(ascii8(answer)).isEqualTo("client1");
peer.listener.iceCandidate("candidate:1 1 udp 1 10.0.0.2 5000 typ host", 0);
relay.received(signal(
0x03,
"client1",
"[{\"sdpMLineIndex\":\"0\",\"candidate\":\"candidate:9 1 udp 1 10.0.0.9 6000 typ host\"}]"));
assertThat(peer.candidates).containsExactly("0:candidate:9 1 udp 1 10.0.0.9 6000 typ host");
// Ours go once gathering is done, or a moment after theirs came.
host.tick();
assertThat(sentToRelay).isEmpty();
now += 2_001;
host.tick();
ByteBuf ours = next();
assertThat((int) ours.readUnsignedByte()).isEqualTo(0x03);
assertThat(ascii8(ours)).isEqualTo("client1");
// The guest's channel opens: the hello goes first, then the world hears the guest.
List<ByteBuffer> sentToGuest = new ArrayList<>();
NetConnection.Listener[] channel = new NetConnection.Listener[1];
peer.listener.dataChannel("lan", listener -> {
channel[0] = listener;
return new Sent(sentToGuest);
});
channel[0].connected();
assertThat(sentToGuest).hasSize(1);
assertThat(HostHello.read(sentToGuest.get(0))).isEqualTo(775);
assertThat(guests).containsExactly("client1");
channel[0].received(ByteBuffer.wrap(new byte[] {0, 1, 2}));
assertThat(heardFromGuest).containsExactly("connected", "bytes 3");
// Connected guests no longer time out.
now += 60_000;
host.tick();
assertThat(stopped).isNull();
assertThat(peer.closed).isFalse();
}
@Test
void aRelayThatGivesNoCodeStops() {
host.start();
relay.connected();
now += 16_000;
host.tick();
assertThat(stopped).isEqualTo("The relay didn't give the world a code");
}
@Test
void aGuestThatNeverConnectsIsDropped() {
host.start();
relay.connected();
relay.received(message(0x00, 0x01, 0x01, 1, 'x'));
relay.received(withAscii8(0x02, "slow"));
now += 16_000;
host.tick();
assertThat(peers.get(0).closed).isTrue();
assertThat(stopped).isNull();
}
@Test
void brokenEscapesInAGuestsCandidatesAreLeftOut() {
host.start();
relay.connected();
relay.received(message(0x00, 0x01, 0x01, 1, 'x'));
relay.received(withAscii8(0x02, "odd"));
relay.received(signal(0x03, "odd", "[{\"sdpMLineIndex\":\"0\",\"candidate\":\"a\\uZZ\\u00e9\\u12\"}]"));
assertThat(peers.get(0).candidates).containsExactly("0:aZZé12");
assertThat(peers.get(0).closed).isFalse();
}
@Test
void aGuestWhoseCandidatesCantBeTakenFailsAloneAndTheWorldStaysShared() {
host.start();
relay.connected();
relay.received(message(0x00, 0x01, 0x01, 1, 'x'));
relay.received(withAscii8(0x02, "bad"));
relay.received(withAscii8(0x02, "good"));
relay.received(signal(0x03, "bad", "[{\"sdpMLineIndex\":\"0\",\"candidate\":\"refused\"}]"));
assertThat(peers.get(0).closed).isTrue();
assertThat(stopped).isNull();
relay.received(signal(0x03, "good", "[{\"sdpMLineIndex\":\"0\",\"candidate\":\"fine\"}]"));
assertThat(peers.get(1).candidates).containsExactly("0:fine");
assertThat(peers.get(1).closed).isFalse();
}
// --- Helpers -----------------------------------------------------------------------------
private ByteBuf next() {
assertThat(sentToRelay).isNotEmpty();
return Unpooled.wrappedBuffer(sentToRelay.remove(0));
}
private static ByteBuffer message(int... bytes) {
byte[] out = new byte[bytes.length];
for (int i = 0; i < bytes.length; i++) {
out[i] = (byte) bytes[i];
}
return ByteBuffer.wrap(out);
}
private static ByteBuffer withAscii8(int id, String text) {
ByteBuf out = Unpooled.buffer();
out.writeByte(id).writeByte(text.length()).writeBytes(text.getBytes(StandardCharsets.ISO_8859_1));
return out.nioBuffer();
}
private static ByteBuffer signal(int id, String peer, String text) {
ByteBuf out = Unpooled.buffer();
out.writeByte(id).writeByte(peer.length()).writeBytes(peer.getBytes(StandardCharsets.ISO_8859_1));
byte[] bytes = text.getBytes(StandardCharsets.ISO_8859_1);
out.writeShort(bytes.length).writeBytes(bytes);
return out.nioBuffer();
}
private static String ascii8(ByteBuf in) {
int length = in.readUnsignedByte();
return in.readCharSequence(length, StandardCharsets.ISO_8859_1).toString();
}
private record Sent(List<ByteBuffer> sent) implements NetConnection {
@Override
public void send(ByteBuffer data) {
sent.add(data);
}
@Override
public void close() {}
@Override
public boolean isOpen() {
return false;
}
@Override
public String remoteDescription() {
return "fake";
}
}
private static final class Peer implements RtcPeer, RemoteVoice {
final RtcPeer.Listener listener;
String remote;
boolean closed;
final List<String> candidates = new ArrayList<>();
Peer(RtcPeer.Listener listener) {
this.listener = listener;
}
@Override
public void sendMicrophone() {}
@Override
public NetConnection openDataChannel(String label, NetConnection.Listener channelListener) {
throw new UnsupportedOperationException();
}
@Override
public void createOffer() {}
@Override
public void setRemoteDescription(String json) {
remote = json;
}
@Override
public void addIceCandidate(String candidate, int sdpMLineIndex) {
if (candidate.contains("refused")) {
// As a browser may, for a candidate it won't take.
throw new IllegalArgumentException("bad candidate");
}
candidates.add(sdpMLineIndex + ":" + candidate);
}
@Override
public RemoteVoice voice() {
return this;
}
@Override
public void close() {
closed = true;
}
@Override
public void setVolume(float volume) {}
@Override
public void setPan(float pan) {}
@Override
public float level() {
return 0;
}
}
}
@@ -0,0 +1,347 @@
package incari.net.relay;
import static org.assertj.core.api.Assertions.assertThat;
import incari.platform.api.net.NetConnection;
import incari.platform.api.net.PlatformNetwork;
import incari.platform.api.rtc.IceServer;
import incari.platform.api.rtc.Microphone;
import incari.platform.api.rtc.PlatformRtc;
import incari.platform.api.rtc.RemoteVoice;
import incari.platform.api.rtc.RtcPeer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.Test;
/** A join against a scripted relay and a fake WebRTC peer. */
class RelayJoinTest {
private long now = 1000;
private final List<ByteBuffer> sentToRelay = new ArrayList<>();
private NetConnection.@Nullable Listener relay;
private boolean relayClosed;
private final FakePeer peer = new FakePeer();
private @Nullable RelayWorldAddress joined;
private @Nullable String failed;
private final PlatformNetwork network = new PlatformNetwork() {
@Override
public NetConnection connect(String host, int port, NetConnection.Listener listener) {
throw new UnsupportedOperationException();
}
@Override
public NetConnection openWebSocket(String url, NetConnection.Listener listener) {
relay = listener;
return new FakeConnection(sentToRelay, () -> relayClosed = true);
}
};
private final PlatformRtc rtc = new PlatformRtc() {
@Override
public boolean supported() {
return true;
}
@Override
public Microphone microphone() {
throw new UnsupportedOperationException();
}
@Override
public RtcPeer createPeer(List<IceServer> iceServers, RtcPeer.Listener listener) {
peer.iceServers = iceServers;
peer.listener = listener;
return peer;
}
};
private final RelayJoin join = new RelayJoin(
network,
rtc,
"wss://relay.example",
"ABCDE",
new RelayJoin.Listener() {
@Override
public void joined(RelayWorldAddress address) {
joined = address;
}
@Override
public void failed(String reason) {
failed = reason;
}
},
() -> now);
@Test
void pairsWithTheHostAndHandsOverTheDataChannel() {
join.start();
relay.connected();
ByteBuf hello = next();
assertThat((int) hello.readUnsignedByte()).isEqualTo(0x00);
assertThat((int) hello.readUnsignedByte()).isEqualTo(0x02);
assertThat((int) hello.readUnsignedByte()).isEqualTo(1);
assertThat(ascii8(hello)).isEqualTo("ABCDE");
relay.received(message(0x00, 0x02, 0x01, 5, 'A', 'B', 'C', 'D', 'E'));
ByteBuf servers = Unpooled.buffer();
servers.writeByte(0x01).writeShort(2);
servers.writeByte('S');
ascii16(servers, "stun:stun.example:3478");
servers.writeByte(0).writeByte(0);
servers.writeByte('T');
ascii16(servers, "turn:turn.example:80");
ascii8(servers, "user");
ascii8(servers, "pass");
relay.received(servers.nioBuffer());
assertThat(peer.iceServers)
.containsExactly(
new IceServer("stun:stun.example:3478", null, null),
new IceServer("turn:turn.example:80", "user", "pass"));
assertThat(peer.channelLabel).isEqualTo("lan");
assertThat(peer.offered).isTrue();
peer.listener.localDescription("{\"type\":\"offer\",\"sdp\":\"v=0\"}");
ByteBuf offer = next();
assertThat((int) offer.readUnsignedByte()).isEqualTo(0x04);
assertThat(ascii8(offer)).isEmpty();
assertThat(bytes16(offer)).isEqualTo("{\"type\":\"offer\",\"sdp\":\"v=0\"}");
relay.received(signal(0x04, "host1", "{\"type\":\"answer\",\"sdp\":\"v=0 answer\"}"));
assertThat(peer.remote).isEqualTo("{\"type\":\"answer\",\"sdp\":\"v=0 answer\"}");
// Candidates go all at once, when gathering is done.
peer.listener.iceCandidate("candidate:1 1 udp 1 10.0.0.2 5000 typ host", 0);
peer.listener.iceCandidate("candidate:2 1 udp 1 10.0.0.3 5001 typ host", 0);
join.tick();
assertThat(sentToRelay).isEmpty();
peer.listener.iceGatheringComplete();
join.tick();
ByteBuf candidates = next();
assertThat((int) candidates.readUnsignedByte()).isEqualTo(0x03);
ascii8(candidates);
assertThat(IceJson.read(bytes16(candidates)))
.extracting(IceJson.Candidate::candidate)
.containsExactly(
"candidate:1 1 udp 1 10.0.0.2 5000 typ host", "candidate:2 1 udp 1 10.0.0.3 5001 typ host");
relay.received(signal(
0x03,
"host1",
"[{\"sdpMLineIndex\":\"0\",\"candidate\":\"candidate:9 1 udp 1 10.0.0.9 6000 typ host\"}]"));
assertThat(peer.candidates).containsExactly("0:candidate:9 1 udp 1 10.0.0.9 6000 typ host");
// The channel opens: the relay hears success, and the address takes over the channel.
peer.channelListener.connected();
ByteBuf success = next();
assertThat((int) success.readUnsignedByte()).isEqualTo(0x05);
assertThat(ascii8(success)).isEqualTo("host1");
assertThat(relayClosed).isTrue();
// A moment for an Incari host's hello; Eagler's hosts never speak first.
assertThat(joined).isNull();
now += HostHello.WAIT_MILLIS + 1;
join.tick();
assertThat(joined).isNotNull();
assertThat(joined.incariProtocol()).isEqualTo(-1);
assertThat(failed).isNull();
peer.channelListener.received(ByteBuffer.wrap(new byte[] {0, 2, 3}));
List<String> heard = new ArrayList<>();
joined.open(new NetConnection.Listener() {
@Override
public void connected() {
heard.add("connected");
}
@Override
public void received(ByteBuffer data) {
heard.add("bytes " + data.remaining());
}
@Override
public void closed(@Nullable Throwable cause) {
heard.add("closed");
}
});
assertThat(heard).containsExactly("connected", "bytes 3");
}
@Test
void anIncariHostsHelloJoinsAtOnceAndIsntPassedOn() {
reachOpenChannel();
assertThat(joined).isNull();
peer.channelListener.received(HostHello.write(775));
join.tick();
assertThat(joined).isNotNull();
assertThat(joined.incariProtocol()).isEqualTo(775);
List<String> heard = new ArrayList<>();
joined.open(new NetConnection.Listener() {
@Override
public void connected() {
heard.add("connected");
}
@Override
public void received(ByteBuffer data) {
heard.add("bytes " + data.remaining());
}
@Override
public void closed(@Nullable Throwable cause) {}
});
assertThat(heard).containsExactly("connected");
}
/** A join up to the open data channel, the relay told. */
private void reachOpenChannel() {
join.start();
relay.connected();
next();
relay.received(message(0x00, 0x02, 0x01, 5, 'A', 'B', 'C', 'D', 'E'));
ByteBuf servers = Unpooled.buffer();
servers.writeByte(0x01).writeShort(0);
relay.received(servers.nioBuffer());
peer.listener.localDescription("{\"type\":\"offer\",\"sdp\":\"v=0\"}");
next();
relay.received(signal(0x04, "host1", "{\"type\":\"answer\",\"sdp\":\"v=0\"}"));
peer.listener.iceGatheringComplete();
join.tick();
next();
relay.received(signal(0x03, "host1", "[]"));
peer.channelListener.connected();
next();
}
@Test
void aWrongCodeFailsWithTheRelaysReason() {
join.start();
relay.connected();
ByteBuf error = Unpooled.buffer();
error.writeByte(0xFF).writeByte(0x05);
ascii16(error, "Incorrect code");
relay.received(error.nioBuffer());
assertThat(failed).contains("ABCDE");
}
@Test
void aSilentRelayTimesOut() {
join.start();
now += 11_000;
join.tick();
assertThat(failed).isEqualTo("The relay didn't answer");
}
// --- Helpers -----------------------------------------------------------------------------
private ByteBuf next() {
assertThat(sentToRelay).isNotEmpty();
return Unpooled.wrappedBuffer(sentToRelay.remove(0));
}
private static ByteBuffer message(int... bytes) {
byte[] out = new byte[bytes.length];
for (int i = 0; i < bytes.length; i++) {
out[i] = (byte) bytes[i];
}
return ByteBuffer.wrap(out);
}
private static ByteBuffer signal(int id, String peer, String text) {
ByteBuf out = Unpooled.buffer();
out.writeByte(id);
ascii8(out, peer);
byte[] bytes = text.getBytes(StandardCharsets.ISO_8859_1);
out.writeShort(bytes.length).writeBytes(bytes);
return out.nioBuffer();
}
private static void ascii8(ByteBuf out, String text) {
out.writeByte(text.length()).writeBytes(text.getBytes(StandardCharsets.ISO_8859_1));
}
private static void ascii16(ByteBuf out, String text) {
out.writeShort(text.length()).writeBytes(text.getBytes(StandardCharsets.ISO_8859_1));
}
private static String ascii8(ByteBuf in) {
int length = in.readUnsignedByte();
return in.readCharSequence(length, StandardCharsets.ISO_8859_1).toString();
}
private static String bytes16(ByteBuf in) {
int length = in.readUnsignedShort();
return in.readCharSequence(length, StandardCharsets.ISO_8859_1).toString();
}
private record FakeConnection(List<ByteBuffer> sent, Runnable onClose) implements NetConnection {
@Override
public void send(ByteBuffer data) {
sent.add(data);
}
@Override
public void close() {
onClose.run();
}
@Override
public boolean isOpen() {
return true;
}
@Override
public String remoteDescription() {
return "fake";
}
}
private static final class FakePeer implements RtcPeer {
List<IceServer> iceServers = List.of();
RtcPeer.Listener listener;
NetConnection.Listener channelListener;
String channelLabel;
boolean offered;
String remote;
final List<String> candidates = new ArrayList<>();
@Override
public void sendMicrophone() {}
@Override
public NetConnection openDataChannel(String label, NetConnection.Listener listener) {
channelLabel = label;
channelListener = listener;
return new FakeConnection(new ArrayList<>(), () -> {});
}
@Override
public void createOffer() {
offered = true;
}
@Override
public void setRemoteDescription(String json) {
remote = json;
}
@Override
public void addIceCandidate(String candidate, int sdpMLineIndex) {
candidates.add(sdpMLineIndex + ":" + candidate);
}
@Override
public RemoteVoice voice() {
throw new UnsupportedOperationException();
}
@Override
public void close() {}
}
}
@@ -0,0 +1,422 @@
package incari.net.tls;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.spec.ECGenParameterSpec;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.RSAPublicKey;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.Certificate;
import org.bouncycastle.asn1.x509.ExtendedKeyUsage;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.KeyPurposeId;
import org.bouncycastle.asn1.x509.KeyUsage;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x509.Time;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class CertificateChainTest {
private static final long NOW = Instant.parse("2026-11-04T12:00:00Z").toEpochMilli();
private static KeyPair rootKey;
private static KeyPair intermediateKey;
private static KeyPair leafKey;
private static KeyPair otherKey;
private static KeyPair ecKey;
private static Certificate root;
@BeforeAll
static void keys() throws Exception {
KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA");
rsa.initialize(2048);
rootKey = rsa.generateKeyPair();
intermediateKey = rsa.generateKeyPair();
leafKey = rsa.generateKeyPair();
otherKey = rsa.generateKeyPair();
KeyPairGenerator ec = KeyPairGenerator.getInstance("EC");
ec.initialize(new ECGenParameterSpec("secp256r1"));
ecKey = ec.generateKeyPair();
root = new Spec("Test Root", "Test Root", rootKey, rootKey).ca(-1).build();
}
// --- Accepted ------------------------------------------------------------------------------
@Test
void acceptsALeafAndIntermediateUnderThePinnedRoot() {
assertThatCode(() -> chain().check("api.example.com", standard(), NOW)).doesNotThrowAnyException();
}
@Test
void acceptsAChainThatAlsoCarriesTheRoot() throws Exception {
List<byte[]> withRoot = new ArrayList<>(standard());
withRoot.add(root.getEncoded());
assertThatCode(() -> chain().check("api.example.com", withRoot, NOW)).doesNotThrowAnyException();
}
@Test
void acceptsAnEcdsaIntermediate() throws Exception {
Certificate intermediate =
new Spec("EC CA", "Test Root", ecKey, rootKey).ca(0).build();
Certificate leaf = new Spec("api.example.com", "EC CA", leafKey, ecKey)
.signedWith("SHA256withECDSA")
.build();
assertThatCode(() ->
chain().check("api.example.com", List.of(leaf.getEncoded(), intermediate.getEncoded()), NOW))
.doesNotThrowAnyException();
}
// --- Refused -------------------------------------------------------------------------------
@Test
void refusesAnotherHost() {
assertThatThrownBy(() -> chain().check("evil.example.net", standard(), NOW))
.isInstanceOf(UntrustedCertificateException.class)
.hasMessageContaining("isn't for evil.example.net");
}
@Test
void refusesAnExpiredLeaf() {
long later = Instant.parse("2031-01-01T00:00:00Z").toEpochMilli();
assertThatThrownBy(() -> chain().check("api.example.com", standard(), later))
.hasMessageContaining("out of date");
}
@Test
void refusesALeafNotYetValid() {
long earlier = Instant.parse("2020-01-01T00:00:00Z").toEpochMilli();
assertThatThrownBy(() -> chain().check("api.example.com", standard(), earlier))
.hasMessageContaining("out of date");
}
@Test
void refusesAChainUnderAnotherRoot() throws Exception {
Certificate intermediate = new Spec("Test CA", "Other Root", intermediateKey, otherKey)
.ca(0)
.build();
Certificate leaf = new Spec("api.example.com", "Test CA", leafKey, intermediateKey).build();
assertThatThrownBy(() ->
chain().check("api.example.com", List.of(leaf.getEncoded(), intermediate.getEncoded()), NOW))
.hasMessageContaining("trusted root");
}
@Test
void refusesARootNameWithAnotherKey() throws Exception {
// Claims the pinned root as issuer, but signed by a different key.
Certificate intermediate = new Spec("Test CA", "Test Root", intermediateKey, otherKey)
.ca(0)
.build();
Certificate leaf = new Spec("api.example.com", "Test CA", leafKey, intermediateKey).build();
assertThatThrownBy(() ->
chain().check("api.example.com", List.of(leaf.getEncoded(), intermediate.getEncoded()), NOW))
.hasMessageContaining("trusted root");
}
@Test
void refusesALeafSignedByANonCa() throws Exception {
Certificate notCa = new Spec("Not A CA", "Test Root", intermediateKey, rootKey).build();
Certificate leaf = new Spec("api.example.com", "Not A CA", leafKey, intermediateKey).build();
assertThatThrownBy(() -> chain().check("api.example.com", List.of(leaf.getEncoded(), notCa.getEncoded()), NOW))
.hasMessageContaining("non-CA");
}
@Test
void refusesACaWithoutCertificateSigning() throws Exception {
Certificate intermediate = new Spec("Test CA", "Test Root", intermediateKey, rootKey)
.ca(0)
.keyUsage(KeyUsage.digitalSignature)
.build();
Certificate leaf = new Spec("api.example.com", "Test CA", leafKey, intermediateKey).build();
assertThatThrownBy(() ->
chain().check("api.example.com", List.of(leaf.getEncoded(), intermediate.getEncoded()), NOW))
.hasMessageContaining("not for that");
}
@Test
void refusesAPathLongerThanItsCaAllows() throws Exception {
KeyPair second = otherKey;
Certificate top =
new Spec("Top CA", "Test Root", intermediateKey, rootKey).ca(0).build();
Certificate middle =
new Spec("Middle CA", "Top CA", second, intermediateKey).ca(-1).build();
Certificate leaf = new Spec("api.example.com", "Middle CA", leafKey, second).build();
assertThatThrownBy(() -> chain().check(
"api.example.com",
List.of(leaf.getEncoded(), middle.getEncoded(), top.getEncoded()),
NOW))
.hasMessageContaining("longer than its CA allows");
}
@Test
void refusesATamperedSignature() throws Exception {
byte[] leaf = standard().get(0);
leaf[leaf.length - 5] ^= 0x01;
List<byte[]> tampered = List.of(leaf, standard().get(1));
assertThatThrownBy(() -> chain().check("api.example.com", tampered, NOW))
.isInstanceOf(UntrustedCertificateException.class);
}
@Test
void refusesALeafForClientsOnly() throws Exception {
Certificate intermediate = intermediate();
Certificate leaf = new Spec("api.example.com", "Test CA", leafKey, intermediateKey)
.usage(KeyPurposeId.id_kp_clientAuth)
.build();
assertThatThrownBy(() ->
chain().check("api.example.com", List.of(leaf.getEncoded(), intermediate.getEncoded()), NOW))
.hasMessageContaining("isn't for servers");
}
@Test
void refusesALeafThatNamesNoPurpose() throws Exception {
Certificate intermediate = intermediate();
Certificate leaf = new Spec("api.example.com", "Test CA", leafKey, intermediateKey)
.noUsage()
.build();
assertThatThrownBy(() ->
chain().check("api.example.com", List.of(leaf.getEncoded(), intermediate.getEncoded()), NOW))
.hasMessageContaining("isn't for servers");
}
@Test
void refusesACaLimitedToCodeSigning() throws Exception {
Certificate intermediate = new Spec("Test CA", "Test Root", intermediateKey, rootKey)
.ca(0)
.caUsage(KeyPurposeId.id_kp_codeSigning)
.build();
Certificate leaf = new Spec("api.example.com", "Test CA", leafKey, intermediateKey).build();
assertThatThrownBy(() ->
chain().check("api.example.com", List.of(leaf.getEncoded(), intermediate.getEncoded()), NOW))
.hasMessageContaining("CA in the server's chain isn't for servers");
}
@Test
void refusesHugeRsaKeysBeforeDoingTheirMath() throws Exception {
Certificate leaf = new Spec("api.example.com", "Test CA", leafKey, intermediateKey).build();
AlgorithmIdentifier rsa = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE);
BigInteger huge = BigInteger.ONE.shiftLeft(16383).add(BigInteger.ONE);
SubjectPublicKeyInfo bigModulus =
new SubjectPublicKeyInfo(rsa, new RSAPublicKey(huge, BigInteger.valueOf(65537)));
assertThatThrownBy(() -> CertificateChain.verifies(leaf, bigModulus)).hasMessageContaining("too big");
BigInteger modulus = BigInteger.ONE.shiftLeft(2047).add(BigInteger.ONE);
SubjectPublicKeyInfo bigExponent = new SubjectPublicKeyInfo(rsa, new RSAPublicKey(modulus, huge));
assertThatThrownBy(() -> CertificateChain.verifies(leaf, bigExponent)).hasMessageContaining("too big");
}
@Test
void refusesAnUnknownCriticalExtension() throws Exception {
Certificate intermediate = intermediate();
Certificate leaf = new Spec("api.example.com", "Test CA", leafKey, intermediateKey)
.critical(new ASN1ObjectIdentifier("1.2.3.4.5"))
.build();
assertThatThrownBy(() ->
chain().check("api.example.com", List.of(leaf.getEncoded(), intermediate.getEncoded()), NOW))
.hasMessageContaining("unknown critical");
}
@Test
void refusesSha1Signatures() throws Exception {
Certificate intermediate = intermediate();
Certificate leaf = new Spec("api.example.com", "Test CA", leafKey, intermediateKey)
.signedWith("SHA1withRSA")
.build();
assertThatThrownBy(() ->
chain().check("api.example.com", List.of(leaf.getEncoded(), intermediate.getEncoded()), NOW))
.hasMessageContaining("unsupported signature");
}
@Test
void refusesAChainOutOfOrder() {
List<byte[]> swapped = List.of(standard().get(1), standard().get(0));
assertThatThrownBy(() -> chain().check("api.example.com", swapped, NOW))
.isInstanceOf(UntrustedCertificateException.class);
}
@Test
void refusesNothingAndRubbish() {
assertThatThrownBy(() -> chain().check("api.example.com", List.of(), NOW))
.hasMessageContaining("no certificate");
assertThatThrownBy(() -> chain().check("api.example.com", List.of(new byte[] {1, 2, 3}), NOW))
.hasMessageContaining("can't be read");
}
@Test
void refusesOverlongChains() {
List<byte[]> many = new ArrayList<>();
for (int i = 0; i <= CertificateChain.MAX_LENGTH; i++) {
many.add(standard().get(0));
}
assertThatThrownBy(() -> chain().check("api.example.com", many, NOW)).hasMessageContaining("too long");
}
// --- Names and dates -----------------------------------------------------------------------
@Test
void wildcardsCoverOneWholeLabel() {
assertThat(CertificateChain.matches("*.mojang.com", "sessionserver.mojang.com"))
.isTrue();
assertThat(CertificateChain.matches("*.mojang.com", "mojang.com")).isFalse();
assertThat(CertificateChain.matches("*.mojang.com", "a.b.mojang.com")).isFalse();
assertThat(CertificateChain.matches("*.mojang.com", "evilmojang.com")).isFalse();
assertThat(CertificateChain.matches("*.com", "mojang.com")).isFalse();
assertThat(CertificateChain.matches("s*.mojang.com", "sessionserver.mojang.com"))
.isFalse();
assertThat(CertificateChain.matches("*.*.com", "a.b.com")).isFalse();
assertThat(CertificateChain.matches("login.live.com", "login.live.com")).isTrue();
assertThat(CertificateChain.matches("login.live.com", "xlogin.live.com"))
.isFalse();
}
@Test
void readsBothDerTimeForms() throws Exception {
assertThat(CertificateChain.epochMillis(new Time(new org.bouncycastle.asn1.DERUTCTime("491231235959Z"))))
.isEqualTo(Instant.parse("2049-12-31T23:59:59Z").toEpochMilli());
assertThat(CertificateChain.epochMillis(new Time(new org.bouncycastle.asn1.DERUTCTime("500101000000Z"))))
.isEqualTo(Instant.parse("1950-01-01T00:00:00Z").toEpochMilli());
assertThat(CertificateChain.epochMillis(
new Time(new org.bouncycastle.asn1.DERGeneralizedTime("20500101000000Z"))))
.isEqualTo(Instant.parse("2050-01-01T00:00:00Z").toEpochMilli());
assertThat(CertificateChain.daysFromCivil(2024, 2, 29)).isEqualTo(19782);
}
@Test
void thePinnedRootsParse() {
assertThat(TrustAnchors.roots()).hasSize(4);
}
// --- Helpers -------------------------------------------------------------------------------
private static CertificateChain chain() {
return new CertificateChain(List.of(root));
}
private static Certificate intermediate() throws Exception {
return new Spec("Test CA", "Test Root", intermediateKey, rootKey).ca(0).build();
}
private static List<byte[]> standard() {
try {
Certificate leaf = new Spec("api.example.com", "Test CA", leafKey, intermediateKey).build();
return List.of(leaf.getEncoded(), intermediate().getEncoded());
} catch (Exception e) {
throw new AssertionError(e);
}
}
/** A certificate to build: subject, issuer, its key, the issuer's key, and the parts tests vary. */
private static final class Spec {
private final String subject;
private final String issuer;
private final KeyPair key;
private final KeyPair issuerKey;
private int pathLength = -2; // -2: not a CA
private int keyUsage = -1;
private KeyPurposeId usage = KeyPurposeId.id_kp_serverAuth;
private boolean noUsage;
private KeyPurposeId caUsage;
private ASN1ObjectIdentifier critical;
private String algorithm = "SHA256withRSA";
Spec(String subject, String issuer, KeyPair key, KeyPair issuerKey) {
this.subject = subject;
this.issuer = issuer;
this.key = key;
this.issuerKey = issuerKey;
}
/** A CA, with a path length or -1 for none. */
Spec ca(int pathLength) {
this.pathLength = pathLength;
return this;
}
Spec keyUsage(int keyUsage) {
this.keyUsage = keyUsage;
return this;
}
Spec usage(KeyPurposeId usage) {
this.usage = usage;
return this;
}
Spec noUsage() {
this.noUsage = true;
return this;
}
Spec caUsage(KeyPurposeId usage) {
this.caUsage = usage;
return this;
}
Spec critical(ASN1ObjectIdentifier oid) {
this.critical = oid;
return this;
}
Spec signedWith(String algorithm) {
this.algorithm = algorithm;
return this;
}
Certificate build() throws Exception {
Date from = Date.from(Instant.parse("2026-01-01T00:00:00Z"));
Date to = Date.from(Instant.parse("2026-01-01T00:00:00Z").plus(1500, ChronoUnit.DAYS));
X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
new X500Name("CN=" + issuer),
BigInteger.valueOf(System.nanoTime()),
from,
to,
new X500Name("CN=" + subject),
key.getPublic());
if (pathLength >= -1) {
builder.addExtension(
Extension.basicConstraints,
true,
pathLength >= 0 ? new BasicConstraints(pathLength) : new BasicConstraints(true));
builder.addExtension(
Extension.keyUsage,
true,
new KeyUsage(keyUsage >= 0 ? keyUsage : KeyUsage.keyCertSign | KeyUsage.cRLSign));
if (caUsage != null) {
builder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(caUsage));
}
} else {
builder.addExtension(
Extension.subjectAlternativeName,
false,
new GeneralNames(new GeneralName(GeneralName.dNSName, subject)));
if (!noUsage) {
builder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(usage));
}
}
if (critical != null) {
builder.addExtension(critical, true, DERNull.INSTANCE);
}
String signing = issuerKey.getPrivate().getAlgorithm().equals("EC") ? "SHA256withECDSA" : algorithm;
return builder.build(new JcaContentSignerBuilder(signing).build(issuerKey.getPrivate()))
.toASN1Structure();
}
}
}
@@ -0,0 +1,70 @@
package incari.net.tls;
import incari.platform.api.net.NetConnection;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.jspecify.annotations.Nullable;
/** A plain TCP socket as a {@link Transport}, with a reader thread, for live tests on a JVM. */
public final class SocketTransport implements Transport {
@Override
public NetConnection connect(String host, int port, NetConnection.Listener listener) {
Socket socket = new Socket();
Thread reader = new Thread(
() -> {
@Nullable Throwable failure = null;
try {
socket.connect(new InetSocketAddress(host, port), 10_000);
listener.connected();
InputStream in = socket.getInputStream();
byte[] buffer = new byte[16384];
int n;
while ((n = in.read(buffer)) >= 0) {
listener.received(ByteBuffer.wrap(Arrays.copyOf(buffer, n)));
}
} catch (IOException e) {
failure = socket.isClosed() ? null : e;
}
listener.closed(failure);
},
"socket " + host);
reader.setDaemon(true);
reader.start();
return new NetConnection() {
@Override
public void send(ByteBuffer data) {
try {
byte[] bytes = new byte[data.remaining()];
data.get(bytes);
socket.getOutputStream().write(bytes);
} catch (IOException e) {
close();
}
}
@Override
public void close() {
try {
socket.close();
} catch (IOException ignored) {
// Closing.
}
}
@Override
public boolean isOpen() {
return socket.isConnected() && !socket.isClosed();
}
@Override
public String remoteDescription() {
return host + ":" + port;
}
};
}
}
@@ -0,0 +1,268 @@
package incari.net.tls;
import static org.assertj.core.api.Assertions.assertThat;
import incari.net.https.HttpRequest;
import incari.net.https.HttpResponse;
import incari.net.https.HttpsClient;
import incari.platform.api.net.NetConnection;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSocket;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.Certificate;
import org.bouncycastle.asn1.x509.ExtendedKeyUsage;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.KeyPurposeId;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/**
* {@link TlsConnection} and {@link HttpsClient} against the JDK's own TLS server on localhost, with a
* chain made for the test: real handshakes (TLS 1.3 and 1.2), no network.
*/
class TlsConnectionTest {
private static Certificate root;
private static SSLContext serverContext;
private SSLServerSocket server;
private Thread serverThread;
@BeforeAll
static void chain() throws Exception {
KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA");
rsa.initialize(2048);
KeyPair rootKey = rsa.generateKeyPair();
KeyPair leafKey = rsa.generateKeyPair();
Date from = Date.from(Instant.now().minus(1, ChronoUnit.DAYS));
Date to = Date.from(Instant.now().plus(30, ChronoUnit.DAYS));
X509v3CertificateBuilder rootBuilder = new JcaX509v3CertificateBuilder(
new X500Name("CN=Local Root"),
BigInteger.ONE,
from,
to,
new X500Name("CN=Local Root"),
rootKey.getPublic());
rootBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
root = rootBuilder
.build(new JcaContentSignerBuilder("SHA256withRSA").build(rootKey.getPrivate()))
.toASN1Structure();
X509v3CertificateBuilder leafBuilder = new JcaX509v3CertificateBuilder(
new X500Name("CN=Local Root"),
BigInteger.TWO,
from,
to,
new X500Name("CN=localhost"),
leafKey.getPublic());
leafBuilder.addExtension(
Extension.subjectAlternativeName,
false,
new GeneralNames(new GeneralName(GeneralName.dNSName, "localhost")));
leafBuilder.addExtension(
Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));
X509Certificate leaf = new JcaX509CertificateConverter()
.getCertificate(
leafBuilder.build(new JcaContentSignerBuilder("SHA256withRSA").build(rootKey.getPrivate())));
KeyStore store = KeyStore.getInstance("PKCS12");
store.load(null, null);
store.setKeyEntry("leaf", leafKey.getPrivate(), new char[0], new X509Certificate[] {leaf});
KeyManagerFactory keys = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keys.init(store, new char[0]);
serverContext = SSLContext.getInstance("TLS");
serverContext.init(keys.getKeyManagers(), null, null);
}
@AfterEach
void stop() throws Exception {
if (server != null) {
server.close();
}
if (truncatingServer != null) {
truncatingServer.close();
}
if (serverThread != null) {
serverThread.join(5000);
}
}
@Test
void sendsARequestAndReadsTheResponseOverTls13() throws Exception {
start("TLSv1.3", "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello", true);
HttpResponse response = client("localhost").send(get()).get(10, TimeUnit.SECONDS);
assertThat(response.status()).isEqualTo(200);
assertThat(response.text()).isEqualTo("hello");
assertThat(lastRequest).startsWith("GET /path HTTP/1.1\r\nHost: localhost\r\n");
}
@Test
void worksOverTls12() throws Exception {
start("TLSv1.2", "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok", true);
assertThat(client("localhost").send(get()).get(10, TimeUnit.SECONDS).text())
.isEqualTo("ok");
}
@Test
void readsABodyThatEndsWithTheConnection() throws Exception {
start("TLSv1.3", "HTTP/1.1 200 OK\r\n\r\nuntil close", true);
assertThat(client("localhost").send(get()).get(10, TimeUnit.SECONDS).text())
.isEqualTo("until close");
}
@Test
void aBodyCutOffWithoutATlsCloseIsRefused() throws Exception {
startTruncating("HTTP/1.1 200 OK\r\n\r\npartial");
assertThat(client("localhost").send(get()))
.failsWithin(10, TimeUnit.SECONDS)
.withThrowableOfType(ExecutionException.class)
.withMessageContaining("without a TLS close");
}
@Test
void refusesAServerWhoseCertificateIsForAnotherName() throws Exception {
start("TLSv1.3", "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", true);
// The leaf names localhost; connect to the same port as 127.0.0.1's "name".
HttpsClient client = new HttpsClient(
new LoopbackTransport(port()),
Set.of("other.test"),
new CertificateChain(List.of(root)),
System::currentTimeMillis);
assertThat(client.send(HttpRequest.get("https://other.test/path", Map.of())))
.failsWithin(10, TimeUnit.SECONDS)
.withThrowableOfType(ExecutionException.class)
.withMessageContaining("isn't for other.test");
}
@Test
void refusesAServerUnderAnUnpinnedRoot() throws Exception {
start("TLSv1.3", "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", true);
HttpsClient client = HttpsClient.pinned(new LoopbackTransport(port()), Set.of("localhost"));
assertThat(client.send(get()))
.failsWithin(10, TimeUnit.SECONDS)
.withThrowableOfType(ExecutionException.class)
.withMessageContaining("trusted root");
}
// --- Helpers -------------------------------------------------------------------------------
private volatile String lastRequest = "";
private static HttpRequest get() {
return HttpRequest.get("https://localhost/path", Map.of());
}
private HttpsClient client(String host) {
return new HttpsClient(
new LoopbackTransport(port()),
Set.of(host),
new CertificateChain(List.of(root)),
System::currentTimeMillis);
}
private int port() {
return truncatingServer != null ? truncatingServer.getLocalPort() : server.getLocalPort();
}
/** Serves one connection: reads the request head, writes {@code response}, closes. */
private void start(String protocol, String response, boolean closeAfter) throws Exception {
server = (SSLServerSocket) serverContext.getServerSocketFactory().createServerSocket(0);
server.setEnabledProtocols(new String[] {protocol});
serverThread = new Thread(() -> {
try (SSLSocket socket = (SSLSocket) server.accept()) {
InputStream in = socket.getInputStream();
ByteArrayOutputStream head = new ByteArrayOutputStream();
while (!head.toString(StandardCharsets.US_ASCII).endsWith("\r\n\r\n")) {
int b = in.read();
if (b < 0) {
return;
}
head.write(b);
}
lastRequest = head.toString(StandardCharsets.US_ASCII);
OutputStream out = socket.getOutputStream();
out.write(response.getBytes(StandardCharsets.US_ASCII));
out.flush();
if (closeAfter) {
socket.shutdownOutput(); // Sends close_notify.
}
} catch (Exception e) {
// The client may hang up first in the failure tests.
}
});
serverThread.setDaemon(true);
serverThread.start();
}
/**
* Serves one connection, then drops the TCP connection under TLS without a close_notify, as a
* hostile proxy cutting the response short would.
*/
private void startTruncating(String response) throws Exception {
java.net.ServerSocket plain = new java.net.ServerSocket(0);
server = (SSLServerSocket) serverContext.getServerSocketFactory().createServerSocket(0);
server.close();
truncatingServer = plain;
serverThread = new Thread(() -> {
try (java.net.Socket raw = plain.accept()) {
SSLSocket tls =
(SSLSocket) serverContext.getSocketFactory().createSocket(raw, null, raw.getPort(), false);
tls.setUseClientMode(false);
InputStream in = tls.getInputStream();
ByteArrayOutputStream head = new ByteArrayOutputStream();
while (!head.toString(StandardCharsets.US_ASCII).endsWith("\r\n\r\n")) {
int b = in.read();
if (b < 0) {
return;
}
head.write(b);
}
tls.getOutputStream().write(response.getBytes(StandardCharsets.US_ASCII));
tls.getOutputStream().flush();
// The raw socket closes here, with no TLS close_notify.
} catch (Exception e) {
// The client hangs up.
}
});
serverThread.setDaemon(true);
serverThread.start();
}
private java.net.ServerSocket truncatingServer;
/** Connects every host name to the local server's port. */
private record LoopbackTransport(int port) implements Transport {
@Override
public NetConnection connect(String host, int ignoredPort, NetConnection.Listener listener) {
return new SocketTransport().connect("127.0.0.1", port, listener);
}
}
}
@@ -0,0 +1,123 @@
package incari.net.wisp;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Test;
class SrvLookupTest {
@Test
void asksForTheMinecraftRecord() {
byte[] query = SrvLookup.query("_minecraft._tcp.example.com", 0x1234);
ByteBuffer in = ByteBuffer.wrap(query);
assertThat(in.getShort() & 0xFFFF).isEqualTo(query.length - 2);
assertThat(in.getShort() & 0xFFFF).isEqualTo(0x1234);
in.position(14);
assertThat(in.get()).isEqualTo((byte) 10);
assertThat(new String(query, 15, 10, StandardCharsets.US_ASCII)).isEqualTo("_minecraft");
assertThat(query[query.length - 3]).isEqualTo((byte) 33); // SRV
}
@Test
void readsTheTargetThroughNameCompression() {
byte[] reply = reply(7, "_minecraft._tcp.example.com", 0, 5, 25599, "play.example.com");
assertThat(SrvLookup.parse(reply, 7)).isEqualTo(new SrvLookup.Target("play.example.com", 25599));
}
@Test
void picksTheLowestPriority() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
header(out, 7, 2);
question(out, "_minecraft._tcp.example.com");
answer(out, 10, 0, 1111, "backup.example.com");
answer(out, 1, 0, 2222, "main.example.com");
assertThat(SrvLookup.parse(out.toByteArray(), 7)).isEqualTo(new SrvLookup.Target("main.example.com", 2222));
}
@Test
void noRecordOrAnotherQueryGivesNothing() {
ByteArrayOutputStream empty = new ByteArrayOutputStream();
header(empty, 7, 0);
question(empty, "_minecraft._tcp.example.com");
assertThat(SrvLookup.parse(empty.toByteArray(), 7)).isNull();
assertThat(SrvLookup.parse(reply(8, "_minecraft._tcp.a.com", 0, 0, 1, "b.com"), 7))
.isNull();
assertThat(SrvLookup.parse(new byte[] {0, 7, (byte) 0x81}, 7)).isNull();
}
@Test
void hostsThatCantBeNamedSkipTheLookup() {
assertThat(SrvLookup.recordName("example.com")).isEqualTo("_minecraft._tcp.example.com");
assertThat(SrvLookup.recordName("a".repeat(64) + ".com")).isNull();
assertThat(SrvLookup.recordName("example..com")).isNull();
}
@Test
void onlyHostNamesOnTheDefaultPortLookUpSrv() {
var proxy = incari.net.WebSocketUrl.parse("wss://w.example/");
assertThat(new WispAddress(proxy, "example.com", 25565).lookUpSrv()).isTrue();
assertThat(new WispAddress(proxy, "example.com", 25566).lookUpSrv()).isFalse();
assertThat(new WispAddress(proxy, "203.0.113.4", 25565).lookUpSrv()).isFalse();
assertThat(new WispAddress(proxy, "2001:db8::1", 25565).lookUpSrv()).isFalse();
}
/** A reply with one SRV answer whose name points back at the question's. */
static byte[] reply(int id, String name, int priority, int weight, int port, String target) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
header(out, id, 1);
question(out, name);
answer(out, priority, weight, port, target);
return out.toByteArray();
}
private static void header(ByteArrayOutputStream out, int id, int answers) {
short16(out, id);
short16(out, 0x8180);
short16(out, 1);
short16(out, answers);
short16(out, 0);
short16(out, 0);
}
private static void question(ByteArrayOutputStream out, String name) {
name(out, name);
short16(out, 33);
short16(out, 1);
}
private static void answer(ByteArrayOutputStream out, int priority, int weight, int port, String target) {
out.write(0xC0); // the question's name, at offset 12
out.write(12);
short16(out, 33);
short16(out, 1);
short16(out, 0);
short16(out, 300);
ByteArrayOutputStream data = new ByteArrayOutputStream();
short16(data, priority);
short16(data, weight);
short16(data, port);
name(data, target);
short16(out, data.size());
out.writeBytes(data.toByteArray());
}
private static void name(ByteArrayOutputStream out, String name) {
for (String label : name.split("\\.", -1)) {
out.write(label.length());
out.writeBytes(label.getBytes(StandardCharsets.US_ASCII));
}
out.write(0);
}
private static void short16(ByteArrayOutputStream out, int value) {
out.write(value >>> 8);
out.write(value);
}
}
@@ -0,0 +1,286 @@
package incari.net.wisp;
import static org.assertj.core.api.Assertions.assertThat;
import incari.net.WebSocketUrl;
import incari.platform.api.net.NetConnection;
import incari.platform.api.net.PlatformNetwork;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.Test;
class WispConnectionTest {
private static final WebSocketUrl PROXY = WebSocketUrl.parse("wss://wisp.example.net/");
private final FakeProxy proxy = new FakeProxy();
private final Heard heard = new Heard();
@Test
void opensAStreamToTheServerAfterTheFirstContinue() {
NetConnection connection = WispConnection.open(proxy, new WispAddress(PROXY, "mc.example.com", 25570), heard);
assertThat(proxy.url).isEqualTo("wss://wisp.example.net/");
assertThat(proxy.sent).isEmpty();
proxy.deliver(packet(3, 0, le32(4)));
assertThat(heard.connected).isTrue();
assertThat(connection.isOpen()).isTrue();
assertThat(proxy.sent).hasSize(1);
ByteBuffer connect = proxy.sent.getFirst();
assertThat(connect.get()).isEqualTo((byte) 1);
assertThat(connect.getInt()).isEqualTo(1);
assertThat(connect.get()).isEqualTo((byte) 1); // TCP
assertThat(connect.getShort() & 0xFFFF).isEqualTo(25570);
assertThat(rest(connect)).isEqualTo("mc.example.com");
}
@Test
void sendsWhatAFlushGathersAsOneDataPacket() {
NetConnection connection = WispConnection.open(proxy, new WispAddress(PROXY, "10.0.0.2", 25565), heard);
proxy.deliver(packet(3, 0, le32(4)));
proxy.sent.clear();
connection.send(ascii("ab"));
connection.send(ascii("cd"));
assertThat(proxy.sent).isEmpty();
connection.flush();
assertThat(proxy.sent).hasSize(1);
ByteBuffer data = proxy.sent.getFirst();
assertThat(data.get()).isEqualTo((byte) 2);
assertThat(data.getInt()).isEqualTo(1);
assertThat(rest(data)).isEqualTo("abcd");
}
@Test
void waitsForTheProxyToGrantMorePackets() {
NetConnection connection = WispConnection.open(proxy, new WispAddress(PROXY, "10.0.0.2", 25565), heard);
proxy.deliver(packet(3, 0, le32(1)));
proxy.sent.clear();
connection.send(ascii("one"));
connection.flush();
connection.send(ascii("two"));
connection.flush();
assertThat(proxy.sent).hasSize(1);
proxy.deliver(packet(3, 1, le32(8)));
assertThat(proxy.sent).hasSize(2);
ByteBuffer second = proxy.sent.get(1);
second.position(5);
assertThat(rest(second)).isEqualTo("two");
}
@Test
void passesTheServersBytesUp() {
WispConnection.open(proxy, new WispAddress(PROXY, "10.0.0.2", 25565), heard);
proxy.deliver(packet(3, 0, le32(4)));
proxy.deliver(packet(2, 1, "hello".getBytes(StandardCharsets.US_ASCII)));
assertThat(heard.received).containsExactly("hello");
}
@Test
void aRefusedStreamClosesWithTheProxysReason() {
WispConnection.open(proxy, new WispAddress(PROXY, "10.0.0.2", 25565), heard);
proxy.deliver(packet(3, 0, le32(4)));
proxy.deliver(packet(4, 1, new byte[] {0x44}));
assertThat(heard.closed).isTrue();
assertThat(heard.cause).hasMessageContaining("refused");
assertThat(proxy.open).isFalse();
}
@Test
void anUnreachableProxyFailsTheConnection() {
WispConnection.open(proxy, new WispAddress(PROXY, "10.0.0.2", 25565), heard);
proxy.listener.closed(null);
assertThat(heard.connected).isFalse();
assertThat(heard.cause).hasMessageContaining("wisp.example.net");
}
@Test
void closingSendsCloseAndTellsTheListenerOnce() {
NetConnection connection = WispConnection.open(proxy, new WispAddress(PROXY, "10.0.0.2", 25565), heard);
proxy.deliver(packet(3, 0, le32(4)));
proxy.sent.clear();
connection.close();
proxy.listener.closed(null);
assertThat(proxy.sent).hasSize(1);
assertThat(proxy.sent.getFirst().get()).isEqualTo((byte) 4);
assertThat(heard.closedCount).isEqualTo(1);
assertThat(heard.cause).isNull();
}
@Test
void followsTheServersSrvRecord() {
WispConnection.open(proxy, new WispAddress(PROXY, "example.com", 25565), heard);
proxy.deliver(packet(3, 0, le32(4)));
// The lookup: a stream to the resolver and the query on it.
assertThat(heard.connected).isFalse();
assertThat(proxy.sent).hasSize(2);
ByteBuffer connect = proxy.sent.getFirst();
connect.position(5);
connect.get();
assertThat(connect.getShort() & 0xFFFF).isEqualTo(53);
assertThat(rest(connect)).isEqualTo("1.1.1.1");
ByteBuffer query = proxy.sent.get(1);
query.position(5);
byte[] framed = new byte[query.remaining()];
query.get(framed);
int id = ((framed[2] & 0xFF) << 8) | (framed[3] & 0xFF);
proxy.sent.clear();
byte[] reply = SrvLookupTest.reply(id, "_minecraft._tcp.example.com", 0, 5, 25599, "play.example.com");
ByteBuffer replyFramed = ByteBuffer.allocate(2 + reply.length)
.putShort((short) reply.length)
.put(reply);
byte[] whole = replyFramed.array();
// In two pieces, as TCP may deliver it.
proxy.deliver(packet(2, 2, java.util.Arrays.copyOfRange(whole, 0, 7)));
proxy.deliver(packet(2, 2, java.util.Arrays.copyOfRange(whole, 7, whole.length)));
assertThat(heard.connected).isTrue();
ByteBuffer game =
proxy.sent.stream().filter(p -> p.get(0) == 1).findFirst().orElseThrow();
game.position(5);
game.get();
assertThat(game.getShort() & 0xFFFF).isEqualTo(25599);
assertThat(rest(game)).isEqualTo("play.example.com");
}
@Test
void noSrvAnswerJoinsTheAddressAsWritten() {
WispConnection.open(proxy, new WispAddress(PROXY, "example.com", 25565), heard);
proxy.deliver(packet(3, 0, le32(4)));
proxy.sent.clear();
proxy.deliver(packet(4, 2, new byte[] {0x42}));
assertThat(heard.connected).isTrue();
ByteBuffer game = proxy.sent.getFirst();
game.position(8);
assertThat(rest(game)).isEqualTo("example.com");
}
private static ByteBuffer packet(int type, int stream, byte[] payload) {
ByteBuffer packet = ByteBuffer.allocate(5 + payload.length).order(ByteOrder.LITTLE_ENDIAN);
packet.put((byte) type).putInt(stream).put(payload);
return packet.flip();
}
private static byte[] le32(int value) {
return ByteBuffer.allocate(4)
.order(ByteOrder.LITTLE_ENDIAN)
.putInt(value)
.array();
}
private static ByteBuffer ascii(String text) {
return ByteBuffer.wrap(text.getBytes(StandardCharsets.US_ASCII));
}
private static String rest(ByteBuffer buffer) {
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
return new String(bytes, StandardCharsets.UTF_8);
}
/** The platform's WebSocket to the proxy, played by the test. */
private static final class FakeProxy implements PlatformNetwork, NetConnection {
@Nullable
String url;
@Nullable
Listener listener;
boolean open = true;
final List<ByteBuffer> sent = new ArrayList<>();
@Override
public NetConnection connect(String host, int port, Listener listener) {
throw new UnsupportedOperationException();
}
@Override
public NetConnection openWebSocket(String url, Listener listener) {
this.url = url;
this.listener = listener;
listener.connected();
return this;
}
void deliver(ByteBuffer message) {
listener.received(message);
}
@Override
public void send(ByteBuffer data) {
sent.add(data.duplicate().order(ByteOrder.LITTLE_ENDIAN));
}
@Override
public void close() {
open = false;
}
@Override
public boolean isOpen() {
return open;
}
@Override
public String remoteDescription() {
return String.valueOf(url);
}
}
private static final class Heard implements NetConnection.Listener {
boolean connected;
boolean closed;
int closedCount;
@Nullable
Throwable cause;
final List<String> received = new ArrayList<>();
@Override
public void connected() {
connected = true;
}
@Override
public void received(ByteBuffer data) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
while (data.hasRemaining()) {
bytes.write(data.get());
}
received.add(bytes.toString(StandardCharsets.US_ASCII));
}
@Override
public void closed(@Nullable Throwable cause) {
closed = true;
closedCount++;
this.cause = cause;
}
}
}