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
+11
View File
@@ -0,0 +1,11 @@
# via
- Netty, the Via libraries and Guava only: no game types, no platform code (`BoundaryTest`).
- Compiled into the browser build: no reflection of Incari's own, no blocking on an event loop,
nothing that writes files. `IncariVia.load` blocks; only the connector thread calls it.
- Keep the stage's handler names (`via-decoder`, `via-relay`, `via-encoder`) and its placement
after "splitter" and "prepender": compression and the Eagler stage depend on it.
- Upgrading Via: bump `viaversion` and `viabackwards` together in `gradle/libs.versions.toml`,
then run the desktop version matrix (`:app-desktop:smokeServer` against each test server) and the
browser checks. Networking changes need a human reviewer (`.github/CODEOWNERS`).
- Test: `./gradlew :via:check`.
+38
View File
@@ -0,0 +1,38 @@
# via: the Via stack in the client
Lets the game join servers of other versions (ADR 0017): ViaVersion for older servers back to
1.8, ViaBackwards for newer ones, as a stage of the connection's pipeline.
## Code map
- `IncariVia`: Incari's Via platform. `configure` (the data folder and the game's protocol),
`load(serverProtocol)` (starts Via on first use and waits for its data), `supports`,
`versionName`, `releases` (for the server list's version button), `shutdown`.
- `ViaPipeline.install(channel, serverProtocol, splitter, prepender)`: adds `via-decoder`,
`via-relay` and `via-encoder` to one connection.
- `ServerVersions` (package-private): tells Via which version each connection's server speaks.
- `ViaSettings`: Via's settings, in memory.
## Invariants
- **No game types**, and nothing of Incari's but this module (`gradle/module-boundaries.txt`).
The client's adapters (`incari.client.net`) decide which version a server speaks.
- **Via starts off the main thread.** `load` waits for mapping data; the connect screen's
connector thread calls it. Never call it from the render thread or a Netty event loop.
- **Via writes no files and parses no YAML**: its configs load from `ViaSettings`.
- **Via's data is on the class path**: the jars on the desktop, the asset pack's `classpath/` in
the browser (`:app-web:assetPack`).
- Via is GPLv3 without Incari's Minecraft exception: see ADR 0002's open issue.
## How to test
```sh
./gradlew :via:check
```
`ViaPipelineTest` loads Via on the JVM and takes a 26.3 login to a 1.8 server and back. End to end,
against vanilla servers behind the development bridge (`tools/wsbridge`):
```sh
./gradlew :app-desktop:smokeServer -Pincari.server=ws://127.0.0.1:8801 # a 1.8.9 server's bridge
```
+29
View File
@@ -0,0 +1,29 @@
plugins {
`java-library`
}
// The Via stack in the client (ADR 0017): ViaVersion and ViaBackwards under a small Incari
// platform, as a stage of the game's Netty pipeline. No game types.
dependencies {
// The Via jars ship in the build (desktop and browser alike); they're GPLv3 (ADR 0017).
api(libs.viaversion)
api(libs.viabackwards)
// What Via is written against besides the libraries it bundles (relocated Gson, fastutil,
// SnakeYAML); at run time the game's own copies, the same versions, are used.
compileOnly(libs.netty.buffer)
compileOnly(libs.netty.transport)
compileOnly(libs.netty.codec.base)
compileOnly(libs.guava)
testImplementation(libs.netty.buffer)
testImplementation(libs.netty.transport)
testImplementation(libs.netty.codec.base)
testImplementation(libs.guava)
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testImplementation(libs.assertj)
testImplementation(libs.archunit)
testRuntimeOnly(libs.junit.launcher)
}
@@ -0,0 +1,342 @@
package incari.via;
import com.viaversion.viabackwards.api.ViaBackwardsPlatform;
import com.viaversion.viaversion.ViaAPIBase;
import com.viaversion.viaversion.ViaManagerImpl;
import com.viaversion.viaversion.api.Via;
import com.viaversion.viaversion.api.ViaAPI;
import com.viaversion.viaversion.api.configuration.ViaVersionConfig;
import com.viaversion.viaversion.api.connection.UserConnection;
import com.viaversion.viaversion.api.platform.ViaInjector;
import com.viaversion.viaversion.api.platform.ViaPlatform;
import com.viaversion.viaversion.api.platform.ViaPlatformLoader;
import com.viaversion.viaversion.api.protocol.version.ProtocolVersion;
import com.viaversion.viaversion.api.protocol.version.VersionProvider;
import com.viaversion.viaversion.api.protocol.version.VersionType;
import com.viaversion.viaversion.commands.ViaCommandHandler;
import com.viaversion.viaversion.libs.fastutil.objects.ObjectLinkedOpenHashSet;
import com.viaversion.viaversion.libs.gson.JsonObject;
import com.viaversion.viaversion.protocol.ProtocolManagerImpl;
import io.netty.buffer.ByteBuf;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import java.util.logging.Logger;
import org.jspecify.annotations.Nullable;
/**
* Via in the client: started on first use (joining a server of another version), then shared by
* every connection. The game speaks its own protocol ({@link #nativeProtocol}); for each connection
* Via is told the server's, and translates both ways.
*
* <p>ViaVersion covers older servers back to 1.8. ViaBackwards covers servers newer than the game
* and loads only when needed (its mappings are memory the common case doesn't use).
*/
public final class IncariVia {
private static final Logger LOGGER = Logger.getLogger("Via");
private static final Object LOCK = new Object();
private static volatile boolean loaded;
private static volatile boolean backwardsLoaded;
private static @Nullable File dataFolder;
private static int nativeProtocol;
private IncariVia() {}
/**
* Sets where Via may keep files and which protocol the game speaks. Call once, before {@link
* #load}; cheap, loads nothing.
*/
public static void configure(File folder, int gameProtocol) {
synchronized (LOCK) {
dataFolder = folder;
nativeProtocol = gameProtocol;
}
}
/** The protocol the game itself speaks. */
public static int nativeProtocol() {
return nativeProtocol;
}
/** Whether Via can take the game to a server speaking {@code protocol}. */
public static boolean supports(int protocol) {
return protocol == nativeProtocol || versionFor(protocol) != null;
}
/**
* The release that speaks {@code protocol}, if Via knows it: "1.8.x", "1.20.3-1.20.4" and so on.
* Needs no loading: the version table is plain data.
*/
public static @Nullable String versionName(int protocol) {
ProtocolVersion version = versionFor(protocol);
return version == null ? null : version.getName();
}
/** Every release Via can join, newest first, as (protocol, name) pairs. */
public static List<Release> releases() {
List<Release> releases = new ArrayList<>();
for (ProtocolVersion version : ProtocolVersion.getProtocols()) {
if (version.getVersionType() == VersionType.RELEASE
&& version.getVersion() >= ProtocolVersion.v1_8.getVersion()) {
releases.add(new Release(version.getVersion(), version.getName()));
}
}
releases.sort((a, b) -> Integer.compare(b.protocol(), a.protocol()));
return releases;
}
/**
* The protocol of the release a server names in words, as a kick message does: "1.8.8",
* "1.20.4", "26.3", or "1.21.x" (the newest 1.21 release Via knows). Returns -1 for a version
* Via can't join.
*/
public static int protocolNamed(String version) {
boolean anyPatch = version.endsWith(".x");
String prefix = anyPatch ? version.substring(0, version.length() - 1) : version;
String minor = anyPatch ? version.substring(0, version.length() - 2) : version;
int best = -1;
for (ProtocolVersion candidate : ProtocolVersion.getProtocols()) {
if (candidate.getVersionType() != VersionType.RELEASE
|| candidate.getVersion() < ProtocolVersion.v1_8.getVersion()) {
continue;
}
for (String included : candidate.getIncludedVersions()) {
boolean matches =
anyPatch ? included.equals(minor) || included.startsWith(prefix) : included.equals(version);
if (matches && candidate.getVersion() > best) {
best = candidate.getVersion();
}
}
}
return best;
}
/** A release a server can speak. */
public record Release(int protocol, String name) {}
private static @Nullable ProtocolVersion versionFor(int protocol) {
if (!ProtocolVersion.isRegistered(VersionType.RELEASE, protocol)) {
return null;
}
ProtocolVersion version = ProtocolVersion.getProtocol(VersionType.RELEASE, protocol);
return version.getVersion() >= ProtocolVersion.v1_8.getVersion() ? version : null;
}
/**
* Starts Via if it isn't running, with what a connection to {@code serverProtocol} needs. Loads
* mapping data, so it takes a while the first time (seconds in the browser): call it off the
* game's main thread, as the connect screen's connector thread does.
*
* @throws IllegalArgumentException if Via can't reach {@code serverProtocol}
*/
public static void load(int serverProtocol) {
ProtocolVersion target = versionFor(serverProtocol);
if (target == null) {
throw new IllegalArgumentException("Via can't translate to protocol " + serverProtocol);
}
synchronized (LOCK) {
if (!loaded) {
start();
loaded = true;
}
if (serverProtocol > nativeProtocol && !backwardsLoaded) {
LOGGER.info("Loading ViaBackwards for a server newer than the game (" + target.getName() + ")");
new BackwardsPlatform();
((ProtocolManagerImpl) Via.getManager().getProtocolManager()).refreshVersions();
backwardsLoaded = true;
}
}
awaitMappings();
}
/**
* Waits for Via's mapping data, which it loads on its own pool: the connection's handshake
* would otherwise wait for it on the network thread.
*/
private static void awaitMappings() {
ProtocolManagerImpl protocols = (ProtocolManagerImpl) Via.getManager().getProtocolManager();
// Propagating errors: a protocol whose data failed to load would fail mid-game instead.
// (Via logs the failure too, but the browser's logging drops the exception.)
while (!protocols.hasLoadedMappings() && !protocols.checkForMappingCompletion(true)) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted while Via loaded its mappings", e);
}
}
}
/** Stops Via's scheduler and connections, if Via was started. The game's exit. */
public static void shutdown() {
synchronized (LOCK) {
if (loaded) {
((ViaManagerImpl) Via.getManager()).destroy();
loaded = false;
}
}
}
private static void start() {
File folder = dataFolder;
if (folder == null) {
throw new IllegalStateException("IncariVia.configure first");
}
long started = System.currentTimeMillis();
Platform platform = new Platform(folder);
ViaManagerImpl manager = ViaManagerImpl.builder()
.platform(platform)
.injector(new Injector())
.loader(new Loader())
.commandHandler(new ViaCommandHandler(false))
.build();
Via.init(manager);
platform.getConf().reload();
manager.init();
manager.onServerLoaded();
ProtocolManagerImpl protocols = (ProtocolManagerImpl) manager.getProtocolManager();
// A client can take any path to a server, however long.
protocols.setMaxProtocolPathSize(Integer.MAX_VALUE);
protocols.setMaxPathDeltaIncrease(-1);
protocols.refreshVersions();
LOGGER.info(
"Via " + platform.getPluginVersion() + " started in " + (System.currentTimeMillis() - started) + " ms");
}
/** Via's view of this client: a proxy in front of servers of every version. */
private static final class Platform implements ViaPlatform<UserConnection> {
private final File folder;
private final ViaVersionConfig config;
private final ViaAPI<UserConnection> api = new ViaAPIBase<>() {
@Override
public ProtocolVersion getPlayerProtocolVersion(UserConnection player) {
return player.getProtocolInfo().protocolVersion();
}
@Override
public void sendRawPacket(UserConnection player, ByteBuf packet) {
player.scheduleSendRawPacket(packet);
}
};
Platform(File folder) {
this.folder = folder;
this.config = new ViaSettings.ViaVersionConfig(new File(folder, "viaversion.yml"), LOGGER);
}
@Override
public Logger getLogger() {
return LOGGER;
}
@Override
public String getPlatformName() {
return "Incari";
}
@Override
public String getPlatformVersion() {
return "dev";
}
@Override
public boolean isProxy() {
return true;
}
@Override
public ViaAPI<UserConnection> getApi() {
return api;
}
@Override
public ViaVersionConfig getConf() {
return config;
}
@Override
public File getDataFolder() {
return folder;
}
}
/** Nothing to inject: Incari adds Via to each connection's pipeline itself ({@link ViaPipeline}). */
private static final class Injector implements ViaInjector {
@Override
public void inject() {}
@Override
public void uninject() {}
@Override
public ProtocolVersion getServerProtocolVersion() {
return getServerProtocolVersions().first();
}
/** Every version: the server behind each connection is whichever one it names. */
@Override
public SortedSet<ProtocolVersion> getServerProtocolVersions() {
SortedSet<ProtocolVersion> versions = new ObjectLinkedOpenHashSet<>();
versions.addAll(ProtocolVersion.getProtocols());
return versions;
}
@Override
public String getEncoderName() {
return ViaPipeline.ENCODER;
}
@Override
public String getDecoderName() {
return ViaPipeline.DECODER;
}
@Override
public JsonObject getDump() {
return new JsonObject();
}
}
/** Registers the connection's server version with Via, in place of Via's own guess. */
private static final class Loader implements ViaPlatformLoader {
@Override
public void load() {
Via.getManager().getProviders().use(VersionProvider.class, new ServerVersions());
}
@Override
public void unload() {}
}
private static final class BackwardsPlatform implements ViaBackwardsPlatform {
BackwardsPlatform() {
init(new ViaSettings.ViaBackwardsConfig(new File(getDataFolder(), "viabackwards.yml"), LOGGER));
enable();
}
@Override
public Logger getLogger() {
return LOGGER;
}
@Override
public boolean isOutdated() {
return false;
}
@Override
public void disable() {}
@Override
public File getDataFolder() {
return Via.getPlatform().getDataFolder();
}
}
}
@@ -0,0 +1,26 @@
package incari.via;
import com.viaversion.viaversion.api.connection.StorableObject;
import com.viaversion.viaversion.api.connection.UserConnection;
import com.viaversion.viaversion.api.protocol.version.ProtocolVersion;
import com.viaversion.viaversion.api.protocol.version.VersionProvider;
/**
* Tells Via which version the server behind a connection speaks. On a server Via would ask the
* server itself; here each connection was told when it was set up ({@link ViaPipeline#install}),
* by the player's choice or the server list's ping.
*/
final class ServerVersions implements VersionProvider {
@Override
public ProtocolVersion getClosestServerProtocol(UserConnection connection) {
Target target = connection.get(Target.class);
if (target == null) {
throw new IllegalStateException("A Via connection without a server version");
}
return target.version();
}
/** The server version of one connection, kept in Via's per-connection storage. */
record Target(ProtocolVersion version) implements StorableObject {}
}
@@ -0,0 +1,253 @@
package incari.via;
import com.viaversion.viaversion.api.connection.UserConnection;
import com.viaversion.viaversion.api.protocol.version.ProtocolVersion;
import com.viaversion.viaversion.api.protocol.version.VersionType;
import com.viaversion.viaversion.connection.UserConnectionImpl;
import com.viaversion.viaversion.exception.CancelCodecException;
import com.viaversion.viaversion.exception.CancelDecoderException;
import com.viaversion.viaversion.exception.CancelEncoderException;
import com.viaversion.viaversion.protocol.ProtocolPipelineImpl;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.DecoderException;
import io.netty.handler.codec.EncoderException;
import io.netty.util.ReferenceCountUtil;
import java.util.ArrayDeque;
import org.jspecify.annotations.Nullable;
/**
* Via as a stage of one connection's pipeline: packets from the server are translated to the
* game's protocol after framing (and decompression), and the game's packets to the server's
* protocol before it. Via sees whole, uncompressed packets both ways, as it does on a proxy.
*
* <p>The stage sits right after the framing handlers the game names "splitter" and "prepender":
* the game adds its compression next to those names too, so decompression lands before Via's
* decoder and compression after its encoder, whenever the server turns it on.
*/
public final class ViaPipeline {
/** The stage's handler names. */
public static final String DECODER = "via-decoder";
public static final String ENCODER = "via-encoder";
public static final String RELAY = "via-relay";
private ViaPipeline() {}
/**
* Adds Via to {@code channel}'s pipeline for a server speaking {@code serverProtocol}, after the
* handlers named {@code splitter} and {@code prepender}. {@link IncariVia#load} must have run.
*/
public static void install(Channel channel, int serverProtocol, String splitter, String prepender) {
ProtocolVersion server = ProtocolVersion.getProtocol(VersionType.RELEASE, serverProtocol);
UserConnection user = new UserConnectionImpl(channel, true);
new ProtocolPipelineImpl(user);
user.put(new ServerVersions.Target(server));
Relay relay = new Relay();
channel.pipeline().addAfter(splitter, DECODER, new Decoder(user));
channel.pipeline().addAfter(DECODER, RELAY, relay);
channel.pipeline().addAfter(prepender, ENCODER, new Encoder(user, relay));
}
/** Whether {@code failure} is Via dropping a packet on purpose. */
static boolean cancelled(Throwable failure) {
for (Throwable cause = failure; cause != null; cause = cause.getCause()) {
if (cause instanceof CancelCodecException) {
return true;
}
}
return false;
}
/**
* Translates each packet from the server. Not Netty's {@code MessageToMessageDecoder}: it
* catches and rethrows each packet Via drops, three throws on top of Via's own, and in the page a
* throw off the main thread costs ten times one on it (ADR 0033). A 1.12 server dropped a dozen
* packets a second. Like Netty's, this releases the input, passes the output on and wraps a
* failure as a {@code DecoderException}.
*/
private static final class Decoder extends ChannelInboundHandlerAdapter {
private final UserConnection user;
private boolean decodeCalled;
private boolean messageProduced;
Decoder(UserConnection user) {
this.user = user;
}
/** The packet translated for the game, or null if Via drops it. */
private @Nullable ByteBuf decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
if (!user.checkIncomingPacket(in.readableBytes())) {
return null;
}
if (!user.shouldTransformPacket()) {
return in.retain();
}
ByteBuf transformed = ctx.alloc().buffer(in.readableBytes()).writeBytes(in);
// Caught, not a finally: a finally rethrows, one more throw per dropped packet.
try {
user.transformIncoming(transformed, CancelDecoderException::generate);
} catch (Throwable failure) {
transformed.release();
if (cancelled(failure)) {
return null;
}
throw failure;
}
return transformed;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object message) {
decodeCalled = true;
if (!(message instanceof ByteBuf in)) {
messageProduced = true;
ctx.fireChannelRead(message);
return;
}
ByteBuf out;
try {
out = decode(ctx, in);
} catch (Exception e) {
// Via drops some packets on purpose (ones the game's version has no use for).
if (cancelled(e)) {
return;
}
throw e instanceof DecoderException d ? d : new DecoderException(e);
} finally {
in.release();
}
if (out != null) {
messageProduced = true;
ctx.fireChannelRead(out);
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
// As MessageToMessageDecoder: ask for more if a read produced nothing without auto-read.
if (decodeCalled && !messageProduced && !ctx.channel().config().isAutoRead()) {
ctx.read();
}
decodeCalled = false;
messageProduced = false;
ctx.fireChannelReadComplete();
}
}
/**
* Translates each packet the game sends. Not Netty's {@code MessageToMessageEncoder}, as with
* the decoder: there a dropped packet costs four more throws, and the game sends one every tick
* that an old server has no equivalent for. Like Netty's, this releases the input, writes the
* output with the game's promise (a dropped packet completes it) and wraps a failure as an
* {@code EncoderException}.
*/
private static final class Encoder extends ChannelOutboundHandlerAdapter {
private final UserConnection user;
private final Relay relay;
Encoder(UserConnection user, Relay relay) {
this.user = user;
this.relay = relay;
}
/** The packet translated for the server, or null if Via drops it. */
private @Nullable ByteBuf encode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
if (!user.checkOutgoingPacket()) {
return null;
}
if (!user.shouldTransformPacket()) {
return in.retain();
}
ByteBuf transformed = ctx.alloc().buffer(in.readableBytes()).writeBytes(in);
relay.encoding = true;
// Caught, not a finally: a finally rethrows, one more throw per dropped packet.
try {
user.transformOutgoing(transformed, CancelEncoderException::generate);
} catch (Throwable failure) {
relay.encoding = false;
transformed.release();
if (cancelled(failure)) {
return null;
}
throw failure;
}
relay.encoding = false;
return transformed;
}
@Override
@SuppressWarnings("FutureReturnValueIgnored") // the game's promise carries the write's outcome
public void write(ChannelHandlerContext ctx, Object message, ChannelPromise promise) {
if (!(message instanceof ByteBuf in)) {
ctx.write(message, promise);
return;
}
ByteBuf out;
try {
out = encode(ctx, in);
} catch (Exception e) {
if (!cancelled(e)) {
throw e instanceof EncoderException d ? d : new EncoderException(e);
}
out = null;
} finally {
in.release();
}
if (out == null) {
// A packet the server's version has no equivalent for: it's done, as far as the game knows.
promise.trySuccess();
return;
}
ctx.write(out, promise);
}
}
/**
* Holds back packets Via hands the game while translating one of the game's own. Via answers
* some packets for the server: when the game finishes the configuration phase (which an old
* server lacks), Via releases the server's queued play packets at once. The game only switches
* protocol after that write returns, so they go on as the next task on the connection's
* thread, in order.
*/
private static final class Relay extends ChannelInboundHandlerAdapter {
/** Set while the encoder translates; the connection's thread only. */
boolean encoding;
private final ArrayDeque<Object> held = new ArrayDeque<>();
@Override
public void channelRead(ChannelHandlerContext ctx, Object message) {
if (!encoding && held.isEmpty()) {
ctx.fireChannelRead(message);
return;
}
if (held.isEmpty()) {
ctx.executor().execute(() -> release(ctx));
}
held.add(message);
}
private void release(ChannelHandlerContext ctx) {
while (!held.isEmpty()) {
ctx.fireChannelRead(held.remove());
}
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
while (!held.isEmpty()) {
ReferenceCountUtil.release(held.remove());
}
}
}
}
@@ -0,0 +1,89 @@
package incari.via;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Via's settings for a client. Via keeps its settings in YAML files it writes next to a server
* plugin; a client has no one to edit those, and the browser build has no YAML parser, so each
* config here starts from Via's defaults plus the few choices below, in memory, and saves nothing.
*/
final class ViaSettings {
private ViaSettings() {}
/** ViaVersion's choices for a client, keyed as in its {@code config.yml}. */
static Map<String, Object> viaVersion() {
Map<String, Object> values = new HashMap<>();
// A client has no update notices to show, and no console to show them on.
values.put("check-for-updates", false);
// 1.8 servers expect a movement packet every tick; newer clients skip idle ones.
values.put("simulate-pt", true);
// Chat reports and signing don't apply across versions.
values.put("enforce-secure-chat", false);
// Rate limits protect a server from its players; a client has no one to limit.
values.put("packet-limiter", section("enabled", false));
values.put("packet-size-limiter", section("enabled", false));
values.put("logging", new HashMap<String, Object>());
return values;
}
/** ViaBackwards' choices: its defaults (the sections it reads must exist). */
static Map<String, Object> viaBackwards() {
Map<String, Object> values = new HashMap<>();
values.put("dialog-style", new HashMap<String, Object>());
return values;
}
private static Map<String, Object> section(String key, Object value) {
Map<String, Object> section = new HashMap<>();
section.put(key, value);
return section;
}
static final class ViaVersionConfig extends com.viaversion.viaversion.configuration.AbstractViaConfig {
ViaVersionConfig(File file, java.util.logging.Logger logger) {
super(file, logger);
}
@Override
public Map<String, Object> loadConfig(File location) {
return viaVersion();
}
@Override
public void save(File location, Map<String, Object> config) {
// In memory only.
}
@Override
public List<String> getUnsupportedOptions() {
return List.of();
}
@Override
public boolean isCheckForUpdates() {
return false;
}
}
static final class ViaBackwardsConfig extends com.viaversion.viabackwards.ViaBackwardsConfig {
ViaBackwardsConfig(File file, java.util.logging.Logger logger) {
super(file, logger);
}
@Override
public Map<String, Object> loadConfig(File location) {
return viaBackwards();
}
@Override
public void save(File location, Map<String, Object> config) {
// In memory only.
}
}
}
@@ -0,0 +1,9 @@
/**
* The Via stack in the client (ADR 0017): ViaVersion and ViaBackwards running
* under a small Incari platform, as a stage of the game's Netty pipeline, so the game joins
* servers of other Minecraft versions. Netty and the Via libraries only; no game types.
*/
@NullMarked
package incari.via;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,23 @@
package incari.via;
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;
/**
* via is Via under a small platform: Netty, the Via libraries and the JDK. It never sees game
* types (the client's adapters decide each server's version) or Incari's platform code.
*/
@AnalyzeClasses(packages = "incari.via", importOptions = ImportOption.DoNotIncludeTests.class)
class BoundaryTest {
@ArchTest
static final ArchRule onlyNettyAndVia = classes()
.should()
.onlyDependOnClassesThat()
.resideInAnyPackage("java..", "org.jspecify..", "io.netty..", "com.viaversion..", "incari.via..")
.allowEmptyShould(true);
}
@@ -0,0 +1,193 @@
package incari.via;
import static org.assertj.core.api.Assertions.assertThat;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.embedded.EmbeddedChannel;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/** Via between a 26.3 game and servers of other versions, in a pipeline shaped like the game's. */
class ViaPipelineTest {
private static final int GAME = 777;
@TempDir
static File folder;
@BeforeAll
static void configure() {
IncariVia.configure(folder, GAME);
}
@Test
void knowsTheReleasesItCanJoin() {
assertThat(IncariVia.supports(47)).isTrue();
assertThat(IncariVia.supports(340)).isTrue();
assertThat(IncariVia.supports(GAME)).isTrue();
assertThat(IncariVia.supports(5)).isFalse(); // 1.7: ViaVersion starts at 1.8
assertThat(IncariVia.versionName(47)).isEqualTo("1.8.x");
assertThat(IncariVia.versionName(765)).isEqualTo("1.20.3-1.20.4");
assertThat(IncariVia.releases().get(0).protocol()).isGreaterThanOrEqualTo(GAME);
}
@Test
void readsVersionsNamedInWords() {
assertThat(IncariVia.protocolNamed("1.8.8")).isEqualTo(47);
assertThat(IncariVia.protocolNamed("1.8.x")).isEqualTo(47);
assertThat(IncariVia.protocolNamed("1.12.2")).isEqualTo(340);
assertThat(IncariVia.protocolNamed("1.20.4")).isEqualTo(765);
// The newest 1.20 release, not 1.20 itself.
assertThat(IncariVia.protocolNamed("1.20.x")).isGreaterThan(765);
assertThat(IncariVia.protocolNamed("1.7.10")).isEqualTo(-1);
assertThat(IncariVia.protocolNamed("banana")).isEqualTo(-1);
}
@Test
void takesTheGameToA18Server() {
IncariVia.load(47);
List<ByteBuf> game = new ArrayList<>();
EmbeddedChannel channel = channel(game);
ViaPipeline.install(channel, 47, "splitter", "prepender");
UUID uuid = UUID.nameUUIDFromBytes("OfflinePlayer:Steve".getBytes(StandardCharsets.UTF_8));
ByteBuf handshake = Unpooled.buffer();
writeVarInt(handshake, 0x00);
writeVarInt(handshake, GAME);
writeString(handshake, "localhost");
handshake.writeShort(25565);
writeVarInt(handshake, 2);
ByteBuf hello = Unpooled.buffer();
writeVarInt(hello, 0x00);
writeString(hello, "Steve");
hello.writeLong(uuid.getMostSignificantBits());
hello.writeLong(uuid.getLeastSignificantBits());
channel.writeOutbound(handshake, hello);
ByteBuf sentHandshake = channel.readOutbound();
assertThat(readVarInt(sentHandshake)).isEqualTo(0x00);
assertThat(readVarInt(sentHandshake)).isEqualTo(47);
ByteBuf sentHello = channel.readOutbound();
assertThat(readVarInt(sentHello)).isEqualTo(0x00);
assertThat(readString(sentHello)).isEqualTo("Steve");
assertThat(sentHello.isReadable()).isFalse(); // 1.8's Login Start is the name alone
// 1.8's Login Success names the UUID as a string; the game gets 26.3's layout.
ByteBuf success = Unpooled.buffer();
writeVarInt(success, 0x02);
writeString(success, uuid.toString());
writeString(success, "Steve");
channel.writeInbound(success);
assertThat(game).hasSize(1);
ByteBuf translated = game.get(0);
assertThat(readVarInt(translated)).isEqualTo(0x02);
assertThat(new UUID(translated.readLong(), translated.readLong())).isEqualTo(uuid);
assertThat(readString(translated)).isEqualTo("Steve");
assertThat(readVarInt(translated)).isZero(); // properties
assertThat(translated.readableBytes()).isEqualTo(16); // 26.2's session id
}
@Test
void dropsWhatA18ServerHasNoUseFor() {
IncariVia.load(47);
List<ByteBuf> game = new ArrayList<>();
EmbeddedChannel channel = channel(game);
ViaPipeline.install(channel, 47, "splitter", "prepender");
UUID uuid = UUID.nameUUIDFromBytes("OfflinePlayer:Alex".getBytes(StandardCharsets.UTF_8));
ByteBuf handshake = Unpooled.buffer();
writeVarInt(handshake, 0x00);
writeVarInt(handshake, GAME);
writeString(handshake, "localhost");
handshake.writeShort(25565);
writeVarInt(handshake, 2);
ByteBuf hello = Unpooled.buffer();
writeVarInt(hello, 0x00);
writeString(hello, "Alex");
hello.writeLong(uuid.getMostSignificantBits());
hello.writeLong(uuid.getLeastSignificantBits());
channel.writeOutbound(handshake, hello);
ByteBuf sentHandshake = channel.readOutbound();
ByteBuf sentHello = channel.readOutbound();
sentHandshake.release();
sentHello.release();
ByteBuf success = Unpooled.buffer();
writeVarInt(success, 0x02);
writeString(success, uuid.toString());
writeString(success, "Alex");
channel.writeInbound(success);
game.forEach(ByteBuf::release);
// The game acknowledges the login, which 1.8 has no packet for: Via drops it, the write
// succeeds, and nothing reaches the server.
ByteBuf acknowledged = Unpooled.buffer();
writeVarInt(acknowledged, 0x03);
ChannelFuture write = channel.writeAndFlush(acknowledged);
assertThat(write.isSuccess()).isTrue();
Object sent = channel.readOutbound();
assertThat(sent).isNull();
// Every buffer the pipeline was handed is released, as Netty's codecs release them.
assertThat(handshake.refCnt()).isZero();
assertThat(hello.refCnt()).isZero();
assertThat(success.refCnt()).isZero();
assertThat(acknowledged.refCnt()).isZero();
}
/** "splitter" and "prepender" stand in for the game's framing; the tail is the game. */
private static EmbeddedChannel channel(List<ByteBuf> game) {
EmbeddedChannel channel = new EmbeddedChannel();
channel.pipeline().addLast("splitter", new ChannelInboundHandlerAdapter());
channel.pipeline().addLast("prepender", new ChannelDuplexHandler());
channel.pipeline().addLast("game", new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
game.add((ByteBuf) msg);
}
});
return channel;
}
private static void writeVarInt(ByteBuf out, int value) {
while ((value & ~0x7F) != 0) {
out.writeByte((value & 0x7F) | 0x80);
value >>>= 7;
}
out.writeByte(value);
}
private static int readVarInt(ByteBuf in) {
int value = 0;
for (int shift = 0; ; shift += 7) {
byte b = in.readByte();
value |= (b & 0x7F) << shift;
if ((b & 0x80) == 0) {
return value;
}
}
}
private static void writeString(ByteBuf out, String value) {
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
writeVarInt(out, bytes.length);
out.writeBytes(bytes);
}
private static String readString(ByteBuf in) {
int length = readVarInt(in);
String value = in.toString(in.readerIndex(), length, StandardCharsets.UTF_8);
in.skipBytes(length);
return value;
}
}