├── pages ├── CNAME └── _config.yml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .idea ├── copyright │ ├── profiles_settings.xml │ └── protocol-gen.xml ├── codeStyles │ ├── codeStyleConfig.xml │ └── Project.xml └── inspectionProfiles │ ├── profiles_settings.xml │ └── protocol-gen.xml ├── .editorconfig ├── renovate.json ├── license.txt ├── .gitattributes ├── license_header.txt ├── settings.gradle.kts ├── .gitignore ├── gradle.properties ├── src └── main │ ├── resources │ └── logback.xml │ └── java │ └── dev │ └── derklaro │ └── protocolgenerator │ ├── downloader │ ├── FileDownloadValidator.java │ ├── Sha1DownloadValidator.java │ └── FileDownloader.java │ ├── protocol │ ├── McPacketFlow.java │ ├── McClassNames.java │ ├── McInit.java │ ├── PacketClassFieldScanner.java │ ├── McProtocolStates.java │ ├── PacketClassInfo.java │ ├── PacketVisitorImplGenerator.java │ ├── ProtocolInfoCollector.java │ └── McProtocolsDecoder.java │ ├── manifest │ ├── McManifestVersionType.java │ ├── McVersionDumper.java │ ├── McManifestVersion.java │ ├── McManifestVersionData.java │ └── McManifestVersionFetcher.java │ ├── util │ └── CatchingFunction.java │ ├── jackson │ └── JacksonSupport.java │ ├── cli │ └── CliArgParser.java │ ├── http │ ├── HttpClientProvider.java │ └── BodyParser.java │ ├── markdown │ ├── MarkdownFormatter.java │ └── MarkdownGenerator.java │ ├── gameversion │ ├── JarGameVersionParser.java │ └── GameVersion.java │ ├── GeneratorCLIArguments.java │ ├── library │ └── McLibraryLoader.java │ ├── reflect │ └── TypeHelper.java │ └── GeneratorEntrypoint.java ├── .github ├── workflows │ └── generate.yml └── readme.md ├── gradlew.bat ├── gradlew └── checkstyle.xml /pages/CNAME: -------------------------------------------------------------------------------- 1 | protocol.derklaro.dev 2 | -------------------------------------------------------------------------------- /pages/_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-hacker 2 | markdown: GFM 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/derklaro/mc-protocol/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 7 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: https://editorconfig.org/ 2 | 3 | # top-most EditorConfig file 4 | root = true 5 | 6 | # Unix-style newlines with a newline ending every file 7 | [*] 8 | charset = utf-8 9 | end_of_line = lf 10 | indent_size = 2 11 | indent_style = space 12 | max_line_length = 120 13 | insert_final_newline = true -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "config:base", 4 | ":rebaseStalePrs" 5 | ], 6 | "labels": [ 7 | "t: dependencies" 8 | ], 9 | "packageRules": [ 10 | { 11 | "description": "Correct Guava version handling", 12 | "matchPackagePrefixes": [ 13 | "com.google.guava:" 14 | ], 15 | "versioning": "regex:^(?\\d+)(\\.(?\\d+))?(\\.(?\\d+))?(-(?.*))?$" 16 | } 17 | ], 18 | "vulnerabilityAlerts": { 19 | "addLabels": [ 20 | "t: security" 21 | ], 22 | "assignees": [ 23 | "@derklaro" 24 | ] 25 | }, 26 | "timezone": "Europe/Berlin", 27 | "schedule": [ 28 | "before 6:00am" 29 | ], 30 | "prHourlyLimit": 10, 31 | "commitMessagePrefix": "chore: ", 32 | "commitMessageAction": "update" 33 | } 34 | -------------------------------------------------------------------------------- /license.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023-2024 Pasqual Koschmieder and contributors 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Normalize as LF in the repository, OS native locally 2 | * text eol=lf 3 | 4 | # These are explicitly windows files and should use crlf 5 | *.bat text eol=crlf 6 | 7 | # These files are text and should be normalized (Convert crlf => lf) 8 | *.bash text eol=lf 9 | *.css text diff=css 10 | *.htm text diff=html 11 | *.html text diff=html 12 | *.java text diff=java 13 | *.sh text eol=lf 14 | 15 | # These files are binary and should be left untouched 16 | # (binary is a macro for -text -diff) 17 | *.a binary 18 | *.lib binary 19 | *.icns binary 20 | *.png binary 21 | *.jpg binary 22 | *.jpeg binary 23 | *.gif binary 24 | *.ico binary 25 | *.mov binary 26 | *.mp4 binary 27 | *.mp3 binary 28 | *.flv binary 29 | *.fla binary 30 | *.swf binary 31 | *.gz binary 32 | *.zip binary 33 | *.jar binary 34 | *.tar binary 35 | *.tar.gz binary 36 | *.7z binary 37 | *.ttf binary 38 | *.pyc binary 39 | *.gpg binary 40 | *.bin binary 41 | -------------------------------------------------------------------------------- /license_header.txt: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | rootProject.name = "mc-protocol-generator" 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # include specific folders in .idea/ 2 | !.idea 3 | .idea/* 4 | # copyright settings 5 | !/.idea/copyright 6 | .idea/copyright/* 7 | !/.idea/copyright/protocol-gen.xml 8 | !/.idea/copyright/profiles_settings.xml 9 | # Code Style settings 10 | !/.idea/codeStyles 11 | .idea/codeStyles/* 12 | !/.idea/codeStyles/Project.xml 13 | !/.idea/codeStyles/codeStyleConfig.xml 14 | # Inspection profiles 15 | !/.idea/inspectionProfiles 16 | .idea/inspectionProfiles/* 17 | !/.idea/inspectionProfiles/protocol-gen.xml 18 | !/.idea/inspectionProfiles/profiles_settings.xml 19 | 20 | # gradle 21 | .gradle/ 22 | build/ 23 | 24 | # fleet 25 | .fleet/ 26 | 27 | # eclipse 28 | *.classpath 29 | *.project 30 | *.settings 31 | /bin/ 32 | /subprojects/*/bin/ 33 | .metadata/ 34 | atlassian-ide-plugin.xml 35 | 36 | # NetBeans 37 | .nb-gradle 38 | .nb-gradle-properties 39 | 40 | # Vim 41 | *.sw[nop] 42 | 43 | # Emacs 44 | *~ 45 | \#*\# 46 | .\#* 47 | 48 | # Textmate 49 | .textmate 50 | 51 | # Sublime Text 52 | *.sublime-* 53 | 54 | # jEnv 55 | .java-version 56 | 57 | # macOS 58 | .DS_Store 59 | 60 | # HPROF 61 | *.hprof 62 | 63 | # Work dirs 64 | /incoming-distributions 65 | /intTestHomeDir 66 | 67 | # Logs 68 | /*.log 69 | 70 | # delombok 71 | */src/main/lombok 72 | 73 | # stuff for generation only 74 | *.tmp 75 | client_libs/ 76 | 77 | # final protocol output 78 | *.md 79 | !.github/readme.md 80 | -------------------------------------------------------------------------------- /.idea/copyright/protocol-gen.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | # 4 | # Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | # 6 | # Permission is hereby granted, free of charge, to any person obtaining a copy 7 | # of this software and associated documentation files (the "Software"), to deal 8 | # in the Software without restriction, including without limitation the rights 9 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | # copies of the Software, and to permit persons to whom the Software is 11 | # furnished to do so, subject to the following conditions: 12 | # 13 | # The above copyright notice and this permission notice shall be included in 14 | # all copies or substantial portions of the Software. 15 | # 16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | # THE SOFTWARE. 23 | # 24 | org.gradle.caching=true 25 | org.gradle.parallel=true 26 | org.gradle.warning.mode=all 27 | org.gradle.logging.level=info 28 | org.gradle.jvmargs=-Xmx2G -XX:MaxMetaspaceSize=512m -Dfile.encoding=UTF-8 29 | -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 24 | 25 | 26 | 27 | 28 | %d{HH:mm:ss.SSS} [%thread] %-5level: %msg%n 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/downloader/FileDownloadValidator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.downloader; 26 | 27 | import java.nio.file.Path; 28 | import lombok.NonNull; 29 | 30 | @FunctionalInterface 31 | public interface FileDownloadValidator { 32 | 33 | static @NonNull FileDownloadValidator ofSha1(@NonNull String sha1) { 34 | return new Sha1DownloadValidator(sha1); 35 | } 36 | 37 | boolean validate(@NonNull Path downloadPath) throws Exception; 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/protocol/McPacketFlow.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.protocol; 26 | 27 | import lombok.NonNull; 28 | 29 | enum McPacketFlow { 30 | 31 | /* packets from server to client */ 32 | CLIENTBOUND, 33 | /* packets from client to server */ 34 | SERVERBOUND; 35 | 36 | public @NonNull McPacketFlow sender() { 37 | return switch (this) { 38 | case CLIENTBOUND -> SERVERBOUND; 39 | case SERVERBOUND -> CLIENTBOUND; 40 | }; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /.github/workflows/generate.yml: -------------------------------------------------------------------------------- 1 | name: "Generate Protocol Specification" 2 | on: 3 | push: 4 | branches: [ "main" ] 5 | tags-ignore: [ "**" ] 6 | workflow_dispatch: 7 | schedule: 8 | - cron: '0 0 * * *' 9 | 10 | jobs: 11 | generate: 12 | name: "Generate Protocol Specification" 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - name: Checkout repository 17 | uses: actions/checkout@v6 18 | 19 | - name: Setup java 20 | uses: actions/setup-java@v5 21 | with: 22 | java-version: 25 23 | check-latest: true 24 | distribution: 'zulu' 25 | 26 | - name: Build Generator 27 | run: ./gradlew clean build shadowJar 28 | 29 | - name: Prepare execute directory 30 | run: | 31 | mkdir -p generation/; 32 | mkdir -p generation/result/; 33 | 34 | cp -r pages/* generation/result/; 35 | cp build/libs/protocol-generator.jar generation/generator.jar; 36 | 37 | - name: Run generator 38 | run: | 39 | cd generation; 40 | java --add-opens=java.base/java.lang.invoke=ALL-UNNAMED -Djoml.nounsafe=true -jar generator.jar --output-file=result/readme.md --version-file=version.txt; 41 | 42 | - name: Export processed version to env 43 | run: | 44 | cd generation; 45 | echo "VERSION=$(cat version.txt)" >> $GITHUB_ENV; 46 | 47 | - name: Push and Tag generated specification 48 | uses: s0/git-publish-subdir-action@develop 49 | env: 50 | REPO: self 51 | BRANCH: gh-pages 52 | FOLDER: generation/result 53 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 54 | SKIP_EMPTY_COMMITS: true 55 | MESSAGE: Update protocol for ${{ env.VERSION }} 56 | TAG: ${{ env.VERSION }} 57 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/protocol/McClassNames.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.protocol; 26 | 27 | final class McClassNames { 28 | 29 | public static final String BOOTSTRAP = "net.minecraft.server.Bootstrap"; 30 | public static final String SHARED_CONSTANTS = "net.minecraft.SharedConstants"; 31 | 32 | public static final String PACKET_VISITOR = "net.minecraft.network.ProtocolInfo$Details$PacketVisitor"; 33 | 34 | private McClassNames() { 35 | throw new UnsupportedOperationException(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/manifest/McManifestVersionType.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.manifest; 26 | 27 | import com.fasterxml.jackson.annotation.JsonIgnore; 28 | import com.fasterxml.jackson.annotation.JsonProperty; 29 | 30 | public enum McManifestVersionType { 31 | /* internally used, not actually supplied by minecraft manifest */ 32 | @JsonIgnore 33 | LATEST, 34 | 35 | @JsonProperty("release") 36 | RELEASE, 37 | @JsonProperty("snapshot") 38 | SNAPSHOT, 39 | @JsonProperty("old_beta") 40 | OLD_BETA, 41 | @JsonProperty("old_alpha") 42 | OLD_ALPHA 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/manifest/McVersionDumper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.manifest; 26 | 27 | import java.io.IOException; 28 | import java.nio.charset.StandardCharsets; 29 | import java.nio.file.Files; 30 | import java.nio.file.Path; 31 | import lombok.NonNull; 32 | 33 | public final class McVersionDumper { 34 | 35 | private final McManifestVersion version; 36 | 37 | public McVersionDumper(@NonNull McManifestVersion version) { 38 | this.version = version; 39 | } 40 | 41 | public void writeTo(@NonNull Path targetFile) throws IOException { 42 | Files.writeString(targetFile, this.version.id(), StandardCharsets.UTF_8); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/manifest/McManifestVersion.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.manifest; 26 | 27 | import java.net.URI; 28 | import java.time.OffsetDateTime; 29 | import lombok.NonNull; 30 | 31 | public record McManifestVersion( 32 | @NonNull String id, 33 | @NonNull McManifestVersionType type, 34 | @NonNull String url, 35 | @NonNull OffsetDateTime releaseTime, 36 | @NonNull String sha1 37 | ) implements Comparable { 38 | 39 | public @NonNull URI uri() { 40 | return URI.create(this.url); 41 | } 42 | 43 | @Override 44 | public int compareTo(@NonNull McManifestVersion other) { 45 | return other.releaseTime().compareTo(this.releaseTime()); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/util/CatchingFunction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.util; 26 | 27 | import java.util.function.Function; 28 | import lombok.NonNull; 29 | import org.jetbrains.annotations.Nullable; 30 | 31 | @FunctionalInterface 32 | public interface CatchingFunction { 33 | 34 | static @NonNull Function asJavaUtil( 35 | @NonNull CatchingFunction function, 36 | @NonNull String exceptionMessage 37 | ) { 38 | return input -> { 39 | try { 40 | return function.apply(input); 41 | } catch (Exception exception) { 42 | throw new IllegalStateException(exceptionMessage, exception); 43 | } 44 | }; 45 | } 46 | 47 | @Nullable 48 | V apply(T input) throws Exception; 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/jackson/JacksonSupport.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.jackson; 26 | 27 | import com.fasterxml.jackson.annotation.JsonAutoDetect; 28 | import tools.jackson.databind.DeserializationFeature; 29 | import tools.jackson.databind.json.JsonMapper; 30 | 31 | public final class JacksonSupport { 32 | 33 | public static final JsonMapper OBJECT_MAPPER = JsonMapper.builder() 34 | .findAndAddModules() 35 | .enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES) 36 | .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) 37 | .changeDefaultVisibility(checker -> checker.withFieldVisibility(JsonAutoDetect.Visibility.ANY)) 38 | .build(); 39 | 40 | private JacksonSupport() { 41 | throw new UnsupportedOperationException(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/protocol/McInit.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.protocol; 26 | 27 | import lombok.NonNull; 28 | 29 | final class McInit { 30 | 31 | private final ClassLoader classLoader; 32 | 33 | public McInit(@NonNull ClassLoader classLoader) { 34 | this.classLoader = classLoader; 35 | } 36 | 37 | public void init() throws Exception { 38 | // detect running version 39 | var sharedConstantsClass = Class.forName(McClassNames.SHARED_CONSTANTS, true, this.classLoader); 40 | var tryDetectVersionMethod = sharedConstantsClass.getMethod("tryDetectVersion"); 41 | tryDetectVersionMethod.invoke(null); 42 | 43 | // bootstrap registries 44 | var bootstrapClass = Class.forName(McClassNames.BOOTSTRAP, true, this.classLoader); 45 | var bootStrapMethod = bootstrapClass.getMethod("bootStrap"); 46 | bootStrapMethod.invoke(null); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/cli/CliArgParser.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.cli; 26 | 27 | import lombok.NonNull; 28 | import net.sourceforge.argparse4j.ArgumentParsers; 29 | import net.sourceforge.argparse4j.inf.Argument; 30 | import net.sourceforge.argparse4j.inf.ArgumentParser; 31 | import net.sourceforge.argparse4j.inf.Namespace; 32 | 33 | public final class CliArgParser { 34 | 35 | private final ArgumentParser argumentParser; 36 | 37 | public CliArgParser(@NonNull String toolName) { 38 | this.argumentParser = ArgumentParsers.newFor(toolName).build().defaultHelp(true); 39 | } 40 | 41 | public @NonNull Argument registerArgument(@NonNull String... names) { 42 | return this.argumentParser.addArgument(names); 43 | } 44 | 45 | public @NonNull Namespace parseCommandLine(@NonNull String[] commandLineArgs) { 46 | return this.argumentParser.parseArgsOrFail(commandLineArgs); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/protocol/PacketClassFieldScanner.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.protocol; 26 | 27 | import java.lang.reflect.Modifier; 28 | import lombok.NonNull; 29 | 30 | final class PacketClassFieldScanner { 31 | 32 | private final Class packetClass; 33 | private final PacketClassInfo baseInfo; 34 | 35 | public PacketClassFieldScanner(@NonNull Class packetClass, @NonNull PacketClassInfo baseInfo) { 36 | this.packetClass = packetClass; 37 | this.baseInfo = baseInfo; 38 | } 39 | 40 | public void scanAndRegisterClassFields() { 41 | // walk up the class tree 42 | var currentClass = this.packetClass; 43 | do { 44 | var fields = currentClass.getDeclaredFields(); 45 | for (var field : fields) { 46 | var fieldModifiers = field.getModifiers(); 47 | if (!Modifier.isStatic(fieldModifiers)) { 48 | var fieldInfo = PacketClassInfo.FieldInfo.ofReflectField(field); 49 | this.baseInfo.registerField(fieldInfo); 50 | } 51 | } 52 | 53 | } while ((currentClass = currentClass.getSuperclass()) != Object.class); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/protocol/McProtocolStates.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.protocol; 26 | 27 | import lombok.NonNull; 28 | 29 | enum McProtocolStates { 30 | 31 | /* state order here reflects into the field order of the final output */ 32 | 33 | HANDSHAKING("handshake"), 34 | STATUS("status"), 35 | LOGIN("login"), 36 | CONFIGURATION("configuration"), 37 | PLAY("game"); 38 | 39 | private static final String PKG_PREFIX_BASE = "net.minecraft.network.protocol.%s"; 40 | 41 | private final String pkg; 42 | private final String displayName; 43 | 44 | McProtocolStates(@NonNull String name) { 45 | this(name, String.format(PKG_PREFIX_BASE, name)); 46 | } 47 | 48 | McProtocolStates(@NonNull String name, @NonNull String pkg) { 49 | this.pkg = pkg; 50 | 51 | var firstChar = Character.toUpperCase(name.charAt(0)); 52 | this.displayName = String.format("%c%s", firstChar, name.substring(1)); 53 | } 54 | 55 | public @NonNull String displayName() { 56 | return this.displayName; 57 | } 58 | 59 | public @NonNull String protocolsClass() { 60 | return String.format("%s.%sProtocols", this.pkg, this.displayName); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/protocol-gen.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 40 | 41 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/manifest/McManifestVersionData.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.manifest; 26 | 27 | import com.fasterxml.jackson.annotation.JsonProperty; 28 | import java.time.OffsetDateTime; 29 | import java.util.List; 30 | import java.util.Map; 31 | 32 | public record McManifestVersionData( 33 | @JsonProperty("id") String id, 34 | @JsonProperty("type") McManifestVersionType type, 35 | @JsonProperty("libraries") List libraries, 36 | @JsonProperty("releaseTime") OffsetDateTime releaseTime, 37 | @JsonProperty("minimumLauncherVersion") int minLauncherVersion, 38 | @JsonProperty("downloads") Map fileDownloads 39 | ) { 40 | 41 | public record Library( 42 | @JsonProperty("name") String id, 43 | @JsonProperty("downloads") Map downloads 44 | ) { 45 | 46 | } 47 | 48 | public record LibraryDownload( 49 | @JsonProperty("path") String pathName, 50 | @JsonProperty("sha1") String sha1, 51 | @JsonProperty("url") String downloadUrl 52 | ) { 53 | 54 | } 55 | 56 | public record FileDownload( 57 | @JsonProperty("sha1") String sha1, 58 | @JsonProperty("url") String downloadUrl 59 | ) { 60 | 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/http/HttpClientProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.http; 26 | 27 | import com.google.common.util.concurrent.ThreadFactoryBuilder; 28 | import java.net.http.HttpClient; 29 | import java.time.Duration; 30 | import java.util.concurrent.Executor; 31 | import java.util.concurrent.Executors; 32 | import lombok.NonNull; 33 | 34 | public final class HttpClientProvider { 35 | 36 | private static final Duration DEFAULT_CONNECT_TIMEOUT = Duration.ofSeconds(15); 37 | private static final HttpClient.Redirect REDIRECT_POLICY = HttpClient.Redirect.NORMAL; 38 | 39 | private static final Executor REQUEST_EXECUTOR = Executors.newCachedThreadPool(new ThreadFactoryBuilder() 40 | .setDaemon(true) 41 | .setNameFormat("http-request-executor-%d") 42 | .setThreadFactory(Executors.defaultThreadFactory()) 43 | .build()); 44 | 45 | private HttpClientProvider() { 46 | throw new UnsupportedOperationException(); 47 | } 48 | 49 | public static @NonNull HttpClient provideClient() { 50 | return HttpClient.newBuilder() 51 | .executor(REQUEST_EXECUTOR) 52 | .followRedirects(REDIRECT_POLICY) 53 | .connectTimeout(DEFAULT_CONNECT_TIMEOUT) 54 | .build(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/markdown/MarkdownFormatter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.markdown; 26 | 27 | import com.google.common.html.HtmlEscapers; 28 | import fun.mingshan.markdown4j.Markdown; 29 | import fun.mingshan.markdown4j.constant.FlagConstants; 30 | import java.io.IOException; 31 | import java.nio.charset.StandardCharsets; 32 | import java.nio.file.Files; 33 | import java.nio.file.Path; 34 | import lombok.NonNull; 35 | 36 | public final class MarkdownFormatter { 37 | 38 | private final Markdown markdown; 39 | 40 | public MarkdownFormatter(@NonNull Markdown markdown) { 41 | this.markdown = markdown; 42 | } 43 | 44 | public void writeTo(@NonNull Path targetFile) throws IOException { 45 | StringBuilder builder = new StringBuilder(); 46 | this.markdown.getBlocks().forEach(block -> { 47 | // join the block lines & escape html chars 48 | var fullRawText = String.join("\n", block.toMd().split(FlagConstants.LINE_BREAK)); 49 | var fullEscapedText = HtmlEscapers.htmlEscaper().escape(fullRawText); 50 | 51 | // append the full text to the builder 52 | builder.append(fullEscapedText).append('\n'); 53 | }); 54 | 55 | Files.writeString(targetFile, builder.toString(), StandardCharsets.UTF_8); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/gameversion/JarGameVersionParser.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.gameversion; 26 | 27 | import dev.derklaro.protocolgenerator.jackson.JacksonSupport; 28 | import java.io.IOException; 29 | import java.io.InputStreamReader; 30 | import java.nio.charset.StandardCharsets; 31 | import java.nio.file.Path; 32 | import java.util.jar.JarFile; 33 | import lombok.NonNull; 34 | 35 | public final class JarGameVersionParser { 36 | 37 | private static final String VERSION_JSON_FILE_NAME = "version.json"; 38 | 39 | private final Path gameJarPath; 40 | 41 | public JarGameVersionParser(@NonNull Path gameJarPath) { 42 | this.gameJarPath = gameJarPath; 43 | } 44 | 45 | public @NonNull GameVersion readGameVersion() throws IOException { 46 | try (var jarFile = new JarFile(this.gameJarPath.toFile())) { 47 | // get the version json entry 48 | var versionJsonEntry = jarFile.getEntry(VERSION_JSON_FILE_NAME); 49 | var versionJsonStream = jarFile.getInputStream(versionJsonEntry); 50 | 51 | // read the file 52 | try (var reader = new InputStreamReader(versionJsonStream, StandardCharsets.UTF_8)) { 53 | return JacksonSupport.OBJECT_MAPPER.readValue(reader, GameVersion.class); 54 | } 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/protocol/PacketClassInfo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.protocol; 26 | 27 | import java.lang.reflect.Field; 28 | import java.lang.reflect.Type; 29 | import java.util.LinkedList; 30 | import java.util.List; 31 | import lombok.NonNull; 32 | 33 | public record PacketClassInfo( 34 | int packetId, 35 | @NonNull String name, 36 | @NonNull String source, 37 | @NonNull String target, 38 | @NonNull List fields 39 | ) implements Comparable { 40 | 41 | public PacketClassInfo(int packetId, @NonNull String name, @NonNull String source, @NonNull String target) { 42 | this(packetId, name, source, target, new LinkedList<>()); 43 | } 44 | 45 | public void registerField(@NonNull FieldInfo fieldInfo) { 46 | this.fields.add(fieldInfo); 47 | } 48 | 49 | @Override 50 | public int compareTo(@NonNull PacketClassInfo other) { 51 | return Integer.compare(this.packetId(), other.packetId()); 52 | } 53 | 54 | public record FieldInfo(@NonNull String name, @NonNull Class rawType, @NonNull Type genericType) { 55 | 56 | public static @NonNull FieldInfo ofReflectField(@NonNull Field field) { 57 | return new FieldInfo(field.getName(), field.getType(), field.getGenericType()); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/downloader/Sha1DownloadValidator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.downloader; 26 | 27 | import java.io.OutputStream; 28 | import java.nio.file.Files; 29 | import java.nio.file.Path; 30 | import java.security.DigestInputStream; 31 | import java.security.MessageDigest; 32 | import java.util.HexFormat; 33 | import lombok.NonNull; 34 | 35 | final class Sha1DownloadValidator implements FileDownloadValidator { 36 | 37 | private final String sha1Hex; 38 | 39 | public Sha1DownloadValidator(@NonNull String sha1Hex) { 40 | this.sha1Hex = sha1Hex; 41 | } 42 | 43 | @Override 44 | public boolean validate(@NonNull Path downloadPath) throws Exception { 45 | var sha1Digest = MessageDigest.getInstance("SHA-1"); 46 | try ( 47 | var fileStream = Files.newInputStream(downloadPath); 48 | var digestStream = new DigestInputStream(fileStream, sha1Digest) 49 | ) { 50 | // read all bytes provided by the stream 51 | digestStream.transferTo(OutputStream.nullOutputStream()); 52 | 53 | // compute the hex of the stream & validate it against the provided hex 54 | var digest = sha1Digest.digest(); 55 | var hexDigest = HexFormat.of().formatHex(digest); 56 | return this.sha1Hex.equals(hexDigest); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/GeneratorCLIArguments.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator; 26 | 27 | import dev.derklaro.protocolgenerator.cli.CliArgParser; 28 | import dev.derklaro.protocolgenerator.manifest.McManifestVersionType; 29 | import lombok.NonNull; 30 | import net.sourceforge.argparse4j.impl.Arguments; 31 | 32 | final class GeneratorCLIArguments { 33 | 34 | private GeneratorCLIArguments() { 35 | throw new UnsupportedOperationException(); 36 | } 37 | 38 | public static void registerDefaultArguments(@NonNull CliArgParser argParser) { 39 | // argument to set the version type to fetch 40 | argParser.registerArgument("-vt", "--version-type") 41 | .setDefault(McManifestVersionType.LATEST) 42 | .help("Sets the argument type to download and parse the protocol of") 43 | .type(Arguments.caseInsensitiveEnumType(McManifestVersionType.class)); 44 | 45 | // the final output file name 46 | argParser.registerArgument("-of", "--output-file") 47 | .setDefault("readme.md") 48 | .help("The name of the output file to export to (the parent directory need to exist)"); 49 | 50 | // if a file with the generated version should be created 51 | argParser.registerArgument("-vf", "--version-file") 52 | .help("Sets an optional file path to dump the target Minecraft version version to"); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/gameversion/GameVersion.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.gameversion; 26 | 27 | import com.fasterxml.jackson.annotation.JsonProperty; 28 | import java.time.OffsetDateTime; 29 | import lombok.NonNull; 30 | 31 | public record GameVersion( 32 | @NonNull String id, 33 | @NonNull String name, 34 | @NonNull @JsonProperty("series_id") String series, 35 | @NonNull @JsonProperty("build_time") OffsetDateTime buildTime, 36 | @NonNull @JsonProperty("pack_version") PackVersion packVersion, 37 | @NonNull @JsonProperty("java_component") String javaComponent, 38 | @JsonProperty("java_version") int javaVersion, 39 | @JsonProperty("protocol_version") int protocolVersion, 40 | @JsonProperty("world_version") int worldVersion, 41 | boolean stable 42 | ) { 43 | 44 | public record PackVersion( 45 | @JsonProperty("resource_major") int resourcePackMajor, 46 | @JsonProperty("resource_minor") int resourcePackMinor, 47 | @JsonProperty("data_major") int dataPackMajor, 48 | @JsonProperty("data_minor") int dataPackMinor 49 | ) { 50 | 51 | public @NonNull String formattedResourcePackVersion() { 52 | return String.format("%d.%d", this.resourcePackMajor, this.resourcePackMinor); 53 | } 54 | 55 | public @NonNull String formattedDataPackVersion() { 56 | return String.format("%d.%d", this.dataPackMajor, this.dataPackMinor); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/protocol/PacketVisitorImplGenerator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.protocol; 26 | 27 | import java.lang.reflect.InvocationHandler; 28 | import java.lang.reflect.Proxy; 29 | import java.util.Map; 30 | import lombok.NonNull; 31 | 32 | final class PacketVisitorImplGenerator { 33 | 34 | private final Class packetVisitorClass; 35 | private final Map targetPacketTypeToIdMap; 36 | 37 | public PacketVisitorImplGenerator( 38 | @NonNull Class packetVisitorClass, 39 | @NonNull Map targetPacketTypeToIdMap 40 | ) { 41 | this.packetVisitorClass = packetVisitorClass; 42 | this.targetPacketTypeToIdMap = targetPacketTypeToIdMap; 43 | } 44 | 45 | public @NonNull Object generatePacketVisitor() { 46 | InvocationHandler packetVisitorHandler = (ignored, method, args) -> { 47 | // accept(PacketType, int) 48 | if (method.getName().equals("accept") 49 | && method.getParameterCount() == 2 50 | && method.getReturnType() == void.class) { 51 | var packetType = args[0]; 52 | var packetId = (Integer) args[1]; 53 | this.targetPacketTypeToIdMap.put(packetType, packetId); 54 | return null; 55 | } 56 | 57 | // unknown method 58 | throw new UnsupportedOperationException("Called unsupported method: " + method.getName() + " on proxy"); 59 | }; 60 | return Proxy.newProxyInstance( 61 | this.packetVisitorClass.getClassLoader(), 62 | new Class[]{this.packetVisitorClass}, 63 | packetVisitorHandler); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/http/BodyParser.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.http; 26 | 27 | import dev.derklaro.protocolgenerator.jackson.JacksonSupport; 28 | import java.io.IOException; 29 | import java.io.InputStream; 30 | import java.io.InputStreamReader; 31 | import java.net.http.HttpResponse; 32 | import java.nio.charset.StandardCharsets; 33 | import java.util.function.Function; 34 | import lombok.NonNull; 35 | import tools.jackson.databind.JsonNode; 36 | 37 | public final class BodyParser { 38 | 39 | private static final Function TO_JSON_OBJECT = stream -> { 40 | try (var reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) { 41 | return JacksonSupport.OBJECT_MAPPER.readTree(reader); 42 | } catch (IOException exception) { 43 | throw new IllegalStateException("Unable to parse json input", exception); 44 | } 45 | }; 46 | 47 | private static final Function, ?> BODY_EXTRACTOR = response -> { 48 | var statusCode = response.statusCode(); 49 | if (statusCode == /* HTTP-OK */ 200) { 50 | return response.body(); 51 | } else { 52 | throw new IllegalStateException("Expected status 200 (OK), got: " + statusCode); 53 | } 54 | }; 55 | 56 | private BodyParser() { 57 | throw new UnsupportedOperationException(); 58 | } 59 | 60 | public static @NonNull Function toJsonObject() { 61 | return TO_JSON_OBJECT; 62 | } 63 | 64 | @SuppressWarnings("unchecked") 65 | public static @NonNull Function, T> bodyExtractorIfOk() { 66 | return (Function, T>) BODY_EXTRACTOR; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /.github/readme.md: -------------------------------------------------------------------------------- 1 | # MC Protocol 2 | 3 | This repository contains a generator which can automatically pull the latest mc version (release or snapshot) from the 4 | mc download servers, deobfuscate it, and generate a markdown file with all connection state, packet flows and packet 5 | fields. 6 | 7 | The specification in a pre-generated form for the current snapshot (updated each day at 12am UTC) is available via: 8 | 9 | * [Website](https://protocol.derklaro.dev/) 10 | * [GitHub](https://github.com/derklaro/mc-protocol/blob/gh-pages/readme.md) 11 | 12 | All versions that were ever generated are [tagged](https://github.com/derklaro/mc-protocol/tags). 13 | 14 | ### Output format 15 | 16 | The final markdown file has 4 fields for each field of a packet: 17 | 18 | * `Index`: The index of the field in the packet class. 19 | * `Type Index`: The index of the field within the fields that have the same type. This information is (for example) 20 | required when working with ProtocolLib which reads fields based on the relative index of the fields' type. 21 | * `Name`: The name of the field. This should be an indicator what the field is supposed to represent. 22 | * `Raw Type`: The raw type of the field, without any generic information. 23 | * `Full Type`: The full generic type of the field, this can be useful to (for example) understand what type of elements 24 | are in a collection. 25 | 26 | ### Running the generator 27 | 28 | To run the generator java version 17 (or newer) is required. You need to build the protocol generator from source using 29 | gradle: 30 | 31 | * Windows: `gradlew.bat build` 32 | * Unix: `./gradlew build` 33 | 34 | The final executable jar is located at: `build/libs/protocol-generator.jar`. When running you can specify the following 35 | options: 36 | 37 | | Name | Description | Default Value | Required | 38 | |---------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------|----------| 39 | | `--version-type` or `-vt` | Sets the version type to process (one of: `RELEASE`, `SNAPSHOT`, `LATEST`). This tries to generate the specification for the latest available version of the type. | `LATEST` | no | 40 | | `--output-file` or `-of` | Sets the file name of the output file to generate. The file contain the generated markdown for the protocol version. Note that parent directories need to be created manually. | `readme.md` | no | 41 | | `--version-file` or `-vf` | Sets the file name to which the processed version id should be dumped. If this option is not specified, the version will not be written to any file. | no default | no | 42 | 43 | ### License 44 | 45 | This generator is released under the terms of the MIT license. See [license.txt](../license.txt) 46 | or https://opensource.org/licenses/MIT. 47 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | 74 | 75 | @rem Execute Gradle 76 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* 77 | 78 | :end 79 | @rem End local scope for the variables with windows NT shell 80 | if %ERRORLEVEL% equ 0 goto mainEnd 81 | 82 | :fail 83 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 84 | rem the _cmd.exe /c_ return code! 85 | set EXIT_CODE=%ERRORLEVEL% 86 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 87 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 88 | exit /b %EXIT_CODE% 89 | 90 | :mainEnd 91 | if "%OS%"=="Windows_NT" endlocal 92 | 93 | :omega 94 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/library/McLibraryLoader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.library; 26 | 27 | import dev.derklaro.protocolgenerator.downloader.FileDownloadValidator; 28 | import dev.derklaro.protocolgenerator.downloader.FileDownloader; 29 | import dev.derklaro.protocolgenerator.manifest.McManifestVersionData; 30 | import java.io.IOException; 31 | import java.net.URL; 32 | import java.net.URLClassLoader; 33 | import java.nio.file.Path; 34 | import java.util.ArrayList; 35 | import java.util.List; 36 | import java.util.concurrent.CompletableFuture; 37 | import lombok.NonNull; 38 | 39 | public final class McLibraryLoader { 40 | 41 | private static final String LIB_ARTIFACT_DOWNLOAD_KEY = "artifact"; 42 | 43 | private final Path libraryDirectory; 44 | private final List libraries = new ArrayList<>(); 45 | 46 | public McLibraryLoader(@NonNull Path libraryDirectory) { 47 | this.libraryDirectory = libraryDirectory; 48 | } 49 | 50 | public @NonNull CompletableFuture loadLibrary(@NonNull McManifestVersionData.Library library) { 51 | var download = library.downloads().get(LIB_ARTIFACT_DOWNLOAD_KEY); 52 | if (download != null) { 53 | var localPath = this.libraryDirectory.resolve(download.pathName()); 54 | var libraryDownload = new FileDownloader(download.downloadUrl(), localPath) 55 | .withValidator(FileDownloadValidator.ofSha1(download.sha1())) 56 | .executeDownload(); 57 | return libraryDownload.thenRun(() -> { 58 | try { 59 | var url = localPath.toUri().toURL(); 60 | this.libraries.add(url); 61 | } catch (IOException exception) { 62 | throw new IllegalStateException("error converting path to url", exception); 63 | } 64 | }); 65 | } else { 66 | return CompletableFuture.completedFuture(null); 67 | } 68 | } 69 | 70 | public @NonNull ClassLoader provideClassLoader() { 71 | var urls = this.libraries.toArray(URL[]::new); 72 | return new URLClassLoader(urls, ClassLoader.getSystemClassLoader()); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/manifest/McManifestVersionFetcher.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.manifest; 26 | 27 | import dev.derklaro.protocolgenerator.http.BodyParser; 28 | import dev.derklaro.protocolgenerator.http.HttpClientProvider; 29 | import dev.derklaro.protocolgenerator.jackson.JacksonSupport; 30 | import dev.derklaro.protocolgenerator.util.CatchingFunction; 31 | import java.net.URI; 32 | import java.net.http.HttpRequest; 33 | import java.net.http.HttpResponse; 34 | import java.util.Collection; 35 | import java.util.Set; 36 | import java.util.concurrent.CompletableFuture; 37 | import lombok.NonNull; 38 | import tools.jackson.databind.JavaType; 39 | import tools.jackson.databind.type.TypeFactory; 40 | 41 | public final class McManifestVersionFetcher { 42 | 43 | private static final URI VERSION_MANIFEST_URI = 44 | URI.create("https://piston-meta.mojang.com/mc/game/version_manifest_v2.json"); 45 | 46 | private static final JavaType COLLECTION_MC_VERSION = 47 | TypeFactory.createDefaultInstance().constructCollectionType(Set.class, McManifestVersion.class); 48 | 49 | public @NonNull CompletableFuture> resolveMcVersions() { 50 | try (var httpClient = HttpClientProvider.provideClient()) { 51 | var request = HttpRequest.newBuilder(VERSION_MANIFEST_URI).build(); 52 | return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream()) 53 | .thenApply(BodyParser.bodyExtractorIfOk()) 54 | .thenApply(BodyParser.toJsonObject()) 55 | .thenApply(CatchingFunction.asJavaUtil(jsonNode -> { 56 | // get the releases section 57 | var versionsSection = jsonNode.get("versions"); 58 | return JacksonSupport.OBJECT_MAPPER.treeToValue(versionsSection, COLLECTION_MC_VERSION); 59 | }, "Unable to parse mc manifest versions")); 60 | } 61 | } 62 | 63 | public @NonNull CompletableFuture parseVersionData(@NonNull McManifestVersion version) { 64 | try (var httpClient = HttpClientProvider.provideClient()) { 65 | var request = HttpRequest.newBuilder(version.uri()).build(); 66 | return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream()) 67 | .thenApply(BodyParser.bodyExtractorIfOk()) 68 | .thenApply(BodyParser.toJsonObject()) 69 | .thenApply(CatchingFunction.asJavaUtil( 70 | jsonNode -> JacksonSupport.OBJECT_MAPPER.treeToValue(jsonNode, McManifestVersionData.class), 71 | "Unable to parse mc manifest versions")); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/downloader/FileDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.downloader; 26 | 27 | import dev.derklaro.protocolgenerator.http.BodyParser; 28 | import dev.derklaro.protocolgenerator.http.HttpClientProvider; 29 | import dev.derklaro.protocolgenerator.util.CatchingFunction; 30 | import java.net.URI; 31 | import java.net.http.HttpRequest; 32 | import java.net.http.HttpResponse; 33 | import java.nio.file.Files; 34 | import java.nio.file.Path; 35 | import java.nio.file.StandardCopyOption; 36 | import java.util.concurrent.CompletableFuture; 37 | import lombok.NonNull; 38 | import org.jetbrains.annotations.CheckReturnValue; 39 | import org.jetbrains.annotations.Nullable; 40 | 41 | public final class FileDownloader { 42 | 43 | private static final CompletableFuture V_COMPLETED_FUTURE = CompletableFuture.completedFuture(null); 44 | 45 | private final URI uri; 46 | private final Path target; 47 | private final FileDownloadValidator validator; 48 | 49 | public FileDownloader(@NonNull URI uri, @NonNull Path target) { 50 | this(uri, target, null); 51 | } 52 | 53 | public FileDownloader(@NonNull String uri, @NonNull Path target) { 54 | this(URI.create(uri), target); 55 | } 56 | 57 | private FileDownloader(@NonNull URI uri, @NonNull Path target, @Nullable FileDownloadValidator validator) { 58 | this.uri = uri; 59 | this.target = target; 60 | this.validator = validator; 61 | } 62 | 63 | @CheckReturnValue 64 | public @NonNull FileDownloader withValidator(@NonNull FileDownloadValidator validator) { 65 | return new FileDownloader(this.uri, this.target, validator); 66 | } 67 | 68 | public @NonNull CompletableFuture executeDownload() { 69 | return this.validateOrDownload(0); 70 | } 71 | 72 | private @NonNull CompletableFuture downloadAndValidate(int retryCount) { 73 | try (var httpClient = HttpClientProvider.provideClient()) { 74 | var req = HttpRequest.newBuilder(this.uri).build(); 75 | return httpClient.sendAsync(req, HttpResponse.BodyHandlers.ofInputStream()) 76 | .thenApply(BodyParser.bodyExtractorIfOk()) 77 | .thenApply(CatchingFunction.asJavaUtil(stream -> { 78 | // create parent directory if necessary 79 | var parent = this.target.getParent(); 80 | if (parent != null) { 81 | Files.createDirectories(parent); 82 | } 83 | 84 | // copy the result to the target location 85 | try (stream) { 86 | Files.copy(stream, this.target, StandardCopyOption.REPLACE_EXISTING); 87 | return null; 88 | } 89 | }, "Unable to download file from " + this.uri + " to " + this.target)) 90 | .thenCompose(__ -> this.validateOrDownload(retryCount)); 91 | } 92 | } 93 | 94 | private @NonNull CompletableFuture validateOrDownload(int retryCount) { 95 | var validationResult = this.validateDownload(); 96 | if (validationResult) { 97 | return V_COMPLETED_FUTURE; 98 | } else if (retryCount <= 3) { 99 | return this.downloadAndValidate(retryCount + 1); 100 | } else { 101 | return CompletableFuture.failedFuture( 102 | new IllegalStateException("Download from" + this.uri + " failed multiple times, aborting")); 103 | } 104 | } 105 | 106 | private boolean validateDownload() { 107 | if (this.validator == null || Files.notExists(this.target)) { 108 | // no validator / download -> download is valid 109 | return false; 110 | } 111 | 112 | try { 113 | return this.validator.validate(this.target); 114 | } catch (Exception exception) { 115 | return false; 116 | } 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/reflect/TypeHelper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.reflect; 26 | 27 | import java.lang.reflect.GenericArrayType; 28 | import java.lang.reflect.ParameterizedType; 29 | import java.lang.reflect.Type; 30 | import java.lang.reflect.TypeVariable; 31 | import java.lang.reflect.WildcardType; 32 | import java.util.StringJoiner; 33 | import lombok.NonNull; 34 | 35 | /** 36 | * This class was originally written for aerogel 38 | * and was modified for usage with Java 17. 39 | */ 40 | public final class TypeHelper { 41 | 42 | private TypeHelper() { 43 | throw new UnsupportedOperationException(); 44 | } 45 | 46 | public static @NonNull String toPrettyString(@NonNull Type type) { 47 | switch (type) { 48 | case Class clazz -> { 49 | // check if the class is enclosed 50 | var enclosingClass = clazz.getEnclosingClass(); 51 | if (enclosingClass != null) { 52 | var prettyEnclosingClass = toPrettyString(enclosingClass); 53 | return prettyEnclosingClass + '$' + clazz.getSimpleName(); 54 | } else { 55 | // top level class 56 | return clazz.getSimpleName(); 57 | } 58 | } 59 | case ParameterizedType parameterizedType -> { 60 | var infoBuilder = new StringBuilder(); 61 | 62 | // append the info about the raw type 63 | var rawPretty = toPrettyString(parameterizedType.getRawType()); 64 | infoBuilder.append(rawPretty); 65 | 66 | // append the type arguments 67 | var typeArguments = parameterizedType.getActualTypeArguments(); 68 | if (typeArguments.length > 0) { 69 | var argumentJoiner = new StringJoiner(", ", "<", ">"); 70 | for (var typeArgument : typeArguments) { 71 | var argumentPretty = toPrettyString(typeArgument); 72 | argumentJoiner.add(argumentPretty); 73 | } 74 | infoBuilder.append(argumentJoiner); 75 | } 76 | 77 | return infoBuilder.toString(); 78 | } 79 | case WildcardType wildcardType -> { 80 | // check the lower bounds of the wildcard type 81 | var lowerBounds = wildcardType.getLowerBounds(); 82 | if (lowerBounds.length > 0) { 83 | var prettyBound = toPrettyString(lowerBounds[0]); 84 | return "? super " + prettyBound; 85 | } 86 | 87 | // check the upper bounds of the type 88 | var upperBounds = wildcardType.getUpperBounds(); 89 | if (upperBounds.length == 0 || upperBounds[0] == Object.class) { 90 | return "?"; 91 | } else { 92 | var prettyBound = toPrettyString(upperBounds[0]); 93 | return "? extends " + prettyBound; 94 | } 95 | } 96 | case GenericArrayType genericArrayType -> { 97 | // get the info about the component type 98 | var prettyComponentType = toPrettyString(genericArrayType.getGenericComponentType()); 99 | return prettyComponentType + "[]"; 100 | } 101 | case TypeVariable typeVariable -> { 102 | // get the raw type of the bounds 103 | var bounds = typeVariable.getBounds(); 104 | var prettyBound = toPrettyString(bounds.length == 0 ? Object.class : bounds[0]); 105 | 106 | // append the name of the variable as well 107 | return prettyBound + " " + typeVariable.getName(); 108 | } 109 | default -> { 110 | // unknown type, just return the toString value 111 | return type.toString(); 112 | } 113 | } 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/protocol/ProtocolInfoCollector.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.protocol; 26 | 27 | import com.google.common.collect.Table; 28 | import com.google.common.collect.Tables; 29 | import java.net.URL; 30 | import java.net.URLClassLoader; 31 | import java.nio.file.Path; 32 | import java.util.ArrayList; 33 | import java.util.Collection; 34 | import java.util.LinkedHashMap; 35 | import java.util.LinkedList; 36 | import java.util.Locale; 37 | import java.util.Map; 38 | import java.util.Objects; 39 | import lombok.NonNull; 40 | 41 | public final class ProtocolInfoCollector { 42 | 43 | private final Path remappedJarPath; 44 | private final ClassLoader libraryClassLoader; 45 | 46 | public ProtocolInfoCollector(@NonNull Path remappedJarPath, @NonNull ClassLoader libraryClassLoader) { 47 | this.remappedJarPath = remappedJarPath; 48 | this.libraryClassLoader = libraryClassLoader; 49 | } 50 | 51 | public @NonNull Table> collectAllPacketInfos() throws Exception { 52 | // build a class loader which is aware of the remapped jar 53 | var remappedJarUrl = this.remappedJarPath.toUri().toURL(); 54 | var loader = new URLClassLoader(new URL[]{remappedJarUrl}, this.libraryClassLoader); 55 | var packetVisitorClass = Class.forName(McClassNames.PACKET_VISITOR, true, loader); 56 | 57 | // important first step: initialize minecraft registries 58 | var mcInitializer = new McInit(loader); 59 | mcInitializer.init(); 60 | 61 | // collect all packets for all protocols & flows 62 | // protocol -> flow -> info 63 | Table> result 64 | = Tables.newCustomTable(new LinkedHashMap<>(), LinkedHashMap::new); 65 | for (var state : McProtocolStates.values()) { 66 | // resolve packet information 67 | var protocolsClass = Class.forName(state.protocolsClass(), true, loader); 68 | var infoDecoder = new McProtocolsDecoder(protocolsClass, loader); 69 | var typeToPacketClassPerFlow = infoDecoder.decodeAssociatedPackets(); 70 | var typeToPacketIdPerFlow = infoDecoder.resolvePacketIds(packetVisitorClass); 71 | 72 | // register for each flow (if present) 73 | for (var flow : McPacketFlow.values()) { 74 | var idMapping = typeToPacketIdPerFlow.get(flow); 75 | var classMapping = typeToPacketClassPerFlow.get(flow); 76 | if (idMapping != null && classMapping != null) { 77 | var idEntries = new ArrayList<>(idMapping.entrySet()); 78 | idEntries.sort(Map.Entry.comparingByValue()); 79 | 80 | for (var entry : idEntries) { 81 | var packetId = entry.getValue(); 82 | var packetType = entry.getKey(); 83 | var packetClass = classMapping.get(packetType); 84 | Objects.requireNonNull(packetClass, "class for packet type missing " + packetType); 85 | 86 | // construct the base packet info 87 | var externalName = this.externalizePacketClassName(flow, packetClass.getSimpleName()); 88 | var baseInfo = new PacketClassInfo(packetId, externalName, flow.sender().name(), flow.name()); 89 | var fieldScanner = new PacketClassFieldScanner(packetClass, baseInfo); 90 | fieldScanner.scanAndRegisterClassFields(); 91 | 92 | // register the packet 93 | var packetInfos = result.get(state.displayName(), flow.name()); 94 | if (packetInfos == null) { 95 | packetInfos = new LinkedList<>(); 96 | result.put(state.displayName(), flow.name(), packetInfos); 97 | } 98 | packetInfos.add(baseInfo); 99 | } 100 | } 101 | } 102 | } 103 | 104 | return result; 105 | } 106 | 107 | /* example: ClientboundSetSimulationDistancePacket -> Set Simulation Distance */ 108 | private @NonNull String externalizePacketClassName(@NonNull McPacketFlow flow, @NonNull String packetName) { 109 | // remove the flow name from the packet class name 110 | var lowerName = packetName.toLowerCase(Locale.ROOT); 111 | var lowerFlowName = flow.name().toLowerCase(Locale.ROOT); 112 | if (lowerName.startsWith(lowerFlowName)) { 113 | packetName = packetName.substring(lowerFlowName.length()); 114 | } 115 | 116 | // remove the packet suffix 117 | if (lowerName.endsWith("packet")) { 118 | packetName = packetName.substring(0, packetName.length() - 6); 119 | } 120 | 121 | // insert space before each upper-camel char 122 | var splitAtCamel = packetName.split("(?=\\p{Lu})"); 123 | return String.join(" ", splitAtCamel); 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/GeneratorEntrypoint.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator; 26 | 27 | import dev.derklaro.protocolgenerator.cli.CliArgParser; 28 | import dev.derklaro.protocolgenerator.downloader.FileDownloadValidator; 29 | import dev.derklaro.protocolgenerator.downloader.FileDownloader; 30 | import dev.derklaro.protocolgenerator.gameversion.JarGameVersionParser; 31 | import dev.derklaro.protocolgenerator.library.McLibraryLoader; 32 | import dev.derklaro.protocolgenerator.manifest.McManifestVersionFetcher; 33 | import dev.derklaro.protocolgenerator.manifest.McManifestVersionType; 34 | import dev.derklaro.protocolgenerator.manifest.McVersionDumper; 35 | import dev.derklaro.protocolgenerator.markdown.MarkdownFormatter; 36 | import dev.derklaro.protocolgenerator.markdown.MarkdownGenerator; 37 | import dev.derklaro.protocolgenerator.protocol.ProtocolInfoCollector; 38 | import dev.derklaro.protocolgenerator.util.CatchingFunction; 39 | import java.io.IOException; 40 | import java.nio.file.Path; 41 | import java.util.ArrayList; 42 | import java.util.List; 43 | import java.util.concurrent.CompletableFuture; 44 | import java.util.function.Supplier; 45 | import lombok.NonNull; 46 | 47 | public final class GeneratorEntrypoint { 48 | 49 | private static final Path LIB_DIR_PATH = Path.of("client_libs"); 50 | private static final Path CLIENT_JAR_PATH = Path.of("client.tmp"); 51 | 52 | static void main(@NonNull String[] args) throws IOException { 53 | // parse the cli arguments 54 | var cliArgumentParser = new CliArgParser("ProtocolGenerator"); 55 | GeneratorCLIArguments.registerDefaultArguments(cliArgumentParser); 56 | var cliNamespace = cliArgumentParser.parseCommandLine(args); 57 | 58 | // resolve all client versions 59 | var versionFetcher = new McManifestVersionFetcher(); 60 | var clientVersions = versionFetcher.resolveMcVersions(); 61 | 62 | // search the requested version 63 | McManifestVersionType versionType = cliNamespace.get("version_type"); 64 | var latestVersionOfType = clientVersions 65 | .thenApply(versions -> versions.stream() 66 | .filter(version -> versionType == McManifestVersionType.LATEST || version.type() == versionType) 67 | .sorted() 68 | .findFirst()) 69 | .thenApply(optional -> { 70 | Supplier versionNotFoundExceptionSupplier = 71 | () -> new IllegalStateException("Unable to find a version with type " + versionType); 72 | return optional.orElseThrow(versionNotFoundExceptionSupplier); 73 | }); 74 | 75 | // deserialize version data 76 | var versionData = latestVersionOfType.thenCompose(versionFetcher::parseVersionData); 77 | 78 | // download the client and client mappings of the version 79 | var versionTypeDownloads = versionData.thenCompose(data -> { 80 | // no null check here as we just require the downloads to present 81 | // in all other cases we cannot proceed anyway 82 | var clientDownloadInfo = data.fileDownloads().get("client"); 83 | return new FileDownloader(clientDownloadInfo.downloadUrl(), CLIENT_JAR_PATH) 84 | .withValidator(FileDownloadValidator.ofSha1(clientDownloadInfo.sha1())) 85 | .executeDownload(); 86 | }); 87 | 88 | // download all required client libraries 89 | var libraryLoader = new McLibraryLoader(LIB_DIR_PATH); 90 | var libraryLoading = versionData.thenCompose(data -> { 91 | List> libDownloadFutures = new ArrayList<>(); 92 | for (var library : data.libraries()) { 93 | var downloadFuture = libraryLoader.loadLibrary(library); 94 | libDownloadFutures.add(downloadFuture); 95 | } 96 | 97 | var futures = libDownloadFutures.toArray(CompletableFuture[]::new); 98 | return CompletableFuture.allOf(futures); 99 | }); 100 | 101 | // combine the loading of the client and the loading of the required libraries 102 | var downloadFuture = CompletableFuture.allOf(versionTypeDownloads, libraryLoading); 103 | 104 | // get the game version from the jar 105 | var gameVersion = downloadFuture 106 | .thenApply(CatchingFunction.asJavaUtil(ignored -> { 107 | var versionParser = new JarGameVersionParser(CLIENT_JAR_PATH); 108 | return versionParser.readGameVersion(); 109 | }, "Unable to read game version of remapped jar")) 110 | .join(); 111 | 112 | // collect the protocol information 113 | var protocolInfos = downloadFuture 114 | .thenApply(CatchingFunction.asJavaUtil(ignored -> { 115 | var protocolInfoGenerator = new ProtocolInfoCollector(CLIENT_JAR_PATH, libraryLoader.provideClassLoader()); 116 | return protocolInfoGenerator.collectAllPacketInfos(); 117 | }, "Unable to resolve packet information")) 118 | .join(); 119 | 120 | // build the final markdown info from the information 121 | var markdownGenerator = new MarkdownGenerator(); 122 | var protocolMarkdown = markdownGenerator.generateProtocolMarkdown(gameVersion, protocolInfos); 123 | 124 | // get the output path to dump the protocol to 125 | var outputFileName = cliNamespace.getString("output_file"); 126 | var outputFilePath = Path.of(outputFileName); 127 | 128 | // format & write the final markdown file 129 | var markdownFormatter = new MarkdownFormatter(protocolMarkdown); 130 | markdownFormatter.writeTo(outputFilePath); 131 | 132 | // dump the version information into the requested file (if any) 133 | var versionFilePath = cliNamespace.getString("version_file"); 134 | if (versionFilePath != null) { 135 | var versionDumper = new McVersionDumper(latestVersionOfType.join()); 136 | versionDumper.writeTo(Path.of(versionFilePath)); 137 | } 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/markdown/MarkdownGenerator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.markdown; 26 | 27 | import com.google.common.base.CaseFormat; 28 | import com.google.common.collect.Table; 29 | import dev.derklaro.protocolgenerator.gameversion.GameVersion; 30 | import dev.derklaro.protocolgenerator.protocol.PacketClassInfo; 31 | import dev.derklaro.protocolgenerator.reflect.TypeHelper; 32 | import fun.mingshan.markdown4j.Markdown; 33 | import fun.mingshan.markdown4j.type.block.StringBlock; 34 | import fun.mingshan.markdown4j.type.block.TableBlock; 35 | import fun.mingshan.markdown4j.type.block.TitleBlock; 36 | import java.time.format.DateTimeFormatter; 37 | import java.util.Collection; 38 | import java.util.HashMap; 39 | import java.util.LinkedList; 40 | import java.util.List; 41 | import java.util.Map; 42 | import lombok.NonNull; 43 | 44 | public final class MarkdownGenerator { 45 | 46 | private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"); 47 | 48 | private static final List FIELD_TABLE_HEADERS = List.of( 49 | "Index", 50 | "Type Index", 51 | "Name", 52 | "Raw Type", 53 | "Full Type"); 54 | private static final List METADATA_TABLE_HEADERS = List.of( 55 | "Series", 56 | "Java Runtime", 57 | "Java Version", 58 | "Protocol Version", 59 | "World Version", 60 | "Resource Pack Version", 61 | "Data Pack Version", 62 | "Build Timestamp (UTC)"); 63 | 64 | public @NonNull Markdown generateProtocolMarkdown( 65 | @NonNull GameVersion currentGameVersion, 66 | @NonNull Table> packetInfos 67 | ) { 68 | var markdownBuilder = Markdown.builder().name("protocol"); 69 | 70 | // append the game version info 71 | this.appendGameVersion(markdownBuilder, currentGameVersion); 72 | 73 | // append each packet information 74 | this.dumpPacketInfos(markdownBuilder, packetInfos); 75 | 76 | // build the final markdown 77 | return markdownBuilder.build(); 78 | } 79 | 80 | private void appendGameVersion(@NonNull Markdown.MarkdownBuilder markdownBuilder, @NonNull GameVersion gameVersion) { 81 | // append the top-level title 82 | var titleContent = "%s (%s)".formatted(gameVersion.name(), gameVersion.stable() ? "Stable" : "Snapshot"); 83 | markdownBuilder.block(TitleBlock.builder().level(TitleBlock.Level.FIRST).content(titleContent).build()); 84 | 85 | // metadata table row values 86 | List metadataRowValues = List.of( 87 | gameVersion.series(), 88 | gameVersion.javaComponent(), 89 | Integer.toString(gameVersion.javaVersion()), 90 | Integer.toString(gameVersion.protocolVersion()), 91 | Integer.toString(gameVersion.worldVersion()), 92 | gameVersion.packVersion().formattedResourcePackVersion(), 93 | gameVersion.packVersion().formattedDataPackVersion(), 94 | DATE_TIME_FORMATTER.format(gameVersion.buildTime())); 95 | 96 | // build the row block 97 | var tableRow = new TableBlock.TableRow(); 98 | tableRow.setRows(metadataRowValues); 99 | 100 | // build and append the table 101 | var tableBlock = TableBlock.builder().titles(METADATA_TABLE_HEADERS).rows(List.of(tableRow)).build(); 102 | markdownBuilder.block(tableBlock); 103 | } 104 | 105 | private void dumpPacketInfos( 106 | @NonNull Markdown.MarkdownBuilder markdownBuilder, 107 | @NonNull Table> packetInfos 108 | ) { 109 | var cellSet = packetInfos.cellSet(); 110 | for (var cell : cellSet) { 111 | // normalize the name of the connection protocol and connection flow 112 | var normalizedPacketFlow = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, cell.getColumnKey()); 113 | var normalizedConnectionProtocol = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, cell.getRowKey()); 114 | 115 | // append the protocol and flow information 116 | var flowContent = "%s (%s)".formatted(normalizedConnectionProtocol, normalizedPacketFlow); 117 | markdownBuilder.block(TitleBlock.builder().level(TitleBlock.Level.SECOND).content(flowContent).build()); 118 | 119 | // check if the flow has packets to dump 120 | var packets = cell.getValue(); 121 | if (packets.isEmpty()) { 122 | var noPacketContent = "This packet flow has no registered packets"; 123 | markdownBuilder.block(StringBlock.builder().content(noPacketContent).build()); 124 | } else { 125 | // append the information of each packet 126 | for (var packetClassInfo : packets) { 127 | // begin the packet info 128 | var titleContent = "0x%s - %s (%c ➔ %c)".formatted( 129 | "%02X".formatted(0xFF & packetClassInfo.packetId()), 130 | packetClassInfo.name(), 131 | packetClassInfo.source().charAt(0), 132 | packetClassInfo.target().charAt(0)); 133 | markdownBuilder.block(TitleBlock.builder().level(TitleBlock.Level.FOURTH).content(titleContent).build()); 134 | 135 | // check if the packet has fields to dump 136 | var fields = packetClassInfo.fields(); 137 | if (fields.isEmpty()) { 138 | var noFieldContent = "Packet has no fields"; 139 | markdownBuilder.block(StringBlock.builder().content(noFieldContent).build()); 140 | } else { 141 | // keep track of the field index we're giving out 142 | var overallIndex = 0; 143 | Map, Integer> indexPerType = new HashMap<>(); 144 | 145 | // dump all packet fields 146 | List fieldTableRows = new LinkedList<>(); 147 | for (var field : fields) { 148 | // get the field index 149 | var overallFieldIndex = overallIndex++; 150 | var fieldTypeIndex = indexPerType.merge(field.rawType(), 1, Integer::sum); 151 | 152 | // get the nice information of the field type 153 | var niceRawType = TypeHelper.toPrettyString(field.rawType()); 154 | var niceGenericType = TypeHelper.toPrettyString(field.genericType()); 155 | 156 | // build the table row values 157 | List rowValues = List.of( 158 | Integer.toString(overallFieldIndex), // no need to subtract, we start at 0 159 | Integer.toString(fieldTypeIndex - 1), // -1 here as this counter starts at 1 160 | field.name(), 161 | niceRawType, 162 | niceGenericType); 163 | 164 | // register the row 165 | var tableRow = new TableBlock.TableRow(); 166 | tableRow.setRows(rowValues); 167 | fieldTableRows.add(tableRow); 168 | } 169 | 170 | // add the final table 171 | var table = TableBlock.builder().titles(FIELD_TABLE_HEADERS).rows(fieldTableRows).build(); 172 | markdownBuilder.block(table); 173 | } 174 | 175 | // add a single blank line below 176 | markdownBuilder.block(StringBlock.builder().content(" ").build()); 177 | } 178 | } 179 | } 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | 118 | 119 | # Determine the Java command to use to start the JVM. 120 | if [ -n "$JAVA_HOME" ] ; then 121 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 122 | # IBM's JDK on AIX uses strange locations for the executables 123 | JAVACMD=$JAVA_HOME/jre/sh/java 124 | else 125 | JAVACMD=$JAVA_HOME/bin/java 126 | fi 127 | if [ ! -x "$JAVACMD" ] ; then 128 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 129 | 130 | Please set the JAVA_HOME variable in your environment to match the 131 | location of your Java installation." 132 | fi 133 | else 134 | JAVACMD=java 135 | if ! command -v java >/dev/null 2>&1 136 | then 137 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 138 | 139 | Please set the JAVA_HOME variable in your environment to match the 140 | location of your Java installation." 141 | fi 142 | fi 143 | 144 | # Increase the maximum file descriptors if we can. 145 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 146 | case $MAX_FD in #( 147 | max*) 148 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 149 | # shellcheck disable=SC2039,SC3045 150 | MAX_FD=$( ulimit -H -n ) || 151 | warn "Could not query maximum file descriptor limit" 152 | esac 153 | case $MAX_FD in #( 154 | '' | soft) :;; #( 155 | *) 156 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 157 | # shellcheck disable=SC2039,SC3045 158 | ulimit -n "$MAX_FD" || 159 | warn "Could not set maximum file descriptor limit to $MAX_FD" 160 | esac 161 | fi 162 | 163 | # Collect all arguments for the java command, stacking in reverse order: 164 | # * args from the command line 165 | # * the main class name 166 | # * -classpath 167 | # * -D...appname settings 168 | # * --module-path (only if needed) 169 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 170 | 171 | # For Cygwin or MSYS, switch paths to Windows format before running java 172 | if "$cygwin" || "$msys" ; then 173 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ 214 | "$@" 215 | 216 | # Stop when "xargs" is not available. 217 | if ! command -v xargs >/dev/null 2>&1 218 | then 219 | die "xargs is not available" 220 | fi 221 | 222 | # Use "xargs" to parse quoted args. 223 | # 224 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 225 | # 226 | # In Bash we could simply go: 227 | # 228 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 229 | # set -- "${ARGS[@]}" "$@" 230 | # 231 | # but POSIX shell has neither arrays nor command substitution, so instead we 232 | # post-process each arg (as a line of input to sed) to backslash-escape any 233 | # character that might be a shell metacharacter, then use eval to reverse 234 | # that process (while maintaining the separation between arguments), and wrap 235 | # the whole thing up as a single "set" statement. 236 | # 237 | # This will of course break if any of these variables contains a newline or 238 | # an unmatched quote. 239 | # 240 | 241 | eval "set -- $( 242 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 243 | xargs -n1 | 244 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 245 | tr '\n' ' ' 246 | )" '"$@"' 247 | 248 | exec "$JAVACMD" "$@" 249 | -------------------------------------------------------------------------------- /src/main/java/dev/derklaro/protocolgenerator/protocol/McProtocolsDecoder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of mc-protocol-generator, licensed under the MIT License (MIT). 3 | * 4 | * Copyright (c) 2023 - 2024 Pasqual K. and contributors 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | package dev.derklaro.protocolgenerator.protocol; 26 | 27 | import dev.derklaro.reflexion.Reflexion; 28 | import dev.derklaro.reflexion.matcher.FieldMatcher; 29 | import dev.derklaro.reflexion.matcher.MethodMatcher; 30 | import java.io.IOException; 31 | import java.lang.reflect.Modifier; 32 | import java.util.EnumMap; 33 | import java.util.HashMap; 34 | import java.util.IdentityHashMap; 35 | import java.util.Locale; 36 | import java.util.Map; 37 | import java.util.Objects; 38 | import java.util.function.Predicate; 39 | import lombok.NonNull; 40 | import org.jetbrains.annotations.Nullable; 41 | import org.objectweb.asm.ClassReader; 42 | import org.objectweb.asm.Handle; 43 | import org.objectweb.asm.Type; 44 | import org.objectweb.asm.tree.AbstractInsnNode; 45 | import org.objectweb.asm.tree.ClassNode; 46 | import org.objectweb.asm.tree.FieldInsnNode; 47 | import org.objectweb.asm.tree.InvokeDynamicInsnNode; 48 | import org.objectweb.asm.tree.MethodInsnNode; 49 | import org.objectweb.asm.tree.MethodNode; 50 | 51 | final class McProtocolsDecoder { 52 | 53 | // matcher for the UnboundProtocol constants in XXXProtocols classes 54 | private static final FieldMatcher PROTOCOL_INFO_MATCHER = FieldMatcher.newMatcher() 55 | .hasModifier(Modifier.STATIC) 56 | .and(field -> { 57 | var typeName = field.getType().getCanonicalName(); 58 | return typeName.endsWith(".UnboundProtocol") || typeName.endsWith(".SimpleUnboundProtocol"); 59 | }); 60 | 61 | // matcher to find the listPackets(PacketVisitor) method in ProtocolInfo$Details 62 | private static final MethodMatcher LIST_PACKETS_MATCHER = MethodMatcher.newMatcher() 63 | .parameterCount(1) 64 | .hasName("listPackets"); 65 | 66 | // matcher for InvokeDynamicInsnNode that constructs the info for a protocol 67 | private static final Predicate PROTOCOL_LAMBDA_BUILDER_FILTER = node -> { 68 | var bsmArgs = node.bsmArgs; 69 | return bsmArgs != null 70 | && bsmArgs.length == 3 71 | && bsmArgs[2] instanceof Type type 72 | && type.getArgumentCount() == 1 73 | && type.getReturnType() == Type.VOID_TYPE 74 | && type.getArgumentTypes()[0].getClassName().endsWith(".ProtocolInfoBuilder"); 75 | }; 76 | 77 | private static final String STREAM_CODEC_DESC = "Lnet/minecraft/network/codec/StreamCodec;"; 78 | private static final String PACKET_TYPE_DESC = "Lnet/minecraft/network/protocol/PacketType;"; 79 | 80 | private final Class targetClass; 81 | private final ClassLoader mcClassLoader; 82 | 83 | public McProtocolsDecoder(@NonNull Class targetClass, @NonNull ClassLoader mcClassLoader) { 84 | this.targetClass = targetClass; 85 | this.mcClassLoader = mcClassLoader; 86 | } 87 | 88 | public @NonNull Map>> decodeAssociatedPackets() throws Exception { 89 | // decode the target class, find the static initializer & all static lambda methods 90 | var decodedClass = this.decodeTargetClass(); 91 | var clinit = this.findClinit(decodedClass); 92 | var staticLambdas = this.resolveLambdaMethods(decodedClass); 93 | if (clinit == null) { 94 | return Map.of(); 95 | } 96 | 97 | // there can be two calls: one for serverbound, one for clientbound 98 | var firstInvokeDynamic = this.findNodeOfType( 99 | InvokeDynamicInsnNode.class, 100 | clinit, 101 | null, 102 | PROTOCOL_LAMBDA_BUILDER_FILTER); 103 | var secondInvokeDynamic = this.findNodeOfType( 104 | InvokeDynamicInsnNode.class, 105 | clinit, 106 | firstInvokeDynamic, 107 | PROTOCOL_LAMBDA_BUILDER_FILTER); 108 | 109 | // resolve the protocol info (ProtocolInfoBuilder type -> Invocation Target for configuration) 110 | var firstProtocolInfo = this.resolveProtocolInvocationInfo(clinit, firstInvokeDynamic); 111 | var secondProtocolInfo = this.resolveProtocolInvocationInfo(clinit, secondInvokeDynamic); 112 | 113 | // do the actual type mapping for (flow -> (type -> class)) 114 | Map>> result = new EnumMap<>(McPacketFlow.class); 115 | this.doMapTypes(staticLambdas, firstProtocolInfo, result); 116 | this.doMapTypes(staticLambdas, secondProtocolInfo, result); 117 | 118 | return result; 119 | } 120 | 121 | public @NonNull Map> resolvePacketIds(@NonNull Class packetVisitorClass) { 122 | Map> result = new EnumMap<>(McPacketFlow.class); 123 | 124 | // resolve the packet ids from the constants in the given class 125 | var protocolInfoFields = Reflexion.on(this.targetClass).findFields(PROTOCOL_INFO_MATCHER); 126 | for (var protocolInfoField : protocolInfoFields) { 127 | // get the details from the protocol info 128 | var protocolInfo = protocolInfoField.getValue().get(); 129 | var details = Reflexion.onBound(protocolInfo) 130 | .findMethod("details") 131 | .flatMap(accessor -> accessor.invoke().asOptional()) 132 | .orElseThrow(); 133 | 134 | // resolve the packet list debug method & flow method 135 | var detailsReflexion = Reflexion.onBound(details); 136 | var listPacketsMethod = detailsReflexion.findMethod(LIST_PACKETS_MATCHER).orElseThrow(); 137 | var flow = detailsReflexion 138 | .findMethod("flow") 139 | .flatMap(accessor -> accessor.invoke().asOptional()) 140 | .orElseThrow(); 141 | 142 | // convert the packet flow, register the packet type to id mapping for the flow 143 | var convertedFlow = this.resolveFlowFromBuilderType(flow.toString()); 144 | if (convertedFlow != null) { 145 | var typeToId = new HashMap(); 146 | var packetVisitorImplGenerator = new PacketVisitorImplGenerator(packetVisitorClass, typeToId); 147 | var packetVisitorImpl = packetVisitorImplGenerator.generatePacketVisitor(); 148 | var ignored = listPacketsMethod.invokeWithArgs(packetVisitorImpl).getOrThrow(); 149 | result.put(convertedFlow, typeToId); 150 | } 151 | } 152 | 153 | return result; 154 | } 155 | 156 | private void doMapTypes( 157 | @NonNull Map lambdas, 158 | @Nullable Map.Entry protocolInfo, 159 | @NonNull Map>> target 160 | ) throws Exception { 161 | if (protocolInfo != null) { 162 | var lambda = lambdas.get(protocolInfo.getValue()); 163 | var flow = this.resolveFlowFromBuilderType(protocolInfo.getKey()); 164 | if (flow != null && lambda != null) { 165 | var packetTypeMappings = this.resolvePacketTypes(lambda); 166 | target.put(flow, packetTypeMappings); 167 | } 168 | } 169 | } 170 | 171 | private @NonNull Map> resolvePacketTypes(@NonNull MethodNode methodNode) throws Exception { 172 | var instructions = methodNode.instructions; 173 | Map> packetTypes = new IdentityHashMap<>(); 174 | 175 | var bundle = false; // bundle packets are registered differently 176 | Class currentPacketClass = null; 177 | 178 | var current = instructions.getLast(); 179 | while (current != null) { 180 | var currentlyBundle = bundle; 181 | switch (current) { 182 | case FieldInsnNode fn when fn.desc.equals(STREAM_CODEC_DESC) -> 183 | // first call must be the call to the codec in the packet class 184 | currentPacketClass = this.loadClassByInternalName(fn.owner); 185 | 186 | case FieldInsnNode fn when fn.desc.equals(PACKET_TYPE_DESC) -> { 187 | // second call must be to the packet type associated with the packet class 188 | Objects.requireNonNull(currentPacketClass, "found packet type access without packet class before"); 189 | 190 | var typeHolderClass = this.loadClassByInternalName(fn.owner); 191 | var typeField = typeHolderClass.getField(fn.name); 192 | var packetType = typeField.get(null); 193 | 194 | packetTypes.put(packetType, currentPacketClass); 195 | bundle = false; 196 | currentPacketClass = null; 197 | } 198 | 199 | case MethodInsnNode mn when mn.name.equals("withBundlePacket") -> 200 | // special case: bundle packets are registered differently into the builder 201 | // than normal packets, set this marker to notify other handlers 202 | bundle = true; 203 | 204 | case MethodInsnNode mn when mn.name.equals("") && currentlyBundle -> { 205 | // when a bundle is registered, a special packet construction is made to the packet that indicates 206 | // to the client that a bundle starts. This is the packet we're recording here which needs to be 207 | // registered separately as the packet type never shows up elsewhere after. 208 | // The class has a type() method which we can use to get the packet type from the class 209 | var bundleDelimiterClass = this.loadClassByInternalName(mn.owner); 210 | var bundleDelimiterPacketType = this.findPacketTypeOfPacket(mn.owner); 211 | packetTypes.put(bundleDelimiterPacketType, bundleDelimiterClass); 212 | } 213 | 214 | case InvokeDynamicInsnNode idn when idn.name.equals("apply") && currentlyBundle -> { 215 | // bundle packet type are registered with a function to construct the target packet type 216 | // therefore the information about the target packet class is directly encoded into the 217 | // target handle of the invokedynamic instruction, just resolve the class from that 218 | var invokeHandle = this.findHandle(idn); 219 | Objects.requireNonNull(invokeHandle, "unable to find target packet handle during bundle registration"); 220 | currentPacketClass = this.loadClassByInternalName(invokeHandle.getOwner()); 221 | } 222 | 223 | default -> { 224 | // ignored node 225 | } 226 | } 227 | 228 | current = current.getPrevious(); 229 | } 230 | 231 | return packetTypes; 232 | } 233 | 234 | private @Nullable Map.Entry resolveProtocolInvocationInfo( 235 | @NonNull MethodNode owner, 236 | @Nullable InvokeDynamicInsnNode node 237 | ) { 238 | if (node == null) { 239 | return null; 240 | } 241 | 242 | // invoke target not found 243 | var invokeTarget = this.findHandle(node); 244 | if (invokeTarget == null) { 245 | return null; 246 | } 247 | 248 | // next token should be the invocation of the ProtocolInfoBuilder.xxx method 249 | var invokingMethod = this.findNodeOfType(MethodInsnNode.class, owner, node); 250 | if (invokingMethod == null) { 251 | return null; 252 | } 253 | 254 | // map method name and invoke target name 255 | var methodName = invokingMethod.name; 256 | var invokeTargetName = invokeTarget.getName(); 257 | return Map.entry(methodName, invokeTargetName); 258 | } 259 | 260 | private @NonNull Object findPacketTypeOfPacket(@NonNull String internalPacketClassName) throws Exception { 261 | var classNode = this.decodeClassByInternalName(internalPacketClassName); 262 | for (var method : classNode.methods) { 263 | if (method.name.equals("type") && method.desc.startsWith("()")) { 264 | var fieldInsnNode = this.findNodeOfType(FieldInsnNode.class, method, null); 265 | if (fieldInsnNode != null) { 266 | var typeHolderClass = this.loadClassByInternalName(fieldInsnNode.owner); 267 | var typeField = typeHolderClass.getField(fieldInsnNode.name); 268 | return typeField.get(null); 269 | } 270 | } 271 | } 272 | 273 | throw new IllegalStateException("cannot resolve packet type from packet class " + internalPacketClassName); 274 | } 275 | 276 | private @NonNull ClassNode decodeTargetClass() throws IOException { 277 | var classFileName = this.targetClass.getName().replace('.', '/'); 278 | return this.decodeClassByInternalName(classFileName); 279 | } 280 | 281 | private @NonNull ClassNode decodeClassByInternalName(@NonNull String internalName) throws IOException { 282 | try (var classFileStream = this.mcClassLoader.getResourceAsStream(internalName + ".class")) { 283 | Objects.requireNonNull(classFileStream, "Class file not found: " + internalName); 284 | var reader = new ClassReader(classFileStream); 285 | 286 | var classNode = new ClassNode(); 287 | reader.accept(classNode, 0); 288 | return classNode; 289 | } 290 | } 291 | 292 | private @Nullable MethodNode findClinit(@NonNull ClassNode classNode) { 293 | for (var method : classNode.methods) { 294 | if (method.name.equals("")) { 295 | return method; 296 | } 297 | } 298 | 299 | return null; 300 | } 301 | 302 | private @Nullable McPacketFlow resolveFlowFromBuilderType(@NonNull String name) { 303 | var lower = name.toLowerCase(Locale.ROOT); 304 | if (lower.contains("serverbound")) { 305 | return McPacketFlow.SERVERBOUND; 306 | } 307 | if (lower.contains("clientbound")) { 308 | return McPacketFlow.CLIENTBOUND; 309 | } 310 | 311 | return null; 312 | } 313 | 314 | private @NonNull Map resolveLambdaMethods(@NonNull ClassNode classNode) { 315 | Map lambdaMethods = new HashMap<>(); 316 | for (var method : classNode.methods) { 317 | if (method.name.startsWith("lambda$static$")) { 318 | lambdaMethods.put(method.name, method); 319 | } 320 | } 321 | 322 | return lambdaMethods; 323 | } 324 | 325 | private @Nullable T findNodeOfType( 326 | @NonNull Class type, 327 | @NonNull MethodNode methodNode, 328 | @Nullable AbstractInsnNode after 329 | ) { 330 | return this.findNodeOfType(type, methodNode, after, ignored -> true); 331 | } 332 | 333 | private @Nullable T findNodeOfType( 334 | @NonNull Class type, 335 | @NonNull MethodNode methodNode, 336 | @Nullable AbstractInsnNode after, 337 | @NonNull Predicate filter 338 | ) { 339 | // either start from the top or from the next node of the insn we want to start after 340 | AbstractInsnNode start; 341 | if (after == null) { 342 | start = methodNode.instructions.getFirst(); 343 | } else { 344 | start = after.getNext(); 345 | } 346 | 347 | AbstractInsnNode current = start; 348 | do { 349 | // either because current.next is null or after.next was null 350 | if (current == null) { 351 | return null; 352 | } 353 | 354 | if (current.getClass() == type) { 355 | var node = type.cast(current); 356 | if (filter.test(node)) { 357 | return node; 358 | } 359 | } 360 | 361 | current = current.getNext(); 362 | } while (true); 363 | } 364 | 365 | private @Nullable Handle findHandle(@NonNull InvokeDynamicInsnNode node) { 366 | for (var arg : node.bsmArgs) { 367 | if (arg instanceof Handle handle) { 368 | return handle; 369 | } 370 | } 371 | return null; 372 | } 373 | 374 | 375 | private @NonNull Class loadClassByInternalName(@NonNull String internalName) throws Exception { 376 | var javaClassName = internalName.replace('/', '.'); 377 | return Class.forName(javaClassName, true, this.mcClassLoader); 378 | } 379 | } 380 | -------------------------------------------------------------------------------- /checkstyle.xml: -------------------------------------------------------------------------------- 1 | 2 | 25 | 26 | 29 | 30 | 31 | 32 | 33 | 34 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 81 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 106 | 107 | 108 | 110 | 111 | 112 | 118 | 119 | 120 | 121 | 122 | 125 | 126 | 127 | 128 | 129 | 133 | 134 | 135 | 136 | 137 | 139 | 140 | 141 | 144 | 145 | 146 | 148 | 150 | 151 | 152 | 153 | 154 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 210 | 211 | 212 | 213 | 215 | 217 | 218 | 219 | 221 | 222 | 223 | 224 | 226 | 227 | 228 | 229 | 231 | 232 | 233 | 234 | 236 | 237 | 238 | 239 | 241 | 242 | 243 | 244 | 246 | 247 | 248 | 249 | 251 | 252 | 253 | 254 | 256 | 257 | 258 | 259 | 261 | 262 | 263 | 264 | 266 | 267 | 268 | 269 | 271 | 272 | 273 | 274 | 275 | 277 | 279 | 281 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 296 | 297 | 298 | 301 | 302 | 303 | 304 | 310 | 311 | 312 | 313 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 10 | 16 | 23 | 603 | --------------------------------------------------------------------------------