Merge pull request 'Add ViaAxiom' (#1) from import-viaaxiom into main
Deploy / Build (push) Successful in 1m31s
Deploy / Deploy (push) Successful in 4s

Reviewed-on: #1
Reviewed-by: YoyoNow <4+yoyonow@noreply.localhost>
This commit was merged in pull request #1.
This commit is contained in:
2026-11-06 09:35:20 +01:00
78 changed files with 4500 additions and 965 deletions
+2 -34
View File
@@ -4,7 +4,6 @@ on:
push:
branches:
- main
- version/*
jobs:
build:
@@ -13,21 +12,6 @@ jobs:
steps:
- name: Checkout sources
uses: actions/checkout@v6
- name: Setup Java 8
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 8
- name: Setup Java 11
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 11
- name: Setup Java 17
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 17
- name: Setup Java
uses: actions/setup-java@v5
with:
@@ -35,11 +19,6 @@ jobs:
java-version: 21
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
- name: Setup Maven Repository
env:
SW_MAVEN_CREDENTIALS: ${{ secrets.SW_MAVEN_CREDENTIALS }}
run: |
echo "$SW_MAVEN_CREDENTIALS" > steamwar.properties
- name: Build with Gradle
run: ./gradlew clean build --no-daemon --no-build-cache --refresh-dependencies
@@ -51,7 +30,7 @@ jobs:
rm -rf deploy
mkdir -p deploy
cp "build/libs/ViaAxiom-all.jar" "deploy/ViaAxiom.jar"
cp velocity/build/libs/viaaxiom-velocity-*[0-9].jar deploy/ViaAxiom.jar
- name: Upload deploy artifacts
uses: actions/upload-artifact@v3
@@ -75,7 +54,7 @@ jobs:
shell: bash
run: |
set -euo pipefail
echo "path=/jars/current" >> "$GITHUB_OUTPUT"
echo "path=/jars/viaaxiom" >> "$GITHUB_OUTPUT"
- name: Upload jars with scp
shell: bash
@@ -107,14 +86,3 @@ jobs:
ssh -i ~/.ssh/deploy_key -p "$port" "${DEPLOY_USER}@${DEPLOY_HOST}" "mv '$DEPLOY_PATH'/upload/* '$DEPLOY_PATH'"
ssh -i ~/.ssh/deploy_key -p "$port" "${DEPLOY_USER}@${DEPLOY_HOST}" "rm -r '$DEPLOY_PATH/upload'"
ssh -i ~/.ssh/deploy_key -p "$port" "${DEPLOY_USER}@${DEPLOY_HOST}" "chmod o-w '$DEPLOY_PATH'/*"
- name: Restart Services
shell: bash
env:
DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
DEPLOY_USER: ${{ secrets.DEPLOY_USER }}
DEPLOY_PORT: ${{ secrets.DEPLOY_PORT }}
DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
run: |
set -euo pipefail
ssh -i ~/.ssh/deploy_key -p "$DEPLOY_PORT" "${DEPLOY_USER}@${DEPLOY_HOST}" "unzip -o /jars/current/sw.zip -d /jars"
+26 -28
View File
@@ -1,35 +1,33 @@
# Package Files
*.jar
# MacOS DS_Store files
.DS_Store
# Gradle
# Gradle cache folder
.gradle
**/build/
!gradle/wrapper/gradle-wrapper.jar
steamwar.properties
# Kotlin
# Gradle build folder
build
# IntelliJ
out/
.idea
*.iml
# mpeltonen/sbt-idea plugin
.idea_modules/
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
# Common working directory
run
# Kotlin compiler state
.kotlin
# IntelliJ IDEA
*.iml
.idea
!.idea/copyright
!.idea/runConfigurations
# Runtime logs
logs
# VSCode
bin/
.vscode
.settings
# Private test tools
tools
# Language Server
**/.project
**/.factorypath
**/.classpath
# Other
lib
/WebsiteBackend/data
/WebsiteBackend/logs
/WebsiteBackend/skins
/WebsiteBackend/config.json
/WebsiteBackend/sessions
# SW
steamwar.properties
-7
View File
@@ -1,7 +0,0 @@
<component name="CopyrightManager">
<settings default="sw">
<module2copyright>
<element module="All" copyright="sw" />
</module2copyright>
</settings>
</component>
-6
View File
@@ -1,6 +0,0 @@
<component name="CopyrightManager">
<copyright>
<option name="notice" value=" This file is a part of the SteamWar software.&#10; &#10; Copyright (C) &amp;#36;today.year SteamWar.de-Serverteam&#10; &#10; This program is free software: you can redistribute it and/or modify&#10; it under the terms of the GNU Affero General Public License as published by&#10; the Free Software Foundation, either version 3 of the License, or&#10; (at your option) any later version.&#10; &#10; This program is distributed in the hope that it will be useful,&#10; but WITHOUT ANY WARRANTY; without even the implied warranty of&#10; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the&#10; GNU Affero General Public License for more details.&#10; &#10; You should have received a copy of the GNU Affero General Public License&#10; along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;." />
<option name="myName" value="sw" />
</copyright>
</component>
-619
View File
@@ -1,619 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Jakob Schulz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+7
View File
@@ -0,0 +1,7 @@
The protocol handling follows AxiomPaperPlugin by Moulberry, MIT licensed.
https://github.com/Moulberry/AxiomPaperPlugin
The built jars bundle these libraries:
zstd-jni, BSD 2-Clause, https://github.com/luben/zstd-jni
Kotlin standard library (Velocity plugin only), Apache 2.0, https://github.com/JetBrains/kotlin
+38
View File
@@ -0,0 +1,38 @@
# ViaAxiom
Translates Axiom traffic between Axiom and Minecraft versions. The Velocity plugin does this on the proxy, so players only need Axiom. The Fabric client mod does the same on the client, for servers you don't run. Never use both on one connection, the IDs would be translated twice.
## Velocity plugin
Needs Java 21 and ViaVersion on the proxy. Add ViaBackwards if clients can be older than a backend. Backends run AxiomPaper as usual, and it still decides permissions.
Build with JDK 21 or newer and put the jar in `plugins/`:
```
./gradlew :velocity:shadowJar
```
The jar ends up in `velocity/build/libs`. It bundles Zstd for Linux x64, Linux arm64 and Windows x64.
| Client | Backend | Result |
|--------|---------------------------------|---------------------------------------------------------------------|
| API 10 | API 9 | Bridged, with block IDs translated if the Minecraft versions differ |
| API 10 | API 10, other Minecraft version | Block IDs translated |
| API 10 | API 10, same Minecraft version | Passed through |
| API 9 | any | Passed through, not translated |
## Fabric mod
Needs ViaFabricPlus. Build with JDK 25, older JDKs skip this module:
```
./gradlew :fabric:build
```
## Layout
`core` holds the protocol codecs and translation. `velocity` and `fabric` are thin adapters around it. Protocol notes are in [docs/protocol.md](docs/protocol.md).
## License
MIT. See [NOTICE.txt](NOTICE.txt) for credits and bundled libraries.
+6 -65
View File
@@ -1,69 +1,10 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2025 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
plugins {
`java-library`
alias(libs.plugins.shadow)
kotlin("jvm") version "2.4.0" apply false
id("net.fabricmc.fabric-loom") version "1.17.21" apply false
id("com.gradleup.shadow") version "9.6.1" apply false
}
val libs = the<VersionCatalogsExtension>().named("libs")
java {
sourceCompatibility = JavaVersion.VERSION_21
targetCompatibility = JavaVersion.VERSION_21
}
tasks.compileJava {
options.encoding = "UTF-8"
}
sourceSets {
main {
java {
srcDirs("src/")
exclude("**/*.kt")
}
resources {
srcDirs("src/")
exclude("**/*.java", "**/*.kt")
}
}
test {
java {
srcDirs("testsrc/")
exclude("**/*.kt")
}
resources {
srcDirs("testsrc/")
exclude("**/*.java", "**/*.kt")
}
}
}
tasks.build {
finalizedBy(tasks.shadowJar)
}
dependencies {
val lombok = libs.findLibrary("lombok").get()
annotationProcessor(lombok)
compileOnly(lombok)
testCompileOnly(lombok)
testAnnotationProcessor(lombok)
subprojects {
version = rootProject.property("mod_version") as String
group = rootProject.property("maven_group") as String
}
+37
View File
@@ -0,0 +1,37 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm")
}
base {
archivesName.set("viaaxiom-core")
}
// Velocity can run on Java 21, so the shared core cannot target the Fabric mod's Java 25.
val targetJavaVersion = 21
repositories {
mavenCentral()
}
dependencies {
api("com.github.luben:zstd-jni:1.5.5-4")
testImplementation(kotlin("test"))
}
tasks.withType<KotlinCompile>().configureEach {
compilerOptions {
jvmTarget.set(JvmTarget.fromTarget(targetJavaVersion.toString()))
freeCompilerArgs.add("-Xjdk-release=$targetJavaVersion")
}
}
tasks.withType<JavaCompile>().configureEach {
options.release.set(targetJavaVersion)
}
tasks.test {
useJUnitPlatform()
}
@@ -0,0 +1,149 @@
package me.wargearsystems.viaaxiom.binary
import java.lang.invoke.MethodHandles
import java.lang.invoke.VarHandle
import java.nio.ByteOrder
import java.nio.charset.StandardCharsets
class AxiomByteReader(
private val bytes: ByteArray,
) {
var readerIndex: Int = 0
private set
val readableBytes: Int
get() = bytes.size - readerIndex
fun isReadable(): Boolean = readableBytes > 0
fun readByte(): Byte {
requireReadable(1)
return bytes[readerIndex++]
}
fun readUnsignedByte(): Int = readByte().toInt() and 0xFF
fun readBoolean(): Boolean = readUnsignedByte() != 0
fun readShort(): Short {
requireReadable(Short.SIZE_BYTES)
val value = ((bytes[readerIndex].toInt() and 0xFF) shl 8) or
(bytes[readerIndex + 1].toInt() and 0xFF)
readerIndex += Short.SIZE_BYTES
return value.toShort()
}
fun readInt(): Int {
requireReadable(Int.SIZE_BYTES)
val value = ((bytes[readerIndex].toInt() and 0xFF) shl 24) or
((bytes[readerIndex + 1].toInt() and 0xFF) shl 16) or
((bytes[readerIndex + 2].toInt() and 0xFF) shl 8) or
(bytes[readerIndex + 3].toInt() and 0xFF)
readerIndex += Int.SIZE_BYTES
return value
}
fun readLong(): Long {
requireReadable(Long.SIZE_BYTES)
var value = 0L
repeat(Long.SIZE_BYTES) {
value = (value shl 8) or (bytes[readerIndex++].toLong() and 0xFFL)
}
return value
}
fun readLongArray(): LongArray {
return readLongArray(readVarInt())
}
fun readLongArray(length: Int): LongArray {
if (length < 0) {
throw AxiomByteCodecException("Long array length cannot be negative: $length")
}
if (length > readableBytes / Long.SIZE_BYTES) {
throw AxiomByteCodecException("Long array exceeds remaining packet bytes")
}
val values = LongArray(length)
for (index in values.indices) {
values[index] = BIG_ENDIAN_LONGS.get(bytes, readerIndex) as Long
readerIndex += Long.SIZE_BYTES
}
return values
}
fun readVarInt(): Int {
var value = 0
var position = 0
while (position < 32) {
val currentByte = readUnsignedByte()
value = value or ((currentByte and 0x7F) shl position)
if ((currentByte and 0x80) == 0) {
return value
}
position += 7
}
throw AxiomByteCodecException("VarInt is too large")
}
fun readByteArray(maxLength: Int = Int.MAX_VALUE): ByteArray {
val length = readVarInt()
if (length > maxLength) {
throw AxiomByteCodecException("Byte array is too long: $length bytes")
}
return readBytes(length)
}
fun readUtf(maxLength: Int = 32767): String {
val byteLength = readVarInt()
if (byteLength < 0) {
throw AxiomByteCodecException("String byte length cannot be negative: $byteLength")
}
if (byteLength > maxLength * 4) {
throw AxiomByteCodecException("Encoded string is too long: $byteLength bytes")
}
val value = String(readBytes(byteLength), StandardCharsets.UTF_8)
if (value.length > maxLength) {
throw AxiomByteCodecException("Decoded string is too long: ${value.length} characters")
}
return value
}
fun readBytes(length: Int): ByteArray {
if (length < 0) {
throw AxiomByteCodecException("Byte length cannot be negative: $length")
}
requireReadable(length)
val value = bytes.copyOfRange(readerIndex, readerIndex + length)
readerIndex += length
return value
}
fun skipBytes(length: Int) {
if (length < 0) {
throw AxiomByteCodecException("Skip length cannot be negative: $length")
}
requireReadable(length)
readerIndex += length
}
fun copyRemaining(): ByteArray = readBytes(readableBytes)
private fun requireReadable(length: Int) {
if (readableBytes < length) {
throw AxiomByteCodecException("Need $length readable bytes, only $readableBytes available")
}
}
}
internal val BIG_ENDIAN_LONGS: VarHandle =
MethodHandles.byteArrayViewVarHandle(LongArray::class.java, ByteOrder.BIG_ENDIAN)
class AxiomByteCodecException(message: String) : IllegalArgumentException(message)
@@ -0,0 +1,98 @@
package me.wargearsystems.viaaxiom.binary
import java.nio.charset.StandardCharsets
class AxiomByteWriter(initialCapacity: Int = 256) {
private var buffer = ByteArray(initialCapacity.coerceAtLeast(16))
var size: Int = 0
private set
fun writeByte(value: Int): AxiomByteWriter {
ensureCapacity(1)
buffer[size++] = value.toByte()
return this
}
fun writeBoolean(value: Boolean): AxiomByteWriter = writeByte(if (value) 1 else 0)
fun writeShort(value: Int): AxiomByteWriter {
writeByte(value ushr 8)
writeByte(value)
return this
}
fun writeInt(value: Int): AxiomByteWriter {
writeByte(value ushr 24)
writeByte(value ushr 16)
writeByte(value ushr 8)
writeByte(value)
return this
}
fun writeLong(value: Long): AxiomByteWriter {
for (shift in 56 downTo 0 step 8) {
writeByte((value ushr shift).toInt())
}
return this
}
fun writeLongArray(values: LongArray, includeLength: Boolean = true): AxiomByteWriter {
if (includeLength) {
writeVarInt(values.size)
}
ensureCapacity(values.size * Long.SIZE_BYTES)
for (value in values) {
BIG_ENDIAN_LONGS.set(buffer, size, value)
size += Long.SIZE_BYTES
}
return this
}
fun writeVarInt(value: Int): AxiomByteWriter {
var remaining = value
while ((remaining and -0x80) != 0) {
writeByte((remaining and 0x7F) or 0x80)
remaining = remaining ushr 7
}
writeByte(remaining)
return this
}
fun writeUtf(value: String, maxLength: Int = 32767): AxiomByteWriter {
if (value.length > maxLength) {
throw AxiomByteCodecException("String is too long: ${value.length} characters")
}
val encoded = value.toByteArray(StandardCharsets.UTF_8)
if (encoded.size > maxLength * 4) {
throw AxiomByteCodecException("Encoded string is too long: ${encoded.size} bytes")
}
writeVarInt(encoded.size)
writeBytes(encoded)
return this
}
fun writeByteArray(bytes: ByteArray): AxiomByteWriter {
writeVarInt(bytes.size)
writeBytes(bytes)
return this
}
fun writeBytes(bytes: ByteArray): AxiomByteWriter {
ensureCapacity(bytes.size)
bytes.copyInto(buffer, size)
size += bytes.size
return this
}
fun toByteArray(): ByteArray = buffer.copyOf(size)
private fun ensureCapacity(additional: Int) {
val required = size + additional
if (required > buffer.size) {
buffer = buffer.copyOf(maxOf(required, buffer.size * 2))
}
}
}
@@ -0,0 +1,56 @@
package me.wargearsystems.viaaxiom.protocol
import me.wargearsystems.viaaxiom.binary.AxiomByteReader
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
object AxiomCustomBlockCodec {
fun rewrite(bytes: ByteArray, mapper: (Int) -> Int): ByteArray {
val reader = AxiomByteReader(bytes)
val writer = AxiomByteWriter()
writer.writeUtf(reader.readUtf()) // identifier
writer.writeUtf(reader.readUtf()) // translation key
val properties = count(reader, writer)
repeat(properties) {
val type = reader.readUnsignedByte()
writer.writeByte(type)
when (type) {
0 -> writer.writeUtf(reader.readUtf())
1 -> writer.writeUtf(reader.readUtf()).writeInt(reader.readInt()).writeInt(reader.readInt())
2 -> {
writer.writeUtf(reader.readUtf())
repeat(count(reader, writer)) { writer.writeUtf(reader.readUtf()) }
}
in 3..15 -> Unit
else -> error("Unsupported Axiom custom block property $type")
}
}
repeat(count(reader, writer)) { state(reader, writer, mapper) }
// Item components differ per version and have no codec here yet.
require(!reader.readBoolean()) { "Cross-version Axiom custom block item icons are not supported yet" }
writer.writeBoolean(false)
repeat(3) { writer.writeBoolean(reader.readBoolean()) }
repeat(count(reader, writer)) { writer.writeUtf(reader.readUtf()) }
writer.writeBoolean(reader.readBoolean())
repeat(4) {
repeat(count(reader, writer)) { state(reader, writer, mapper); state(reader, writer, mapper) }
}
require(count(reader, writer) == 0 && reader.readableBytes == 0) { "Unknown Axiom custom block extension" }
return writer.toByteArray()
}
private fun count(reader: AxiomByteReader, writer: AxiomByteWriter): Int {
val count = reader.readVarInt()
require(count in 0..65_536) { "Invalid custom block collection count" }
writer.writeVarInt(count)
return count
}
private fun state(reader: AxiomByteReader, writer: AxiomByteWriter, mapper: (Int) -> Int) {
val id = reader.readVarInt()
if (id == -1) writer.writeVarInt(-1).writeUtf(reader.readUtf())
else {
require(id >= 0) { "Invalid custom block state ID" }
writer.writeVarInt(mapper(id))
}
}
}
@@ -0,0 +1,45 @@
package me.wargearsystems.viaaxiom.protocol
import me.wargearsystems.viaaxiom.binary.AxiomByteReader
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
data class AxiomCustomPayloadFrame(
val packetId: Int,
val channel: String,
val payloadBytes: ByteArray,
)
object AxiomCustomPayloadFrameCodec {
fun read(frameBytes: ByteArray): AxiomCustomPayloadFrame {
val reader = AxiomByteReader(frameBytes)
return AxiomCustomPayloadFrame(
packetId = reader.readVarInt(),
channel = reader.readUtf(),
payloadBytes = reader.copyRemaining(),
)
}
fun readIfCustomPayload(frameBytes: ByteArray, customPayloadPacketId: Int): AxiomCustomPayloadFrame? {
val reader = AxiomByteReader(frameBytes)
val packetId = reader.readVarInt()
if (packetId != customPayloadPacketId) return null
return AxiomCustomPayloadFrame(packetId, reader.readUtf(), reader.copyRemaining())
}
fun write(frame: AxiomCustomPayloadFrame): ByteArray {
return AxiomByteWriter()
.writeVarInt(frame.packetId)
.writeUtf(frame.channel)
.writeBytes(frame.payloadBytes)
.toByteArray()
}
fun rewriteIfCustomPayload(
frameBytes: ByteArray,
customPayloadPacketId: Int,
rewriter: (AxiomCustomPayloadFrame) -> ByteArray,
): ByteArray {
val frame = readIfCustomPayload(frameBytes, customPayloadPacketId) ?: return frameBytes
return write(frame.copy(payloadBytes = rewriter(frame)))
}
}
@@ -0,0 +1,63 @@
package me.wargearsystems.viaaxiom.protocol
import me.wargearsystems.viaaxiom.binary.AxiomByteReader
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
object AxiomEnableCodec {
fun read(bytes: ByteArray, apiVersion: Int = AxiomProtocol.LEGACY_API_VERSION): AxiomEnable {
val reader = AxiomByteReader(bytes)
return read(reader, apiVersion)
}
fun read(reader: AxiomByteReader, apiVersion: Int = AxiomProtocol.LEGACY_API_VERSION): AxiomEnable {
require(apiVersion == AxiomProtocol.LEGACY_API_VERSION || apiVersion == AxiomProtocol.API_VERSION) {
"Unsupported Axiom API version: $apiVersion"
}
val enabled = reader.readBoolean()
if (!enabled) return AxiomEnable(false, 0, 0, 0, 0)
if (apiVersion == AxiomProtocol.LEGACY_API_VERSION) {
return AxiomEnable(true, reader.readInt(), reader.readVarInt(), reader.readVarInt(), reader.readVarInt())
}
val configVersion = reader.readUnsignedByte()
require(configVersion == 0) { "Unsupported Axiom server config version: $configVersion" }
val blueprintVersion = reader.readVarInt()
val splitSize = reader.readInt()
val maximumSize = reader.readInt()
require(splitSize > 1 && maximumSize > 0) { "Invalid Axiom tunnel limits" }
// Upstream always sends these empty, and their format is unknown.
val customDataCount = reader.readVarInt()
require(customDataCount == 0) { "Axiom custom data overrides are not supported" }
val rotationCount = reader.readVarInt()
require(rotationCount == 0) { "Axiom rotation overrides are not supported" }
val channelCount = reader.readVarInt()
require(channelCount in 0..1024) { "Invalid Axiom channel count: $channelCount" }
val channels = List(channelCount) { reader.readUtf() }
require(reader.readableBytes == 0) { "Trailing bytes in API 10 enable" }
return AxiomEnable(
enabled = true, blueprintVersion = blueprintVersion,
customDataOverridesCount = customDataCount, rotationOverridesCount = rotationCount,
serverConfigVersion = configVersion, tunnelSplitSize = splitSize,
maximumTunnelPacketSize = maximumSize, supportedServerboundChannels = channels,
)
}
fun write(enable: AxiomEnable, apiVersion: Int = AxiomProtocol.LEGACY_API_VERSION): ByteArray {
require(apiVersion == AxiomProtocol.LEGACY_API_VERSION || apiVersion == AxiomProtocol.API_VERSION)
val writer = AxiomByteWriter().writeBoolean(enable.enabled)
if (!enable.enabled) return writer.toByteArray()
if (apiVersion == AxiomProtocol.LEGACY_API_VERSION) {
return writer.writeInt(enable.maxBufferSize).writeVarInt(enable.blueprintVersion)
.writeVarInt(enable.customDataOverridesCount).writeVarInt(enable.rotationOverridesCount).toByteArray()
}
require(enable.serverConfigVersion == 0)
require(enable.customDataOverridesCount == 0 && enable.rotationOverridesCount == 0)
val splitSize = requireNotNull(enable.tunnelSplitSize)
val maximumSize = requireNotNull(enable.maximumTunnelPacketSize)
require(splitSize > 1 && maximumSize > 0)
require(enable.supportedServerboundChannels.size <= 1024)
writer.writeByte(0).writeVarInt(enable.blueprintVersion).writeInt(splitSize).writeInt(maximumSize)
.writeVarInt(0).writeVarInt(0).writeVarInt(enable.supportedServerboundChannels.size)
enable.supportedServerboundChannels.forEach { writer.writeUtf(it) }
return writer.toByteArray()
}
}
@@ -0,0 +1,36 @@
package me.wargearsystems.viaaxiom.protocol
data class AxiomHello(
val apiVersion: Int,
val dataVersion: Int,
val protocolVersion: Int,
val handshakeId: Long? = null,
) {
val isSupportedApi: Boolean
get() = apiVersion == AxiomProtocol.LEGACY_API_VERSION || apiVersion == AxiomProtocol.API_VERSION
}
data class AxiomEnable(
val enabled: Boolean,
val maxBufferSize: Int = 0,
val blueprintVersion: Int,
val customDataOverridesCount: Int,
val rotationOverridesCount: Int,
val serverConfigVersion: Int? = null,
val tunnelSplitSize: Int? = null,
val maximumTunnelPacketSize: Int? = null,
val supportedServerboundChannels: List<String> = emptyList(),
)
data class AxiomTranslationSession(
val hello: AxiomHello,
val serverProtocolVersion: Int,
val serverDataVersion: Int? = null,
val enable: AxiomEnable? = null,
) {
val protocolMismatch: Boolean
get() = hello.protocolVersion != serverProtocolVersion
val dataVersionMismatch: Boolean
get() = serverDataVersion != null && hello.dataVersion != serverDataVersion
}
@@ -0,0 +1,62 @@
package me.wargearsystems.viaaxiom.protocol
import me.wargearsystems.viaaxiom.binary.AxiomByteReader
class AxiomHandshakeTracker {
var hello: AxiomHello? = null
private set
var enable: AxiomEnable? = null
private set
var challengeId: Long? = null
private set
var goodbyeReason: String? = null
private set
fun observe(direction: AxiomPayloadDirection, channel: String, bytes: ByteArray) {
when (AxiomPayloadKey(direction, channel)) {
AxiomPayloadKey(AxiomPayloadDirection.CLIENTBOUND, AxiomProtocol.channel("hello")) -> {
reset()
require(bytes.size == Long.SIZE_BYTES) { "Invalid Axiom handshake challenge" }
challengeId = AxiomByteReader(bytes).readLong()
}
AxiomPayloadKey(AxiomPayloadDirection.SERVERBOUND, AxiomProtocol.channel("hello")) -> {
hello = null
enable = null
val candidate = AxiomHelloCodec.read(bytes)
if (candidate.apiVersion == AxiomProtocol.API_VERSION) {
require(challengeId != null && candidate.handshakeId == challengeId) {
"Axiom hello does not match the server handshake challenge"
}
} else {
require(challengeId == null) { "API 9 hello cannot answer an API 10 challenge" }
}
hello = candidate
goodbyeReason = null
}
AxiomPayloadKey(AxiomPayloadDirection.CLIENTBOUND, AxiomProtocol.channel("enable")) -> {
enable = null
val apiVersion = requireNotNull(hello) { "Axiom enable received before client hello" }.apiVersion
enable = AxiomEnableCodec.read(bytes, apiVersion)
}
AxiomPayloadKey(AxiomPayloadDirection.CLIENTBOUND, AxiomProtocol.channel("redo_handshake")) -> reset()
AxiomPayloadKey(AxiomPayloadDirection.CLIENTBOUND, AxiomProtocol.channel("goodbye")) -> {
reset()
goodbyeReason = AxiomByteReader(bytes).readUtf()
}
}
}
fun session(serverProtocolVersion: Int?, serverDataVersion: Int? = null): AxiomTranslationSession? {
val hello = hello ?: return null
val enable = enable ?: return null
if (!enable.enabled || serverProtocolVersion == null) return null
return AxiomTranslationSession(hello, serverProtocolVersion, serverDataVersion, enable)
}
fun reset() {
hello = null
enable = null
challengeId = null
goodbyeReason = null
}
}
@@ -0,0 +1,38 @@
package me.wargearsystems.viaaxiom.protocol
import me.wargearsystems.viaaxiom.binary.AxiomByteReader
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
object AxiomHelloCodec {
fun read(bytes: ByteArray): AxiomHello {
val reader = AxiomByteReader(bytes)
val hello = read(reader)
require(reader.readableBytes == 0) { "Trailing bytes in Axiom hello" }
return hello
}
fun read(reader: AxiomByteReader): AxiomHello {
val apiVersion = reader.readVarInt()
require(apiVersion == AxiomProtocol.LEGACY_API_VERSION || apiVersion == AxiomProtocol.API_VERSION) {
"Unsupported Axiom API version: $apiVersion"
}
val dataVersion = reader.readVarInt()
val protocolVersion = reader.readVarInt()
val handshakeId = if (apiVersion == AxiomProtocol.API_VERSION) reader.readLong() else null
return AxiomHello(apiVersion, dataVersion, protocolVersion, handshakeId)
}
fun write(hello: AxiomHello): ByteArray {
require(hello.isSupportedApi) { "Unsupported Axiom API version: ${hello.apiVersion}" }
val writer = AxiomByteWriter()
.writeVarInt(hello.apiVersion)
.writeVarInt(hello.dataVersion)
.writeVarInt(hello.protocolVersion)
if (hello.apiVersion == AxiomProtocol.API_VERSION) {
writer.writeLong(requireNotNull(hello.handshakeId) { "API 10 hello requires a handshake ID" })
} else {
require(hello.handshakeId == null) { "API 9 hello cannot contain a handshake ID" }
}
return writer.toByteArray()
}
}
@@ -0,0 +1,120 @@
package me.wargearsystems.viaaxiom.protocol
import me.wargearsystems.viaaxiom.binary.AxiomByteReader
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
import me.wargearsystems.viaaxiom.translation.AxiomPayload
import me.wargearsystems.viaaxiom.translation.AxiomPayloadTranslator
import java.util.UUID
/** API 10 client <-> API 9 server. The server still decides permissions and activation. */
class AxiomLegacyBridge(
private val serverProtocolVersion: Int,
private val translator: AxiomPayloadTranslator,
private val challengeSource: () -> Long = { UUID.randomUUID().mostSignificantBits },
) {
private val channels = linkedSetOf<String>()
private var modernServer = false
private var challenge: Long? = null
private var hello: AxiomHello? = null
private var enable: AxiomEnable? = null
private val tunnel = AxiomTunnelCollector()
val awaitingLegacyChallenge: Boolean
get() = !modernServer && challenge == null && "axiom:hello" in channels && "axiom:tunnel" !in channels
val active: Boolean get() = !modernServer && challenge != null
fun register(bytes: ByteArray) {
require(bytes.size <= 131_072) { "Oversized channel registration" }
channels.addAll(bytes.toString(Charsets.UTF_8).split('\u0000').filter(AxiomProtocol::isAxiomChannel))
if ("axiom:tunnel" in channels) {
modernServer = true
clearNegotiation()
}
}
fun createChallenge(packetId: Int): AxiomCustomPayloadFrame? {
if (!awaitingLegacyChallenge) return null
val id = challengeSource()
challenge = id
return AxiomCustomPayloadFrame(packetId, "axiom:hello", AxiomByteWriter().writeLong(id).toByteArray())
}
fun clientbound(frame: AxiomCustomPayloadFrame): AxiomCustomPayloadFrame {
if (frame.channel == "axiom:hello" || frame.channel == "axiom:goodbye") {
modernServer = true
clearNegotiation()
return frame
}
if (!active) return frame
if (frame.channel == "axiom:redo_handshake") {
clearNegotiation()
val id = challengeSource()
challenge = id
return frame.copy(channel = "axiom:hello", payloadBytes = AxiomByteWriter().writeLong(id).toByteArray())
}
if (frame.channel == "axiom:enable") {
val reader = AxiomByteReader(frame.payloadBytes)
val legacy = AxiomEnableCodec.read(reader, 9)
require(reader.readableBytes == 0 && legacy.customDataOverridesCount == 0 && legacy.rotationOverridesCount == 0) {
"Unsupported legacy Axiom configuration"
}
require(!legacy.enabled || hello != null) { "Legacy enable before client hello" }
require(!legacy.enabled || legacy.maxBufferSize in 1..AxiomTunnelCodec.DEFAULT_MAXIMUM_PACKET_SIZE) {
"Unsupported legacy Axiom buffer limit"
}
enable = legacy
tunnel.clear()
val supported = channels.filter { it in AxiomProtocol.SERVERBOUND_CHANNELS && it != "axiom:tunnel" }
val modern = legacy.copy(
serverConfigVersion = 0,
tunnelSplitSize = AxiomTunnelCodec.DEFAULT_SPLIT_SIZE,
maximumTunnelPacketSize = legacy.maxBufferSize,
// The bridge terminates the tunnel, the API 9 server never sees it.
supportedServerboundChannels = supported + "axiom:tunnel",
)
return frame.copy(payloadBytes = AxiomEnableCodec.write(modern, 10))
}
return rewrite(frame, AxiomPayloadDirection.CLIENTBOUND)
}
/** Null consumes an intermediate tunnel fragment. */
fun serverbound(frame: AxiomCustomPayloadFrame): AxiomCustomPayloadFrame? {
if (!active) return frame
if (frame.channel == "axiom:hello") {
val candidate = AxiomHelloCodec.read(frame.payloadBytes)
require(candidate.apiVersion == 10 && candidate.handshakeId == challenge) { "Unexpected legacy bridge challenge reply" }
hello = candidate
enable = null
tunnel.clear()
// The bridge translates IDs, so the server must not.
return frame.copy(payloadBytes = AxiomHelloCodec.write(candidate.copy(apiVersion = 9,
protocolVersion = serverProtocolVersion, handshakeId = null)))
}
if (frame.channel != "axiom:tunnel") return rewrite(frame, AxiomPayloadDirection.SERVERBOUND)
val negotiated = requireNotNull(enable?.takeIf { it.enabled }) { "Tunnel sent before legacy server enabled Axiom" }
val fragments = tunnel.add(frame.payloadBytes, AxiomTunnelCodec.DEFAULT_SPLIT_SIZE, negotiated.maxBufferSize) ?: return null
val packet = AxiomTunnelCodec.decode(fragments, maximumPacketSize = negotiated.maxBufferSize)
require(packet.channel in channels && packet.channel in AxiomProtocol.SERVERBOUND_CHANNELS && packet.channel != "axiom:hello") {
"Legacy server did not register ${packet.channel}"
}
val output = rewrite(frame.copy(channel = packet.channel, payloadBytes = packet.payload), AxiomPayloadDirection.SERVERBOUND)
val largeChannels = setOf("axiom:set_buffer", "axiom:upload_blueprint", "axiom:annotation_update")
val maximum = if (output.channel in largeChannels) negotiated.maxBufferSize else 32_767
require(output.payloadBytes.size <= maximum) { "${output.channel} exceeds legacy transport limit ($maximum)" }
return output
}
private fun rewrite(frame: AxiomCustomPayloadFrame, direction: AxiomPayloadDirection): AxiomCustomPayloadFrame {
if (enable?.enabled != true) return frame
val session = AxiomTranslationSession(requireNotNull(hello), serverProtocolVersion, enable = enable)
return frame.copy(payloadBytes = translator.rewrite(AxiomPayload(direction, frame.channel, frame.payloadBytes), session))
}
private fun clearNegotiation() {
challenge = null
hello = null
enable = null
tunnel.clear()
}
}
@@ -0,0 +1,54 @@
package me.wargearsystems.viaaxiom.protocol
import me.wargearsystems.viaaxiom.translation.AxiomPayload
import me.wargearsystems.viaaxiom.translation.AxiomPayloadTranslator
import me.wargearsystems.viaaxiom.translation.AxiomTunnelTranslationEngine
/** API 10 client <-> API 10 server on another Minecraft version. */
class AxiomModernBridge(
private val serverProtocolVersion: Int,
private val translator: AxiomPayloadTranslator,
) {
private val handshake = AxiomHandshakeTracker()
private val tunnelEngine = AxiomTunnelTranslationEngine(translator)
private val tunnel = AxiomTunnelCollector()
fun clientbound(frame: AxiomCustomPayloadFrame): AxiomCustomPayloadFrame {
if (frame.channel in HANDSHAKE_CHANNELS) {
tunnel.clear()
handshake.observe(AxiomPayloadDirection.CLIENTBOUND, frame.channel, frame.payloadBytes)
return frame
}
val session = session ?: return frame
return frame.copy(payloadBytes = translator.rewrite(
AxiomPayload(AxiomPayloadDirection.CLIENTBOUND, frame.channel, frame.payloadBytes), session))
}
/** Empty consumes an intermediate tunnel fragment. Translation can change the fragment count. */
fun serverbound(frame: AxiomCustomPayloadFrame): List<AxiomCustomPayloadFrame> {
if (frame.channel == "axiom:hello") {
if (handshake.challengeId == null) return listOf(frame)
tunnel.clear()
handshake.observe(AxiomPayloadDirection.SERVERBOUND, frame.channel, frame.payloadBytes)
// The bridge translates IDs, so the server must not.
val hello = requireNotNull(handshake.hello)
return listOf(frame.copy(payloadBytes = AxiomHelloCodec.write(hello.copy(protocolVersion = serverProtocolVersion))))
}
val session = session ?: return listOf(frame)
if (frame.channel != "axiom:tunnel") {
return listOf(frame.copy(payloadBytes = translator.rewrite(
AxiomPayload(AxiomPayloadDirection.SERVERBOUND, frame.channel, frame.payloadBytes), session)))
}
val enable = requireNotNull(session.enable)
val fragments = tunnel.add(frame.payloadBytes, requireNotNull(enable.tunnelSplitSize),
requireNotNull(enable.maximumTunnelPacketSize)) ?: return emptyList()
return tunnelEngine.rewrite(fragments, session).map { frame.copy(payloadBytes = it) }
}
private val session: AxiomTranslationSession?
get() = handshake.session(serverProtocolVersion)
private companion object {
val HANDSHAKE_CHANNELS = setOf("axiom:hello", "axiom:enable", "axiom:goodbye", "axiom:redo_handshake")
}
}
@@ -0,0 +1,75 @@
package me.wargearsystems.viaaxiom.protocol
object AxiomProtocol {
const val NAMESPACE: String = "axiom"
const val API_VERSION: Int = 10
const val LEGACY_API_VERSION: Int = 9
const val MIN_POSITION_LONG: Long = -9223371899415820288L
val CLIENTBOUND_CHANNELS: Set<String> = setOf(
channel("enable"),
channel("hello"),
channel("goodbye"),
channel("redo_handshake"),
channel("response_chunk_data"),
channel("response_entity_data"),
channel("register_world_properties"),
channel("set_world_property"),
channel("ack_world_properties"),
channel("restrictions"),
channel("marker_data"),
channel("marker_nbt_response"),
channel("annotation_update"),
channel("add_server_heightmap"),
channel("custom_blocks"),
channel("register_custom_block_v2"),
channel("ignore_display_entities"),
channel("register_custom_items"),
channel("blueprint_manifest"),
channel("response_blueprint"),
)
val SERVERBOUND_CHANNELS: Set<String> = setOf(
channel("hello"),
channel("tunnel"),
channel("tick_blocks"),
channel("set_gamemode"),
channel("set_fly_speed"),
channel("teleport"),
channel("set_world_time"),
channel("set_no_physical_trigger"),
channel("set_world_property"),
channel("request_chunk_data"),
channel("request_entity_data"),
channel("spawn_entity"),
channel("manipulate_entity"),
channel("delete_entity"),
channel("marker_nbt_request"),
channel("set_block"),
channel("set_buffer"),
channel("upload_blueprint"),
channel("request_blueprint"),
channel("annotation_update"),
)
val BLOCK_STATE_TRANSLATION_CHANNELS: Set<AxiomPayloadKey> = setOf(
AxiomPayloadKey(AxiomPayloadDirection.SERVERBOUND, channel("set_block")),
AxiomPayloadKey(AxiomPayloadDirection.SERVERBOUND, channel("set_buffer")),
AxiomPayloadKey(AxiomPayloadDirection.CLIENTBOUND, channel("response_chunk_data")),
AxiomPayloadKey(AxiomPayloadDirection.CLIENTBOUND, channel("register_custom_block_v2")),
)
fun channel(path: String): String = "$NAMESPACE:$path"
fun isAxiomChannel(channel: String): Boolean = channel.startsWith("$NAMESPACE:")
}
enum class AxiomPayloadDirection {
CLIENTBOUND,
SERVERBOUND,
}
data class AxiomPayloadKey(
val direction: AxiomPayloadDirection,
val channel: String,
)
@@ -0,0 +1,54 @@
package me.wargearsystems.viaaxiom.protocol
import me.wargearsystems.viaaxiom.binary.AxiomByteReader
import me.wargearsystems.viaaxiom.translation.AxiomPayloadTranslator
import java.util.UUID
/**
* One player's Axiom traffic to one backend.
*
* An exception means the frame could not be translated. Never forward such a frame,
* its IDs would select the wrong blocks.
*/
class AxiomProxySession(
private val clientProtocolVersion: Int,
private val serverProtocolVersion: Int,
translator: AxiomPayloadTranslator,
challengeSource: () -> Long = { UUID.randomUUID().mostSignificantBits },
) {
private val legacy = AxiomLegacyBridge(serverProtocolVersion, translator, challengeSource)
private val modern = AxiomModernBridge(serverProtocolVersion, translator)
/** Set for clients other than API 10, which talk to the backend directly. */
var passthrough = false
private set
val awaitingLegacyChallenge: Boolean
get() = !passthrough && legacy.awaitingLegacyChallenge
fun backendRegistered(bytes: ByteArray) = legacy.register(bytes)
fun startLegacyHandshake(): AxiomCustomPayloadFrame? = if (passthrough) null else legacy.createChallenge(0)
fun clientbound(frame: AxiomCustomPayloadFrame): AxiomCustomPayloadFrame {
if (passthrough) return frame
val output = legacy.clientbound(frame)
if (legacy.active || !versionsDiffer) return output
return modern.clientbound(output)
}
/** Empty consumes an intermediate tunnel fragment. */
fun serverbound(frame: AxiomCustomPayloadFrame): List<AxiomCustomPayloadFrame> {
if (passthrough) return listOf(frame)
if (frame.channel == "axiom:hello" && AxiomByteReader(frame.payloadBytes).readVarInt() != AxiomProtocol.API_VERSION) {
passthrough = true
return listOf(frame)
}
if (legacy.active) return listOfNotNull(legacy.serverbound(frame))
if (!versionsDiffer) return listOf(frame)
return modern.serverbound(frame)
}
private val versionsDiffer: Boolean
get() = clientProtocolVersion != serverProtocolVersion
}
@@ -0,0 +1,57 @@
package me.wargearsystems.viaaxiom.protocol
import me.wargearsystems.viaaxiom.binary.AxiomByteReader
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
object AxiomResponseChunkDataPayloadCodec {
fun rewriteSections(
bytes: ByteArray,
sectionRewriter: (reader: AxiomByteReader, writer: AxiomByteWriter) -> Unit,
): ByteArray {
val reader = AxiomByteReader(bytes)
val writer = AxiomByteWriter(bytes.size)
writer.writeLong(reader.readLong()) // Request id.
copyBlockEntities(reader, writer)
copySections(reader, writer, sectionRewriter)
writer.writeBoolean(reader.readBoolean()) // Finished.
writer.writeBytes(reader.copyRemaining())
return writer.toByteArray()
}
private fun copyBlockEntities(reader: AxiomByteReader, writer: AxiomByteWriter) {
while (true) {
val blockEntityPos = reader.readLong()
writer.writeLong(blockEntityPos)
if (blockEntityPos == AxiomProtocol.MIN_POSITION_LONG) {
break
}
writer.writeVarInt(reader.readVarInt()) // Original NBT size.
writer.writeByte(reader.readUnsignedByte()) // Compression dictionary id.
writer.writeByteArray(reader.readByteArray())
}
}
private fun copySections(
reader: AxiomByteReader,
writer: AxiomByteWriter,
sectionRewriter: (reader: AxiomByteReader, writer: AxiomByteWriter) -> Unit,
) {
while (true) {
val sectionIndex = reader.readLong()
writer.writeLong(sectionIndex)
if (sectionIndex == AxiomProtocol.MIN_POSITION_LONG) {
break
}
val hasContainer = reader.readBoolean()
writer.writeBoolean(hasContainer)
if (hasContainer) {
sectionRewriter(reader, writer)
}
}
}
}
@@ -0,0 +1,23 @@
package me.wargearsystems.viaaxiom.protocol
import me.wargearsystems.viaaxiom.binary.AxiomByteReader
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
object AxiomSetBlockPayloadCodec {
fun rewriteBlockStateIds(bytes: ByteArray, mapper: (Int) -> Int): ByteArray {
val reader = AxiomByteReader(bytes)
val writer = AxiomByteWriter()
val blockCount = reader.readVarInt()
writer.writeVarInt(blockCount)
repeat(blockCount) {
writer.writeLong(reader.readLong())
writer.writeVarInt(mapper(reader.readVarInt()))
}
writer.writeBytes(reader.copyRemaining())
return writer.toByteArray()
}
}
@@ -0,0 +1,54 @@
package me.wargearsystems.viaaxiom.protocol
import me.wargearsystems.viaaxiom.binary.AxiomByteReader
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
object AxiomSetBufferPayloadCodec {
private const val BLOCK_BUFFER_TYPE: Int = 0
fun rewriteBlockSections(
bytes: ByteArray,
sectionRewriter: (reader: AxiomByteReader, writer: AxiomByteWriter) -> Unit,
): ByteArray {
val reader = AxiomByteReader(bytes)
val writer = AxiomByteWriter(bytes.size)
writer.writeUtf(reader.readUtf()) // Dimension resource key value.
writer.writeLong(reader.readLong()) // UUID most significant bits.
writer.writeLong(reader.readLong()) // UUID least significant bits.
val type = reader.readUnsignedByte()
writer.writeByte(type)
if (type != BLOCK_BUFFER_TYPE) {
writer.writeBytes(reader.copyRemaining())
return writer.toByteArray()
}
while (true) {
val sectionIndex = reader.readLong()
writer.writeLong(sectionIndex)
if (sectionIndex == AxiomProtocol.MIN_POSITION_LONG) {
break
}
sectionRewriter(reader, writer)
copyBlockEntities(reader, writer)
}
writer.writeBytes(reader.copyRemaining())
return writer.toByteArray()
}
private fun copyBlockEntities(reader: AxiomByteReader, writer: AxiomByteWriter) {
val blockEntityCount = reader.readVarInt()
writer.writeVarInt(blockEntityCount)
repeat(blockEntityCount) {
writer.writeShort(reader.readShort().toInt())
writer.writeVarInt(reader.readVarInt()) // Original NBT size.
writer.writeByte(reader.readUnsignedByte()) // Compression dictionary id.
writer.writeByteArray(reader.readByteArray())
}
}
}
@@ -0,0 +1,86 @@
package me.wargearsystems.viaaxiom.protocol
import com.github.luben.zstd.Zstd
import com.github.luben.zstd.ZstdException
import me.wargearsystems.viaaxiom.binary.AxiomByteReader
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
import java.io.ByteArrayOutputStream
data class AxiomTunnelPacket(val channel: String, val payload: ByteArray, val compressed: Boolean = false)
/** API 10 serverbound transport. Split size includes the one-byte fragment flags. */
object AxiomTunnelCodec {
const val FIRST = 1
const val LAST = 2
const val ZSTD_COMPRESSED = 1
const val DEFAULT_SPLIT_SIZE = 31_000
const val DEFAULT_MAXIMUM_PACKET_SIZE = 2_097_152
private const val MAX_HEADER_SIZE = 131_080
fun decode(
fragments: List<ByteArray>,
splitSize: Int = DEFAULT_SPLIT_SIZE,
maximumPacketSize: Int = DEFAULT_MAXIMUM_PACKET_SIZE,
): AxiomTunnelPacket {
require(splitSize > 1 && maximumPacketSize > 0)
require(fragments.isNotEmpty()) { "Empty Axiom tunnel packet" }
val combined = ByteArrayOutputStream()
val maximumEncodedSize = Zstd.compressBound(maximumPacketSize.toLong()) + MAX_HEADER_SIZE
fragments.forEachIndexed { index, fragment ->
require(fragment.size in 2..splitSize) { "Invalid Axiom tunnel fragment size" }
val expectedFlags = (if (index == 0) FIRST else 0) or (if (index == fragments.lastIndex) LAST else 0)
require((fragment[0].toInt() and 0xFF) == expectedFlags) { "Invalid Axiom tunnel fragment order or flags" }
require(combined.size().toLong() + fragment.size - 1 <= maximumEncodedSize) { "Axiom tunnel packet exceeds limit" }
combined.write(fragment, 1, fragment.size - 1)
}
val reader = AxiomByteReader(combined.toByteArray())
val channel = reader.readUtf()
require(AxiomProtocol.isAxiomChannel(channel) && channel != AxiomProtocol.channel("tunnel")) {
"Invalid tunneled Axiom channel: $channel"
}
val uncompressedSize = reader.readInt()
require(uncompressedSize in 0..maximumPacketSize) { "Axiom tunnel payload exceeds limit" }
val flags = reader.readUnsignedByte()
require(flags == 0 || flags == ZSTD_COMPRESSED) { "Unsupported Axiom tunnel packet flags: $flags" }
val body = reader.copyRemaining()
val compressed = flags == ZSTD_COMPRESSED
val payload = if (compressed) {
val destination = ByteArray(uncompressedSize)
val result = try {
Zstd.decompressByteArray(destination, 0, destination.size, body, 0, body.size)
} catch (exception: ZstdException) {
throw IllegalArgumentException("Invalid Zstd Axiom tunnel payload", exception)
}
require(!Zstd.isError(result)) { "Invalid Zstd Axiom tunnel payload: ${Zstd.getErrorName(result)}" }
require(result == uncompressedSize.toLong()) { "Axiom tunnel decompressed size mismatch" }
destination
} else {
require(body.size == uncompressedSize) { "Axiom tunnel payload size mismatch" }
body
}
return AxiomTunnelPacket(channel, payload, compressed)
}
fun encode(
packet: AxiomTunnelPacket,
splitSize: Int = DEFAULT_SPLIT_SIZE,
maximumPacketSize: Int = DEFAULT_MAXIMUM_PACKET_SIZE,
): List<ByteArray> {
require(splitSize > 1 && maximumPacketSize > 0)
require(packet.payload.size <= maximumPacketSize) { "Axiom tunnel payload exceeds limit" }
require(AxiomProtocol.isAxiomChannel(packet.channel) && packet.channel != AxiomProtocol.channel("tunnel"))
val body = if (packet.compressed) Zstd.compress(packet.payload) else packet.payload
val bytes = AxiomByteWriter().writeUtf(packet.channel).writeInt(packet.payload.size)
.writeByte(if (packet.compressed) ZSTD_COMPRESSED else 0).writeBytes(body).toByteArray()
val bodyPerFragment = splitSize - 1
val count = ((bytes.size.toLong() + bodyPerFragment - 1) / bodyPerFragment).toInt()
return List(count) { index ->
val from = index * bodyPerFragment
val length = minOf(bodyPerFragment, bytes.size - from)
ByteArray(length + 1).also { fragment ->
fragment[0] = ((if (index == 0) FIRST else 0) or (if (index == count - 1) LAST else 0)).toByte()
bytes.copyInto(fragment, 1, from, from + length)
}
}
}
}
@@ -0,0 +1,36 @@
package me.wargearsystems.viaaxiom.protocol
class AxiomTunnelCollector {
private val fragments = mutableListOf<ByteArray>()
private var collectedBytes = 0L
/** Null until [fragment] completes a packet. */
fun add(fragment: ByteArray, splitSize: Int, maximumPacketSize: Int): List<ByteArray>? {
try {
require(fragment.size in 2..splitSize) { "Invalid tunnel fragment length" }
val flags = fragment[0].toInt() and 0xFF
require(flags in 0..3) { "Invalid tunnel flags" }
if (flags and AxiomTunnelCodec.FIRST != 0) {
require(fragments.isEmpty()) { "New tunnel before previous tunnel completed" }
} else require(fragments.isNotEmpty()) { "Tunnel continuation without first fragment" }
collectedBytes += fragment.size - 1
require(collectedBytes <= maximumPacketSize.toLong() + COMPRESSION_MARGIN) { "Tunnel exceeds server limit" }
fragments += fragment
if (flags and AxiomTunnelCodec.LAST == 0) return null
} catch (failure: IllegalArgumentException) {
clear()
throw failure
}
return fragments.toList().also { clear() }
}
fun clear() {
fragments.clear()
collectedBytes = 0
}
private companion object {
/** Incompressible payloads plus the header can slightly exceed the uncompressed limit. */
const val COMPRESSION_MARGIN = 262_144L
}
}
@@ -0,0 +1,326 @@
package me.wargearsystems.viaaxiom.protocol
import me.wargearsystems.viaaxiom.binary.AxiomByteReader
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
import kotlin.math.max
/** Unboxed, because a section can need 4096 lookups. */
fun interface BlockStateIdMapper {
fun map(id: Int): Int
}
object PalettedContainerCodec {
const val PROTOCOL_1_21_5: Int = 770
private const val BLOCK_COUNT: Int = 4096
private const val BLOCK_HIGHEST_BITS_PER_VALUE: Int = 8
private const val MIN_BLOCK_BITS_PER_VALUE: Int = 4
fun rewriteBlockStateIds(
reader: AxiomByteReader,
writer: AxiomByteWriter,
protocolVersion: Int,
globalPaletteBits: Int,
mapper: BlockStateIdMapper,
targetProtocolVersion: Int = protocolVersion,
targetGlobalPaletteBits: Int = globalPaletteBits,
) {
val sameLayout = globalPaletteBits == targetGlobalPaletteBits &&
(protocolVersion >= PROTOCOL_1_21_5) == (targetProtocolVersion >= PROTOCOL_1_21_5)
if (sameLayout) {
rewriteInPlace(reader, writer, protocolVersion, globalPaletteBits, mapper)
return
}
val container = readBlockContainer(reader, protocolVersion, globalPaletteBits)
container.replaceIds(mapper::map)
writeBlockContainer(writer, container, targetProtocolVersion, targetGlobalPaletteBits)
}
/** Palette indexes are copied as they are, and global IDs are mapped inside the packed longs. */
private fun rewriteInPlace(
reader: AxiomByteReader,
writer: AxiomByteWriter,
protocolVersion: Int,
globalPaletteBits: Int,
mapper: BlockStateIdMapper,
) {
require(protocolVersion >= 757) { "Palette formats before Minecraft 1.18 are not supported" }
require(globalPaletteBits in 9..31) { "Invalid global palette width: $globalPaletteBits" }
val encodedBits = reader.readUnsignedByte()
writer.writeByte(encodedBits)
if (encodedBits == 0) {
writer.writeVarInt(mappedId(mapper, reader.readVarInt(), globalPaletteBits))
writeValues(writer, protocolVersion, readValues(reader, protocolVersion, bitsPerValue = 0))
return
}
val bitsPerValue = normalizeBitsPerValue(encodedBits, globalPaletteBits)
if (bitsPerValue == globalPaletteBits) {
val values = readValues(reader, protocolVersion, bitsPerValue)
mapGlobalValues(values, bitsPerValue, mapper)
writeValues(writer, protocolVersion, values)
return
}
val paletteLength = reader.readVarInt()
require(paletteLength in 1..(1 shl bitsPerValue)) { "Invalid palette length: $paletteLength" }
writer.writeVarInt(paletteLength)
repeat(paletteLength) {
writer.writeVarInt(mappedId(mapper, reader.readVarInt(), globalPaletteBits))
}
val values = readValues(reader, protocolVersion, bitsPerValue)
requirePaletteIndexes(values, bitsPerValue, paletteLength)
writeValues(writer, protocolVersion, values)
}
private fun mappedId(mapper: BlockStateIdMapper, id: Int, globalPaletteBits: Int): Int {
val mapped = mapper.map(id)
require(mapped >= 0 && mapped.toLong() < (1L shl globalPaletteBits)) {
"Block state ID does not fit the target registry width"
}
return mapped
}
private fun mapGlobalValues(values: LongArray, bitsPerValue: Int, mapper: BlockStateIdMapper) {
val mask = (1L shl bitsPerValue) - 1L
val valuesPerLong = 64 / bitsPerValue
var remaining = BLOCK_COUNT
for (cellIndex in values.indices) {
val cell = values[cellIndex]
var mappedCell = 0L
var position = 0
while (position < valuesPerLong && remaining > 0) {
val shift = position * bitsPerValue
val id = ((cell ushr shift) and mask).toInt()
mappedCell = mappedCell or (mappedId(mapper, id, bitsPerValue).toLong() shl shift)
position++
remaining--
}
values[cellIndex] = mappedCell
}
}
private fun requirePaletteIndexes(values: LongArray, bitsPerValue: Int, paletteLength: Int) {
val mask = (1L shl bitsPerValue) - 1L
val valuesPerLong = 64 / bitsPerValue
var remaining = BLOCK_COUNT
for (cell in values) {
var current = cell
var position = 0
while (position < valuesPerLong && remaining > 0) {
require((current and mask) < paletteLength) { "Block value references an absent palette entry" }
current = current ushr bitsPerValue
position++
remaining--
}
}
}
fun readBlockContainer(
reader: AxiomByteReader,
protocolVersion: Int,
globalPaletteBits: Int,
): PalettedContainerData {
require(protocolVersion >= 757) { "Palette formats before Minecraft 1.18 are not supported" }
require(globalPaletteBits in 9..31) { "Invalid global palette width: $globalPaletteBits" }
var bitsPerValue = reader.readUnsignedByte()
if (bitsPerValue == 0) {
val palette = mutableListOf(reader.readVarInt())
readValues(reader, protocolVersion, bitsPerValue = 0)
return PalettedContainerData(palette, IntArray(BLOCK_COUNT))
}
bitsPerValue = normalizeBitsPerValue(bitsPerValue, globalPaletteBits)
val palette = mutableListOf<Int>()
val values: IntArray
if (bitsPerValue != globalPaletteBits) {
val paletteLength = reader.readVarInt()
require(paletteLength in 1..(1 shl bitsPerValue)) { "Invalid palette length: $paletteLength" }
repeat(paletteLength) {
palette += reader.readVarInt()
}
values = unpackValues(readValues(reader, protocolVersion, bitsPerValue), bitsPerValue)
require(values.all { it in palette.indices }) { "Block value references an absent palette entry" }
} else {
val rawIds = unpackValues(readValues(reader, protocolVersion, bitsPerValue), bitsPerValue)
val indexesById = mutableMapOf<Int, Int>()
// Global values are registry IDs, whereas PalettedContainerData stores palette indexes.
values = IntArray(BLOCK_COUNT) { index ->
indexesById.getOrPut(rawIds[index]) {
palette.add(rawIds[index])
palette.lastIndex
}
}
}
return PalettedContainerData(palette, values)
}
fun writeBlockContainer(
writer: AxiomByteWriter,
container: PalettedContainerData,
protocolVersion: Int,
globalPaletteBits: Int,
) {
require(protocolVersion >= 757) { "Palette formats before Minecraft 1.18 are not supported" }
require(globalPaletteBits in 9..31) { "Invalid global palette width: $globalPaletteBits" }
val paletteSize = container.palette.size
require(paletteSize in 1..BLOCK_COUNT) { "Invalid palette size: $paletteSize" }
require(container.palette.all { it >= 0 && it.toLong() < (1L shl globalPaletteBits) }) {
"Block state ID does not fit the target registry width"
}
if (paletteSize == 1) {
writer.writeByte(0)
writer.writeVarInt(container.palette[0])
writeValues(writer, protocolVersion, longArrayOf())
return
}
val bitsPerValue = bitsPerValue(paletteSize, globalPaletteBits)
writer.writeByte(bitsPerValue)
val values = if (bitsPerValue == globalPaletteBits) {
IntArray(BLOCK_COUNT) { container.idAt(it) }
} else {
writer.writeVarInt(paletteSize)
for (id in container.palette) {
writer.writeVarInt(id)
}
IntArray(BLOCK_COUNT) { container.paletteIndexAt(it) }
}
writeValues(
writer = writer,
protocolVersion = protocolVersion,
values = packValues(bitsPerValue, values),
)
}
private fun normalizeBitsPerValue(bitsPerValue: Int, globalPaletteBits: Int): Int {
if (bitsPerValue < 0 || bitsPerValue > BLOCK_HIGHEST_BITS_PER_VALUE) {
return globalPaletteBits
}
return max(MIN_BLOCK_BITS_PER_VALUE, bitsPerValue)
}
private fun bitsPerValue(paletteSize: Int, globalPaletteBits: Int): Int {
val bits = max(MIN_BLOCK_BITS_PER_VALUE, ceilLog2(paletteSize))
return if (bits > BLOCK_HIGHEST_BITS_PER_VALUE) globalPaletteBits else bits
}
private fun readValues(reader: AxiomByteReader, protocolVersion: Int, bitsPerValue: Int): LongArray {
if (protocolVersion >= PROTOCOL_1_21_5) {
if (bitsPerValue == 0) {
return longArrayOf()
}
return reader.readLongArray(expectedLongArrayLength(bitsPerValue))
}
val length = reader.readVarInt()
val expected = if (bitsPerValue == 0) 0 else expectedLongArrayLength(bitsPerValue)
require(length == expected) { "Invalid palette data length: $length, expected $expected" }
return reader.readLongArray(length)
}
private fun writeValues(
writer: AxiomByteWriter,
protocolVersion: Int,
values: LongArray,
) {
if (protocolVersion >= PROTOCOL_1_21_5) {
writer.writeLongArray(values, includeLength = false)
} else {
writer.writeLongArray(values, includeLength = true)
}
}
private fun expectedLongArrayLength(bitsPerValue: Int): Int {
val valuesPerLong = 64 / bitsPerValue
return (BLOCK_COUNT + valuesPerLong - 1) / valuesPerLong
}
private fun unpackValues(values: LongArray, bitsPerValue: Int): IntArray {
val unpacked = IntArray(BLOCK_COUNT)
if (values.isEmpty() || bitsPerValue == 0) {
return unpacked
}
val maxValue = (1L shl bitsPerValue) - 1L
val valuesPerLong = 64 / bitsPerValue
var index = 0
for (cell in values) {
var current = cell
repeat(valuesPerLong) {
if (index >= BLOCK_COUNT) {
return unpacked
}
unpacked[index++] = (current and maxValue).toInt()
current = current ushr bitsPerValue
}
}
return unpacked
}
private fun packValues(bitsPerValue: Int, values: IntArray): LongArray {
val maxValue = (1L shl bitsPerValue) - 1L
val valuesPerLong = 64 / bitsPerValue
val packed = LongArray((values.size + valuesPerLong - 1) / valuesPerLong)
var index = 0
for (cellIndex in packed.indices) {
var cell = 0L
var bitIndex = 0
val limit = minOf(index + valuesPerLong, values.size)
while (index < limit) {
cell = cell or ((values[index++].toLong() and maxValue) shl bitIndex)
bitIndex += bitsPerValue
}
packed[cellIndex] = cell
}
return packed
}
private fun ceilLog2(value: Int): Int {
return if (value > 0) 32 - Integer.numberOfLeadingZeros(value - 1) else 0
}
}
class PalettedContainerData(
val palette: MutableList<Int>,
private val paletteIndexes: IntArray,
) {
init {
require(paletteIndexes.size == 4096) { "A block section must contain 4096 values" }
require(palette.isNotEmpty() && paletteIndexes.all { it in palette.indices }) { "Invalid block palette indexes" }
}
fun idAt(index: Int): Int = palette[paletteIndexes[index]]
fun paletteIndexAt(index: Int): Int = paletteIndexes[index]
fun replaceIds(mapper: (Int) -> Int) {
if (palette.isEmpty()) {
return
}
val newPalette = ArrayList<Int>(palette.size)
val indexesById = HashMap<Int, Int>(palette.size * 2)
val remap = IntArray(palette.size)
for (oldIndex in palette.indices) {
val mappedId = mapper(palette[oldIndex])
remap[oldIndex] = indexesById.getOrPut(mappedId) {
newPalette += mappedId
newPalette.lastIndex
}
}
for (i in paletteIndexes.indices) {
paletteIndexes[i] = remap[paletteIndexes[i]]
}
palette.clear()
palette += newPalette
}
}
@@ -0,0 +1,31 @@
package me.wargearsystems.viaaxiom.translation
import me.wargearsystems.viaaxiom.protocol.AxiomCustomPayloadFrameCodec
import me.wargearsystems.viaaxiom.protocol.AxiomPayloadDirection
import me.wargearsystems.viaaxiom.protocol.AxiomTranslationSession
class AxiomFrameTranslationEngine(
private val payloadTranslator: AxiomPayloadTranslator,
) {
fun rewrite(
frameBytes: ByteArray,
customPayloadPacketId: Int,
direction: AxiomPayloadDirection,
session: AxiomTranslationSession,
): ByteArray {
return AxiomCustomPayloadFrameCodec.rewriteIfCustomPayload(
frameBytes = frameBytes,
customPayloadPacketId = customPayloadPacketId,
) { frame ->
payloadTranslator.rewrite(
payload = AxiomPayload(
direction = direction,
channel = frame.channel,
bytes = frame.payloadBytes,
),
session = session,
)
}
}
}
@@ -0,0 +1,90 @@
package me.wargearsystems.viaaxiom.translation
import me.wargearsystems.viaaxiom.protocol.AxiomPayloadDirection
import me.wargearsystems.viaaxiom.protocol.AxiomPayloadKey
import me.wargearsystems.viaaxiom.protocol.AxiomProtocol
import me.wargearsystems.viaaxiom.protocol.AxiomSetBlockPayloadCodec
import me.wargearsystems.viaaxiom.protocol.AxiomTranslationSession
import me.wargearsystems.viaaxiom.protocol.AxiomSetBufferPayloadCodec
import me.wargearsystems.viaaxiom.protocol.AxiomResponseChunkDataPayloadCodec
import me.wargearsystems.viaaxiom.protocol.PalettedContainerCodec
import me.wargearsystems.viaaxiom.protocol.AxiomCustomBlockCodec
data class BlockStatePaletteWidths(val client: Int, val server: Int) {
init {
require(client in 9..31 && server in 9..31)
}
}
data class AxiomPayload(
val direction: AxiomPayloadDirection,
val channel: String,
val bytes: ByteArray,
) {
val key: AxiomPayloadKey
get() = AxiomPayloadKey(direction, channel)
}
interface AxiomPayloadTranslator {
fun rewrite(payload: AxiomPayload, session: AxiomTranslationSession): ByteArray
}
class AxiomTranslationEngine(
private val blockStateIdTranslator: BlockStateIdTranslator,
private val paletteWidths: BlockStatePaletteWidths? = null,
) : AxiomPayloadTranslator {
override fun rewrite(payload: AxiomPayload, session: AxiomTranslationSession): ByteArray {
if (!session.protocolMismatch || !AxiomProtocol.isAxiomChannel(payload.channel)) {
return payload.bytes
}
if (payload.key !in AxiomProtocol.BLOCK_STATE_TRANSLATION_CHANNELS) {
return payload.bytes
}
return when (payload.key) {
AxiomPayloadKey(AxiomPayloadDirection.SERVERBOUND, AxiomProtocol.channel("set_block")) -> {
rewriteSetBlock(payload.bytes)
}
AxiomPayloadKey(AxiomPayloadDirection.SERVERBOUND, AxiomProtocol.channel("set_buffer")) -> {
rewriteSetBuffer(payload.bytes, session)
}
AxiomPayloadKey(AxiomPayloadDirection.CLIENTBOUND, AxiomProtocol.channel("response_chunk_data")) -> {
rewriteResponseChunkData(payload.bytes, session)
}
AxiomPayloadKey(AxiomPayloadDirection.CLIENTBOUND, AxiomProtocol.channel("register_custom_block_v2")) -> {
rewriteRegisterCustomBlock(payload.bytes)
}
else -> payload.bytes
}
}
private fun rewriteSetBlock(bytes: ByteArray): ByteArray {
return AxiomSetBlockPayloadCodec.rewriteBlockStateIds(bytes, blockStateIdTranslator::clientToServer)
}
private fun rewriteSetBuffer(bytes: ByteArray, session: AxiomTranslationSession): ByteArray {
val widths = paletteWidths ?: return bytes
return AxiomSetBufferPayloadCodec.rewriteBlockSections(bytes) { reader, writer ->
PalettedContainerCodec.rewriteBlockStateIds(
reader, writer, session.hello.protocolVersion, widths.client,
blockStateIdTranslator::clientToServer, session.serverProtocolVersion, widths.server,
)
}
}
private fun rewriteResponseChunkData(bytes: ByteArray, session: AxiomTranslationSession): ByteArray {
val widths = paletteWidths ?: return bytes
return AxiomResponseChunkDataPayloadCodec.rewriteSections(bytes) { reader, writer ->
PalettedContainerCodec.rewriteBlockStateIds(
reader, writer, session.serverProtocolVersion, widths.server,
blockStateIdTranslator::serverToClient, session.hello.protocolVersion, widths.client,
)
}
}
private fun rewriteRegisterCustomBlock(bytes: ByteArray): ByteArray {
// Raw IDs need mapping. The codec keeps -1/string states as they are.
return AxiomCustomBlockCodec.rewrite(bytes, blockStateIdTranslator::serverToClient)
}
}
@@ -0,0 +1,20 @@
package me.wargearsystems.viaaxiom.translation
import me.wargearsystems.viaaxiom.protocol.AxiomPayloadDirection
import me.wargearsystems.viaaxiom.protocol.AxiomTranslationSession
import me.wargearsystems.viaaxiom.protocol.AxiomTunnelCodec
class AxiomTunnelTranslationEngine(private val payloadTranslator: AxiomPayloadTranslator) {
fun rewrite(fragments: List<ByteArray>, session: AxiomTranslationSession): List<ByteArray> {
val enable = requireNotNull(session.enable) { "Axiom tunnel requires negotiated server limits" }
val splitSize = requireNotNull(enable.tunnelSplitSize)
val maximumSize = requireNotNull(enable.maximumTunnelPacketSize)
val packet = AxiomTunnelCodec.decode(fragments, splitSize, maximumSize)
require(packet.channel in enable.supportedServerboundChannels) { "Server does not support ${packet.channel}" }
val translated = payloadTranslator.rewrite(
AxiomPayload(AxiomPayloadDirection.SERVERBOUND, packet.channel, packet.payload), session,
)
if (translated.contentEquals(packet.payload)) return fragments
return AxiomTunnelCodec.encode(packet.copy(payload = translated), splitSize, maximumSize)
}
}
@@ -0,0 +1,83 @@
package me.wargearsystems.viaaxiom.translation
interface BlockStateIdTranslator {
fun clientToServer(blockStateId: Int): Int
fun serverToClient(blockStateId: Int): Int
}
enum class BlockStateMappingDirection {
CLIENT_TO_SERVER,
SERVER_TO_CLIENT,
}
data class MissingBlockStatePolicy(
val clientToServerFallbackId: Int,
val serverToClientFallbackId: Int,
) {
companion object {
fun placeholder(fallbackId: Int): MissingBlockStatePolicy {
return MissingBlockStatePolicy(
clientToServerFallbackId = fallbackId,
serverToClientFallbackId = fallbackId,
)
}
}
}
object IdentityBlockStateIdTranslator : BlockStateIdTranslator {
override fun clientToServer(blockStateId: Int): Int = blockStateId
override fun serverToClient(blockStateId: Int): Int = blockStateId
}
class TableBlockStateIdTranslator(
private val clientToServer: IntArray,
private val serverToClient: IntArray,
private val missingBlockStatePolicy: MissingBlockStatePolicy,
private val onMissingBlockState: ((direction: BlockStateMappingDirection, missingId: Int, fallbackId: Int) -> Unit)? = null,
) : BlockStateIdTranslator {
constructor(
clientToServer: IntArray,
serverToClient: IntArray,
fallbackId: Int,
) : this(clientToServer, serverToClient, MissingBlockStatePolicy.placeholder(fallbackId))
override fun clientToServer(blockStateId: Int): Int {
return translate(
table = clientToServer,
blockStateId = blockStateId,
fallbackId = missingBlockStatePolicy.clientToServerFallbackId,
direction = BlockStateMappingDirection.CLIENT_TO_SERVER,
)
}
override fun serverToClient(blockStateId: Int): Int {
return translate(
table = serverToClient,
blockStateId = blockStateId,
fallbackId = missingBlockStatePolicy.serverToClientFallbackId,
direction = BlockStateMappingDirection.SERVER_TO_CLIENT,
)
}
private fun translate(
table: IntArray,
blockStateId: Int,
fallbackId: Int,
direction: BlockStateMappingDirection,
): Int {
if (blockStateId < 0 || blockStateId >= table.size) {
onMissingBlockState?.invoke(direction, blockStateId, fallbackId)
return fallbackId
}
val mapped = table[blockStateId]
if (mapped >= 0) {
return mapped
}
onMissingBlockState?.invoke(direction, blockStateId, fallbackId)
return fallbackId
}
}
@@ -0,0 +1,38 @@
package me.wargearsystems.viaaxiom.translation
/** ViaVersion mapping tables run server-to-client, in reverse protocol-path order. */
object BlockStateMappingChain {
fun compose(serverToClientSteps: List<IntArray>, clientRegistrySize: Int, clientStoneId: Int): Pair<IntArray, IntArray> {
require(clientRegistrySize > 0 && clientStoneId in 0 until clientRegistrySize)
val serverSize = serverToClientSteps.firstOrNull()?.size ?: clientRegistrySize
require(serverSize > 0)
val serverToClient = IntArray(serverSize) { id ->
var mapped = id
for (step in serverToClientSteps) mapped = if (mapped in step.indices) step[mapped] else -1
if (mapped in 0 until clientRegistrySize) mapped else -1
}
val clientToServer = IntArray(clientRegistrySize) { -1 }
// On collisions, keep the earliest canonical state, as upstream Axiom does.
for (serverId in serverToClient.indices.reversed()) {
val clientId = serverToClient[serverId]
if (clientId >= 0) clientToServer[clientId] = serverId
}
require(clientToServer[clientStoneId] >= 0) { "Mapping chain cannot map the stone placeholder" }
return clientToServer to serverToClient
}
/** Block states with no counterpart become stone. */
fun translationEngine(
serverToClientSteps: List<IntArray>,
clientRegistrySize: Int,
clientStoneId: Int,
onMissingBlockState: (direction: BlockStateMappingDirection, missingId: Int, fallbackId: Int) -> Unit,
): AxiomTranslationEngine {
val (clientToServer, serverToClient) = compose(serverToClientSteps, clientRegistrySize, clientStoneId)
val translator = TableBlockStateIdTranslator(clientToServer, serverToClient,
MissingBlockStatePolicy(clientToServer[clientStoneId], clientStoneId), onMissingBlockState)
return AxiomTranslationEngine(translator, BlockStatePaletteWidths(paletteBits(clientRegistrySize), paletteBits(serverToClient.size)))
}
private fun paletteBits(registrySize: Int) = maxOf(9, 32 - Integer.numberOfLeadingZeros(registrySize - 1))
}
@@ -0,0 +1,76 @@
package me.wargearsystems.viaaxiom.binary
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class AxiomByteCodecTest {
@Test
fun `varint round trips minecraft edge values`() {
val values = listOf(0, 1, 2, 127, 128, 255, 25565, Int.MAX_VALUE, -1, Int.MIN_VALUE)
for (value in values) {
val bytes = AxiomByteWriter().writeVarInt(value).toByteArray()
val reader = AxiomByteReader(bytes)
assertEquals(value, reader.readVarInt())
assertEquals(0, reader.readableBytes)
}
}
@Test
fun `primitive values round trip in network byte order`() {
val bytes = AxiomByteWriter()
.writeBoolean(true)
.writeByte(0xFE)
.writeShort(0x3456)
.writeInt(0x12345678)
.writeLong(-9223371899415820288L)
.writeByteArray(byteArrayOf(9, 8, 7))
.toByteArray()
val reader = AxiomByteReader(bytes)
assertEquals(true, reader.readBoolean())
assertEquals(0xFE, reader.readUnsignedByte())
assertEquals(0x3456, reader.readShort().toInt())
assertEquals(0x12345678, reader.readInt())
assertEquals(-9223371899415820288L, reader.readLong())
assertContentEquals(byteArrayOf(9, 8, 7), reader.readByteArray())
assertEquals(0, reader.readableBytes)
}
@Test
fun `utf strings round trip`() {
val bytes = AxiomByteWriter()
.writeUtf("axiom:hello")
.writeUtf("stone")
.toByteArray()
val reader = AxiomByteReader(bytes)
assertEquals("axiom:hello", reader.readUtf())
assertEquals("stone", reader.readUtf())
assertEquals(0, reader.readableBytes)
}
@Test
fun `copy remaining preserves unread bytes`() {
val bytes = byteArrayOf(1, 2, 3, 4, 5)
val reader = AxiomByteReader(bytes)
assertEquals(1, reader.readUnsignedByte())
assertContentEquals(byteArrayOf(2, 3, 4, 5), reader.copyRemaining())
assertEquals(0, reader.readableBytes)
}
@Test
fun `oversized varint fails`() {
val oversized = byteArrayOf(0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x01)
assertFailsWith<AxiomByteCodecException> {
AxiomByteReader(oversized).readVarInt()
}
}
}
@@ -0,0 +1,47 @@
package me.wargearsystems.viaaxiom.protocol
import me.wargearsystems.viaaxiom.binary.AxiomByteReader
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
import kotlin.test.*
class AxiomCustomBlockCodecTest {
@Test fun `raw states and rotation mappings are rewritten`() {
val output = AxiomCustomBlockCodec.rewrite(packet(false)) { it + 100 }
val reader = AxiomByteReader(output)
assertEquals("test:block", reader.readUtf())
assertEquals("test.translation", reader.readUtf())
assertEquals(0, reader.readVarInt())
assertEquals(1, reader.readVarInt())
assertEquals(105, reader.readVarInt())
repeat(4) { reader.readBoolean() }
assertEquals(0, reader.readVarInt())
reader.readBoolean()
assertEquals(1, reader.readVarInt())
assertEquals(105, reader.readVarInt())
assertEquals(106, reader.readVarInt())
repeat(4) { assertEquals(0, reader.readVarInt()) }
assertEquals(0, reader.readableBytes)
}
@Test fun `string based mismatch states preserve their layout`() {
val input = packet(true)
assertContentEquals(input, AxiomCustomBlockCodec.rewrite(input) { error("String states should not map") })
}
@Test fun `embedded item components fail explicitly instead of decoding wrong registry`() {
val input = AxiomByteWriter().writeUtf("test:block").writeUtf("test.translation")
.writeVarInt(0).writeVarInt(0).writeBoolean(true).toByteArray()
assertFailsWith<IllegalArgumentException> { AxiomCustomBlockCodec.rewrite(input) { it } }
}
private fun packet(strings: Boolean): ByteArray {
val writer = AxiomByteWriter().writeUtf("test:block").writeUtf("test.translation").writeVarInt(0).writeVarInt(1)
fun state(id: Int) { if (strings) writer.writeVarInt(-1).writeUtf("minecraft:stone") else writer.writeVarInt(id) }
state(5)
repeat(4) { writer.writeBoolean(false) }
writer.writeVarInt(0).writeBoolean(true).writeVarInt(1)
state(5); state(6)
repeat(4) { writer.writeVarInt(0) }
return writer.toByteArray()
}
}
@@ -0,0 +1,71 @@
package me.wargearsystems.viaaxiom.protocol
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertNull
class AxiomCustomPayloadFrameCodecTest {
@Test
fun `reads custom payload frame when packet id matches`() {
val frameBytes = frameBytes(packetId = 12, channel = "axiom:hello", payload = byteArrayOf(1, 2, 3))
val frame = AxiomCustomPayloadFrameCodec.readIfCustomPayload(frameBytes, customPayloadPacketId = 12)
requireNotNull(frame)
assertEquals(12, frame.packetId)
assertEquals("axiom:hello", frame.channel)
assertContentEquals(byteArrayOf(1, 2, 3), frame.payloadBytes)
}
@Test
fun `reads custom payload frame without a known packet id`() {
val frameBytes = frameBytes(packetId = 12, channel = "axiom:hello", payload = byteArrayOf(1, 2, 3))
val frame = AxiomCustomPayloadFrameCodec.read(frameBytes)
assertEquals(12, frame.packetId)
assertEquals("axiom:hello", frame.channel)
assertContentEquals(byteArrayOf(1, 2, 3), frame.payloadBytes)
}
@Test
fun `returns null when packet id does not match`() {
val frameBytes = frameBytes(packetId = 11, channel = "axiom:hello", payload = byteArrayOf(1, 2, 3))
assertNull(AxiomCustomPayloadFrameCodec.readIfCustomPayload(frameBytes, customPayloadPacketId = 12))
}
@Test
fun `unrelated packet is not parsed as a custom payload`() {
val frameBytes = byteArrayOf(11, 127)
assertNull(AxiomCustomPayloadFrameCodec.readIfCustomPayload(frameBytes, customPayloadPacketId = 12))
assertContentEquals(frameBytes, AxiomCustomPayloadFrameCodec.rewriteIfCustomPayload(frameBytes, 12) {
error("Unrelated packets must not be rewritten")
})
}
@Test
fun `rewrites only the payload bytes`() {
val original = frameBytes(packetId = 12, channel = "axiom:set_block", payload = byteArrayOf(1, 2, 3))
val rewritten = AxiomCustomPayloadFrameCodec.rewriteIfCustomPayload(original, customPayloadPacketId = 12) {
byteArrayOf(9, 8, 7)
}
val frame = AxiomCustomPayloadFrameCodec.readIfCustomPayload(rewritten, customPayloadPacketId = 12)
requireNotNull(frame)
assertEquals(12, frame.packetId)
assertEquals("axiom:set_block", frame.channel)
assertContentEquals(byteArrayOf(9, 8, 7), frame.payloadBytes)
}
private fun frameBytes(packetId: Int, channel: String, payload: ByteArray): ByteArray {
return AxiomByteWriter()
.writeVarInt(packetId)
.writeUtf(channel)
.writeBytes(payload)
.toByteArray()
}
}
@@ -0,0 +1,20 @@
package me.wargearsystems.viaaxiom.protocol
import kotlin.test.Test
import kotlin.test.assertEquals
class AxiomEnableCodecTest {
@Test
fun `enable payload header round trips`() {
val enable = AxiomEnable(
enabled = true,
maxBufferSize = 1_048_576,
blueprintVersion = 2,
customDataOverridesCount = 0,
rotationOverridesCount = 0,
)
assertEquals(enable, AxiomEnableCodec.read(AxiomEnableCodec.write(enable)))
}
}
@@ -0,0 +1,38 @@
package me.wargearsystems.viaaxiom.protocol
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class AxiomHelloCodecTest {
@Test
fun `hello payload round trips`() {
val hello = AxiomHello(
apiVersion = 9,
dataVersion = 4438,
protocolVersion = 773,
)
assertEquals(hello, AxiomHelloCodec.read(AxiomHelloCodec.write(hello)))
}
@Test
fun `hello exposes api compatibility`() {
assertTrue(AxiomHello(9, 4438, 773).isSupportedApi)
assertFalse(AxiomHello(8, 4438, 773).isSupportedApi)
}
@Test
fun `translation session exposes protocol and data mismatches`() {
val session = AxiomTranslationSession(
hello = AxiomHello(apiVersion = 9, dataVersion = 4438, protocolVersion = 772),
serverProtocolVersion = 773,
serverDataVersion = 4438,
)
assertTrue(session.protocolMismatch)
assertFalse(session.dataVersionMismatch)
}
}
@@ -0,0 +1,129 @@
package me.wargearsystems.viaaxiom.protocol
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
import me.wargearsystems.viaaxiom.translation.*
import kotlin.test.*
class AxiomLegacyBridgeTest {
private val challenge = 42L
private val channels = "axiom:hello\u0000axiom:set_block\u0000axiom:set_buffer\u0000axiom:request_chunk_data"
private val engine = AxiomTranslationEngine(TableBlockStateIdTranslator(
intArrayOf(0, 2, 1), intArrayOf(0, 2, 1), 0), BlockStatePaletteWidths(15, 15))
@Test fun `registration starts legacy handshake only once`() {
val bridge = bridge()
val frame = assertNotNull(bridge.createChallenge(24))
assertEquals(24, frame.packetId)
assertEquals("axiom:hello", frame.channel)
assertContentEquals(AxiomByteWriter().writeLong(challenge).toByteArray(), frame.payloadBytes)
assertNull(bridge.createChallenge(24))
}
@Test fun `native API 10 server is never downgraded`() {
val bridge = bridge()
bridge.register("axiom:tunnel".toByteArray())
assertNull(bridge.createChallenge(24))
val hello = modernHello()
assertSame(hello, bridge.serverbound(hello))
}
@Test fun `real challenge supersedes pending legacy detection`() {
val bridge = bridge()
bridge.createChallenge(24)
val actual = AxiomCustomPayloadFrame(24, "axiom:hello", AxiomByteWriter().writeLong(99).toByteArray())
assertSame(actual, bridge.clientbound(actual))
assertFalse(bridge.active)
val reply = modernHello()
assertSame(reply, bridge.serverbound(reply))
}
@Test fun `client hello retains data version but advertises API 9 and server registry protocol`() {
val bridge = bridge()
bridge.createChallenge(24)
val output = assertNotNull(bridge.serverbound(modernHello()))
assertEquals(AxiomHello(9, 5000, 771), AxiomHelloCodec.read(output.payloadBytes))
}
@Test fun `wrong challenge cannot activate bridge`() {
val bridge = bridge()
bridge.createChallenge(24)
assertFailsWith<IllegalArgumentException> { bridge.serverbound(modernHello(99)) }
assertFailsWith<IllegalArgumentException> { bridge.clientbound(legacyEnable()) }
}
@Test fun `server enable is converted to modern config with only registered capabilities`() {
val bridge = negotiated()
val output = bridge.clientbound(legacyEnable())
val modern = AxiomEnableCodec.read(output.payloadBytes, 10)
assertTrue(modern.enabled)
assertEquals(0, modern.serverConfigVersion)
assertEquals(1_048_576, modern.maximumTunnelPacketSize)
assertTrue("axiom:tunnel" in modern.supportedServerboundChannels)
assertTrue("axiom:set_buffer" in modern.supportedServerboundChannels)
assertFalse("axiom:tick_blocks" in modern.supportedServerboundChannels)
}
@Test fun `server refusal remains disabled and prevents tunneling`() {
val bridge = negotiated()
val output = bridge.clientbound(legacyEnable(false))
assertFalse(AxiomEnableCodec.read(output.payloadBytes, 10).enabled)
assertFailsWith<IllegalArgumentException> { bridge.serverbound(tunnel("axiom:set_block", byteArrayOf(0)).single()) }
}
@Test fun `compressed multi fragment tunnel becomes one legacy payload`() {
val body = ByteArray(90_000) { ((it * 31 + it / 17) and 255).toByte() }
val frames = tunnel("axiom:set_buffer", body, compressed = true, split = 64)
assertTrue(frames.size > 1)
// Test transport independently; an opaque payload translator preserves this fixture.
val transportBridge = AxiomLegacyBridge(771, object : AxiomPayloadTranslator {
override fun rewrite(payload: AxiomPayload, session: AxiomTranslationSession) = payload.bytes
}) { challenge }
transportBridge.register(channels.toByteArray())
transportBridge.createChallenge(24)
transportBridge.serverbound(modernHello())
transportBridge.clientbound(legacyEnable())
frames.dropLast(1).forEach { assertNull(transportBridge.serverbound(it)) }
val output = assertNotNull(transportBridge.serverbound(frames.last()))
assertEquals("axiom:set_buffer", output.channel)
assertContentEquals(body, output.payloadBytes)
}
@Test fun `block IDs are rewritten after extracting tunnel`() {
val body = AxiomByteWriter().writeVarInt(1).writeLong(123).writeVarInt(1).toByteArray()
val output = assertNotNull(enabled().serverbound(tunnel("axiom:set_block", body).single()))
assertContentEquals(AxiomByteWriter().writeVarInt(1).writeLong(123).writeVarInt(2).toByteArray(), output.payloadBytes)
}
@Test fun `unregistered channels and out of order fragments fail closed`() {
assertFailsWith<IllegalArgumentException> { enabled().serverbound(tunnel("axiom:tick_blocks", byteArrayOf(0)).single()) }
val continuation = AxiomCustomPayloadFrame(20, "axiom:tunnel", byteArrayOf(2, 1))
assertFailsWith<IllegalArgumentException> { enabled().serverbound(continuation) }
}
@Test fun `redo handshake clears buffered fragments and requires new hello`() {
val bridge = enabled()
val fragmented = tunnel("axiom:set_buffer", ByteArray(100), split = 32)
assertNull(bridge.serverbound(fragmented.first()))
val redo = bridge.clientbound(AxiomCustomPayloadFrame(24, "axiom:redo_handshake", byteArrayOf()))
assertEquals("axiom:hello", redo.channel)
assertFailsWith<IllegalArgumentException> { bridge.serverbound(fragmented.last()) }
bridge.serverbound(modernHello())
bridge.clientbound(legacyEnable())
val body = byteArrayOf(0)
assertNotNull(bridge.serverbound(tunnel("axiom:set_block", body).single()))
}
@Test fun `nonempty legacy overrides are rejected`() {
val bridge = negotiated()
val payload = AxiomByteWriter().writeBoolean(true).writeInt(1000).writeVarInt(2).writeVarInt(1).writeVarInt(0).toByteArray()
assertFailsWith<IllegalArgumentException> { bridge.clientbound(AxiomCustomPayloadFrame(24, "axiom:enable", payload)) }
}
private fun bridge() = AxiomLegacyBridge(771, engine) { challenge }.also { it.register(channels.toByteArray()) }
private fun negotiated() = bridge().also { it.createChallenge(24); it.serverbound(modernHello()) }
private fun enabled() = negotiated().also { it.clientbound(legacyEnable()) }
private fun modernHello(id: Long = challenge) = AxiomCustomPayloadFrame(20, "axiom:hello", AxiomHelloCodec.write(AxiomHello(10, 5000, 776, id)))
private fun legacyEnable(enabled: Boolean = true) = AxiomCustomPayloadFrame(24, "axiom:enable", AxiomEnableCodec.write(AxiomEnable(enabled, 1_048_576, 2, 0, 0), 9))
private fun tunnel(channel: String, bytes: ByteArray, compressed: Boolean = false, split: Int = 31_000) =
AxiomTunnelCodec.encode(AxiomTunnelPacket(channel, bytes, compressed), split).map { AxiomCustomPayloadFrame(20, "axiom:tunnel", it) }
}
@@ -0,0 +1,99 @@
package me.wargearsystems.viaaxiom.protocol
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
import kotlin.test.*
class AxiomModernHandshakeTest {
private val challenge = 0x0102030405060708L
private val helloBytes = AxiomByteWriter().writeVarInt(10).writeVarInt(5000)
.writeVarInt(775).writeLong(challenge).toByteArray()
private val enableBytes = AxiomByteWriter().writeBoolean(true).writeByte(0).writeVarInt(2)
.writeInt(31_000).writeInt(2_097_152).writeVarInt(0).writeVarInt(0)
.writeVarInt(2).writeUtf("axiom:tunnel").writeUtf("axiom:set_buffer").toByteArray()
@Test fun `API 10 hello preserves the server-issued ID`() {
val hello = AxiomHelloCodec.read(helloBytes)
assertEquals(challenge, hello.handshakeId)
assertTrue(hello.isSupportedApi)
assertContentEquals(helloBytes, AxiomHelloCodec.write(hello))
}
@Test fun `API 10 hello rejects missing challenge ID and unknown API`() {
assertFailsWith<IllegalArgumentException> { AxiomHelloCodec.read(helloBytes.copyOf(helloBytes.size - 8)) }
assertFailsWith<IllegalArgumentException> { AxiomHelloCodec.write(AxiomHello(10, 5000, 775)) }
assertFailsWith<IllegalArgumentException> { AxiomHelloCodec.read(byteArrayOf(11, 0, 0)) }
}
@Test fun `API 10 enable decodes upstream server config without using legacy buffer layout`() {
val enable = AxiomEnableCodec.read(enableBytes, 10)
assertEquals(0, enable.serverConfigVersion)
assertEquals(31_000, enable.tunnelSplitSize)
assertEquals(2_097_152, enable.maximumTunnelPacketSize)
assertEquals(listOf("axiom:tunnel", "axiom:set_buffer"), enable.supportedServerboundChannels)
assertContentEquals(enableBytes, AxiomEnableCodec.write(enable, 10))
}
@Test fun `unknown server config and nonempty overrides reject unsupported layout`() {
val changedVersion = enableBytes.copyOf().also { it[1] = 1 }
assertFailsWith<IllegalArgumentException> { AxiomEnableCodec.read(changedVersion, 10) }
val overrides = AxiomByteWriter().writeBoolean(true).writeByte(0).writeVarInt(2)
.writeInt(31_000).writeInt(2_097_152).writeVarInt(1).toByteArray()
assertFailsWith<IllegalArgumentException> { AxiomEnableCodec.read(overrides, 10) }
}
@Test fun `handshake is directional and does not invent a server version`() {
val tracker = negotiatedTracker()
assertEquals(challenge, tracker.challengeId)
assertEquals(775, tracker.hello?.protocolVersion)
assertNull(tracker.session(null))
assertTrue(assertNotNull(tracker.session(773)).protocolMismatch)
tracker.observe(AxiomPayloadDirection.SERVERBOUND, "axiom:goodbye", byteArrayOf())
assertNotNull(tracker.enable)
}
@Test fun `wrong challenge never creates a session`() {
val tracker = AxiomHandshakeTracker()
tracker.observe(AxiomPayloadDirection.CLIENTBOUND, "axiom:hello", AxiomByteWriter().writeLong(challenge + 1).toByteArray())
assertFailsWith<IllegalArgumentException> {
tracker.observe(AxiomPayloadDirection.SERVERBOUND, "axiom:hello", helloBytes)
}
assertNull(tracker.hello)
assertNull(tracker.session(773))
}
@Test fun `redo handshake and goodbye clear old negotiation`() {
val tracker = negotiatedTracker()
tracker.observe(AxiomPayloadDirection.CLIENTBOUND, "axiom:redo_handshake", byteArrayOf())
assertNull(tracker.hello)
assertNull(tracker.enable)
assertNull(tracker.challengeId)
val goodbyeTracker = negotiatedTracker()
goodbyeTracker.observe(AxiomPayloadDirection.CLIENTBOUND, "axiom:goodbye", AxiomByteWriter().writeUtf("Missing axiom.use permission").toByteArray())
assertNull(goodbyeTracker.session(773))
assertEquals("Missing axiom.use permission", goodbyeTracker.goodbyeReason)
}
@Test fun `disabled and malformed enable invalidate previous session`() {
val tracker = negotiatedTracker()
tracker.observe(AxiomPayloadDirection.CLIENTBOUND, "axiom:enable", byteArrayOf(0))
assertNull(tracker.session(773))
assertFalse(assertNotNull(tracker.enable).enabled)
assertFailsWith<IllegalArgumentException> {
tracker.observe(AxiomPayloadDirection.CLIENTBOUND, "axiom:enable", byteArrayOf(1, 3))
}
assertNull(tracker.enable)
}
@Test fun `legacy handshake still negotiates API 9`() {
val tracker = AxiomHandshakeTracker()
tracker.observe(AxiomPayloadDirection.SERVERBOUND, "axiom:hello", byteArrayOf(9, 0, 1))
tracker.observe(AxiomPayloadDirection.CLIENTBOUND, "axiom:enable", AxiomEnableCodec.write(AxiomEnable(true, 1000, 2, 0, 0)))
assertEquals(9, assertNotNull(tracker.session(2)).hello.apiVersion)
}
private fun negotiatedTracker() = AxiomHandshakeTracker().also {
it.observe(AxiomPayloadDirection.CLIENTBOUND, "axiom:hello", AxiomByteWriter().writeLong(challenge).toByteArray())
it.observe(AxiomPayloadDirection.SERVERBOUND, "axiom:hello", helloBytes)
it.observe(AxiomPayloadDirection.CLIENTBOUND, "axiom:enable", enableBytes)
}
}
@@ -0,0 +1,126 @@
package me.wargearsystems.viaaxiom.protocol
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
import me.wargearsystems.viaaxiom.translation.*
import kotlin.test.*
class AxiomProxySessionTest {
private val challenge = 42L
private val legacyChannels = "axiom:hello\u0000axiom:set_block\u0000axiom:set_buffer"
private val modernChannels = "$legacyChannels\u0000axiom:tunnel"
private val engine = AxiomTranslationEngine(TableBlockStateIdTranslator(
intArrayOf(0, 2, 1), intArrayOf(0, 2, 1), 0), BlockStatePaletteWidths(15, 15))
@Test fun `API 9 backend is bridged`() {
val session = session()
session.backendRegistered(legacyChannels.toByteArray())
assertTrue(session.awaitingLegacyChallenge)
assertEquals("axiom:hello", assertNotNull(session.startLegacyHandshake()).channel)
val hello = session.serverbound(modernHello()).single()
assertEquals(AxiomHello(9, 5000, 771), AxiomHelloCodec.read(hello.payloadBytes))
val enable = session.clientbound(frame("axiom:enable", AxiomEnableCodec.write(AxiomEnable(true, 1_048_576, 2, 0, 0), 9)))
assertTrue(AxiomEnableCodec.read(enable.payloadBytes, 10).enabled)
}
@Test fun `API 10 backend on another version gets the backend protocol in the hello`() {
val session = enabled()
assertFalse(session.awaitingLegacyChallenge)
session.clientbound(frame("axiom:goodbye", AxiomByteWriter().writeUtf("again").toByteArray()))
session.clientbound(challengeFrame())
val hello = session.serverbound(modernHello()).single()
assertEquals(AxiomHello(10, 5000, 771, challenge), AxiomHelloCodec.read(hello.payloadBytes))
}
@Test fun `API 10 small payloads are translated`() {
val output = enabled().serverbound(frame("axiom:set_block", setBlock(1))).single()
assertContentEquals(setBlock(2), output.payloadBytes)
}
@Test fun `API 10 tunnel is translated and keeps server split size`() {
val fragments = AxiomTunnelCodec.encode(AxiomTunnelPacket("axiom:set_block", setBlock(1)), SPLIT)
val output = enabled().serverbound(frame("axiom:tunnel", fragments.single()))
val packet = AxiomTunnelCodec.decode(output.map { it.payloadBytes }, SPLIT)
assertEquals("axiom:set_block", packet.channel)
assertContentEquals(setBlock(2), packet.payload)
}
@Test fun `API 10 fragments are held until the last one`() {
val body = AxiomByteWriter().writeVarInt(50).apply { repeat(50) { writeLong(it.toLong()).writeVarInt(1) } }.toByteArray()
val fragments = AxiomTunnelCodec.encode(AxiomTunnelPacket("axiom:set_block", body), 32)
assertTrue(fragments.size > 1)
val session = enabled(split = 32)
fragments.dropLast(1).forEach { assertTrue(session.serverbound(frame("axiom:tunnel", it)).isEmpty()) }
val output = session.serverbound(frame("axiom:tunnel", fragments.last()))
val packet = AxiomTunnelCodec.decode(output.map { it.payloadBytes }, 32)
val expected = AxiomByteWriter().writeVarInt(50).apply { repeat(50) { writeLong(it.toLong()).writeVarInt(2) } }.toByteArray()
assertContentEquals(expected, packet.payload)
}
@Test fun `tunnel continuation without a first fragment fails closed`() {
assertFailsWith<IllegalArgumentException> { enabled().serverbound(frame("axiom:tunnel", byteArrayOf(2, 1))) }
}
@Test fun `API 10 matching versions pass through untouched`() {
val session = AxiomProxySession(776, 776, engine) { challenge }
session.backendRegistered(modernChannels.toByteArray())
session.clientbound(challengeFrame())
val hello = modernHello()
assertSame(hello, session.serverbound(hello).single())
val tunnel = frame("axiom:tunnel", byteArrayOf(3, 1))
assertSame(tunnel, session.serverbound(tunnel).single())
}
@Test fun `matching versions with an API 9 backend still bridge the API`() {
val session = AxiomProxySession(771, 771, engine) { challenge }
session.backendRegistered(legacyChannels.toByteArray())
assertNotNull(session.startLegacyHandshake())
val hello = session.serverbound(frame("axiom:hello", AxiomHelloCodec.write(AxiomHello(10, 5000, 771, challenge)))).single()
assertEquals(9, AxiomHelloCodec.read(hello.payloadBytes).apiVersion)
}
@Test fun `API 9 client is left to negotiate directly`() {
val session = session()
session.backendRegistered(legacyChannels.toByteArray())
val hello = frame("axiom:hello", AxiomHelloCodec.write(AxiomHello(9, 5000, 776)))
assertSame(hello, session.serverbound(hello).single())
assertTrue(session.passthrough)
assertFalse(session.awaitingLegacyChallenge)
val edit = frame("axiom:set_block", setBlock(1))
assertSame(edit, session.serverbound(edit).single())
}
@Test fun `unknown client API does not break the session`() {
val session = session()
val hello = frame("axiom:hello", AxiomByteWriter().writeVarInt(11).toByteArray())
assertSame(hello, session.serverbound(hello).single())
assertTrue(session.passthrough)
}
@Test fun `unknown enable format fails rather than running untranslated`() {
val session = session()
session.backendRegistered(modernChannels.toByteArray())
session.clientbound(challengeFrame())
session.serverbound(modernHello())
val enable = AxiomByteWriter().writeBoolean(true).writeByte(7).toByteArray()
assertFailsWith<IllegalArgumentException> { session.clientbound(frame("axiom:enable", enable)) }
}
private fun session() = AxiomProxySession(776, 771, engine) { challenge }
private fun enabled(split: Int = SPLIT) = session().also {
it.backendRegistered(modernChannels.toByteArray())
it.clientbound(challengeFrame())
it.serverbound(modernHello())
it.clientbound(frame("axiom:enable", AxiomEnableCodec.write(AxiomEnable(
enabled = true, blueprintVersion = 2, customDataOverridesCount = 0, rotationOverridesCount = 0,
serverConfigVersion = 0, tunnelSplitSize = split, maximumTunnelPacketSize = 2_097_152,
supportedServerboundChannels = listOf("axiom:set_block", "axiom:set_buffer", "axiom:tunnel")), 10)))
}
private fun frame(channel: String, bytes: ByteArray) = AxiomCustomPayloadFrame(0, channel, bytes)
private fun challengeFrame() = frame("axiom:hello", AxiomByteWriter().writeLong(challenge).toByteArray())
private fun modernHello() = frame("axiom:hello", AxiomHelloCodec.write(AxiomHello(10, 5000, 776, challenge)))
private fun setBlock(id: Int) = AxiomByteWriter().writeVarInt(1).writeLong(123).writeVarInt(id).toByteArray()
private companion object {
const val SPLIT = 31_000
}
}
@@ -0,0 +1,69 @@
package me.wargearsystems.viaaxiom.protocol
import me.wargearsystems.viaaxiom.binary.AxiomByteReader
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
class AxiomResponseChunkDataPayloadCodecTest {
@Test
fun `rewrites present section payloads and preserves response structure`() {
val original = responsePayload(
sectionPayload = byteArrayOf(1, 2, 3),
finished = false,
)
val rewritten = AxiomResponseChunkDataPayloadCodec.rewriteSections(original) { reader, writer ->
assertContentEquals(byteArrayOf(1, 2, 3), reader.readByteArray())
writer.writeByteArray(byteArrayOf(9, 8, 7))
}
val reader = AxiomByteReader(rewritten)
assertEquals(42L, reader.readLong())
assertBlockEntityCopied(reader)
assertEquals(AxiomProtocol.MIN_POSITION_LONG, reader.readLong())
assertEquals(0x2122232425262728L, reader.readLong())
assertEquals(true, reader.readBoolean())
assertContentEquals(byteArrayOf(9, 8, 7), reader.readByteArray())
assertEquals(0x3132333435363738L, reader.readLong())
assertEquals(false, reader.readBoolean())
assertEquals(AxiomProtocol.MIN_POSITION_LONG, reader.readLong())
assertEquals(false, reader.readBoolean())
assertEquals(99, reader.readVarInt())
assertEquals(0, reader.readableBytes)
}
private fun responsePayload(sectionPayload: ByteArray, finished: Boolean): ByteArray {
val writer = AxiomByteWriter()
.writeLong(42L)
writeBlockEntity(writer)
writer
.writeLong(AxiomProtocol.MIN_POSITION_LONG)
.writeLong(0x2122232425262728L)
.writeBoolean(true)
.writeByteArray(sectionPayload)
.writeLong(0x3132333435363738L)
.writeBoolean(false)
.writeLong(AxiomProtocol.MIN_POSITION_LONG)
.writeBoolean(finished)
.writeVarInt(99)
return writer.toByteArray()
}
private fun writeBlockEntity(writer: AxiomByteWriter) {
writer
.writeLong(0x0102030405060708L)
.writeVarInt(1234)
.writeByte(0)
.writeByteArray(byteArrayOf(5, 4, 3))
}
private fun assertBlockEntityCopied(reader: AxiomByteReader) {
assertEquals(0x0102030405060708L, reader.readLong())
assertEquals(1234, reader.readVarInt())
assertEquals(0, reader.readUnsignedByte())
assertContentEquals(byteArrayOf(5, 4, 3), reader.readByteArray())
}
}
@@ -0,0 +1,43 @@
package me.wargearsystems.viaaxiom.protocol
import me.wargearsystems.viaaxiom.binary.AxiomByteReader
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
class AxiomSetBlockPayloadCodecTest {
@Test
fun `rewrites only block state ids in leading block map`() {
val passthroughTail = AxiomByteWriter()
.writeBoolean(true)
.writeVarInt(1)
.writeLong(0x1112131415161718L)
.writeVarInt(128)
.writeBoolean(false)
.writeLong(0x2122232425262728L)
.writeVarInt(2)
.writeVarInt(0)
.toByteArray()
val payload = AxiomByteWriter()
.writeVarInt(2)
.writeLong(0x0102030405060708L)
.writeVarInt(10)
.writeLong(0x090A0B0C0D0E0F10L)
.writeVarInt(20)
.writeBytes(passthroughTail)
.toByteArray()
val rewritten = AxiomSetBlockPayloadCodec.rewriteBlockStateIds(payload) { id -> id + 1000 }
val reader = AxiomByteReader(rewritten)
assertEquals(2, reader.readVarInt())
assertEquals(0x0102030405060708L, reader.readLong())
assertEquals(1010, reader.readVarInt())
assertEquals(0x090A0B0C0D0E0F10L, reader.readLong())
assertEquals(1020, reader.readVarInt())
assertContentEquals(passthroughTail, reader.copyRemaining())
}
}
@@ -0,0 +1,90 @@
package me.wargearsystems.viaaxiom.protocol
import me.wargearsystems.viaaxiom.binary.AxiomByteReader
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
class AxiomSetBufferPayloadCodecTest {
@Test
fun `rewrites block section payloads and preserves block entities plus tail`() {
val original = setBufferPayload(
type = 0,
sectionPayload = byteArrayOf(1, 2, 3),
)
val rewritten = AxiomSetBufferPayloadCodec.rewriteBlockSections(original) { reader, writer ->
assertContentEquals(byteArrayOf(1, 2, 3), reader.readByteArray())
writer.writeByteArray(byteArrayOf(9, 8, 7, 6))
}
val reader = AxiomByteReader(rewritten)
assertEquals("minecraft:overworld", reader.readUtf())
assertEquals(0x0102030405060708L, reader.readLong())
assertEquals(0x1112131415161718L, reader.readLong())
assertEquals(0, reader.readUnsignedByte())
assertEquals(0x2122232425262728L, reader.readLong())
assertContentEquals(byteArrayOf(9, 8, 7, 6), reader.readByteArray())
assertBlockEntityCopied(reader)
assertEquals(AxiomProtocol.MIN_POSITION_LONG, reader.readLong())
assertEquals(64, reader.readVarInt())
assertEquals(0, reader.readableBytes)
}
@Test
fun `passes non block buffer payloads through after header`() {
val original = setBufferPayload(
type = 1,
sectionPayload = byteArrayOf(1, 2, 3),
)
val rewritten = AxiomSetBufferPayloadCodec.rewriteBlockSections(original) { _, _ ->
error("Biome buffers should not invoke block section rewriter")
}
assertContentEquals(original, rewritten)
}
private fun setBufferPayload(type: Int, sectionPayload: ByteArray): ByteArray {
val writer = AxiomByteWriter()
.writeUtf("minecraft:overworld")
.writeLong(0x0102030405060708L)
.writeLong(0x1112131415161718L)
.writeByte(type)
if (type == 0) {
writer
.writeLong(0x2122232425262728L)
.writeByteArray(sectionPayload)
writeBlockEntity(writer)
writer
.writeLong(AxiomProtocol.MIN_POSITION_LONG)
.writeVarInt(64)
} else {
writer
.writeByteArray(sectionPayload)
.writeVarInt(64)
}
return writer.toByteArray()
}
private fun writeBlockEntity(writer: AxiomByteWriter) {
writer
.writeVarInt(1)
.writeShort(0x00AF)
.writeVarInt(1234)
.writeByte(0)
.writeByteArray(byteArrayOf(5, 4, 3, 2, 1))
}
private fun assertBlockEntityCopied(reader: AxiomByteReader) {
assertEquals(1, reader.readVarInt())
assertEquals(0x00AF, reader.readShort().toInt())
assertEquals(1234, reader.readVarInt())
assertEquals(0, reader.readUnsignedByte())
assertContentEquals(byteArrayOf(5, 4, 3, 2, 1), reader.readByteArray())
}
}
@@ -0,0 +1,51 @@
package me.wargearsystems.viaaxiom.protocol
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
import kotlin.test.*
class AxiomTunnelCodecTest {
@Test fun `uncompressed single fragment matches upstream wire format`() {
val fragment = AxiomByteWriter().writeByte(3).writeUtf("axiom:set_block").writeInt(3)
.writeByte(0).writeBytes(byteArrayOf(5, 6, 7)).toByteArray()
val packet = AxiomTunnelCodec.decode(listOf(fragment))
assertEquals("axiom:set_block", packet.channel)
assertContentEquals(byteArrayOf(5, 6, 7), packet.payload)
assertFalse(packet.compressed)
assertContentEquals(fragment, AxiomTunnelCodec.encode(packet).single())
}
@Test fun `fragmented packets obey total fragment size and recover exact payload`() {
val packet = AxiomTunnelPacket("axiom:set_buffer", ByteArray(257) { it.toByte() })
val fragments = AxiomTunnelCodec.encode(packet, splitSize = 23)
assertTrue(fragments.size > 2)
assertTrue(fragments.all { it.size <= 23 })
assertEquals(1, fragments.first()[0].toInt())
assertEquals(2, fragments.last()[0].toInt())
assertContentEquals(packet.payload, AxiomTunnelCodec.decode(fragments, 23).payload)
}
@Test fun `actual Zstd compression survives split transport`() {
val packet = AxiomTunnelPacket("axiom:set_buffer", ByteArray(16384) { (it * 17).toByte() }, true)
val fragments = AxiomTunnelCodec.encode(packet, 71)
assertTrue(fragments.size > 1)
val decoded = AxiomTunnelCodec.decode(fragments, 71)
assertTrue(decoded.compressed)
assertContentEquals(packet.payload, decoded.payload)
}
@Test fun `rejects out of order fragments and oversized decoded payload`() {
val packet = AxiomTunnelPacket("axiom:set_buffer", ByteArray(100), true)
val fragments = AxiomTunnelCodec.encode(packet, 10)
assertFailsWith<IllegalArgumentException> { AxiomTunnelCodec.decode(fragments.reversed(), 10) }
assertFailsWith<IllegalArgumentException> { AxiomTunnelCodec.decode(fragments, 10, 99) }
assertFailsWith<IllegalArgumentException> { AxiomTunnelCodec.encode(packet, 10, 99) }
}
@Test fun `rejects mismatched declared length corrupt compression and unknown flags`() {
for ((length, flags) in listOf(100 to 0, 3 to 1, 3 to 2, -1 to 0)) {
val fragment = AxiomByteWriter().writeByte(3).writeUtf("axiom:set_block").writeInt(length)
.writeByte(flags).writeBytes(byteArrayOf(5, 6, 7)).toByteArray()
assertFailsWith<IllegalArgumentException> { AxiomTunnelCodec.decode(listOf(fragment)) }
}
}
}
@@ -0,0 +1,119 @@
package me.wargearsystems.viaaxiom.protocol
import me.wargearsystems.viaaxiom.binary.AxiomByteReader
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
import kotlin.test.*
class PalettedContainerCodecTest {
@Test fun `singleton consumes exactly one section across both formats`() {
for (protocol in listOf(769, 770)) {
val bytes = AxiomByteWriter().writeByte(0).writeVarInt(1234).also {
if (protocol < 770) it.writeVarInt(0)
}.writeInt(0x12345678).toByteArray()
val reader = AxiomByteReader(bytes)
val container = PalettedContainerCodec.readBlockContainer(reader, protocol, 15)
assertEquals(1234, container.idAt(4095))
assertEquals(0x12345678, reader.readInt())
assertEquals(0, reader.readableBytes)
}
}
@Test fun `local palette conversion preserves indexes and merges colliding states`() {
val input = AxiomByteWriter().writeByte(4).writeVarInt(2).writeVarInt(2).writeVarInt(3)
.writeVarInt(256).writeLongArray(LongArray(256) { 0x1010101010101010L }, false).toByteArray()
val output = AxiomByteWriter()
PalettedContainerCodec.rewriteBlockStateIds(AxiomByteReader(input), output, 769, 15, { 700 }, 770, 16)
assertContentEquals(AxiomByteWriter().writeByte(0).writeVarInt(700).toByteArray(), output.toByteArray())
}
@Test fun `global wire IDs become indexes and sparse registry IDs survive mapping`() {
// Four 15-bit entries per long, with one slot unused at the top.
val packed = 1000L or (2000L shl 15) or (1000L shl 30) or (2000L shl 45)
val input = AxiomByteWriter().writeByte(15).writeLongArray(LongArray(1024) { packed }, false)
.writeByte(42).toByteArray()
val reader = AxiomByteReader(input)
val container = PalettedContainerCodec.readBlockContainer(reader, 770, 15)
assertEquals(1000, container.idAt(0))
assertEquals(2000, container.idAt(4095))
assertEquals(42, reader.readUnsignedByte())
container.replaceIds { it + 1 }
assertEquals(1001, container.idAt(0))
assertEquals(2001, container.idAt(4095))
}
@Test fun `global palette writes every value across partial final long`() {
val data = PalettedContainerData((1000..1299).toMutableList(), IntArray(4096) { it % 300 })
for (protocol in listOf(769, 770)) {
val writer = AxiomByteWriter()
PalettedContainerCodec.writeBlockContainer(writer, data, protocol, 13)
val bytes = writer.toByteArray()
assertEquals(13, bytes[0].toInt())
val restored = PalettedContainerCodec.readBlockContainer(AxiomByteReader(bytes), protocol, 13)
repeat(4096) { assertEquals(1000 + it % 300, restored.idAt(it)) }
}
}
@Test fun `same layout rewrite decodes like the full conversion`() {
val random = kotlin.random.Random(7)
val mapper = { id: Int -> (id * 3 + 1) % 500 }
for (protocol in listOf(769, 770)) {
for (distinct in listOf(1, 2, 16, 17, 256, 300)) {
for (width in listOf(9, 13, 15)) {
val ids = List(distinct) { random.nextInt(500) }.distinct()
val source = PalettedContainerData(ids.toMutableList(), IntArray(4096) { random.nextInt(ids.size) })
val input = AxiomByteWriter().also { PalettedContainerCodec.writeBlockContainer(it, source, protocol, width) }
.writeByte(42).toByteArray()
val output = AxiomByteWriter()
val reader = AxiomByteReader(input)
PalettedContainerCodec.rewriteBlockStateIds(reader, output, protocol, width, mapper)
assertEquals(42, reader.readUnsignedByte())
val result = AxiomByteReader(output.toByteArray())
val actual = PalettedContainerCodec.readBlockContainer(result, protocol, width)
assertEquals(0, result.readableBytes)
repeat(4096) { assertEquals(mapper(source.idAt(it)), actual.idAt(it)) }
}
}
}
}
@Test fun `palette indexes are copied without changing the packed data`() {
val packed = LongArray(256) { 0x0123012301230123L }
val input = AxiomByteWriter().writeByte(4).writeVarInt(4).writeVarInt(5).writeVarInt(6).writeVarInt(7).writeVarInt(8)
.writeLongArray(packed, false).toByteArray()
val output = AxiomByteWriter()
PalettedContainerCodec.rewriteBlockStateIds(AxiomByteReader(input), output, 770, 15, { 700 })
val expected = AxiomByteWriter().writeByte(4).writeVarInt(4).writeVarInt(700).writeVarInt(700).writeVarInt(700).writeVarInt(700)
.writeLongArray(packed, false).toByteArray()
assertContentEquals(expected, output.toByteArray())
}
@Test fun `same layout rewrite rejects bad indexes and IDs that do not fit`() {
val badIndex = AxiomByteWriter().writeByte(4).writeVarInt(1).writeVarInt(1)
.writeLongArray(LongArray(256) { 2L }, false).toByteArray()
assertFailsWith<IllegalArgumentException> {
PalettedContainerCodec.rewriteBlockStateIds(AxiomByteReader(badIndex), AxiomByteWriter(), 770, 15, { it })
}
val singleton = AxiomByteWriter().writeByte(0).writeVarInt(1).toByteArray()
assertFailsWith<IllegalArgumentException> {
PalettedContainerCodec.rewriteBlockStateIds(AxiomByteReader(singleton), AxiomByteWriter(), 770, 15, { 32768 })
}
val global = AxiomByteWriter().writeByte(15).writeLongArray(LongArray(1024), false).toByteArray()
assertFailsWith<IllegalArgumentException> {
PalettedContainerCodec.rewriteBlockStateIds(AxiomByteReader(global), AxiomByteWriter(), 770, 15, { -1 })
}
}
@Test fun `rejects invalid palette indexes and mismatched array sizes`() {
val invalidIndex = AxiomByteWriter().writeByte(4).writeVarInt(1).writeVarInt(1)
.writeLongArray(LongArray(256) { 2L }, false).toByteArray()
assertFailsWith<IllegalArgumentException> { PalettedContainerCodec.readBlockContainer(AxiomByteReader(invalidIndex), 770, 15) }
val invalidLength = AxiomByteWriter().writeByte(0).writeVarInt(1).writeVarInt(1).writeLong(0).toByteArray()
assertFailsWith<IllegalArgumentException> { PalettedContainerCodec.readBlockContainer(AxiomByteReader(invalidLength), 769, 15) }
}
@Test fun `target width overflow is rejected instead of truncating block IDs`() {
val data = PalettedContainerData(mutableListOf(32768), IntArray(4096))
assertFailsWith<IllegalArgumentException> { PalettedContainerCodec.writeBlockContainer(AxiomByteWriter(), data, 770, 15) }
}
}
@@ -0,0 +1,73 @@
package me.wargearsystems.viaaxiom.translation
import me.wargearsystems.viaaxiom.binary.AxiomByteReader
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
import me.wargearsystems.viaaxiom.protocol.*
import kotlin.test.*
class AxiomBulkTranslationTest {
private val engine = AxiomTranslationEngine(object : BlockStateIdTranslator {
override fun clientToServer(blockStateId: Int) = blockStateId + 1000
override fun serverToClient(blockStateId: Int) = blockStateId - 1000
}, BlockStatePaletteWidths(15, 16))
private val session = AxiomTranslationSession(AxiomHello(9, 1, 769), 770)
@Test fun `set buffer rewrites multiple real palettes and preserves compressed block entities`() {
val writer = AxiomByteWriter().writeUtf("minecraft:overworld").writeLong(10).writeLong(20).writeByte(0)
for ((section, state) in listOf(100L to 2, 200L to 3)) {
writer.writeLong(section).writeByte(0).writeVarInt(state).writeVarInt(0)
writer.writeVarInt(1).writeShort(42).writeVarInt(7).writeByte(0).writeByteArray(byteArrayOf(9, 8, 7))
}
writer.writeLong(AxiomProtocol.MIN_POSITION_LONG).writeVarInt(64)
val result = engine.rewrite(AxiomPayload(AxiomPayloadDirection.SERVERBOUND, "axiom:set_buffer", writer.toByteArray()), session)
val reader = AxiomByteReader(result)
assertEquals("minecraft:overworld", reader.readUtf())
assertEquals(10, reader.readLong())
assertEquals(20, reader.readLong())
assertEquals(0, reader.readUnsignedByte())
for ((section, state) in listOf(100L to 1002, 200L to 1003)) {
assertEquals(section, reader.readLong())
assertEquals(state, PalettedContainerCodec.readBlockContainer(reader, 770, 16).idAt(4095))
assertEquals(1, reader.readVarInt())
assertEquals(42, reader.readShort().toInt())
assertEquals(7, reader.readVarInt())
assertEquals(0, reader.readUnsignedByte())
assertContentEquals(byteArrayOf(9, 8, 7), reader.readByteArray())
}
assertEquals(AxiomProtocol.MIN_POSITION_LONG, reader.readLong())
assertEquals(64, reader.readVarInt())
assertEquals(0, reader.readableBytes)
}
@Test fun `response maps server palette to legacy client format and retains missing sections`() {
val bytes = AxiomByteWriter().writeLong(77).writeLong(AxiomProtocol.MIN_POSITION_LONG)
.writeLong(100).writeBoolean(true).writeByte(0).writeVarInt(1002)
.writeLong(200).writeBoolean(false).writeLong(AxiomProtocol.MIN_POSITION_LONG)
.writeBoolean(true).toByteArray()
val result = engine.rewrite(AxiomPayload(AxiomPayloadDirection.CLIENTBOUND, "axiom:response_chunk_data", bytes), session)
val reader = AxiomByteReader(result)
assertEquals(77, reader.readLong())
assertEquals(AxiomProtocol.MIN_POSITION_LONG, reader.readLong())
assertEquals(100, reader.readLong())
assertTrue(reader.readBoolean())
assertEquals(2, PalettedContainerCodec.readBlockContainer(reader, 769, 15).idAt(0))
assertEquals(200, reader.readLong())
assertFalse(reader.readBoolean())
assertEquals(AxiomProtocol.MIN_POSITION_LONG, reader.readLong())
assertTrue(reader.readBoolean())
assertEquals(0, reader.readableBytes)
}
@Test fun `biome buffer passes through without touching its body`() {
val bytes = AxiomByteWriter().writeUtf("minecraft:overworld").writeLong(10).writeLong(20)
.writeByte(1).writeBytes(byteArrayOf(1, 2, 3)).toByteArray()
assertContentEquals(bytes, engine.rewrite(AxiomPayload(AxiomPayloadDirection.SERVERBOUND, "axiom:set_buffer", bytes), session))
}
@Test fun `bulk rewriting requires explicit registry widths`() {
val bytes = byteArrayOf(1, 2, 3)
assertContentEquals(bytes, AxiomTranslationEngine(IdentityBlockStateIdTranslator).rewrite(
AxiomPayload(AxiomPayloadDirection.SERVERBOUND, "axiom:set_buffer", bytes), session,
))
}
}
@@ -0,0 +1,85 @@
package me.wargearsystems.viaaxiom.translation
import me.wargearsystems.viaaxiom.binary.AxiomByteReader
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
import me.wargearsystems.viaaxiom.protocol.AxiomCustomPayloadFrameCodec
import me.wargearsystems.viaaxiom.protocol.AxiomHello
import me.wargearsystems.viaaxiom.protocol.AxiomPayloadDirection
import me.wargearsystems.viaaxiom.protocol.AxiomProtocol
import me.wargearsystems.viaaxiom.protocol.AxiomTranslationSession
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
class AxiomFrameTranslationEngineTest {
private val frameEngine = AxiomFrameTranslationEngine(
AxiomTranslationEngine(
TableBlockStateIdTranslator(
clientToServer = intArrayOf(0, 101, 102),
serverToClient = intArrayOf(0, 201, 202),
fallbackId = 0,
),
),
)
@Test
fun `rewrites set block payload inside a matching custom payload frame`() {
val rewrittenFrame = frameEngine.rewrite(
frameBytes = customPayloadFrame(packetId = 12, channel = AxiomProtocol.channel("set_block"), payload = setBlockPayload(2)),
customPayloadPacketId = 12,
direction = AxiomPayloadDirection.SERVERBOUND,
session = session(clientProtocol = 772, serverProtocol = 773),
)
val frame = AxiomCustomPayloadFrameCodec.readIfCustomPayload(rewrittenFrame, customPayloadPacketId = 12)
requireNotNull(frame)
val payload = AxiomByteReader(frame.payloadBytes)
assertEquals(1, payload.readVarInt())
assertEquals(0x0102030405060708L, payload.readLong())
assertEquals(102, payload.readVarInt())
}
@Test
fun `passes through when the packet id is not custom payload`() {
val frame = customPayloadFrame(packetId = 11, channel = AxiomProtocol.channel("set_block"), payload = setBlockPayload(2))
val rewrittenFrame = frameEngine.rewrite(
frameBytes = frame,
customPayloadPacketId = 12,
direction = AxiomPayloadDirection.SERVERBOUND,
session = session(clientProtocol = 772, serverProtocol = 773),
)
assertContentEquals(frame, rewrittenFrame)
}
private fun customPayloadFrame(packetId: Int, channel: String, payload: ByteArray): ByteArray {
return AxiomByteWriter()
.writeVarInt(packetId)
.writeUtf(channel)
.writeBytes(payload)
.toByteArray()
}
private fun setBlockPayload(blockStateId: Int): ByteArray {
return AxiomByteWriter()
.writeVarInt(1)
.writeLong(0x0102030405060708L)
.writeVarInt(blockStateId)
.writeBoolean(false)
.toByteArray()
}
private fun session(clientProtocol: Int, serverProtocol: Int): AxiomTranslationSession {
return AxiomTranslationSession(
hello = AxiomHello(
apiVersion = AxiomProtocol.API_VERSION,
dataVersion = 4438,
protocolVersion = clientProtocol,
),
serverProtocolVersion = serverProtocol,
)
}
}
@@ -0,0 +1,80 @@
package me.wargearsystems.viaaxiom.translation
import me.wargearsystems.viaaxiom.binary.AxiomByteReader
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
import me.wargearsystems.viaaxiom.protocol.AxiomHello
import me.wargearsystems.viaaxiom.protocol.AxiomPayloadDirection
import me.wargearsystems.viaaxiom.protocol.AxiomProtocol
import me.wargearsystems.viaaxiom.protocol.AxiomTranslationSession
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
class AxiomTranslationEngineTest {
private val translator = TableBlockStateIdTranslator(
clientToServer = intArrayOf(0, 101, 102, 103),
serverToClient = intArrayOf(0, 201, 202, 203),
fallbackId = 0,
)
private val engine = AxiomTranslationEngine(translator)
@Test
fun `passes through when protocol versions match`() {
val payload = setBlockPayload(blockStateId = 2)
val rewritten = engine.rewrite(
payload = AxiomPayload(AxiomPayloadDirection.SERVERBOUND, AxiomProtocol.channel("set_block"), payload),
session = session(clientProtocol = 773, serverProtocol = 773),
)
assertContentEquals(payload, rewritten)
}
@Test
fun `passes through non axiom channels`() {
val payload = byteArrayOf(1, 2, 3)
val rewritten = engine.rewrite(
payload = AxiomPayload(AxiomPayloadDirection.SERVERBOUND, "minecraft:brand", payload),
session = session(clientProtocol = 772, serverProtocol = 773),
)
assertContentEquals(payload, rewritten)
}
@Test
fun `rewrites serverbound set block ids on protocol mismatch`() {
val rewritten = engine.rewrite(
payload = AxiomPayload(
direction = AxiomPayloadDirection.SERVERBOUND,
channel = AxiomProtocol.channel("set_block"),
bytes = setBlockPayload(blockStateId = 2),
),
session = session(clientProtocol = 772, serverProtocol = 773),
)
val reader = AxiomByteReader(rewritten)
assertEquals(1, reader.readVarInt())
assertEquals(0x0102030405060708L, reader.readLong())
assertEquals(102, reader.readVarInt())
}
private fun setBlockPayload(blockStateId: Int): ByteArray {
return AxiomByteWriter()
.writeVarInt(1)
.writeLong(0x0102030405060708L)
.writeVarInt(blockStateId)
.writeBoolean(false)
.toByteArray()
}
private fun session(clientProtocol: Int, serverProtocol: Int): AxiomTranslationSession {
return AxiomTranslationSession(
hello = AxiomHello(
apiVersion = AxiomProtocol.API_VERSION,
dataVersion = 4438,
protocolVersion = clientProtocol,
),
serverProtocolVersion = serverProtocol,
)
}
}
@@ -0,0 +1,43 @@
package me.wargearsystems.viaaxiom.translation
import me.wargearsystems.viaaxiom.binary.AxiomByteReader
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
import me.wargearsystems.viaaxiom.protocol.*
import kotlin.test.*
class AxiomTunnelTranslationEngineTest {
private val enable = AxiomEnable(true, 0, 2, 0, 0, 0, 17, 1024, listOf("axiom:set_block"))
private val session = AxiomTranslationSession(AxiomHello(10, 5000, 775, 42), 773, enable = enable)
private val translator = AxiomTranslationEngine(object : BlockStateIdTranslator {
override fun clientToServer(blockStateId: Int) = 100_000 + blockStateId
override fun serverToClient(blockStateId: Int) = blockStateId
})
@Test fun `fragmented compressed upload translates inner IDs and preserves tail`() {
val payload = AxiomByteWriter().writeVarInt(1).writeLong(123).writeVarInt(2)
.writeBytes(byteArrayOf(0, 9, 8, 7)).toByteArray()
for (compressed in listOf(false, true)) {
val fragments = AxiomTunnelCodec.encode(AxiomTunnelPacket("axiom:set_block", payload, compressed), 17, 1024)
val result = AxiomTunnelTranslationEngine(translator).rewrite(fragments, session)
assertTrue(result.all { it.size <= 17 })
val packet = AxiomTunnelCodec.decode(result, 17, 1024)
assertEquals(compressed, packet.compressed)
val reader = AxiomByteReader(packet.payload)
assertEquals(1, reader.readVarInt())
assertEquals(123, reader.readLong())
assertEquals(100_002, reader.readVarInt())
assertContentEquals(byteArrayOf(0, 9, 8, 7), reader.copyRemaining())
}
}
@Test fun `unchanged payload retains original compression and fragment bytes`() {
val payload = AxiomByteWriter().writeVarInt(0).writeBoolean(false).toByteArray()
val fragments = AxiomTunnelCodec.encode(AxiomTunnelPacket("axiom:set_block", payload, true), 17, 1024)
assertSame(fragments, AxiomTunnelTranslationEngine(translator).rewrite(fragments, session))
}
@Test fun `refuses channels not advertised by server`() {
val fragments = AxiomTunnelCodec.encode(AxiomTunnelPacket("axiom:delete_entity", byteArrayOf()), 17, 1024)
assertFailsWith<IllegalArgumentException> { AxiomTunnelTranslationEngine(translator).rewrite(fragments, session) }
}
}
@@ -0,0 +1,65 @@
package me.wargearsystems.viaaxiom.translation
import kotlin.test.Test
import kotlin.test.assertEquals
class BlockStateIdTranslatorTest {
@Test
fun `uses directional placeholders for missing block state ids`() {
val translator = TableBlockStateIdTranslator(
clientToServer = intArrayOf(0, 10, -1),
serverToClient = intArrayOf(0, -1, 20),
missingBlockStatePolicy = MissingBlockStatePolicy(
clientToServerFallbackId = 5,
serverToClientFallbackId = 6,
),
)
assertEquals(10, translator.clientToServer(1))
assertEquals(5, translator.clientToServer(2))
assertEquals(5, translator.clientToServer(99))
assertEquals(20, translator.serverToClient(2))
assertEquals(6, translator.serverToClient(1))
assertEquals(6, translator.serverToClient(99))
}
@Test
fun `single placeholder constructor applies in both directions`() {
val translator = TableBlockStateIdTranslator(
clientToServer = intArrayOf(-1),
serverToClient = intArrayOf(-1),
fallbackId = 7,
)
assertEquals(7, translator.clientToServer(0))
assertEquals(7, translator.serverToClient(0))
}
@Test
fun `reports missing block state fallback usage`() {
val reports = mutableListOf<Triple<BlockStateMappingDirection, Int, Int>>()
val translator = TableBlockStateIdTranslator(
clientToServer = intArrayOf(-1),
serverToClient = intArrayOf(-1),
missingBlockStatePolicy = MissingBlockStatePolicy(
clientToServerFallbackId = 5,
serverToClientFallbackId = 6,
),
onMissingBlockState = { direction, missingId, fallbackId ->
reports += Triple(direction, missingId, fallbackId)
},
)
translator.clientToServer(0)
translator.serverToClient(99)
assertEquals(
listOf(
Triple(BlockStateMappingDirection.CLIENT_TO_SERVER, 0, 5),
Triple(BlockStateMappingDirection.SERVER_TO_CLIENT, 99, 6),
),
reports,
)
}
}
@@ -0,0 +1,22 @@
package me.wargearsystems.viaaxiom.translation
import kotlin.test.*
class BlockStateMappingChainTest {
@Test fun `multi version mappings compose in server to client order`() {
val (outbound, inbound) = BlockStateMappingChain.compose(listOf(intArrayOf(0, 2, 1), intArrayOf(0, 1, 3)), 5, 1)
assertContentEquals(intArrayOf(0, 3, 1), inbound)
assertContentEquals(intArrayOf(0, 2, -1, 1, -1), outbound)
}
@Test fun `many to one collision prefers earlier canonical server state`() {
val (outbound, _) = BlockStateMappingChain.compose(listOf(intArrayOf(0, 1, 1, 2)), 3, 1)
assertEquals(1, outbound[1])
}
@Test fun `missing mappings remain missing and stone must exist`() {
val (_, inbound) = BlockStateMappingChain.compose(listOf(intArrayOf(0, 1, -1, 99)), 3, 1)
assertContentEquals(intArrayOf(0, 1, -1, -1), inbound)
assertFailsWith<IllegalArgumentException> { BlockStateMappingChain.compose(listOf(intArrayOf(0, -1)), 3, 1) }
}
}
+47
View File
@@ -0,0 +1,47 @@
# Axiom protocol notes
Taken from [AxiomPaperPlugin](https://github.com/Moulberry/AxiomPaperPlugin). The "API version" is Axiom's own wire version.
## Handshake
API 9: the client sends `axiom:hello` with VarInt API, data and protocol versions. The server answers with `axiom:enable`.
API 10: the server sends `axiom:hello` first, holding a long challenge. The client replies with the same three VarInts plus that long. Failures arrive as `axiom:goodbye` with a string.
Neither handshake carries the server's Minecraft version. The hello's protocol field describes the client, and the server translates IDs itself if it differs from its own. ViaAxiom writes the backend's protocol there, so only ViaAxiom translates.
An API 9 server has no hello to send. ViaAxiom detects it from `minecraft:register` containing `axiom:hello` without `axiom:tunnel`, and makes up the challenge itself.
`axiom:enable` fields:
| API 9 | API 10 |
|---|---|
| boolean enabled | boolean enabled |
| int max buffer size | byte config version, currently 0 |
| VarInt blueprint version | VarInt blueprint version |
| VarInt custom data overrides | int tunnel split size, default 31000 |
| VarInt rotation overrides | int max tunnel packet size, default 2097152 |
| | VarInt custom data overrides, always 0 |
| | VarInt rotation overrides, always 0 |
| | VarInt count, then serverbound channel names |
## Tunnel
API 10 sends large serverbound packets through `axiom:tunnel`. Each fragment starts with a flag byte, FIRST=1 and LAST=2. The joined body is the channel name, an int uncompressed size, a flag byte (1 means Zstd), and the payload. API 9 sends those packets raw instead, which needs Paper's large payload decoder.
Translation can change a packet's size, so ViaAxiom collects all fragments, translates, and splits again.
## Payloads with block IDs
| Channel | Direction | IDs |
|---|---|---|
| `axiom:set_block` | serverbound | map of long position to VarInt state |
| `axiom:set_buffer` | serverbound | paletted sections, type 0 only |
| `axiom:response_chunk_data` | clientbound | paletted sections |
| `axiom:register_custom_block_v2` | clientbound | VarInt state, or -1 and a string |
`set_buffer` is a dimension key, a UUID, a type byte, then sections of long index, paletted container, and block entities, ending at `-9223371899415820288`.
Paletted containers lost their long array length in protocol 770 (1.21.5). Bits per value of 0 is a single value, 4 to 8 uses a local palette, and anything higher stores global IDs.
The Axiom empty state is `void_air`, which means "leave this block alone". It must never become a placeholder.
+95
View File
@@ -0,0 +1,95 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm")
id("net.fabricmc.fabric-loom")
}
base {
archivesName.set(project.property("archives_base_name") as String)
}
val targetJavaVersion = 25
java {
toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion)
// Minecraft 26.2 uses official names; Loom packages the JAR without remapping.
withSourcesJar()
}
loom {
splitEnvironmentSourceSets()
mods {
register("viaaxiom") {
sourceSet("main")
sourceSet("client")
}
}
}
val bundledCore: Configuration by configurations.creating {
isCanBeConsumed = false
isTransitive = false
}
dependencies {
minecraft("com.mojang:minecraft:${project.property("minecraft_version")}")
implementation("net.fabricmc:fabric-loader:${project.property("loader_version")}")
implementation("net.fabricmc:fabric-language-kotlin:${project.property("kotlin_loader_version")}")
implementation("net.fabricmc.fabric-api:fabric-api:${project.property("fabric_version")}")
implementation(project(":core"))
bundledCore(project(":core"))
testImplementation(kotlin("test"))
include("com.github.luben:zstd-jni:1.5.5-4")
}
tasks.processResources {
val minecraftVersion = project.property("minecraft_version") as String
val loaderVersion = project.property("loader_version") as String
val kotlinLoaderVersion = project.property("kotlin_loader_version") as String
inputs.property("version", project.version)
inputs.property("minecraft_version", minecraftVersion)
inputs.property("loader_version", loaderVersion)
filteringCharset = "UTF-8"
filesMatching("fabric.mod.json") {
expand(
"version" to project.version,
"minecraft_version" to minecraftVersion,
"loader_version" to loaderVersion,
"kotlin_loader_version" to kotlinLoaderVersion
)
}
}
tasks.withType<JavaCompile>().configureEach {
options.encoding = "UTF-8"
options.release.set(targetJavaVersion)
}
tasks.withType<KotlinCompile>().configureEach {
compilerOptions.jvmTarget.set(JvmTarget.fromTarget(targetJavaVersion.toString()))
}
tasks.test {
useJUnitPlatform()
}
sourceSets.test {
compileClasspath += sourceSets["client"].output + sourceSets["client"].compileClasspath
runtimeClasspath += sourceSets["client"].output + sourceSets["client"].runtimeClasspath
}
tasks.jar {
from(bundledCore.elements.map { jars -> jars.map { zipTree(it) } }) {
exclude("META-INF/**")
}
from(files(rootProject.file("LICENSE.txt"), rootProject.file("NOTICE.txt"))) {
rename { "${it}_${project.base.archivesName.get()}" }
}
}
@@ -0,0 +1,44 @@
package me.wargearsystems.viaaxiom.mixin.client;
import io.netty.channel.ChannelHandlerContext;
import me.wargearsystems.viaaxiom.client.network.AxiomNettyBridge;
import net.minecraft.network.Connection;
import net.minecraft.network.ConnectionProtocol;
import net.minecraft.network.ProtocolInfo;
import net.minecraft.network.PacketListener;
import io.netty.channel.Channel;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Final;
import net.minecraft.network.protocol.PacketFlow;
import me.wargearsystems.viaaxiom.protocol.AxiomPayloadDirection;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(Connection.class)
public abstract class ClientConnectionMixin {
@Shadow private Channel channel;
@Shadow @Final private PacketFlow receiving;
@Inject(method = "channelActive", at = @At("TAIL"))
private void viaaxiom$installAxiomTranslator(ChannelHandlerContext context, CallbackInfo ci) {
if (receiving != PacketFlow.CLIENTBOUND) return;
AxiomNettyBridge.INSTANCE.install(context.pipeline());
}
@Inject(method = "setupInboundProtocol", at = @At("TAIL"))
private void viaaxiom$inboundProtocol(ProtocolInfo<?> protocol, PacketListener listener, CallbackInfo ci) {
if (receiving != PacketFlow.CLIENTBOUND) return;
Runnable update = () -> AxiomNettyBridge.INSTANCE.protocolChanged(channel.pipeline(),
AxiomPayloadDirection.CLIENTBOUND, protocol.id() == ConnectionProtocol.PLAY);
if (channel.eventLoop().inEventLoop()) update.run(); else channel.eventLoop().execute(update);
}
@Inject(method = "setupOutboundProtocol", at = @At("TAIL"))
private void viaaxiom$outboundProtocol(ProtocolInfo<?> protocol, CallbackInfo ci) {
if (receiving != PacketFlow.CLIENTBOUND) return;
Runnable update = () -> AxiomNettyBridge.INSTANCE.protocolChanged(channel.pipeline(),
AxiomPayloadDirection.SERVERBOUND, protocol.id() == ConnectionProtocol.PLAY);
if (channel.eventLoop().inEventLoop()) update.run(); else channel.eventLoop().execute(update);
}
}
@@ -0,0 +1,214 @@
package me.wargearsystems.viaaxiom.client.network
import me.wargearsystems.viaaxiom.protocol.AxiomCustomPayloadFrame
import me.wargearsystems.viaaxiom.protocol.AxiomCustomPayloadFrameCodec
import me.wargearsystems.viaaxiom.protocol.AxiomEnable
import me.wargearsystems.viaaxiom.protocol.AxiomHello
import me.wargearsystems.viaaxiom.protocol.AxiomHandshakeTracker
import me.wargearsystems.viaaxiom.protocol.AxiomPayloadDirection
import me.wargearsystems.viaaxiom.protocol.AxiomProtocol
import me.wargearsystems.viaaxiom.protocol.AxiomTranslationSession
import me.wargearsystems.viaaxiom.translation.AxiomFrameTranslationEngine
import me.wargearsystems.viaaxiom.translation.AxiomTranslationEngine
import me.wargearsystems.viaaxiom.translation.BlockStateIdTranslator
import me.wargearsystems.viaaxiom.translation.BlockStatePaletteWidths
import org.slf4j.LoggerFactory
import io.netty.channel.ChannelHandlerContext
import io.netty.buffer.Unpooled
import me.wargearsystems.viaaxiom.protocol.AxiomLegacyBridge
import java.util.concurrent.TimeUnit
import io.netty.channel.Channel
class AxiomClientTranslationState(
private val legacyBridgeFactory: (Channel) -> AxiomLegacyBridge = ViaFabricPlusMappingProvider::createLegacyBridge,
) {
private val logger = LoggerFactory.getLogger("ViaAxiom")
private val handshake = AxiomHandshakeTracker()
private var frameTranslationEngine: AxiomFrameTranslationEngine? = null
private var serverProtocolVersion: Int? = null
private var clientboundPlay = false
private var serverboundPlay = false
private var legacyBridge: AxiomLegacyBridge? = null
private var bridgeAttempted = false
private var modernHandshakeSeen = false
private val registeredChannels = linkedSetOf<String>()
private var generation = 0L
fun protocolChanged(direction: AxiomPayloadDirection, play: Boolean) {
if (direction == AxiomPayloadDirection.CLIENTBOUND) {
generation++
clientboundPlay = play
clientboundCustomPayloadPacketId = null
handshake.reset()
legacyBridge = null
bridgeAttempted = false
modernHandshakeSeen = false
registeredChannels.clear()
} else {
serverboundPlay = play
serverboundCustomPayloadPacketId = null
}
}
fun receive(context: ChannelHandlerContext, bytes: ByteArray): ByteArray {
if (!clientboundPlay) return bytes
val frame = readFrame(bytes, clientboundCustomPayloadPacketId) ?: return bytes
if (frame.channel == "minecraft:register") {
clientboundCustomPayloadPacketId = frame.packetId
registeredChannels.addAll(frame.payloadBytes.toString(Charsets.UTF_8).split('\u0000'))
val axiomChannels = registeredChannels.filter(AxiomProtocol::isAxiomChannel)
if (axiomChannels.isNotEmpty()) logger.info("Axiom server channels (packet {}): {}", frame.packetId, axiomChannels.joinToString(", "))
legacyBridge?.register(frame.payloadBytes)
if (!modernHandshakeSeen && "axiom:hello" in registeredChannels && "axiom:tunnel" !in registeredChannels && !bridgeAttempted) {
bridgeAttempted = true
val scheduledGeneration = generation
context.executor().schedule({
if (!context.channel().isActive || !clientboundPlay || generation != scheduledGeneration || modernHandshakeSeen || "axiom:tunnel" in registeredChannels) return@schedule
runCatching {
val bridge = legacyBridgeFactory(context.channel())
bridge.register(registeredChannels.joinToString("\u0000").toByteArray(Charsets.UTF_8))
legacyBridge = bridge
val challenge = bridge.createChallenge(frame.packetId) ?: return@runCatching
logger.info("Starting API 10 -> API 9 Axiom handshake bridge")
context.fireChannelRead(Unpooled.wrappedBuffer(AxiomCustomPayloadFrameCodec.write(challenge)))
context.fireChannelReadComplete()
}.onFailure { logger.warn("Legacy Axiom bridge unavailable: {}", it.cause?.message ?: it.message) }
}, 500, TimeUnit.MILLISECONDS)
}
return bytes
}
if (!AxiomProtocol.isAxiomChannel(frame.channel)) return bytes
clientboundCustomPayloadPacketId = frame.packetId
if (frame.channel == "axiom:hello" || frame.channel == "axiom:goodbye") modernHandshakeSeen = true
legacyBridge?.let {
val rewritten = it.clientbound(frame)
if (it.active) {
if (frame.channel == "axiom:enable") logger.info("Translated legacy Axiom enable into API 10 server configuration")
return AxiomCustomPayloadFrameCodec.write(rewritten)
}
}
observe(AxiomPayloadDirection.CLIENTBOUND, bytes)
return rewriteClientbound(bytes)
}
/** Null means this fragment is buffered until the final fragment is written. */
fun send(bytes: ByteArray): ByteArray? {
if (!serverboundPlay) return bytes
val frame = readFrame(bytes, serverboundCustomPayloadPacketId) ?: return bytes
if (frame.channel == "minecraft:register") {
serverboundCustomPayloadPacketId = frame.packetId
return bytes
}
if (!AxiomProtocol.isAxiomChannel(frame.channel)) return bytes
serverboundCustomPayloadPacketId = frame.packetId
legacyBridge?.takeIf { it.active }?.let { bridge ->
val rewritten = bridge.serverbound(frame) ?: return null
if (frame.channel == "axiom:hello") logger.info("Translated Axiom client hello into API 9 using server registry IDs")
return AxiomCustomPayloadFrameCodec.write(rewritten)
}
observe(AxiomPayloadDirection.SERVERBOUND, bytes)
return rewriteServerbound(bytes)
}
private fun readFrame(bytes: ByteArray, packetId: Int?): AxiomCustomPayloadFrame? = runCatching {
if (packetId == null) AxiomCustomPayloadFrameCodec.read(bytes)
else AxiomCustomPayloadFrameCodec.readIfCustomPayload(bytes, packetId)
}.getOrNull()
/** The provider must account for any Axiom mappings already performed by the server. */
fun configureTranslation(
serverProtocolVersion: Int,
blockStateIdTranslator: BlockStateIdTranslator,
paletteWidths: BlockStatePaletteWidths,
) {
this.serverProtocolVersion = serverProtocolVersion
frameTranslationEngine = AxiomFrameTranslationEngine(AxiomTranslationEngine(blockStateIdTranslator, paletteWidths))
}
var serverboundCustomPayloadPacketId: Int? = null
private set
var clientboundCustomPayloadPacketId: Int? = null
private set
val hello: AxiomHello?
get() = handshake.hello
val enable: AxiomEnable?
get() = handshake.enable
val session: AxiomTranslationSession?
// The handshake does not carry the server's protocol, a provider has to supply it.
get() = handshake.session(serverProtocolVersion)
fun observe(direction: AxiomPayloadDirection, frameBytes: ByteArray): AxiomCustomPayloadFrame? {
val knownPacketId = when (direction) {
AxiomPayloadDirection.CLIENTBOUND -> clientboundCustomPayloadPacketId
AxiomPayloadDirection.SERVERBOUND -> serverboundCustomPayloadPacketId
}
val frame = if (knownPacketId == null) {
runCatching { AxiomCustomPayloadFrameCodec.read(frameBytes) }.getOrNull()
} else {
runCatching { AxiomCustomPayloadFrameCodec.readIfCustomPayload(frameBytes, knownPacketId) }.getOrNull()
} ?: return null
if (!AxiomProtocol.isAxiomChannel(frame.channel)) {
return null
}
when (direction) {
AxiomPayloadDirection.CLIENTBOUND -> clientboundCustomPayloadPacketId = frame.packetId
AxiomPayloadDirection.SERVERBOUND -> serverboundCustomPayloadPacketId = frame.packetId
}
runCatching { handshake.observe(direction, frame.channel, frame.payloadBytes) }
.onFailure { logger.warn("Cannot observe {} {}: {}", direction, frame.channel, it.message) }
if (direction == AxiomPayloadDirection.CLIENTBOUND && frame.channel == AxiomProtocol.channel("enable")) {
enable?.let {
logger.info("Axiom API {} enabled={}; client-side mappings configured={}", hello?.apiVersion, it.enabled, frameTranslationEngine != null)
}
}
if (direction == AxiomPayloadDirection.CLIENTBOUND && frame.channel == AxiomProtocol.channel("goodbye")) {
handshake.goodbyeReason?.let { logger.info("Axiom disabled: {}", it) }
}
return frame
}
fun rewriteServerbound(frameBytes: ByteArray): ByteArray {
val packetId = serverboundCustomPayloadPacketId ?: return frameBytes
val session = session ?: return frameBytes
val engine = frameTranslationEngine ?: return frameBytes
return runCatching {
engine.rewrite(
frameBytes = frameBytes,
customPayloadPacketId = packetId,
direction = AxiomPayloadDirection.SERVERBOUND,
session = session,
)
}.getOrElse {
logger.warn("Could not rewrite serverbound Axiom payload: {}", it.message)
frameBytes
}
}
fun rewriteClientbound(frameBytes: ByteArray): ByteArray {
val packetId = clientboundCustomPayloadPacketId ?: return frameBytes
val session = session ?: return frameBytes
val engine = frameTranslationEngine ?: return frameBytes
return runCatching {
engine.rewrite(
frameBytes = frameBytes,
customPayloadPacketId = packetId,
direction = AxiomPayloadDirection.CLIENTBOUND,
session = session,
)
}.getOrElse {
logger.warn("Could not rewrite clientbound Axiom payload: {}", it.message)
frameBytes
}
}
}
@@ -0,0 +1,52 @@
package me.wargearsystems.viaaxiom.client.network
import io.netty.channel.ChannelPipeline
import io.netty.util.AttributeKey
import me.wargearsystems.viaaxiom.protocol.AxiomPayloadDirection
import org.slf4j.LoggerFactory
object AxiomNettyBridge {
private const val INBOUND_HANDLER_NAME = "viaaxiom:raw_axiom_inbound"
private const val OUTBOUND_HANDLER_NAME = "viaaxiom:raw_axiom_outbound"
private const val DECODER_HANDLER_NAME = "decoder"
private const val ENCODER_HANDLER_NAME = "encoder"
private val STATE = AttributeKey.valueOf<AxiomClientTranslationState>("viaaxiom:state")
private val logger = LoggerFactory.getLogger("ViaAxiom")
fun install(pipeline: ChannelPipeline) = install(pipeline) { AxiomClientTranslationState() }
fun install(pipeline: ChannelPipeline, stateFactory: () -> AxiomClientTranslationState) {
// Before login, Minecraft uses inbound_config/outbound_config instead of codecs.
// Position here so replacement with decoder/encoder retains the byte-level hook.
val inboundAnchor = if (pipeline.get(DECODER_HANDLER_NAME) != null) DECODER_HANDLER_NAME else "inbound_config"
val outboundAnchor = if (pipeline.get(ENCODER_HANDLER_NAME) != null) ENCODER_HANDLER_NAME else "outbound_config"
if (pipeline.get(inboundAnchor) == null || pipeline.get(outboundAnchor) == null) return
val state = pipeline.channel().attr(STATE).get() ?: stateFactory().also {
pipeline.channel().attr(STATE).set(it)
}
// Krypton adds decompression immediately before decoder, while ViaFabricPlus
// can move its own codec. Restore the native, uncompressed side of both codecs.
if (!immediatelyBefore(pipeline, INBOUND_HANDLER_NAME, inboundAnchor)) {
if (pipeline.get(INBOUND_HANDLER_NAME) != null) pipeline.remove(INBOUND_HANDLER_NAME)
pipeline.addBefore(inboundAnchor, INBOUND_HANDLER_NAME, RawAxiomInboundHandler(state))
}
if (!immediatelyBefore(pipeline, OUTBOUND_HANDLER_NAME, outboundAnchor)) {
if (pipeline.get(OUTBOUND_HANDLER_NAME) != null) pipeline.remove(OUTBOUND_HANDLER_NAME)
pipeline.addBefore(outboundAnchor, OUTBOUND_HANDLER_NAME, RawAxiomOutboundHandler(state))
}
}
fun protocolChanged(pipeline: ChannelPipeline, direction: AxiomPayloadDirection, play: Boolean) {
install(pipeline)
pipeline.channel().attr(STATE).get()?.protocolChanged(direction, play)
if (play) logger.info("Axiom {} play pipeline: {}", direction, pipeline.names().joinToString(" -> "))
}
private fun immediatelyBefore(pipeline: ChannelPipeline, handler: String, anchor: String): Boolean {
val names = pipeline.names()
val index = names.indexOf(handler)
return index >= 0 && index + 1 < names.size && names[index + 1] == anchor
}
}
@@ -0,0 +1,47 @@
package me.wargearsystems.viaaxiom.client.network
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import me.wargearsystems.viaaxiom.protocol.AxiomPayloadDirection
class RawAxiomInboundHandler(
private val state: AxiomClientTranslationState,
) : ChannelInboundHandlerAdapter() {
override fun userEventTriggered(context: ChannelHandlerContext, event: Any) {
super.userEventTriggered(context, event)
// Krypton fires a pipeline event after adding/removing its compression codecs.
if (event.javaClass.name == "me.steinborn.krypton.mod.shared.misc.KryptonPipelineEvent") {
context.executor().execute {
if (context.channel().isActive) AxiomNettyBridge.install(context.pipeline())
}
}
}
override fun channelRead(context: ChannelHandlerContext, message: Any) {
if (message is ByteBuf) {
val originalBytes = message.copyReadableBytes()
val rewrittenBytes = try {
state.receive(context, originalBytes)
} catch (failure: Exception) {
message.release()
context.fireExceptionCaught(failure)
return
}
if (!rewrittenBytes.contentEquals(originalBytes)) {
message.release()
super.channelRead(context, Unpooled.wrappedBuffer(rewrittenBytes))
return
}
}
super.channelRead(context, message)
}
private fun ByteBuf.copyReadableBytes(): ByteArray {
val bytes = ByteArray(readableBytes())
getBytes(readerIndex(), bytes)
return bytes
}
}
@@ -0,0 +1,76 @@
package me.wargearsystems.viaaxiom.client.network
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelPromise
import io.netty.channel.ChannelDuplexHandler
import java.nio.channels.ClosedChannelException
import me.wargearsystems.viaaxiom.protocol.AxiomCustomPayloadFrameCodec
class RawAxiomOutboundHandler(
private val state: AxiomClientTranslationState,
) : ChannelDuplexHandler() {
private val pendingFragments = mutableListOf<ChannelPromise>()
override fun write(context: ChannelHandlerContext, message: Any, promise: ChannelPromise) {
if (message is ByteBuf) {
val originalBytes = message.copyReadableBytes()
val rewrittenBytes = try {
state.send(originalBytes)
} catch (failure: Exception) {
message.release()
promise.tryFailure(failure)
failPending(failure)
context.fireExceptionCaught(failure)
return
}
if (rewrittenBytes == null) {
message.release()
pendingFragments += promise
return
}
// Only the final tunnel write owns the buffered fragment promises. Unrelated
// packets between fragments must not complete them prematurely.
val isTunnel = runCatching {
AxiomCustomPayloadFrameCodec.read(originalBytes).channel == "axiom:tunnel"
}.getOrDefault(false)
val outputPromise = if (isTunnel && pendingFragments.isNotEmpty()) {
val promises = pendingFragments.toList() + promise
pendingFragments.clear()
context.newPromise().also { combined ->
combined.addListener { future ->
promises.forEach { if (future.isSuccess) it.trySuccess() else it.tryFailure(future.cause()) }
}
}
} else promise
if (!rewrittenBytes.contentEquals(originalBytes)) {
message.release()
super.write(context, Unpooled.wrappedBuffer(rewrittenBytes), outputPromise)
return
}
}
super.write(context, message, promise)
}
override fun channelInactive(context: ChannelHandlerContext) {
failPending(ClosedChannelException())
super.channelInactive(context)
}
override fun handlerRemoved(context: ChannelHandlerContext) {
failPending(ClosedChannelException())
super.handlerRemoved(context)
}
private fun failPending(failure: Throwable) {
pendingFragments.forEach { it.tryFailure(failure) }
pendingFragments.clear()
}
private fun ByteBuf.copyReadableBytes(): ByteArray {
val bytes = ByteArray(readableBytes())
getBytes(readerIndex(), bytes)
return bytes
}
}
@@ -0,0 +1,62 @@
package me.wargearsystems.viaaxiom.client.network
import io.netty.channel.Channel
import me.wargearsystems.viaaxiom.protocol.AxiomLegacyBridge
import me.wargearsystems.viaaxiom.translation.*
import net.minecraft.SharedConstants
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.Blocks
import org.slf4j.LoggerFactory
/** Optional integration through the public ViaFabricPlus/ViaVersion interfaces. */
object ViaFabricPlusMappingProvider {
private val logger = LoggerFactory.getLogger("ViaAxiom")
fun createLegacyBridge(channel: Channel): AxiomLegacyBridge {
val nativeVersion = SharedConstants.getProtocolVersion()
val api = Class.forName("com.viaversion.viafabricplus.ViaFabricPlus").getMethod("api").invoke(null)
val translation = call("com.viaversion.viafabricplus.api.ViaFabricPlusAPI", api, "protocolTranslation")!!
val target = Class.forName("com.viaversion.viafabricplus.api.protocoltranslator.ProtocolTranslation")
.getMethod("targetVersion", Channel::class.java).invoke(translation, channel)
val serverVersion = call("com.viaversion.viaversion.api.protocol.version.ProtocolVersion", target, "getVersion") as Int
require(serverVersion >= 770) { "Legacy bridge currently requires Minecraft 1.21.5 or newer" }
val clientSize = Block.BLOCK_STATE_REGISTRY.size()
val stone = Block.getId(Blocks.STONE.defaultBlockState())
val steps = mutableListOf<IntArray>()
if (nativeVersion != serverVersion) {
val manager = Class.forName("com.viaversion.viaversion.api.Via").getMethod("getManager").invoke(null)
val protocols = call("com.viaversion.viaversion.api.ViaManager", manager, "getProtocolManager")!!
val managerClass = Class.forName("com.viaversion.viaversion.api.protocol.ProtocolManager")
val path = managerClass.getMethod("getProtocolPath", Int::class.javaPrimitiveType, Int::class.javaPrimitiveType)
.invoke(protocols, nativeVersion, serverVersion) as? List<*>
?: error("No ViaVersion mapping path from $nativeVersion to $serverVersion")
for (entry in path.asReversed()) {
val protocol = call("com.viaversion.viaversion.api.protocol.ProtocolPathEntry", entry!!, "protocol")!!
managerClass.getMethod("completeMappingDataLoading", Class::class.java).invoke(protocols, protocol.javaClass)
val data = call("com.viaversion.viaversion.api.protocol.Protocol", protocol, "getMappingData") ?: continue
val mappings = call("com.viaversion.viaversion.api.data.MappingData", data, "getBlockStateMappings") ?: continue
val size = call("com.viaversion.viaversion.api.data.Mappings", mappings, "size") as Int
require(size in 1..1_000_000) { "Invalid block registry mapping size" }
val getNewId = Class.forName("com.viaversion.viaversion.api.data.Mappings")
.getMethod("getNewId", Int::class.javaPrimitiveType)
steps += IntArray(size) { getNewId.invoke(mappings, it) as Int }
}
}
val (clientToServer, _) = BlockStateMappingChain.compose(steps, clientSize, stone)
val empty = Block.getId(Blocks.VOID_AIR.defaultBlockState())
require(clientToServer[empty] >= 0) { "Mapping chain cannot preserve Axiom's empty block state" }
var reportedMissing = false
val engine = BlockStateMappingChain.translationEngine(steps, clientSize, stone) { direction, id, fallback ->
if (!reportedMissing) {
reportedMissing = true
logger.warn("Axiom {} block state {} has no mapping; using stone placeholder {}", direction, id, fallback)
}
}
logger.info("Legacy Axiom bridge mappings ready: protocol {} -> {}, block registries {} -> {}",
nativeVersion, serverVersion, clientSize, steps.firstOrNull()?.size ?: clientSize)
return AxiomLegacyBridge(serverVersion, engine)
}
private fun call(type: String, receiver: Any, method: String): Any? =
Class.forName(type).getMethod(method).invoke(receiver)
}
@@ -0,0 +1,15 @@
{
"required": true,
"minVersion": "0.8",
"package": "me.wargearsystems.viaaxiom.mixin.client",
"compatibilityLevel": "JAVA_25",
"client": [
"ClientConnectionMixin"
],
"injectors": {
"defaultRequire": 1
},
"overwrites": {
"requireAnnotations": true
}
}
+20
View File
@@ -0,0 +1,20 @@
{
"schemaVersion": 1,
"id": "viaaxiom",
"version": "${version}",
"name": "ViaAxiom",
"description": "Translates Axiom traffic between client and server versions",
"authors": ["Jakob Schulz"],
"license": "MIT",
"environment": "client",
"mixins": [
"viaaxiom.client.mixins.json"
],
"depends": {
"fabricloader": ">=${loader_version}",
"fabric-language-kotlin": ">=${kotlin_loader_version}",
"fabric-api": "*",
"minecraft": "${minecraft_version}",
"java": ">=25"
}
}
@@ -0,0 +1,154 @@
package me.wargearsystems.viaaxiom.client.network
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelInboundHandlerAdapter
import io.netty.channel.ChannelOutboundHandlerAdapter
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.embedded.EmbeddedChannel
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
import me.wargearsystems.viaaxiom.protocol.*
import me.wargearsystems.viaaxiom.translation.*
import java.util.concurrent.TimeUnit
import kotlin.test.*
class AxiomNettyBridgeTest {
@Test fun `compression insertion and ViaFabricPlus reorder retain uncompressed native payload hook`() {
val channel = EmbeddedChannel()
channel.pipeline().addLast("decoder", ChannelInboundHandlerAdapter())
channel.pipeline().addLast("encoder", ChannelOutboundHandlerAdapter())
val (temporaryChannel, state) = channel()
temporaryChannel.finishAndReleaseAll()
AxiomNettyBridge.install(channel.pipeline()) { state }
// Model Krypton's insertion after ViaAxiom was installed at channelActive.
channel.pipeline().addBefore("decoder", "decompress", object : ChannelInboundHandlerAdapter() {
override fun channelRead(context: ChannelHandlerContext, message: Any) {
val input = message as ByteBuf
assertEquals(77, input.readUnsignedByte().toInt())
context.fireChannelRead(input)
}
})
channel.pipeline().addBefore("decoder", "via-decoder", ChannelInboundHandlerAdapter())
channel.pipeline().addBefore("encoder", "compress", ChannelOutboundHandlerAdapter())
channel.pipeline().addBefore("encoder", "via-encoder", ChannelOutboundHandlerAdapter())
AxiomNettyBridge.protocolChanged(channel.pipeline(), AxiomPayloadDirection.CLIENTBOUND, true)
AxiomNettyBridge.protocolChanged(channel.pipeline(), AxiomPayloadDirection.SERVERBOUND, true)
val names = channel.pipeline().names()
assertTrue(names.indexOf("decompress") < names.indexOf("viaaxiom:raw_axiom_inbound"))
assertTrue(names.indexOf("via-decoder") < names.indexOf("viaaxiom:raw_axiom_inbound"))
assertEquals(names.indexOf("encoder") - 1, names.indexOf("viaaxiom:raw_axiom_outbound"))
val compressed = Unpooled.buffer().writeByte(77).writeBytes(AxiomCustomPayloadFrameCodec.write(registration()))
channel.writeInbound(compressed)
assertEquals("minecraft:register", frame(channel.readInbound()).channel)
channel.advanceTimeBy(600, TimeUnit.MILLISECONDS)
channel.runScheduledPendingTasks()
assertEquals("axiom:hello", frame(assertNotNull(channel.readInbound<ByteBuf>())).channel)
channel.finishAndReleaseAll()
}
@Test fun `hooks are installed before initial configuration handlers and survive replacement`() {
val channel = EmbeddedChannel()
channel.pipeline().addLast("inbound_config", ChannelInboundHandlerAdapter())
channel.pipeline().addLast("outbound_config", ChannelOutboundHandlerAdapter())
AxiomNettyBridge.install(channel.pipeline())
val names = channel.pipeline().names()
assertTrue(names.indexOf("viaaxiom:raw_axiom_inbound") < names.indexOf("inbound_config"))
assertTrue(names.indexOf("viaaxiom:raw_axiom_outbound") < names.indexOf("outbound_config"))
channel.pipeline().replace("inbound_config", "decoder", ChannelInboundHandlerAdapter())
channel.pipeline().replace("outbound_config", "encoder", ChannelOutboundHandlerAdapter())
AxiomNettyBridge.install(channel.pipeline())
assertEquals(1, channel.pipeline().names().count { it == "viaaxiom:raw_axiom_inbound" })
channel.finishAndReleaseAll()
}
@Test fun `legacy registration produces challenge and rewrites real outbound hello`() {
val (channel, _) = channel()
register(channel)
val challenge = frame(assertNotNull(channel.readInbound<ByteBuf>()))
assertEquals("axiom:hello", challenge.channel)
channel.writeOutbound(buffer(AxiomCustomPayloadFrame(20, "axiom:hello", AxiomHelloCodec.write(AxiomHello(10, 5000, 776, 42)))))
val outgoing = frame(assertNotNull(channel.readOutbound<ByteBuf>()))
assertEquals(AxiomHello(9, 5000, 771), AxiomHelloCodec.read(outgoing.payloadBytes))
channel.finishAndReleaseAll()
}
@Test fun `fragment promises wait for combined write and unrelated writes do not complete them`() {
val (channel, _) = channel()
negotiate(channel)
val body = ByteArray(1000)
val fragments = AxiomTunnelCodec.encode(AxiomTunnelPacket("axiom:set_buffer", body), splitSize = 128)
val promises = fragments.dropLast(1).map { fragment ->
channel.newPromise().also { channel.pipeline().write(buffer(AxiomCustomPayloadFrame(20, "axiom:tunnel", fragment)), it) }
}
assertTrue(promises.none { it.isDone })
channel.writeOutbound(Unpooled.wrappedBuffer(byteArrayOf(0)))
assertTrue(promises.none { it.isDone })
assertContentEquals(byteArrayOf(0), bytes(channel.readOutbound()))
channel.writeOutbound(buffer(AxiomCustomPayloadFrame(20, "axiom:tunnel", fragments.last())))
assertTrue(promises.all { it.isSuccess })
val output = frame(channel.readOutbound())
assertEquals("axiom:set_buffer", output.channel)
assertContentEquals(body, output.payloadBytes)
channel.finishAndReleaseAll()
}
@Test fun `disconnect fails pending writes and releases buffered ByteBufs`() {
val (channel, _) = channel()
negotiate(channel)
val fragments = AxiomTunnelCodec.encode(AxiomTunnelPacket("axiom:set_buffer", ByteArray(500)), splitSize = 128)
val input = buffer(AxiomCustomPayloadFrame(20, "axiom:tunnel", fragments.first()))
val promise = channel.newPromise()
channel.pipeline().write(input, promise)
assertEquals(0, input.refCnt())
assertFalse(promise.isDone)
channel.close()
assertTrue(promise.isDone)
assertFalse(promise.isSuccess)
channel.finishAndReleaseAll()
}
@Test fun `configuration phase registrations cannot start play handshake and stale callbacks are cancelled`() {
val (channel, state) = channel()
state.protocolChanged(AxiomPayloadDirection.CLIENTBOUND, false)
register(channel)
assertNull(channel.readInbound<ByteBuf>())
state.protocolChanged(AxiomPayloadDirection.CLIENTBOUND, true)
channel.writeInbound(buffer(registration()))
bytes(channel.readInbound())
state.protocolChanged(AxiomPayloadDirection.CLIENTBOUND, false)
channel.advanceTimeBy(600, TimeUnit.MILLISECONDS)
channel.runScheduledPendingTasks()
assertNull(channel.readInbound<ByteBuf>())
channel.finishAndReleaseAll()
}
private fun channel(): Pair<EmbeddedChannel, AxiomClientTranslationState> {
val state = AxiomClientTranslationState {
AxiomLegacyBridge(771, object : AxiomPayloadTranslator {
override fun rewrite(payload: AxiomPayload, session: AxiomTranslationSession) = payload.bytes
}) { 42 }
}
state.protocolChanged(AxiomPayloadDirection.CLIENTBOUND, true)
state.protocolChanged(AxiomPayloadDirection.SERVERBOUND, true)
return EmbeddedChannel(RawAxiomInboundHandler(state), RawAxiomOutboundHandler(state)) to state
}
private fun registration() = AxiomCustomPayloadFrame(24, "minecraft:register", "axiom:hello\u0000axiom:set_buffer".toByteArray())
private fun register(channel: EmbeddedChannel) {
channel.writeInbound(buffer(registration()))
bytes(channel.readInbound())
channel.advanceTimeBy(600, TimeUnit.MILLISECONDS)
channel.runScheduledPendingTasks()
}
private fun negotiate(channel: EmbeddedChannel) {
register(channel)
bytes(channel.readInbound())
channel.writeOutbound(buffer(AxiomCustomPayloadFrame(20, "axiom:hello", AxiomHelloCodec.write(AxiomHello(10, 5000, 776, 42)))))
bytes(channel.readOutbound())
channel.writeInbound(buffer(AxiomCustomPayloadFrame(24, "axiom:enable", AxiomEnableCodec.write(AxiomEnable(true, 1_048_576, 2, 0, 0)))))
bytes(channel.readInbound())
}
private fun buffer(frame: AxiomCustomPayloadFrame) = Unpooled.wrappedBuffer(AxiomCustomPayloadFrameCodec.write(frame))
private fun frame(buffer: ByteBuf) = AxiomCustomPayloadFrameCodec.read(bytes(buffer))
private fun bytes(buffer: ByteBuf): ByteArray = ByteArray(buffer.readableBytes()).also { buffer.readBytes(it); buffer.release() }
}
+8 -23
View File
@@ -1,23 +1,8 @@
#
# This file is a part of the SteamWar software.
#
# Copyright (C) 2025 SteamWar.de-Serverteam
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
org.gradle.daemon = true
org.gradle.parallel = true
org.gradle.workers.max = 16
org.gradle.jvmargs = -Xmx4096m
org.gradle.jvmargs=-Xmx1G
minecraft_version=26.2
loader_version=0.19.5
kotlin_loader_version=1.13.12+kotlin.2.4.0
mod_version=1.0.0
maven_group=me.wargearsystems
archives_base_name=viaaxiom
fabric_version=0.161.0+26.2
Binary file not shown.
+1 -25
View File
@@ -1,25 +1 @@
#
# This file is a part of the SteamWar software.
#
# Copyright (C) 2025 SteamWar.de-Serverteam
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
#Sun Aug 04 18:22:15 CEST 2024
distributionBase = GRADLE_USER_HOME
distributionPath = wrapper/dists
distributionUrl = https\://services.gradle.org/distributions/gradle-8.14-bin.zip
zipStoreBase = GRADLE_USER_HOME
zipStorePath = wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-bin.zip
Vendored
+18 -7
View File
@@ -55,7 +55,7 @@
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
@@ -80,13 +80,10 @@ do
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@@ -143,12 +140,16 @@ fi
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
@@ -193,6 +194,10 @@ if "$cygwin" || "$msys" ; then
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
@@ -205,6 +210,12 @@ set -- \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
Vendored
+7 -4
View File
@@ -26,6 +26,7 @@ if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@@ -40,7 +41,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
@@ -75,13 +76,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
+11 -106
View File
@@ -1,115 +1,20 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2025 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import org.apache.tools.ant.taskdefs.condition.Os
import java.net.URI
import java.util.*
pluginManagement {
plugins {
kotlin("plugin.lombok") version "2.3.20"
}
}
rootProject.name = "ViaAxiom"
private val isInCi by lazy { Os.isFamily(Os.FAMILY_UNIX) && ProcessBuilder("hostname").start().inputStream.bufferedReader().readText().startsWith("steamwar.de") }
dependencyResolutionManagement {
repositories {
maven {
url = URI("https://m2.dv8tion.net/releases")
content {
includeGroup("net.dv8tion")
maven("https://maven.fabricmc.net/") {
name = "Fabric"
}
gradlePluginPortal()
}
}
maven {
url = URI("https://maven.enginehub.org/repo")
content {
includeGroup("com.sk89q.worldedit")
includeGroup("com.sk89q.worldedit.worldedit-libs")
}
}
rootProject.name = "viaaxiom"
maven {
if (isInCi) {
url = URI("file:///var/www/maven/")
} else {
url = URI("https://maven.steamwar.de/")
credentials {
val swProps = Properties()
swProps.load(rootDir.resolve("steamwar.properties").inputStream())
include("core", "velocity")
username = swProps.getProperty("maven.username")
password = swProps.getProperty("maven.password")
}
}
val tasks = gradle.startParameter.taskNames
val proxyOnly = tasks.isNotEmpty() && tasks.all { it.startsWith(":velocity:") || it.startsWith(":core:") }
content {
includeGroup("de.steamwar")
}
}
maven {
url = URI("https://repo.codemc.io/repository/maven-snapshots/")
content {
includeGroup("net.wesjd")
}
}
maven {
url = URI("https://libraries.minecraft.net")
content {
includeGroup("com.mojang")
}
}
maven {
url = URI("https://repo.viaversion.com")
content {
includeGroup("com.viaversion")
}
}
maven {
url = URI("https://repo.papermc.io/repository/maven-public/")
content {
includeGroup("org.bukkit")
includeGroup("org.spigotmc")
includeGroup("io.papermc.paper")
includeGroup("com.velocitypowered")
includeGroup("net.md-5")
}
}
mavenCentral()
}
versionCatalogs {
create("libs") {
plugin("shadow", "com.github.johnrengelman.shadow").version("8.1.1")
library("lombok", "org.projectlombok:lombok:1.18.32")
library("axiom", "de.steamwar:axiompaper:RELEASE")
library("velocity", "de.steamwar:velocity:RELEASE")
library("velocityapi", "com.velocitypowered:velocity-api:3.5.0-SNAPSHOT")
library("viaapi", "com.viaversion:viaversion-api:4.3.1")
library("viavelocity", "com.viaversion:viaversion-velocity:4.3.1")
}
}
// Minecraft 26.2 needs Java 25, and Loom sets it up during configuration.
if (JavaVersion.current() >= JavaVersion.VERSION_25 && !proxyOnly) {
include("fabric")
}
View File
+1 -34
View File
@@ -2,37 +2,4 @@ build:
- "./gradlew build --no-daemon"
artifacts:
"/jars/BauSystem.jar": "BauSystem/build/libs/BauSystem-all.jar"
"/jars/BauSystem-1.12.jar": "LegacyBauSystem/build/libs/LegacyBauSystem.jar"
"/jars/FightSystem.jar": "FightSystem/build/libs/FightSystem-all.jar"
#"/binarys/FightSystem_Standalone.jar": "FightSystem/FightSystem_Standalone/build/libs/FightSystem_Standalone-all.jar"
"/jars/KotlinCore.jar": "KotlinCore/build/libs/KotlinCore-all.jar"
"/jars/TNTLeague.jar": "TNTLeague/build/libs/TNTLeague.jar"
"/jars/LobbySystem.jar": "LobbySystem/build/libs/LobbySystem.jar"
"/jars/MissileWars.jar": "MissileWars/build/libs/MissileWars.jar"
"/jars/RealTime.jar": "Realtime/build/libs/Realtime.jar"
"/jars/SchematicSystem.jar": "SchematicSystem/build/libs/SchematicSystem-all.jar"
"/jars/SpigotCore.jar": "SpigotCore/build/libs/SpigotCore-all.jar"
"/jars/Builder.jar": "Teamserver/build/libs/Teamserver.jar"
"/jars/TowerRun.jar": "TowerRun/build/libs/TowerRun.jar"
"/jars/PersistentVelocityCore.jar": "VelocityCore/Persistent/build/libs/Persistent.jar"
"/jars/DependenciesVelocityCore.jar": "VelocityCore/Dependencies/build/libs/Dependencies-all.jar"
"/jars/VelocityCore.jar": "VelocityCore/build/libs/VelocityCore-all.jar"
"/usr/local/bin/deployarena.py": "VelocityCore/deployarena.py"
"/jars/website-api.jar": "WebsiteBackend/build/libs/WebsiteBackend-all.jar"
release:
- "rm -rf /jars/sw"
- "unzip -o CLI/build/distributions/sw.zip -d /jars"
- "sudo systemctl restart api.service"
"/jars/viaaxiom/ViaAxiom.jar": "velocity/build/libs/viaaxiom-velocity-1.0.0.jar"
+74
View File
@@ -0,0 +1,74 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm")
id("com.gradleup.shadow")
}
base {
archivesName.set("viaaxiom-velocity")
}
val targetJavaVersion = 21
repositories {
mavenCentral()
maven("https://repo.papermc.io/repository/maven-public/")
maven("https://repo.viaversion.com/")
}
dependencies {
implementation(project(":core"))
implementation(kotlin("stdlib"))
compileOnly("com.velocitypowered:velocity-api:3.4.0")
compileOnly("com.viaversion:viaversion-api:5.12.2")
// Velocity's API does not expose Netty; the proxy supplies it at runtime.
compileOnly("io.netty:netty-all:4.2.19.Final")
testImplementation(kotlin("test"))
testImplementation("com.velocitypowered:velocity-api:3.4.0")
testImplementation("io.netty:netty-all:4.2.19.Final")
}
tasks.processResources {
inputs.property("version", project.version)
filteringCharset = "UTF-8"
filesMatching("velocity-plugin.json") {
expand("version" to project.version)
}
}
tasks.withType<KotlinCompile>().configureEach {
compilerOptions {
jvmTarget.set(JvmTarget.fromTarget(targetJavaVersion.toString()))
freeCompilerArgs.add("-Xjdk-release=$targetJavaVersion")
}
}
tasks.withType<JavaCompile>().configureEach {
options.release.set(targetJavaVersion)
}
tasks.test {
useJUnitPlatform()
}
tasks.shadowJar {
archiveClassifier.set("")
// Zstd cannot be relocated, its JNI symbols are bound to the package name.
relocate("kotlin", "me.wargearsystems.viaaxiom.shaded.kotlin")
exclude("aix/**", "darwin/**", "freebsd/**", "win/x86/**", "win/aarch64/**")
exclude("linux/arm/**", "linux/i386/**", "linux/loongarch64/**", "linux/mips64/**", "linux/ppc64/**",
"linux/ppc64le/**", "linux/riscv64/**", "linux/s390x/**")
from(rootProject.file("LICENSE.txt"), rootProject.file("NOTICE.txt"))
}
tasks.jar {
archiveClassifier.set("thin")
}
tasks.assemble {
dependsOn(tasks.shadowJar)
}
@@ -0,0 +1,163 @@
package me.wargearsystems.viaaxiom.velocity
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import io.netty.util.ReferenceCountUtil
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
import me.wargearsystems.viaaxiom.protocol.AxiomCustomPayloadFrame
import me.wargearsystems.viaaxiom.protocol.AxiomProtocol
import me.wargearsystems.viaaxiom.protocol.AxiomProxySession
import org.slf4j.Logger
import java.util.concurrent.TimeUnit
/** Outlives server switches. Client and backend channels share the player's event loop. */
internal class PlayerAxiomState {
@Volatile
var session: AxiomProxySession? = null
}
/** Drops frames it cannot translate, their IDs would select the wrong blocks. */
internal class AxiomServerboundHandler(
private val state: PlayerAxiomState,
private val messages: PluginMessages,
private val logger: Logger,
) : ChannelInboundHandlerAdapter() {
override fun channelRead(context: ChannelHandlerContext, packet: Any) {
val session = state.session
if (session == null || !messages.isPluginMessage(packet) || !AxiomProtocol.isAxiomChannel(messages.channel(packet))) {
context.fireChannelRead(packet)
return
}
val frame = AxiomCustomPayloadFrame(0, messages.channel(packet), messages.bytes(packet))
ReferenceCountUtil.release(packet)
val output = try {
session.serverbound(frame)
} catch (failure: RuntimeException) {
logger.warn("Dropped serverbound {}: {}", frame.channel, failure.message)
return
}
output.forEach { context.fireChannelRead(messages.create(it.channel, it.payloadBytes)) }
}
}
/**
* Added when the backend channel is created. Packets decoded together with JoinGame pass before
* ServerConnectedEvent runs, so registrations are recorded and Axiom packets held until [attach].
*/
internal class AxiomClientboundHandler(
private val messages: PluginMessages,
private val logger: Logger,
) : ChannelInboundHandlerAdapter() {
private class Attachment(
val session: AxiomProxySession,
val state: PlayerAxiomState,
val sendToClient: (channel: String, bytes: ByteArray) -> Unit,
)
private lateinit var context: ChannelHandlerContext
private var waiting = true
private var attachment: Attachment? = null
private val registrations = mutableListOf<ByteArray>()
private val held = mutableListOf<Any>()
private var legacyHandshakeScheduled = false
override fun handlerAdded(context: ChannelHandlerContext) {
this.context = context
}
fun attach(session: AxiomProxySession, state: PlayerAxiomState, sendToClient: (String, ByteArray) -> Unit) {
context.executor().execute {
attachment = Attachment(session, state, sendToClient)
release()
}
}
fun detach() {
context.executor().execute(::release)
}
private fun release() {
waiting = false
registrations.forEach(::registered)
registrations.clear()
val packets = held.toList()
held.clear()
packets.forEach { channelRead(context, it) }
}
override fun channelRead(context: ChannelHandlerContext, packet: Any) {
if (!messages.isPluginMessage(packet)) {
context.fireChannelRead(packet)
return
}
val channel = messages.channel(packet)
if (channel == "minecraft:register") {
if (waiting) registrations += messages.bytes(packet) else registered(messages.bytes(packet))
context.fireChannelRead(packet)
} else if (!AxiomProtocol.isAxiomChannel(channel)) {
context.fireChannelRead(packet)
} else if (waiting && held.size < MAX_HELD_PACKETS) {
held += packet
} else {
translate(context, channel, packet)
}
}
private fun translate(context: ChannelHandlerContext, channel: String, packet: Any) {
val attachment = attachment
if (attachment == null) {
context.fireChannelRead(packet)
return
}
val frame = AxiomCustomPayloadFrame(0, channel, messages.bytes(packet))
ReferenceCountUtil.release(packet)
val output = try {
attachment.session.clientbound(frame)
} catch (failure: RuntimeException) {
logger.warn("Dropped clientbound {}: {}", channel, failure.message)
if (channel == "axiom:enable") {
attachment.sendToClient("axiom:goodbye", AxiomByteWriter().writeUtf("ViaAxiom: ${failure.message}").toByteArray())
}
return
}
context.fireChannelRead(messages.create(output.channel, output.payloadBytes))
}
private fun registered(bytes: ByteArray) {
val attachment = attachment ?: return
val session = attachment.session
try {
session.backendRegistered(bytes)
} catch (failure: IllegalArgumentException) {
logger.warn("Ignored backend channel registration: {}", failure.message)
return
}
if (legacyHandshakeScheduled || !session.awaitingLegacyChallenge) return
legacyHandshakeScheduled = true
// Backends may register across several packets, and axiom:tunnel marks them as API 10.
context.executor().schedule({
if (context.channel().isActive && attachment.state.session === session) {
session.startLegacyHandshake()?.let { attachment.sendToClient(it.channel, it.payloadBytes) }
}
}, LEGACY_HANDSHAKE_DELAY_MILLIS, TimeUnit.MILLISECONDS)
}
override fun channelInactive(context: ChannelHandlerContext) {
releaseHeld()
super.channelInactive(context)
}
override fun handlerRemoved(context: ChannelHandlerContext) {
releaseHeld()
}
private fun releaseHeld() {
held.forEach(ReferenceCountUtil::release)
held.clear()
}
private companion object {
const val LEGACY_HANDSHAKE_DELAY_MILLIS = 500L
const val MAX_HELD_PACKETS = 256
}
}
@@ -0,0 +1,69 @@
package me.wargearsystems.viaaxiom.velocity
import com.velocitypowered.api.proxy.Player
import com.velocitypowered.api.proxy.ProxyServer
import io.netty.buffer.ByteBuf
import io.netty.buffer.ByteBufHolder
import io.netty.buffer.ByteBufUtil
import io.netty.buffer.Unpooled
import io.netty.channel.Channel
import io.netty.channel.ChannelInitializer
/** Velocity's API exposes neither channels nor packets, and its proxy module is not published. */
internal object VelocityConnections {
const val MINECRAFT_DECODER = "minecraft-decoder"
fun clientChannel(player: Player): Channel = channelOf(call(player, "getConnection"))
/** The backend named by a ServerConnectedEvent stays in flight until the event completes. */
fun incomingBackendChannel(player: Player): Channel {
val connection = requireNotNull(call(player, "getConnectionInFlight")) { "No backend connection in flight" }
return channelOf(requireNotNull(call(connection, "getConnection")) { "Backend connection closed" })
}
fun onBackendChannel(proxy: ProxyServer, configure: (Channel) -> Unit) {
val connectionManager = proxy.javaClass.getDeclaredField("cm").apply { isAccessible = true }.get(proxy)
val holder = requireNotNull(call(connectionManager, "getBackendChannelInitializer"))
@Suppress("UNCHECKED_CAST")
val original = requireNotNull(call(holder, "get")) as ChannelInitializer<Channel>
holder.javaClass.getMethod("set", ChannelInitializer::class.java).invoke(holder, WrappingInitializer(original, configure))
}
private class WrappingInitializer(
private val original: ChannelInitializer<Channel>,
private val configure: (Channel) -> Unit,
) : ChannelInitializer<Channel>() {
override fun initChannel(channel: Channel) {
INIT_CHANNEL.invoke(original, channel)
configure(channel)
}
// Velocity reuses one initializer for every backend connection.
override fun isSharable() = true
}
private val INIT_CHANNEL = ChannelInitializer::class.java.getDeclaredMethod("initChannel", Channel::class.java)
.apply { isAccessible = true }
private fun channelOf(connection: Any?): Channel = call(requireNotNull(connection), "getChannel") as Channel
private fun call(receiver: Any, method: String): Any? = receiver.javaClass.getMethod(method).invoke(receiver)
}
internal interface PluginMessages {
fun isPluginMessage(packet: Any): Boolean
fun channel(packet: Any): String
fun bytes(packet: Any): ByteArray
fun create(channel: String, bytes: ByteArray): Any
}
internal class VelocityPluginMessages : PluginMessages {
private val type = Class.forName("com.velocitypowered.proxy.protocol.packet.PluginMessagePacket")
private val getChannel = type.getMethod("getChannel")
private val constructor = type.getConstructor(String::class.java, ByteBuf::class.java)
override fun isPluginMessage(packet: Any) = type.isInstance(packet)
override fun channel(packet: Any) = getChannel.invoke(packet) as String
override fun bytes(packet: Any): ByteArray = ByteBufUtil.getBytes((packet as ByteBufHolder).content())
override fun create(channel: String, bytes: ByteArray): Any = constructor.newInstance(channel, Unpooled.wrappedBuffer(bytes))
}
@@ -0,0 +1,77 @@
package me.wargearsystems.viaaxiom.velocity
import com.google.inject.Inject
import com.velocitypowered.api.event.Subscribe
import com.velocitypowered.api.event.player.ServerConnectedEvent
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent
import com.velocitypowered.api.proxy.Player
import com.velocitypowered.api.proxy.ProxyServer
import com.velocitypowered.api.proxy.messages.MinecraftChannelIdentifier
import com.viaversion.viaversion.api.Via
import io.netty.channel.Channel
import io.netty.util.AttributeKey
import me.wargearsystems.viaaxiom.protocol.AxiomProxySession
import org.slf4j.Logger
class ViaAxiomPlugin @Inject constructor(private val proxy: ProxyServer, private val logger: Logger) {
private val mappings = ViaBlockMappings(logger)
private val messages = VelocityPluginMessages()
@Subscribe
fun onProxyInitialize(event: ProxyInitializeEvent) {
VelocityConnections.onBackendChannel(proxy) { channel ->
channel.pipeline().addAfter(VelocityConnections.MINECRAFT_DECODER, HANDLER_NAME, AxiomClientboundHandler(messages, logger))
}
}
/** Not on the event loop, so building mappings cannot stall players. */
@Subscribe
fun onServerConnected(event: ServerConnectedEvent) {
val player = event.player
val serverName = event.server.serverInfo.name
var backend: AxiomClientboundHandler? = null
try {
backend = VelocityConnections.incomingBackendChannel(player).pipeline().get(HANDLER_NAME) as AxiomClientboundHandler
val clientChannel = VelocityConnections.clientChannel(player)
val state = clientChannel.attr(STATE).setIfAbsent(PlayerAxiomState()) ?: clientChannel.attr(STATE).get()
state.session = null
val clientProtocol = player.protocolVersion.protocol
val serverProtocol = Via.proxyPlatform().protocolDetectorService().serverProtocolVersion(serverName).version
if (minOf(clientProtocol, serverProtocol) < MINIMUM_PROTOCOL) {
logger.info("Not translating Axiom for {} on {}: protocols {} -> {} are below {}. " +
"If the backend version is wrong, set it under velocity-servers in ViaVersion's config.",
player.username, serverName, clientProtocol, serverProtocol, MINIMUM_PROTOCOL)
backend.detach()
return
}
val session = AxiomProxySession(clientProtocol, serverProtocol, mappings.engine(clientProtocol, serverProtocol))
installServerbound(clientChannel, state)
state.session = session
backend.attach(session, state) { channel, bytes -> sendToClient(player, channel, bytes) }
logger.debug("Axiom session for {} on {}: protocol {} -> {}", player.username, serverName, clientProtocol, serverProtocol)
} catch (failure: Exception) {
logger.warn("Axiom translation unavailable for {} on {}: {}", player.username, serverName, failure.toString())
backend?.detach()
}
}
private fun sendToClient(player: Player, channel: String, bytes: ByteArray) {
player.sendPluginMessage(MinecraftChannelIdentifier.from(channel), bytes)
}
private fun installServerbound(channel: Channel, state: PlayerAxiomState) {
val pipeline = channel.pipeline()
if (pipeline.get(HANDLER_NAME) == null) {
pipeline.addAfter(VelocityConnections.MINECRAFT_DECODER, HANDLER_NAME, AxiomServerboundHandler(state, messages, logger))
}
}
private companion object {
/** Minecraft 1.21.5. The older palette format is not verified. */
const val MINIMUM_PROTOCOL = 770
const val HANDLER_NAME = "viaaxiom"
val STATE: AttributeKey<PlayerAxiomState> = AttributeKey.valueOf("viaaxiom:state")
}
}
@@ -0,0 +1,49 @@
package me.wargearsystems.viaaxiom.velocity
import com.viaversion.viaversion.api.Via
import me.wargearsystems.viaaxiom.translation.AxiomTranslationEngine
import me.wargearsystems.viaaxiom.translation.BlockStateMappingChain
import me.wargearsystems.viaaxiom.translation.IdentityBlockStateIdTranslator
import org.slf4j.Logger
import java.util.concurrent.ConcurrentHashMap
internal class ViaBlockMappings(private val logger: Logger) {
private val engines = ConcurrentHashMap<Pair<Int, Int>, AxiomTranslationEngine>()
fun engine(clientProtocol: Int, serverProtocol: Int): AxiomTranslationEngine =
engines.computeIfAbsent(clientProtocol to serverProtocol) { build(clientProtocol, serverProtocol) }
private fun build(clientProtocol: Int, serverProtocol: Int): AxiomTranslationEngine {
if (clientProtocol == serverProtocol) return AxiomTranslationEngine(IdentityBlockStateIdTranslator)
val protocols = Via.getManager().protocolManager
val path = protocols.getProtocolPath(clientProtocol, serverProtocol)
?: error("No ViaVersion path from protocol $clientProtocol to $serverProtocol. Is ViaBackwards installed?")
val steps = mutableListOf<IntArray>()
var clientRegistrySize = 0
for (entry in path.asReversed()) {
protocols.completeMappingDataLoading(entry.protocol().javaClass)
val mappings = entry.protocol().mappingData?.blockStateMappings ?: continue
steps += IntArray(mappings.size()) { mappings.getNewId(it) }
clientRegistrySize = mappings.mappedSize()
}
// Without block changes the registries match, and both sides use the 1.21.5 palette format.
if (steps.isEmpty()) return AxiomTranslationEngine(IdentityBlockStateIdTranslator)
var reportedMissing = false
val engine = BlockStateMappingChain.translationEngine(steps, clientRegistrySize, STONE_STATE_ID) { direction, id, fallback ->
if (!reportedMissing) {
reportedMissing = true
logger.warn("Axiom {} block state {} has no mapping; using stone placeholder {}", direction, id, fallback)
}
}
logger.info("Axiom mappings ready: protocol {} -> {}, block registries {} -> {}",
clientProtocol, serverProtocol, clientRegistrySize, steps.first().size)
return engine
}
private companion object {
/** The ID of minecraft:stone in every version since 1.13. */
const val STONE_STATE_ID = 1
}
}
@@ -0,0 +1,12 @@
{
"id": "viaaxiom",
"name": "ViaAxiom",
"version": "${version}",
"description": "Translates Axiom traffic between client and backend versions",
"authors": ["Jakob Schulz"],
"main": "me.wargearsystems.viaaxiom.velocity.ViaAxiomPlugin",
"dependencies": [
{ "id": "viaversion", "optional": false },
{ "id": "viabackwards", "optional": true }
]
}