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
@@ -0,0 +1,230 @@
package incari.tools.wsbridge;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoop;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import javax.imageio.ImageIO;
import org.jspecify.annotations.Nullable;
/**
* The backend's vanilla status (the server list ping), turned into the MOTD answer an Eagler
* server gives a query ({@code Accept: motd}): up to two MOTD lines in legacy formatting, player
* counts and names, the icon as 64x64 RGBA pixels, and (an Incari extension, which Eagler servers
* don't send) the backend's protocol version, so the client's automatic version choice finds it.
*/
// Writes and closes are fire-and-forget: a failed one closes its channel, which fails the future.
@SuppressWarnings("FutureReturnValueIgnored")
final class BackendStatus {
private BackendStatus() {}
/** The Eagler MOTD for the server at {@code target}; fails if it doesn't answer. */
static CompletableFuture<Motd> query(EventLoop loop, InetSocketAddress target) {
CompletableFuture<Motd> result = new CompletableFuture<>();
new Bootstrap()
.group(loop)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel channel) {
channel.pipeline().addLast(new VarIntFrames.Splitter(), new StatusReader(result));
}
})
.connect(target)
.addListener((ChannelFutureListener) future -> {
if (!future.isSuccess()) {
result.completeExceptionally(future.cause());
return;
}
Channel channel = future.channel();
ByteBuf handshake = channel.alloc().buffer();
Packets.writeVarInt(handshake, 0x00);
Packets.writeVarInt(handshake, -1); // any version: the answer is the same
Packets.writeString(handshake, target.getHostString());
handshake.writeShort(target.getPort());
Packets.writeVarInt(handshake, 1); // status
channel.write(framed(channel, handshake));
ByteBuf request = channel.alloc().buffer(1);
Packets.writeVarInt(request, 0x00);
channel.writeAndFlush(framed(channel, request));
});
return result;
}
private static ByteBuf framed(Channel channel, ByteBuf packet) {
ByteBuf out = channel.alloc().buffer(packet.readableBytes() + 3);
VarIntFrames.writeLength(out, packet.readableBytes());
out.writeBytes(packet);
packet.release();
return out;
}
/** The parts of the MOTD answer. The icon is only ever read, to send it. */
@SuppressWarnings("ArrayRecordComponent")
record Motd(List<String> lines, int online, int max, List<String> players, byte @Nullable [] icon, int protocol) {
JsonObject toJson() {
JsonObject data = new JsonObject();
data.addProperty("cache", false);
JsonArray motd = new JsonArray();
lines.forEach(motd::add);
data.add("motd", motd);
data.addProperty("icon", icon != null);
data.addProperty("online", online);
data.addProperty("max", max);
JsonArray names = new JsonArray();
players.forEach(names::add);
data.add("players", names);
data.addProperty("protocol", protocol);
return data;
}
}
private static final class StatusReader extends ChannelInboundHandlerAdapter {
private final CompletableFuture<Motd> result;
StatusReader(CompletableFuture<Motd> result) {
this.result = result;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object message) {
ByteBuf packet = (ByteBuf) message;
try {
if (Packets.readVarInt(packet) == 0x00) {
result.complete(parse(Packets.readString(packet)));
}
} catch (RuntimeException | IOException e) {
result.completeExceptionally(e);
} finally {
packet.release();
ctx.close();
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
result.completeExceptionally(new IOException("The server closed without a status"));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
result.completeExceptionally(cause);
ctx.close();
}
}
static Motd parse(String json) throws IOException {
JsonObject status = JsonParser.parseString(json).getAsJsonObject();
StringBuilder text = new StringBuilder();
if (status.has("description")) {
appendLegacy(text, status.get("description"));
}
List<String> lines = new ArrayList<>();
for (String line : text.toString().split("\n", -1)) {
if (lines.size() < 2) {
lines.add(line);
}
}
int online = 0;
int max = 0;
List<String> names = new ArrayList<>();
if (status.has("players")) {
JsonObject players = status.getAsJsonObject("players");
online = players.get("online").getAsInt();
max = players.get("max").getAsInt();
if (players.has("sample")) {
for (JsonElement sample : players.getAsJsonArray("sample")) {
names.add(sample.getAsJsonObject().get("name").getAsString());
}
}
}
int protocol = status.has("version")
? status.getAsJsonObject("version").get("protocol").getAsInt()
: -1;
byte[] icon = status.has("favicon") ? icon(status.get("favicon").getAsString()) : null;
return new Motd(lines, online, max, names, icon, protocol);
}
/** Text components flattened to legacy formatting codes, as Eagler MOTDs are written. */
private static void appendLegacy(StringBuilder out, JsonElement component) {
if (component.isJsonPrimitive()) {
out.append(component.getAsString());
return;
}
if (component.isJsonArray()) {
for (JsonElement part : component.getAsJsonArray()) {
appendLegacy(out, part);
}
return;
}
JsonObject object = component.getAsJsonObject();
if (object.has("color")) {
String code = colorCode(object.get("color").getAsString());
if (code != null) {
out.append('§').append(code);
}
}
if (object.has("text")) {
out.append(object.get("text").getAsString());
}
if (object.has("extra")) {
appendLegacy(out, object.get("extra"));
}
}
private static @Nullable String colorCode(String name) {
String[] names = {
"black", "dark_blue", "dark_green", "dark_aqua", "dark_red", "dark_purple", "gold", "gray",
"dark_gray", "blue", "green", "aqua", "red", "light_purple", "yellow", "white"
};
for (int i = 0; i < names.length; i++) {
if (names[i].equals(name)) {
return Integer.toHexString(i);
}
}
return null;
}
/** A {@code data:image/png;base64,...} favicon as 64x64 RGBA bytes. */
private static byte @Nullable [] icon(String favicon) throws IOException {
int comma = favicon.indexOf(',');
if (comma < 0) {
return null;
}
BufferedImage image =
ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(favicon.substring(comma + 1))));
if (image == null || image.getWidth() != 64 || image.getHeight() != 64) {
return null;
}
byte[] rgba = new byte[64 * 64 * 4];
for (int i = 0; i < 64 * 64; i++) {
int argb = image.getRGB(i % 64, i / 64);
rgba[i * 4] = (byte) (argb >>> 16);
rgba[i * 4 + 1] = (byte) (argb >>> 8);
rgba[i * 4 + 2] = (byte) argb;
rgba[i * 4 + 3] = (byte) (argb >>> 24);
}
return rgba;
}
}
@@ -0,0 +1,73 @@
package incari.tools.wsbridge;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.handler.codec.DecoderException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
/**
* The Java protocol's packet compression, on the bridge's link to the server: once the server
* sets a threshold, each packet starts with its uncompressed length as a VarInt, 0 meaning "sent
* as is"; longer ones are zlib-compressed.
*/
final class Compression {
private Compression() {}
static ByteBuf decompress(ByteBufAllocator alloc, ByteBuf packet) {
int length = Packets.readVarInt(packet);
if (length == 0) {
return packet.retainedSlice();
}
byte[] input = new byte[packet.readableBytes()];
packet.readBytes(input);
Inflater inflater = new Inflater();
try {
inflater.setInput(input);
byte[] output = new byte[length];
int done = 0;
while (done < length && !inflater.finished()) {
int inflated = inflater.inflate(output, done, length - done);
if (inflated == 0 && inflater.needsInput()) {
break;
}
done += inflated;
}
if (done != length) {
throw new DecoderException("A compressed packet was " + done + " bytes, not " + length);
}
return alloc.buffer(length).writeBytes(output);
} catch (DataFormatException e) {
throw new DecoderException("A malformed compressed packet", e);
} finally {
inflater.end();
}
}
static ByteBuf compress(ByteBufAllocator alloc, ByteBuf packet, int threshold) {
int length = packet.readableBytes();
ByteBuf out = alloc.buffer(length + 5);
if (length < threshold) {
Packets.writeVarInt(out, 0);
out.writeBytes(packet, packet.readerIndex(), length);
return out;
}
byte[] input = new byte[length];
packet.getBytes(packet.readerIndex(), input);
Deflater deflater = new Deflater();
try {
deflater.setInput(input);
deflater.finish();
Packets.writeVarInt(out, length);
byte[] buffer = new byte[8192];
while (!deflater.finished()) {
out.writeBytes(buffer, 0, deflater.deflate(buffer));
}
return out;
} finally {
deflater.end();
}
}
}
@@ -0,0 +1,337 @@
package incari.tools.wsbridge;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketCloseStatus;
import java.net.InetSocketAddress;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.UUID;
import java.util.function.Consumer;
import org.jspecify.annotations.Nullable;
/**
* The server side of one Eagler connection, as EaglerXServer runs it: Eagler's handshake with the
* client over the WebSocket, then a vanilla login to the Java server over TCP (the handshake and
* Login Start in the version the client asked for), then packets both ways. Everything runs on the
* WebSocket's event loop. Eagler's own messages from the client ({@code 0xEE}: skin requests) are
* dropped: the bridge has no skins to give.
*/
// Writes and closes are fire-and-forget: a failed one closes its channel, which is logged.
@SuppressWarnings("FutureReturnValueIgnored")
final class EaglerConnection {
private static final int CLIENT_VERSION = 0x01;
private static final int SERVER_VERSION = 0x02;
private static final int VERSION_MISMATCH = 0x03;
private static final int CLIENT_REQUEST_LOGIN = 0x04;
private static final int SERVER_ALLOW_LOGIN = 0x05;
private static final int CLIENT_PROFILE_DATA = 0x07;
private static final int CLIENT_FINISH_LOGIN = 0x08;
private static final int SERVER_FINISH_LOGIN = 0x09;
private static final int SERVER_ERROR = 0xFF;
private static final int ERROR_CUSTOM_MESSAGE = 0x08;
/** 1.20.2: the client acknowledges its login before configuration. */
private static final int LOGIN_ACKNOWLEDGED = 764;
private enum State {
AWAITING_VERSION,
AWAITING_LOGIN,
LOGGING_IN,
AWAITING_FINISH,
PLAY,
CLOSED
}
private final Channel webSocket;
private final InetSocketAddress target;
private final int id;
private final Consumer<String> log;
/** The server's packets between its Login Success and the client's finish. */
private final Queue<ByteBuf> held = new ArrayDeque<>();
private State state = State.AWAITING_VERSION;
private int protocol;
private @Nullable Channel tcp;
/** The server's compression threshold once it turns compression on; -1 while it's off. */
private int compression = -1;
EaglerConnection(Channel webSocket, InetSocketAddress target, int id, Consumer<String> log) {
this.webSocket = webSocket;
this.target = target;
this.id = id;
this.log = log;
}
/** One binary message from the client. */
void fromClient(ByteBuf message) {
try {
switch (state) {
case AWAITING_VERSION -> clientVersion(message);
case AWAITING_LOGIN -> requestLogin(message);
case AWAITING_FINISH -> finishing(message);
case PLAY -> play(message);
default -> {
// Logging in to the server, or closed: the client has nothing to say yet.
}
}
} catch (IndexOutOfBoundsException e) {
error("Invalid Packet");
}
}
void close() {
state = State.CLOSED;
while (!held.isEmpty()) {
held.remove().release();
}
if (tcp != null) {
tcp.close();
}
}
private void clientVersion(ByteBuf in) {
if (in.readUnsignedByte() != CLIENT_VERSION || in.readUnsignedByte() != 0x02) {
log.accept("#" + id + " not an Eagler V2+ client");
webSocket.close();
return;
}
boolean v5 = false;
for (int i = in.readUnsignedShort(); i > 0; i--) {
v5 |= in.readUnsignedShort() == 5;
}
int best = -1;
for (int i = in.readUnsignedShort(); i > 0; i--) {
best = Math.max(best, in.readUnsignedShort());
}
String brand = Packets.readByteAscii(in);
String version = Packets.readByteAscii(in);
if (!v5 || best < 0) {
ByteBuf out = webSocket.alloc().buffer();
out.writeByte(VERSION_MISMATCH);
out.writeShort(1);
out.writeShort(5);
out.writeShort(2);
out.writeShort(0);
out.writeShort(0xFFFF);
Packets.writeByteAscii(out, "This bridge speaks Eagler protocol V5 only");
send(out);
WebSocketBridge.closeWebSocket(webSocket, WebSocketCloseStatus.NORMAL_CLOSURE);
return;
}
protocol = best;
log.accept("#" + id + " Eagler client " + brand + " " + version + ", Minecraft protocol " + protocol);
ByteBuf out = webSocket.alloc().buffer();
out.writeByte(SERVER_VERSION);
out.writeShort(5);
out.writeShort(protocol);
Packets.writeByteAscii(out, "incari-wsbridge");
Packets.writeByteAscii(out, "dev");
out.writeByte(0); // no auth
out.writeShort(0);
out.writeBoolean(false);
send(out);
state = State.AWAITING_LOGIN;
}
private void requestLogin(ByteBuf in) {
if (in.readUnsignedByte() != CLIENT_REQUEST_LOGIN) {
error("Wrong Request Login Packet");
return;
}
String name = Packets.readByteAscii(in);
if (!name.matches("[A-Za-z0-9_]{3,16}")) {
error("Invalid Username");
return;
}
state = State.LOGGING_IN;
UUID uuid = Packets.offlineUuid(name);
tcp = new Bootstrap()
.group(webSocket.eventLoop())
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel channel) {
channel.pipeline().addLast(new VarIntFrames.Splitter(), new ServerSide());
}
})
.connect(target)
.addListener((ChannelFutureListener) future -> {
if (!future.isSuccess()) {
log.accept("#" + id + " can't reach " + target + ": " + future.cause());
error("Can't reach the server");
return;
}
Channel server = future.channel();
ByteBuf handshake = server.alloc().buffer();
Packets.writeVarInt(handshake, 0x00);
Packets.writeVarInt(handshake, protocol);
Packets.writeString(handshake, target.getHostString());
handshake.writeShort(target.getPort());
Packets.writeVarInt(handshake, 2); // login
toServer(handshake);
ByteBuf start = server.alloc().buffer();
Packets.writeVarInt(start, 0x00);
Packets.writeString(start, name);
if (protocol >= LOGIN_ACKNOWLEDGED) {
Packets.writeUuid(start, uuid);
}
toServer(start);
})
.channel();
}
/** The server accepted the login: the client may finish its own. */
private void loggedIn(String name, UUID uuid) {
state = State.AWAITING_FINISH;
ByteBuf out = webSocket.alloc().buffer();
out.writeByte(SERVER_ALLOW_LOGIN);
Packets.writeByteAscii(out, name);
Packets.writeUuid(out, uuid);
Packets.writeVarInt(out, 0); // no capabilities
out.writeByte(0);
send(out);
}
private void finishing(ByteBuf in) {
switch (in.readUnsignedByte()) {
case CLIENT_PROFILE_DATA -> {
// A skin and a cape, which the bridge has no one to show to.
}
case CLIENT_FINISH_LOGIN -> {
if (protocol >= LOGIN_ACKNOWLEDGED) {
ByteBuf acknowledged = webSocket.alloc().buffer(1);
Packets.writeVarInt(acknowledged, 0x03);
toServer(acknowledged);
}
ByteBuf out = webSocket.alloc().buffer(1);
out.writeByte(SERVER_FINISH_LOGIN);
send(out);
state = State.PLAY;
while (!held.isEmpty()) {
webSocket.write(new BinaryWebSocketFrame(held.remove()));
}
webSocket.flush();
}
default -> error("Wrong Packet");
}
}
private void play(ByteBuf packet) {
if (packet.getUnsignedByte(packet.readerIndex()) == 0xEE) {
return;
}
toServer(packet.retain());
}
private void toServer(ByteBuf packet) {
Channel server = tcp;
if (server == null) {
packet.release();
return;
}
ByteBuf out = server.alloc().buffer(packet.readableBytes() + 8);
if (compression >= 0) {
ByteBuf body = Compression.compress(server.alloc(), packet, compression);
VarIntFrames.writeLength(out, body.readableBytes());
out.writeBytes(body);
body.release();
} else {
VarIntFrames.writeLength(out, packet.readableBytes());
out.writeBytes(packet);
}
packet.release();
server.writeAndFlush(out);
}
private void send(ByteBuf message) {
webSocket.writeAndFlush(new BinaryWebSocketFrame(message));
}
/** Refuses the client with {@code message}, which it shows as the reason. */
private void error(String message) {
if (state == State.CLOSED) {
return;
}
log.accept("#" + id + " refused: " + message);
ByteBuf out = webSocket.alloc().buffer();
out.writeByte(SERVER_ERROR);
out.writeByte(ERROR_CUSTOM_MESSAGE);
Packets.writeShortUtf8(out, message);
webSocket.writeAndFlush(new BinaryWebSocketFrame(out));
WebSocketBridge.closeWebSocket(webSocket, WebSocketCloseStatus.NORMAL_CLOSURE);
close();
}
/** The Java server's side: its login, then its packets as messages. */
private final class ServerSide extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object message) {
ByteBuf packet = (ByteBuf) message;
if (compression >= 0) {
ByteBuf inflated = Compression.decompress(ctx.alloc(), packet);
packet.release();
packet = inflated;
}
if (state == State.PLAY) {
webSocket.writeAndFlush(new BinaryWebSocketFrame(packet));
return;
}
if (state == State.AWAITING_FINISH) {
held.add(packet);
return;
}
try {
login(packet);
} catch (IndexOutOfBoundsException e) {
error("The server sent a malformed login packet");
} finally {
packet.release();
}
}
private void login(ByteBuf packet) {
int id = Packets.readVarInt(packet);
switch (id) {
case 0x00 -> error(Packets.readString(packet));
case 0x01 -> error("The server is in online mode; the bridge needs online-mode=false");
case 0x02 -> {
UUID uuid;
if (protocol >= 735) {
uuid = new UUID(packet.readLong(), packet.readLong());
} else {
uuid = UUID.fromString(Packets.readString(packet));
}
loggedIn(Packets.readString(packet), uuid);
}
// Set Compression: the link to the server is compressed from here; the client's isn't.
case 0x03 -> compression = Packets.readVarInt(packet);
default -> error("The server sent login packet " + id + ", which the bridge doesn't handle");
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
log.accept("#" + id + " server closed the connection");
WebSocketBridge.closeWebSocket(webSocket, WebSocketCloseStatus.NORMAL_CLOSURE);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
log.accept("#" + id + " server connection error: " + cause);
ctx.close();
}
}
}
@@ -0,0 +1,42 @@
package incari.tools.wsbridge;
import java.net.InetSocketAddress;
import java.util.concurrent.CountDownLatch;
/**
* {@code incari-wsbridge [--bind 127.0.0.1] [--listen 8816] [--target 127.0.0.1:25565]}: bridges
* WebSocket clients on {@code --listen} to a Java server at {@code --target}. Runs until killed.
* Binds to the loopback interface unless told otherwise; it's a development tool.
*/
public final class Main {
private Main() {}
public static void main(String[] args) throws InterruptedException {
String bind = "127.0.0.1";
int listen = 8816;
String target = "127.0.0.1:25565";
for (int i = 0; i < args.length; i += 2) {
String value = i + 1 < args.length ? args[i + 1] : "";
switch (args[i]) {
case "--bind" -> bind = value;
case "--listen" -> listen = Integer.parseInt(value);
case "--target" -> target = value;
default -> {
System.err.println("Usage: incari-wsbridge [--bind host] [--listen port] [--target host:port]");
System.exit(2);
}
}
}
int colon = target.lastIndexOf(':');
InetSocketAddress server = colon < 0
? new InetSocketAddress(target, 25565)
: new InetSocketAddress(target.substring(0, colon), Integer.parseInt(target.substring(colon + 1)));
WebSocketBridge bridge =
WebSocketBridge.start(new InetSocketAddress(bind, listen), server, System.out::println);
System.out.println("Bridging ws://" + bind + ":" + bridge.address().getPort() + "/ to " + server);
Runtime.getRuntime().addShutdownHook(new Thread(bridge::close));
new CountDownLatch(1).await();
}
}
@@ -0,0 +1,71 @@
package incari.tools.wsbridge;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.DecoderException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
/** The few wire types the bridge reads and writes while it stands in for an Eagler proxy's login. */
final class Packets {
private Packets() {}
static void writeVarInt(ByteBuf out, int value) {
VarIntFrames.writeLength(out, 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");
}
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);
String value = in.toString(in.readerIndex(), length, StandardCharsets.UTF_8);
in.skipBytes(length);
return value;
}
static void writeUuid(ByteBuf out, UUID uuid) {
out.writeLong(uuid.getMostSignificantBits());
out.writeLong(uuid.getLeastSignificantBits());
}
/** An Eagler handshake string: an unsigned byte length, then ASCII. */
static String readByteAscii(ByteBuf in) {
int length = in.readUnsignedByte();
String value = in.toString(in.readerIndex(), length, StandardCharsets.US_ASCII);
in.skipBytes(length);
return value;
}
static void writeByteAscii(ByteBuf out, String value) {
byte[] bytes = value.getBytes(StandardCharsets.US_ASCII);
out.writeByte(bytes.length);
out.writeBytes(bytes);
}
static void writeShortUtf8(ByteBuf out, String value) {
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
out.writeShort(bytes.length);
out.writeBytes(bytes);
}
/** The UUID an offline-mode server gives {@code name}, as Eagler proxies compute it too. */
static UUID offlineUuid(String name) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(StandardCharsets.UTF_8));
}
}
@@ -0,0 +1,68 @@
package incari.tools.wsbridge;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.CorruptedFrameException;
import java.util.List;
/**
* The Java protocol's stream framing, as the bridge sees it: each packet is prefixed with its
* length as a VarInt (7 bits per byte, low bits first, high bit set on all but the last byte), at
* most three bytes long. The bridge never looks inside a packet.
*/
final class VarIntFrames {
/** Three VarInt bytes hold 21 bits. */
static final int MAX_FRAME = (1 << 21) - 1;
private VarIntFrames() {}
/** Writes {@code length} as a VarInt. */
static void writeLength(ByteBuf out, int length) {
int remaining = length;
while ((remaining & ~0x7F) != 0) {
out.writeByte((remaining & 0x7F) | 0x80);
remaining >>>= 7;
}
out.writeByte(remaining);
}
/** Splits a TCP byte stream into packets, emitting each without its length prefix. */
static final class Splitter extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
while (true) {
int start = in.readerIndex();
int length = 0;
int shift = 0;
boolean complete = false;
for (int i = 0; i < 3 && in.isReadable(); i++) {
int b = in.readUnsignedByte();
length |= (b & 0x7F) << shift;
shift += 7;
if ((b & 0x80) == 0) {
complete = true;
break;
}
}
if (!complete) {
if (in.readerIndex() - start >= 3) {
throw new CorruptedFrameException("A frame length longer than 21 bits");
}
in.readerIndex(start);
return;
}
if (length == 0) {
throw new CorruptedFrameException("A zero-length frame");
}
if (in.readableBytes() < length) {
in.readerIndex(start);
return;
}
out.add(in.readRetainedSlice(length));
}
}
}
}
@@ -0,0 +1,220 @@
package incari.tools.wsbridge;
import com.google.gson.JsonObject;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.MultiThreadIoEventLoopGroup;
import io.netty.channel.nio.NioIoHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketCloseStatus;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolConfig;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import java.net.InetSocketAddress;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import org.jspecify.annotations.Nullable;
/**
* A development stand-in for an Eagler proxy (EaglerXServer) in front of one Java server: it
* answers Eagler's MOTD query from the server's status, runs the server side of Eagler's handshake
* (protocol V5), logs the player in to the server over TCP itself, then bridges packets: each
* binary message becomes one length-prefixed packet on the TCP side, and each packet the server
* sends becomes one binary message (ADR 0009, ADR 0016). The server must run with {@code
* online-mode=false}, as it would behind a real Eagler proxy; if it compresses packets, the bridge
* decompresses them (Eagler clients never see compression).
*
* <p>A development tool, for trying Incari's Eagler transport against vanilla servers of any
* version. It has no limits or authentication and must never face the internet.
*/
// Writes and closes are fire-and-forget: a failed one closes its channel, which the handlers log.
@SuppressWarnings("FutureReturnValueIgnored")
public final class WebSocketBridge implements AutoCloseable {
/** The same limit as the client's transport: larger than any packet the game allows. */
private static final int MAX_MESSAGE = 8 * 1024 * 1024;
/** How long a client has to answer a close frame before the connection is cut. */
private static final long CLOSE_TIMEOUT_MILLIS = 2000;
private final InetSocketAddress target;
private final Consumer<String> log;
private final EventLoopGroup group = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());
private final AtomicInteger connections = new AtomicInteger();
private @Nullable Channel server;
private WebSocketBridge(InetSocketAddress target, Consumer<String> log) {
this.target = target;
this.log = log;
}
/**
* Starts listening.
*
* @param listen where WebSocket clients connect; port 0 picks a free one
* @param target the Java server's TCP address
*/
public static WebSocketBridge start(InetSocketAddress listen, InetSocketAddress target, Consumer<String> log)
throws InterruptedException {
WebSocketBridge bridge = new WebSocketBridge(target, log);
bridge.server = new ServerBootstrap()
.group(bridge.group)
.channel(NioServerSocketChannel.class)
.childOption(ChannelOption.TCP_NODELAY, true)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel channel) {
WebSocketServerProtocolConfig config = WebSocketServerProtocolConfig.newBuilder()
.websocketPath("/")
// Any path: Eagler-style addresses often carry one.
.checkStartsWith(true)
.maxFramePayloadLength(MAX_MESSAGE)
.build();
channel.pipeline()
.addLast(new HttpServerCodec())
.addLast(new HttpObjectAggregator(64 * 1024))
.addLast(new WebSocketServerProtocolHandler(config))
.addLast(new WebSocketFrameAggregator(MAX_MESSAGE))
.addLast(bridge.new WebSocketSide());
}
})
.bind(listen)
.sync()
.channel();
return bridge;
}
/** The address it listens on (with the port chosen, if 0 was asked for). */
public InetSocketAddress address() {
return (InetSocketAddress) Objects.requireNonNull(server).localAddress();
}
@Override
public void close() {
if (server != null) {
server.close().syncUninterruptibly();
}
group.shutdownGracefully().syncUninterruptibly();
}
/**
* One WebSocket client, met the way an Eagler proxy meets it: a text {@code Accept: motd} asks
* for the MOTD; otherwise the first binary message opens Eagler's handshake (protocol V5), the
* bridge logs in to the server itself, and only then bridges packets.
*/
private final class WebSocketSide extends ChannelInboundHandlerAdapter {
private @Nullable EaglerConnection login;
private int id;
private boolean first = true;
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object event) {
if (!(event instanceof WebSocketServerProtocolHandler.HandshakeComplete handshake)) {
ctx.fireUserEventTriggered(event);
return;
}
id = connections.incrementAndGet();
log.accept("#" + id + " WebSocket " + ctx.channel().remoteAddress() + " " + handshake.requestUri());
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object message) {
if (!(message instanceof WebSocketFrame frame)) {
ctx.fireChannelRead(message);
return;
}
try {
if (first) {
first = false;
if (frame instanceof TextWebSocketFrame text) {
answerQuery(ctx.channel(), text.text());
return;
}
login = new EaglerConnection(ctx.channel(), target, id, log);
}
EaglerConnection current = login;
if (frame instanceof BinaryWebSocketFrame
&& current != null
&& frame.content().isReadable()) {
current.fromClient(frame.content());
}
} finally {
frame.release();
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
EaglerConnection current = login;
if (current != null) {
log.accept("#" + id + " WebSocket closed");
current.close();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
log.accept("#" + id + " WebSocket error: " + cause);
ctx.close();
}
private void answerQuery(Channel webSocket, String query) {
if (!query.trim().equalsIgnoreCase("accept: motd")) {
log.accept("#" + id + " unknown query: " + query);
closeWebSocket(webSocket, WebSocketCloseStatus.POLICY_VIOLATION);
return;
}
BackendStatus.query(webSocket.eventLoop(), target).whenComplete((motd, failure) -> {
if (failure != null) {
log.accept("#" + id + " MOTD: " + target + " didn't answer: " + failure);
closeWebSocket(webSocket, WebSocketCloseStatus.ENDPOINT_UNAVAILABLE);
return;
}
JsonObject answer = new JsonObject();
answer.addProperty("name", "incari-wsbridge");
answer.addProperty("brand", "incari");
answer.addProperty("vers", "dev");
answer.addProperty("cracked", true);
answer.addProperty("time", System.currentTimeMillis());
answer.addProperty("type", "motd");
answer.add("data", motd.toJson());
webSocket.write(new TextWebSocketFrame(answer.toString()));
byte[] icon = motd.icon();
if (icon != null) {
webSocket.write(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(icon)));
}
webSocket.flush();
closeWebSocket(webSocket, WebSocketCloseStatus.NORMAL_CLOSURE);
});
}
}
/**
* Closes a WebSocket the way the protocol asks: a close frame, then the client's answer closes
* the connection (the protocol handler does that), with a cut-off for a client that doesn't
* answer. Dropping the connection right after the frame can reach a browser as an abnormal
* close (1006), which it reports as an error, ahead of the packets before it (a kick's reason).
*/
static void closeWebSocket(Channel webSocket, WebSocketCloseStatus status) {
if (webSocket.isActive()) {
webSocket.writeAndFlush(new CloseWebSocketFrame(status));
webSocket.eventLoop().schedule(() -> webSocket.close(), CLOSE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
}
}
}
@@ -0,0 +1,5 @@
/** A development WebSocket-to-TCP bridge for testing the client against a vanilla server. */
@NullMarked
package incari.tools.wsbridge;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,273 @@
package incari.tools.wsbridge;
import static org.assertj.core.api.Assertions.assertThat;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** The bridge between a raw Eagler client (the JDK's WebSocket) and a scripted vanilla server. */
class WebSocketBridgeTest {
private ServerSocket server;
private WebSocketBridge bridge;
private final HttpClient http = HttpClient.newHttpClient();
@BeforeEach
void start() throws Exception {
server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress());
bridge = WebSocketBridge.start(
new InetSocketAddress(InetAddress.getLoopbackAddress(), 0),
(InetSocketAddress) server.getLocalSocketAddress(),
message -> {});
}
@AfterEach
void stop() throws IOException {
bridge.close();
server.close();
http.close();
}
@Test
void logsInToTheServerAndThenBridgesPackets() throws Exception {
Messages messages = new Messages();
WebSocket client = connect("/any/path", messages);
client.sendBinary(clientVersion(47), true).get(5, TimeUnit.SECONDS);
ByteBuf version = messages.next();
assertThat((int) version.readUnsignedByte()).isEqualTo(0x02);
assertThat(version.readUnsignedShort()).isEqualTo(5);
assertThat(version.readUnsignedShort()).isEqualTo(47);
client.sendBinary(requestLogin("Steve"), true).get(5, TimeUnit.SECONDS);
try (Socket backend = server.accept()) {
DataInputStream in = new DataInputStream(backend.getInputStream());
ByteBuf handshake = readFrame(in);
assertThat(Packets.readVarInt(handshake)).isEqualTo(0x00);
assertThat(Packets.readVarInt(handshake)).isEqualTo(47);
ByteBuf start = readFrame(in);
assertThat(Packets.readVarInt(start)).isEqualTo(0x00);
assertThat(Packets.readString(start)).isEqualTo("Steve");
assertThat(start.isReadable()).isFalse(); // no UUID before 1.20.2
// Login Success (1.8: the UUID as a string), then the first play packet at once.
UUID uuid = Packets.offlineUuid("Steve");
OutputStream out = backend.getOutputStream();
ByteBuf success = Unpooled.buffer();
Packets.writeVarInt(success, 0x02);
Packets.writeString(success, uuid.toString());
Packets.writeString(success, "Steve");
writeFrame(out, success);
writeFrame(out, Unpooled.wrappedBuffer(new byte[] {0x01, 42}));
ByteBuf allow = messages.next();
assertThat((int) allow.readUnsignedByte()).isEqualTo(0x05);
assertThat(Packets.readByteAscii(allow)).isEqualTo("Steve");
assertThat(new UUID(allow.readLong(), allow.readLong())).isEqualTo(uuid);
client.sendBinary(ByteBuffer.wrap(new byte[] {0x07, 0x00}), true).get(5, TimeUnit.SECONDS);
client.sendBinary(ByteBuffer.wrap(new byte[] {0x08}), true).get(5, TimeUnit.SECONDS);
assertThat((int) messages.next().readUnsignedByte()).isEqualTo(0x09);
ByteBuf held = messages.next();
assertThat(held.readableBytes()).isEqualTo(2);
assertThat((int) held.getByte(1)).isEqualTo(42);
// Packets both ways; Eagler's own messages stay with the bridge.
client.sendBinary(ByteBuffer.wrap(new byte[] {(byte) 0xEE, 0x03}), true)
.get(5, TimeUnit.SECONDS);
client.sendBinary(ByteBuffer.wrap(new byte[] {0x05, 0x06}), true).get(5, TimeUnit.SECONDS);
ByteBuf forwarded = readFrame(in);
assertThat(forwarded.readableBytes()).isEqualTo(2);
assertThat((int) forwarded.getByte(0)).isEqualTo(0x05);
}
assertThat(messages.closed.get(5, TimeUnit.SECONDS)).isEqualTo(WebSocket.NORMAL_CLOSURE);
}
@Test
void aModernClientSendsItsUuidAndAcknowledgesTheLogin() throws Exception {
Messages messages = new Messages();
WebSocket client = connect("/", messages);
client.sendBinary(clientVersion(777), true).get(5, TimeUnit.SECONDS);
messages.next();
client.sendBinary(requestLogin("Alex"), true).get(5, TimeUnit.SECONDS);
try (Socket backend = server.accept()) {
DataInputStream in = new DataInputStream(backend.getInputStream());
readFrame(in);
ByteBuf start = readFrame(in);
Packets.readVarInt(start);
assertThat(Packets.readString(start)).isEqualTo("Alex");
assertThat(new UUID(start.readLong(), start.readLong())).isEqualTo(Packets.offlineUuid("Alex"));
ByteBuf success = Unpooled.buffer();
Packets.writeVarInt(success, 0x02);
Packets.writeUuid(success, Packets.offlineUuid("Alex"));
Packets.writeString(success, "Alex");
Packets.writeVarInt(success, 0);
writeFrame(backend.getOutputStream(), success);
assertThat((int) messages.next().readUnsignedByte()).isEqualTo(0x05);
client.sendBinary(ByteBuffer.wrap(new byte[] {0x08}), true).get(5, TimeUnit.SECONDS);
ByteBuf acknowledged = readFrame(in);
assertThat(Packets.readVarInt(acknowledged)).isEqualTo(0x03);
assertThat((int) messages.next().readUnsignedByte()).isEqualTo(0x09);
}
}
@Test
void theMotdComesFromTheServersStatus() throws Exception {
Messages messages = new Messages();
connect("/", messages).sendText("Accept: motd", true).get(5, TimeUnit.SECONDS);
try (Socket backend = server.accept()) {
DataInputStream in = new DataInputStream(backend.getInputStream());
ByteBuf handshake = readFrame(in);
Packets.readVarInt(handshake);
Packets.readVarInt(handshake);
Packets.readString(handshake);
handshake.readShort();
assertThat(Packets.readVarInt(handshake)).isEqualTo(1);
readFrame(in);
ByteBuf status = Unpooled.buffer();
Packets.writeVarInt(status, 0x00);
Packets.writeString(
status,
"{\"version\":{\"name\":\"1.12.2\",\"protocol\":340},"
+ "\"players\":{\"max\":20,\"online\":1,\"sample\":[{\"name\":\"Notch\",\"id\":\"x\"}]},"
+ "\"description\":{\"text\":\"A \",\"extra\":[{\"text\":\"server\",\"color\":\"gold\"}]}}");
writeFrame(backend.getOutputStream(), status);
String answer = messages.texts.poll(5, TimeUnit.SECONDS);
assertThat(answer)
.contains("\"type\":\"motd\"")
.contains("\"motd\":[\"A §6server\"]")
.contains("\"online\":1")
.contains("\"max\":20")
.contains("\"players\":[\"Notch\"]")
.contains("\"icon\":false")
.contains("\"protocol\":340");
}
}
private WebSocket connect(String path, Messages messages) throws Exception {
URI uri = URI.create("ws://127.0.0.1:" + bridge.address().getPort() + path);
return http.newWebSocketBuilder().buildAsync(uri, messages).get(5, TimeUnit.SECONDS);
}
private static ByteBuffer clientVersion(int protocol) {
ByteBuf out = Unpooled.buffer();
out.writeByte(0x01);
out.writeByte(0x02);
out.writeShort(1);
out.writeShort(5);
out.writeShort(1);
out.writeShort(protocol);
Packets.writeByteAscii(out, "Test");
Packets.writeByteAscii(out, "1");
out.writeBoolean(false);
Packets.writeByteAscii(out, "Steve");
return out.nioBuffer();
}
private static ByteBuffer requestLogin(String name) {
ByteBuf out = Unpooled.buffer();
out.writeByte(0x04);
Packets.writeByteAscii(out, name);
Packets.writeByteAscii(out, "");
out.writeByte(0);
out.writeBoolean(false);
out.writeByte(0);
Packets.writeVarInt(out, 0);
out.writeByte(0);
return out.nioBuffer();
}
private static ByteBuf readFrame(DataInputStream in) throws IOException {
int length = 0;
for (int shift = 0; ; shift += 7) {
int b = in.readUnsignedByte();
length |= (b & 0x7F) << shift;
if ((b & 0x80) == 0) {
break;
}
}
byte[] packet = new byte[length];
in.readFully(packet);
return Unpooled.wrappedBuffer(packet);
}
private static void writeFrame(OutputStream out, ByteBuf packet) throws IOException {
ByteBuf framed = Unpooled.buffer();
VarIntFrames.writeLength(framed, packet.readableBytes());
framed.writeBytes(packet);
byte[] bytes = new byte[framed.readableBytes()];
framed.readBytes(bytes);
out.write(bytes);
out.flush();
}
/** Collects whole messages (binary as buffers, text as strings) and the close code. */
private static final class Messages implements WebSocket.Listener {
final BlockingQueue<ByteBuf> received = new LinkedBlockingQueue<>();
final BlockingQueue<String> texts = new LinkedBlockingQueue<>();
final CompletableFuture<Integer> closed = new CompletableFuture<>();
private final ByteArrayOutputStream current = new ByteArrayOutputStream();
private final StringBuilder text = new StringBuilder();
@Override
public CompletionStage<?> onBinary(WebSocket webSocket, ByteBuffer data, boolean last) {
byte[] chunk = new byte[data.remaining()];
data.get(chunk);
current.writeBytes(chunk);
if (last) {
received.add(Unpooled.wrappedBuffer(current.toByteArray()));
current.reset();
}
webSocket.request(1);
return null;
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
text.append(data);
if (last) {
texts.add(text.toString());
text.setLength(0);
}
webSocket.request(1);
return null;
}
@Override
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
closed.complete(statusCode);
return null;
}
ByteBuf next() throws InterruptedException {
ByteBuf message = received.poll(5, TimeUnit.SECONDS);
assertThat(message).as("a message within 5 s").isNotNull();
return message;
}
}
}