├── .github ├── ISSUE_TEMPLATE │ ├── blank.md │ ├── config.yml │ └── version-request.yml └── workflows │ ├── automatic_release.yml │ ├── on_issue_version_request.yml │ └── sniffcraft_build.yml ├── .gitignore ├── .gitmodules ├── 3rdparty └── glad │ ├── include │ ├── KHR │ │ └── khrplatform.h │ └── glad │ │ └── glad.h │ └── src │ └── glad.c ├── CMakeLists.txt ├── LICENSE ├── README.md ├── cmake ├── asio.cmake ├── botcraft.cmake ├── glad.cmake ├── glfw.cmake ├── imgui.cmake ├── opengl.cmake ├── openssl.cmake └── zlib.cmake ├── conf ├── custom.json ├── default.json └── no_spam.json └── sniffcraft ├── CMakeLists.txt ├── include └── sniffcraft │ ├── BaseProxy.hpp │ ├── Compression.hpp │ ├── Connection.hpp │ ├── DataProcessor.hpp │ ├── LogItem.hpp │ ├── Logger.hpp │ ├── MinecraftEncryptionDataProcessor.hpp │ ├── MinecraftProxy.hpp │ ├── NetworkRecapItem.hpp │ ├── PacketUtilities.hpp │ ├── ReplayModLogger.hpp │ ├── Zip │ ├── DosTime.hpp │ └── ZeptoZip.hpp │ ├── conf.hpp │ ├── enums.hpp │ └── server.hpp └── src ├── BaseProxy.cpp ├── Compression.cpp ├── Connection.cpp ├── Logger.cpp ├── MinecraftEncryptionDataProcessor.cpp ├── MinecraftProxy.cpp ├── ReplayModLogger.cpp ├── Zip └── ZeptoZip.cpp ├── conf.cpp ├── main.cpp └── server.cpp /.github/ISSUE_TEMPLATE/blank.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Standard issue 3 | about: "Use this issue template for anything else than requesting binaries for a specific version" 4 | --- 5 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: true 2 | contact_links: 3 | - name: Discord Server 4 | url: https://discord.gg/wECVsTbjA9 5 | about: Community Discord server for Botcraft and SniffCraft projects 6 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/version-request.yml: -------------------------------------------------------------------------------- 1 | name: Precompiled binaries version request 2 | description: Use this template to automatically trigger binaries compilation for a specific Minecraft version. 3 | title: "[Version request]" 4 | labels: ["version request"] 5 | 6 | body: 7 | - type: dropdown 8 | id: version 9 | attributes: 10 | label: Minecraft version 11 | description: Which version of Minecraft do you want binaries for? 12 | options: 13 | - "1.12.2" 14 | - "1.13" 15 | - "1.13.1" 16 | - "1.13.2" 17 | - "1.14" 18 | - "1.14.1" 19 | - "1.14.2" 20 | - "1.14.3" 21 | - "1.14.4" 22 | - "1.15" 23 | - "1.15.1" 24 | - "1.15.2" 25 | - "1.16" 26 | - "1.16.1" 27 | - "1.16.2" 28 | - "1.16.3" 29 | - "1.16.4" 30 | - "1.16.5" 31 | - "1.17" 32 | - "1.17.1" 33 | - "1.18" 34 | - "1.18.1" 35 | - "1.18.2" 36 | - "1.19" 37 | - "1.19.1" 38 | - "1.19.2" 39 | - "1.19.3" 40 | - "1.19.4" 41 | - "1.20" 42 | - "1.20.1" 43 | - "1.20.2" 44 | - "1.20.3" 45 | - "1.20.4" 46 | - "1.20.5" 47 | - "1.20.6" 48 | - "1.21" 49 | - "1.21.1" 50 | - "1.21.2" 51 | - "1.21.3" 52 | - "1.21.4" 53 | - "1.21.5" 54 | validations: 55 | required: true -------------------------------------------------------------------------------- /.github/workflows/automatic_release.yml: -------------------------------------------------------------------------------- 1 | name: Automatic Release 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | paths-ignore: 8 | - 'README.md' 9 | - '.gitignore' 10 | - 'LICENSE' 11 | 12 | 13 | jobs: 14 | build_os_matrix: 15 | name: ${{ matrix.config.name }} 16 | strategy: 17 | fail-fast: false 18 | matrix: 19 | config: 20 | - { 21 | name: Windows, 22 | os: windows-latest 23 | } 24 | - { 25 | name: Linux, 26 | os: ubuntu-latest 27 | } 28 | - { 29 | name: macOS, 30 | os: macos-latest 31 | } 32 | uses: ./.github/workflows/sniffcraft_build.yml 33 | with: 34 | os: ${{ matrix.config.os }} 35 | 36 | 37 | release: 38 | runs-on: ubuntu-latest 39 | needs: 40 | - build_os_matrix 41 | steps: 42 | - uses: actions/checkout@v4 43 | with: 44 | fetch-depth: 0 45 | 46 | - name: Download Linux artifact 47 | uses: actions/download-artifact@v4 48 | with: 49 | name: sniffcraft-Linux 50 | path: linux 51 | 52 | - name: Download Windows artifact 53 | uses: actions/download-artifact@v4 54 | with: 55 | name: sniffcraft-Windows 56 | path: windows 57 | 58 | - name: Download macOS artifact 59 | uses: actions/download-artifact@v4 60 | with: 61 | name: sniffcraft-macOS 62 | path: macos 63 | 64 | - name: Download version artifact 65 | uses: actions/download-artifact@v4 66 | with: 67 | name: MC-version 68 | path: version 69 | 70 | - name: Retrieve MC game version 71 | id: mc-version 72 | run: echo "version=$(cat version/version.txt)" >> $GITHUB_OUTPUT 73 | 74 | - name: Create release note 75 | run: | 76 | echo Automatically generated binaries with GUI support for Minecraft ${{ steps.mc-version.outputs.version }}. > release_note.txt 77 | echo -en '\n' >> release_note.txt 78 | echo "Examples of conf files can be found [here](https://github.com/${{ github.repository }}/tree/master/conf)." >> release_note.txt 79 | echo -en '\n' >> release_note.txt 80 | echo "💡 If you need binaries for a previous version of Minecraft, you can open [an issue using this link](https://github.com/${{ github.repository }}/issues/new?assignees=&labels=version+request&template=version-request.yml&title=%5BVersion+request%5D) and it will be automagically generated for you in a few minutes." >> release_note.txt 81 | echo -en '\n' >> release_note.txt 82 | echo **Changes:** >> release_note.txt 83 | 84 | - name: Append git commits 85 | run: git log latest..HEAD --oneline --no-merges >> release_note.txt 86 | 87 | - name: Rename artifacts 88 | run: | 89 | mv linux/sniffcraft sniffcraft-linux-${{ steps.mc-version.outputs.version }} 90 | mv windows/sniffcraft.exe sniffcraft-windows-${{ steps.mc-version.outputs.version }}.exe 91 | mv macos/sniffcraft sniffcraft-macos-${{ steps.mc-version.outputs.version }} 92 | 93 | - name: Remove old latest release 94 | run: gh release delete latest --repo ${{ github.repository }} --cleanup-tag -y 95 | env: 96 | GH_TOKEN: ${{ github.token }} 97 | 98 | - name: Create new latest release 99 | run: > 100 | gh release create latest 101 | sniffcraft-linux-${{ steps.mc-version.outputs.version }} 102 | sniffcraft-windows-${{ steps.mc-version.outputs.version }}.exe 103 | sniffcraft-macos-${{ steps.mc-version.outputs.version }} 104 | --repo ${{ github.repository }} 105 | --latest 106 | -F release_note.txt 107 | -t Latest 108 | env: 109 | GH_TOKEN: ${{ github.token }} 110 | -------------------------------------------------------------------------------- /.github/workflows/on_issue_version_request.yml: -------------------------------------------------------------------------------- 1 | name: Build version on issue request 2 | 3 | on: 4 | issues: 5 | types: [opened, reopened] 6 | 7 | concurrency: 8 | group: ${{ github.workflow }} 9 | 10 | jobs: 11 | check_if_build_needed: 12 | runs-on: ubuntu-latest 13 | outputs: 14 | is_valid_request: ${{ steps.check.outputs.is_valid_request }} 15 | version: ${{ steps.retrieve.outputs.version }} 16 | value: ${{ steps.exist.outputs.value }} 17 | steps: 18 | - id: check 19 | name: Check if issue is a request 20 | run: echo "is_valid_request=${{ startsWith(github.event.issue.title, '[Version request]') }}" >> $GITHUB_OUTPUT 21 | 22 | - id: retrieve 23 | name: Retrieve the version from body 24 | if: ${{ steps.check.outputs.is_valid_request == 'true' }} 25 | env: 26 | BODY: ${{ github.event.issue.body }} 27 | run: echo "version="$(echo "$BODY" | tail -n1) >> $GITHUB_OUTPUT 28 | 29 | - id: exist 30 | name: Check if version already exists in release 31 | if: ${{ steps.check.outputs.is_valid_request == 'true' }} 32 | run: echo "value="$(gh release view latest --repo ${{ github.repository }} --json assets -q "[.assets.[].name | select(endswith(\"${{ steps.retrieve.outputs.version }}\"))] | length") >> $GITHUB_OUTPUT 33 | env: 34 | GH_TOKEN: ${{ github.token }} 35 | 36 | 37 | os_matrix: 38 | needs: check_if_build_needed 39 | name: ${{ matrix.config.name }} 40 | if: ${{ needs.check_if_build_needed.outputs.is_valid_request == 'true' && needs.check_if_build_needed.outputs.value == 0 }} 41 | secrets: inherit 42 | strategy: 43 | fail-fast: false 44 | matrix: 45 | config: 46 | - { 47 | name: Windows, 48 | os: windows-latest 49 | } 50 | - { 51 | name: Linux, 52 | os: ubuntu-latest 53 | } 54 | - { 55 | name: MacOS, 56 | os: macos-latest 57 | } 58 | uses: ./.github/workflows/sniffcraft_build.yml 59 | with: 60 | os: ${{ matrix.config.os }} 61 | version: ${{ needs.check_if_build_needed.outputs.version }} 62 | issue: ${{ github.event.issue.html_url }} 63 | 64 | 65 | notify_build_started: 66 | runs-on: ubuntu-latest 67 | needs: check_if_build_needed 68 | if: ${{ needs.check_if_build_needed.outputs.is_valid_request == 'true' && needs.check_if_build_needed.outputs.value == 0 }} 69 | steps: 70 | - name: Notify issue 71 | run: gh issue comment ${{ github.event.issue.html_url }} --repo ${{ github.repository }} -b "Build process started. You can follow the build progress [here](https://github.com/${{ github.repository }}/actions) or subscribe to this issue to be notified when binaries are ready." 72 | env: 73 | GH_TOKEN: ${{ github.token }} 74 | 75 | 76 | notify_already_exists: 77 | runs-on: ubuntu-latest 78 | needs: check_if_build_needed 79 | if: ${{ needs.check_if_build_needed.outputs.is_valid_request == 'true' && needs.check_if_build_needed.outputs.value != 0 }} 80 | steps: 81 | - name: Notify issue 82 | run: | 83 | echo "Binaries for ${{ needs.check_if_build_needed.outputs.version }} are already available in the [latest release](https://github.com/${{ github.repository }}/releases/tag/latest)." > body.txt 84 | echo -en '\n' >> body.txt 85 | echo You can close this issue. If you need an updated build for the same Minecraft version in the future, you can reopen this issue to trigger a new build instead of creating a new one. >> body.txt 86 | gh issue comment ${{ github.event.issue.html_url }} --repo ${{ github.repository }} --body-file body.txt 87 | env: 88 | GH_TOKEN: ${{ github.token }} 89 | 90 | 91 | update_release: 92 | runs-on: ubuntu-latest 93 | needs: 94 | - check_if_build_needed 95 | - os_matrix 96 | - notify_build_started 97 | steps: 98 | - name: Download Linux artifact 99 | uses: actions/download-artifact@v4 100 | with: 101 | name: sniffcraft-Linux 102 | path: linux 103 | 104 | - name: Download Windows artifact 105 | uses: actions/download-artifact@v4 106 | with: 107 | name: sniffcraft-Windows 108 | path: windows 109 | 110 | - name: Download macOS artifact 111 | uses: actions/download-artifact@v4 112 | with: 113 | name: sniffcraft-macOS 114 | path: macos 115 | 116 | - name: Rename artifacts 117 | run: | 118 | mv linux/sniffcraft sniffcraft-linux-${{ needs.check_if_build_needed.outputs.version }} 119 | mv windows/sniffcraft.exe sniffcraft-windows-${{ needs.check_if_build_needed.outputs.version }}.exe 120 | mv macos/sniffcraft sniffcraft-macos-${{ needs.check_if_build_needed.outputs.version }} 121 | 122 | - name: Upload files to release 123 | run: > 124 | gh release upload latest 125 | sniffcraft-linux-${{ needs.check_if_build_needed.outputs.version }} 126 | sniffcraft-windows-${{ needs.check_if_build_needed.outputs.version }}.exe 127 | sniffcraft-macos-${{ needs.check_if_build_needed.outputs.version }} 128 | --repo ${{ github.repository }} 129 | env: 130 | GH_TOKEN: ${{ github.token }} 131 | 132 | - name: Comment on associated issue 133 | run: | 134 | echo "New binaries available in the [latest release](https://github.com/${{ github.repository }}/releases/tag/latest) for version ${{ needs.check_if_build_needed.outputs.version }}" > body.txt 135 | echo -en '\n' >> body.txt 136 | echo You can now close this issue. If you need an updated build for the same Minecraft version in the future, you can reopen this issue to trigger a new build instead of creating a new issue. >> body.txt 137 | gh issue comment ${{ github.event.issue.html_url }} --repo ${{ github.repository }} --body-file body.txt 138 | env: 139 | GH_TOKEN: ${{ github.token }} 140 | -------------------------------------------------------------------------------- /.github/workflows/sniffcraft_build.yml: -------------------------------------------------------------------------------- 1 | name: Sniffcraft Build 2 | 3 | on: 4 | workflow_call: 5 | inputs: 6 | os: 7 | description: OS we want to build for 8 | required: true 9 | type: string 10 | version: 11 | description: Minecraft Version 12 | required: false 13 | default: latest 14 | type: string 15 | issue: 16 | description: URL of the issue requesting this build 17 | required: false 18 | default: "" 19 | type: string 20 | 21 | env: 22 | BUILD_TYPE: Release 23 | CMAKE_GENERATOR: ${{ inputs.os == 'windows-latest' && 'Visual Studio 17 2022' || 'Unix Makefiles' }} 24 | VERSION: ${{ inputs.version }} 25 | ISSUE_URL: ${{ inputs.issue }} 26 | 27 | jobs: 28 | build: 29 | runs-on: ${{ inputs.os }} 30 | 31 | steps: 32 | - uses: actions/checkout@v4 33 | with: 34 | fetch-depth: 1 35 | 36 | - name: Install Linux deps 37 | if: runner.os == 'Linux' 38 | run: | 39 | sudo apt update 40 | sudo apt install -y libwayland-dev libxkbcommon-dev xorg-dev 41 | 42 | - name: Create build folder 43 | run: cmake -E make_directory ${{ runner.workspace }}/build 44 | 45 | - name: Set environment variable for macOS 46 | if: ${{ inputs.os == 'macos-latest' }} 47 | run: echo "CMAKE_OSX_ARCHITECTURES=arm64;x86_64" >> $GITHUB_ENV 48 | 49 | - name: Configure cmake 50 | shell: bash 51 | working-directory: ${{ runner.workspace }}/build 52 | run: > 53 | cmake -G "$CMAKE_GENERATOR" 54 | -DCMAKE_BUILD_TYPE=$BUILD_TYPE 55 | -DGAME_VERSION="$VERSION" 56 | -DSNIFFCRAFT_WITH_ENCRYPTION=ON 57 | -DSNIFFCRAFT_FORCE_LOCAL_ZLIB=ON 58 | -DSNIFFCRAFT_FORCE_LOCAL_OPENSSL=ON 59 | -DSNIFFCRAFT_WITH_GUI=ON 60 | -S $GITHUB_WORKSPACE 61 | -B . 62 | 63 | - name: Upload version artifact 64 | if: runner.os == 'Linux' 65 | uses: actions/upload-artifact@v4 66 | with: 67 | name: MC-version 68 | path: ${{ runner.workspace }}/build/version.txt 69 | retention-days: 1 70 | 71 | - name: Build all 72 | shell: bash 73 | id: build 74 | working-directory: ${{ runner.workspace }}/build 75 | run: cmake --build . --config $BUILD_TYPE --parallel 2 76 | 77 | - name: Notify issue if build failed 78 | if: failure() && steps.build.conclusion == 'failure' && inputs.issue 79 | shell: bash 80 | run: | 81 | echo "${{ runner.os }} build failed. Logs can be found [here](https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }})." > body.txt 82 | echo -en '\n' >> body.txt 83 | echo -en '\n' >> body.txt 84 | echo @${{ github.repository_owner }} you might want to take a look. >> body.txt 85 | gh issue comment $ISSUE_URL --repo ${{ github.repository }} --body-file body.txt 86 | env: 87 | GH_TOKEN: ${{ github.token }} 88 | 89 | - name: Upload artifact 90 | uses: actions/upload-artifact@v4 91 | with: 92 | name: sniffcraft-${{ runner.os }} 93 | path: ${{ github.workspace }}/bin/sniffcraft* 94 | retention-days: 1 95 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | bin/ 2 | build/ 3 | lib/ -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "3rdparty/asio"] 2 | path = 3rdparty/asio 3 | url = https://github.com/chriskohlhoff/asio.git 4 | [submodule "3rdparty/botcraft"] 5 | path = 3rdparty/botcraft 6 | url = https://github.com/adepierre/Botcraft.git 7 | [submodule "3rdparty/zlib"] 8 | path = 3rdparty/zlib 9 | url = https://github.com/madler/zlib.git 10 | [submodule "3rdparty/openssl"] 11 | path = 3rdparty/openssl 12 | url = https://github.com/janbar/openssl-cmake 13 | -------------------------------------------------------------------------------- /3rdparty/glad/include/KHR/khrplatform.h: -------------------------------------------------------------------------------- 1 | #ifndef __khrplatform_h_ 2 | #define __khrplatform_h_ 3 | 4 | /* 5 | ** Copyright (c) 2008-2018 The Khronos Group Inc. 6 | ** 7 | ** Permission is hereby granted, free of charge, to any person obtaining a 8 | ** copy of this software and/or associated documentation files (the 9 | ** "Materials"), to deal in the Materials without restriction, including 10 | ** without limitation the rights to use, copy, modify, merge, publish, 11 | ** distribute, sublicense, and/or sell copies of the Materials, and to 12 | ** permit persons to whom the Materials are furnished to do so, subject to 13 | ** the following conditions: 14 | ** 15 | ** The above copyright notice and this permission notice shall be included 16 | ** in all copies or substantial portions of the Materials. 17 | ** 18 | ** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 19 | ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 20 | ** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 21 | ** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | ** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 23 | ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 24 | ** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. 25 | */ 26 | 27 | /* Khronos platform-specific types and definitions. 28 | * 29 | * The master copy of khrplatform.h is maintained in the Khronos EGL 30 | * Registry repository at https://github.com/KhronosGroup/EGL-Registry 31 | * The last semantic modification to khrplatform.h was at commit ID: 32 | * 67a3e0864c2d75ea5287b9f3d2eb74a745936692 33 | * 34 | * Adopters may modify this file to suit their platform. Adopters are 35 | * encouraged to submit platform specific modifications to the Khronos 36 | * group so that they can be included in future versions of this file. 37 | * Please submit changes by filing pull requests or issues on 38 | * the EGL Registry repository linked above. 39 | * 40 | * 41 | * See the Implementer's Guidelines for information about where this file 42 | * should be located on your system and for more details of its use: 43 | * http://www.khronos.org/registry/implementers_guide.pdf 44 | * 45 | * This file should be included as 46 | * #include 47 | * by Khronos client API header files that use its types and defines. 48 | * 49 | * The types in khrplatform.h should only be used to define API-specific types. 50 | * 51 | * Types defined in khrplatform.h: 52 | * khronos_int8_t signed 8 bit 53 | * khronos_uint8_t unsigned 8 bit 54 | * khronos_int16_t signed 16 bit 55 | * khronos_uint16_t unsigned 16 bit 56 | * khronos_int32_t signed 32 bit 57 | * khronos_uint32_t unsigned 32 bit 58 | * khronos_int64_t signed 64 bit 59 | * khronos_uint64_t unsigned 64 bit 60 | * khronos_intptr_t signed same number of bits as a pointer 61 | * khronos_uintptr_t unsigned same number of bits as a pointer 62 | * khronos_ssize_t signed size 63 | * khronos_usize_t unsigned size 64 | * khronos_float_t signed 32 bit floating point 65 | * khronos_time_ns_t unsigned 64 bit time in nanoseconds 66 | * khronos_utime_nanoseconds_t unsigned time interval or absolute time in 67 | * nanoseconds 68 | * khronos_stime_nanoseconds_t signed time interval in nanoseconds 69 | * khronos_boolean_enum_t enumerated boolean type. This should 70 | * only be used as a base type when a client API's boolean type is 71 | * an enum. Client APIs which use an integer or other type for 72 | * booleans cannot use this as the base type for their boolean. 73 | * 74 | * Tokens defined in khrplatform.h: 75 | * 76 | * KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values. 77 | * 78 | * KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0. 79 | * KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0. 80 | * 81 | * Calling convention macros defined in this file: 82 | * KHRONOS_APICALL 83 | * KHRONOS_APIENTRY 84 | * KHRONOS_APIATTRIBUTES 85 | * 86 | * These may be used in function prototypes as: 87 | * 88 | * KHRONOS_APICALL void KHRONOS_APIENTRY funcname( 89 | * int arg1, 90 | * int arg2) KHRONOS_APIATTRIBUTES; 91 | */ 92 | 93 | #if defined(__SCITECH_SNAP__) && !defined(KHRONOS_STATIC) 94 | # define KHRONOS_STATIC 1 95 | #endif 96 | 97 | /*------------------------------------------------------------------------- 98 | * Definition of KHRONOS_APICALL 99 | *------------------------------------------------------------------------- 100 | * This precedes the return type of the function in the function prototype. 101 | */ 102 | #if defined(KHRONOS_STATIC) 103 | /* If the preprocessor constant KHRONOS_STATIC is defined, make the 104 | * header compatible with static linking. */ 105 | # define KHRONOS_APICALL 106 | #elif defined(_WIN32) 107 | # define KHRONOS_APICALL __declspec(dllimport) 108 | #elif defined (__SYMBIAN32__) 109 | # define KHRONOS_APICALL IMPORT_C 110 | #elif defined(__ANDROID__) 111 | # define KHRONOS_APICALL __attribute__((visibility("default"))) 112 | #else 113 | # define KHRONOS_APICALL 114 | #endif 115 | 116 | /*------------------------------------------------------------------------- 117 | * Definition of KHRONOS_APIENTRY 118 | *------------------------------------------------------------------------- 119 | * This follows the return type of the function and precedes the function 120 | * name in the function prototype. 121 | */ 122 | #if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__) 123 | /* Win32 but not WinCE */ 124 | # define KHRONOS_APIENTRY __stdcall 125 | #else 126 | # define KHRONOS_APIENTRY 127 | #endif 128 | 129 | /*------------------------------------------------------------------------- 130 | * Definition of KHRONOS_APIATTRIBUTES 131 | *------------------------------------------------------------------------- 132 | * This follows the closing parenthesis of the function prototype arguments. 133 | */ 134 | #if defined (__ARMCC_2__) 135 | #define KHRONOS_APIATTRIBUTES __softfp 136 | #else 137 | #define KHRONOS_APIATTRIBUTES 138 | #endif 139 | 140 | /*------------------------------------------------------------------------- 141 | * basic type definitions 142 | *-----------------------------------------------------------------------*/ 143 | #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__) 144 | 145 | 146 | /* 147 | * Using 148 | */ 149 | #include 150 | typedef int32_t khronos_int32_t; 151 | typedef uint32_t khronos_uint32_t; 152 | typedef int64_t khronos_int64_t; 153 | typedef uint64_t khronos_uint64_t; 154 | #define KHRONOS_SUPPORT_INT64 1 155 | #define KHRONOS_SUPPORT_FLOAT 1 156 | /* 157 | * To support platform where unsigned long cannot be used interchangeably with 158 | * inptr_t (e.g. CHERI-extended ISAs), we can use the stdint.h intptr_t. 159 | * Ideally, we could just use (u)intptr_t everywhere, but this could result in 160 | * ABI breakage if khronos_uintptr_t is changed from unsigned long to 161 | * unsigned long long or similar (this results in different C++ name mangling). 162 | * To avoid changes for existing platforms, we restrict usage of intptr_t to 163 | * platforms where the size of a pointer is larger than the size of long. 164 | */ 165 | #if defined(__SIZEOF_LONG__) && defined(__SIZEOF_POINTER__) 166 | #if __SIZEOF_POINTER__ > __SIZEOF_LONG__ 167 | #define KHRONOS_USE_INTPTR_T 168 | #endif 169 | #endif 170 | 171 | #elif defined(__VMS ) || defined(__sgi) 172 | 173 | /* 174 | * Using 175 | */ 176 | #include 177 | typedef int32_t khronos_int32_t; 178 | typedef uint32_t khronos_uint32_t; 179 | typedef int64_t khronos_int64_t; 180 | typedef uint64_t khronos_uint64_t; 181 | #define KHRONOS_SUPPORT_INT64 1 182 | #define KHRONOS_SUPPORT_FLOAT 1 183 | 184 | #elif defined(_WIN32) && !defined(__SCITECH_SNAP__) 185 | 186 | /* 187 | * Win32 188 | */ 189 | typedef __int32 khronos_int32_t; 190 | typedef unsigned __int32 khronos_uint32_t; 191 | typedef __int64 khronos_int64_t; 192 | typedef unsigned __int64 khronos_uint64_t; 193 | #define KHRONOS_SUPPORT_INT64 1 194 | #define KHRONOS_SUPPORT_FLOAT 1 195 | 196 | #elif defined(__sun__) || defined(__digital__) 197 | 198 | /* 199 | * Sun or Digital 200 | */ 201 | typedef int khronos_int32_t; 202 | typedef unsigned int khronos_uint32_t; 203 | #if defined(__arch64__) || defined(_LP64) 204 | typedef long int khronos_int64_t; 205 | typedef unsigned long int khronos_uint64_t; 206 | #else 207 | typedef long long int khronos_int64_t; 208 | typedef unsigned long long int khronos_uint64_t; 209 | #endif /* __arch64__ */ 210 | #define KHRONOS_SUPPORT_INT64 1 211 | #define KHRONOS_SUPPORT_FLOAT 1 212 | 213 | #elif 0 214 | 215 | /* 216 | * Hypothetical platform with no float or int64 support 217 | */ 218 | typedef int khronos_int32_t; 219 | typedef unsigned int khronos_uint32_t; 220 | #define KHRONOS_SUPPORT_INT64 0 221 | #define KHRONOS_SUPPORT_FLOAT 0 222 | 223 | #else 224 | 225 | /* 226 | * Generic fallback 227 | */ 228 | #include 229 | typedef int32_t khronos_int32_t; 230 | typedef uint32_t khronos_uint32_t; 231 | typedef int64_t khronos_int64_t; 232 | typedef uint64_t khronos_uint64_t; 233 | #define KHRONOS_SUPPORT_INT64 1 234 | #define KHRONOS_SUPPORT_FLOAT 1 235 | 236 | #endif 237 | 238 | 239 | /* 240 | * Types that are (so far) the same on all platforms 241 | */ 242 | typedef signed char khronos_int8_t; 243 | typedef unsigned char khronos_uint8_t; 244 | typedef signed short int khronos_int16_t; 245 | typedef unsigned short int khronos_uint16_t; 246 | 247 | /* 248 | * Types that differ between LLP64 and LP64 architectures - in LLP64, 249 | * pointers are 64 bits, but 'long' is still 32 bits. Win64 appears 250 | * to be the only LLP64 architecture in current use. 251 | */ 252 | #ifdef KHRONOS_USE_INTPTR_T 253 | typedef intptr_t khronos_intptr_t; 254 | typedef uintptr_t khronos_uintptr_t; 255 | #elif defined(_WIN64) 256 | typedef signed long long int khronos_intptr_t; 257 | typedef unsigned long long int khronos_uintptr_t; 258 | #else 259 | typedef signed long int khronos_intptr_t; 260 | typedef unsigned long int khronos_uintptr_t; 261 | #endif 262 | 263 | #if defined(_WIN64) 264 | typedef signed long long int khronos_ssize_t; 265 | typedef unsigned long long int khronos_usize_t; 266 | #else 267 | typedef signed long int khronos_ssize_t; 268 | typedef unsigned long int khronos_usize_t; 269 | #endif 270 | 271 | #if KHRONOS_SUPPORT_FLOAT 272 | /* 273 | * Float type 274 | */ 275 | typedef float khronos_float_t; 276 | #endif 277 | 278 | #if KHRONOS_SUPPORT_INT64 279 | /* Time types 280 | * 281 | * These types can be used to represent a time interval in nanoseconds or 282 | * an absolute Unadjusted System Time. Unadjusted System Time is the number 283 | * of nanoseconds since some arbitrary system event (e.g. since the last 284 | * time the system booted). The Unadjusted System Time is an unsigned 285 | * 64 bit value that wraps back to 0 every 584 years. Time intervals 286 | * may be either signed or unsigned. 287 | */ 288 | typedef khronos_uint64_t khronos_utime_nanoseconds_t; 289 | typedef khronos_int64_t khronos_stime_nanoseconds_t; 290 | #endif 291 | 292 | /* 293 | * Dummy value used to pad enum types to 32 bits. 294 | */ 295 | #ifndef KHRONOS_MAX_ENUM 296 | #define KHRONOS_MAX_ENUM 0x7FFFFFFF 297 | #endif 298 | 299 | /* 300 | * Enumerated boolean type 301 | * 302 | * Values other than zero should be considered to be true. Therefore 303 | * comparisons should not be made against KHRONOS_TRUE. 304 | */ 305 | typedef enum { 306 | KHRONOS_FALSE = 0, 307 | KHRONOS_TRUE = 1, 308 | KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM 309 | } khronos_boolean_enum_t; 310 | 311 | #endif /* __khrplatform_h_ */ 312 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.15) 2 | 3 | project(SniffCraft) 4 | 5 | set_property(GLOBAL PROPERTY USE_FOLDERS ON) 6 | 7 | option(SNIFFCRAFT_WITH_ENCRYPTION "Activate for online mode support" ON) 8 | option(SNIFFCRAFT_WITH_GUI "Activate for GUI support" ON) 9 | option(SNIFFCRAFT_FORCE_LOCAL_ZLIB "Force using a local install of zlib even if already present on the system" OFF) 10 | option(SNIFFCRAFT_FORCE_LOCAL_OPENSSL "Force using a local install of openSSL even if already present on the system" OFF) 11 | 12 | # Add Asio 13 | include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/asio.cmake") 14 | 15 | # Add Zlib 16 | include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/zlib.cmake") 17 | 18 | # Add OpenSSL 19 | if(SNIFFCRAFT_WITH_ENCRYPTION) 20 | include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/openssl.cmake") 21 | endif(SNIFFCRAFT_WITH_ENCRYPTION) 22 | 23 | # Add ProtocolCraft 24 | include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/botcraft.cmake") 25 | 26 | # Add GUI related dependencies 27 | if(SNIFFCRAFT_WITH_GUI) 28 | set(FETCHCONTENT_QUIET TRUE) 29 | include(FetchContent) 30 | include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/glad.cmake") 31 | include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/opengl.cmake") 32 | include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/glfw.cmake") 33 | include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/imgui.cmake") 34 | endif(SNIFFCRAFT_WITH_GUI) 35 | 36 | # Check pthreads 37 | find_package(Threads) 38 | 39 | # Version selection stuffs 40 | set(GAME_VERSION "latest" CACHE STRING "Each version of the game uses a specific protocol. Make sure this matches the version of your server.") 41 | set(GameVersionValues "1.12.2;1.13;1.13.1;1.13.2;1.14;1.14.1;1.14.2;1.14.3;1.14.4;1.15;1.15.1;1.15.2;1.16;1.16.1;1.16.2;1.16.3;1.16.4;1.16.5;1.17;1.17.1;1.18;1.18.1;1.18.2;1.19;1.19.1;1.19.2;1.19.3;1.19.4;1.20;1.20.1;1.20.2;1.20.3;1.20.4;1.20.5;1.20.6;1.21;1.21.1;1.21.2;1.21.3;1.21.4;1.21.5;latest") 42 | set(ProtocolVersionValues "340;393;401;404;477;480;485;490;498;573;575;578;735;736;751;753;754;754;755;756;757;757;758;759;760;760;761;762;763;763;764;765;765;766;766;767;767;768;768;769;770") 43 | set_property(CACHE GAME_VERSION PROPERTY STRINGS ${GameVersionValues}) 44 | 45 | if(GAME_VERSION STREQUAL "latest") 46 | list(GET GameVersionValues -2 GAME_VERSION) 47 | endif() 48 | 49 | list(FIND GameVersionValues ${GAME_VERSION} game_version_index) 50 | list(GET ProtocolVersionValues ${game_version_index} PROTOCOL_VERSION) 51 | message(STATUS "Selected game version: " ${GAME_VERSION} " || Protocol: " ${PROTOCOL_VERSION}) 52 | file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/version.txt" ${GAME_VERSION}) 53 | file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/protocol.txt" ${PROTOCOL_VERSION}) 54 | 55 | 56 | add_subdirectory(3rdparty/botcraft/protocolCraft) 57 | add_subdirectory(sniffcraft) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Build status](https://github.com/adepierre/Sniffcraft/actions/workflows/automatic_release.yml/badge.svg) 2 | [![Discord](https://badgen.net/badge/icon/discord?icon=discord&label)](https://discord.gg/wECVsTbjA9) 3 | 4 | # SniffCraft 5 | 6 | SniffCraft is a cross-platform C++ proxy which let you inspect the content of each packet sent through any minecraft client and server. It can run either with a GUI or in headless mode. 7 | 8 | It works as a man-in-the-middle: instead of connecting directly to the server, you ask your client to connect to SniffCraft which then is connected to the server. All packets are transmitted to their original recipient and are simultaneously logged on-the-fly. 9 | 10 | ``` 11 | ┌────────┐ ┌──────────────┐ ┌────────┐ 12 | │ ├───────► - - - - - - -├───────► │ 13 | │ Client │ │ SniffCraft │ │ Server │ 14 | │ ◄───────┤- - - - - - - ◄───────┤ │ 15 | └────────┘ └──────┬───────┘ └────────┘ 16 | │ 17 | ▼ 18 | Logfile 19 | ``` 20 | 21 | ## Features 22 | 23 | - Supported minecraft versions: all official releases from 1.12.2 to 1.21.5 24 | - GUI mode 25 | - Packet logging with different levels of details (ignore packet, log packet name only, log full packet content) 26 | - Detailed network usage recap 27 | - Compression is supported 28 | - Byte level packet inspection 29 | - Offline ("cracked") mode and online mode (with Microsoft account) are supported 30 | - Secure chat is supported 31 | - Logging raw packets at byte level 32 | - Configuration (which packet to log/ignore) can be changed on-the-fly without restarting 33 | - Automatically create a session file to log information, can also optionally log to console at the same time 34 | - Save full session to binary file and reopen them later in the GUI 35 | - Creating a [replay mod](https://github.com/ReplayMod/ReplayMod) capture of the session is also possible, see [Replay Mod section](#replay-mod) for more details 36 | - No log at all is possible, in this case, SniffCraft becomes a pure proxy that you can adapt to block/modify any packet you want 37 | 38 | 1.20.5 transfer packet is **not** supported yet. 39 | 40 | Sniffcraft GUI 41 | 42 | 43 | ### Encryption is supported 44 | 45 | Encryption is supported by moving the authentication step from the client to Sniffcraft. This means that all the traffic from the client to Sniffcraft is not encrypted, but the traffic between Sniffcraft and the server is. 46 | 47 | There are two options in the conf file regarding authentication. ``Online`` must be true to connect to a server with authentication activated. SniffCraft will prompt you instructions on the console to log in with a Microsoft account (only the first time, will use cached credentials for the next ones, you can cache multiple Microsoft accounts using different ``MicrosoftAccountCacheKey``). 48 | 49 | Depending on the version you are using, there are additional restrictions regarding authentication: 50 | - for versions up to 1.18.2 and 1.19.3+, you can use any client you want ("cracked" or regular with any account) as long as you are authenticated with a valid account in sniffcraft. 51 | - for versions 1.19 to 1.19.2, there are two subcases: 52 | - if the server has the option `enforce-secure-profile` set to false, then it's the same as for the other versions, you can use any client you want. 53 | - if the server has the option `enforce-secure-profile` set to true, then you **must** use a client authenticated with the **same** account you are using in Sniffcraft. Otherwise you will be kicked out for signing key mismatch as soon as you try to send a chat message. 54 | 55 | If you want to be sure Sniffcraft is using the latest certificates for your account (for 1.19+ versions), you can set botcraft_cached_credentials\["TheMicrosoftAccountCacheKeyYouSet"\]\["certificates"\]\["expires_date"\] to 0 and Sniffcraft will then retreive the latest ones from Mojang server. 56 | 57 | ### Mod support 58 | 59 | Sniffcraft has been confirmed to work with heavily modded client/server using Forge. It is however not regularly tested against all possible modded environments and some adjustments might be required in some cases. If you find such a case, please open an issue or join the [community discord server](https://discord.gg/wECVsTbjA9) and describe the usecase with as much details as possible (minecraft version, server IP, client/server mods etc...). 60 | 61 | If you want to print the content of Custom Payload packets (both from client and server), you need to use protocolCraft plugins to extend the protocol knowledge with mod-specific packets. See the [protocolCraft-plugin](https://github.com/adepierre/protocolcraft-plugin) repo for details. 62 | 63 | ## GUI support 64 | 65 | If compiled with the cmake option SNIFFCRAFT_WITH_GUI, a GUI will appear when starting SniffCraft. This can be disabled by launching it with the ``--headless`` command line argument. In GUI mode, packets data are kept in memory while the session is displayed in GUI. This is usually not really an issue for regular usecase. However, if you plan to do some multi-hours long capture sessions or have a lot of sessions running simultaneously, it is recommended to use the ``--headless`` argument (or SniffCraft compiled without GUI enabled). This way, all data will only be stored in files and not in the RAM. SniffCraft binary files (**NOT** text files) can be reimported later in the GUI by simply dragging them onto SniffCraft window. 66 | 67 | ## Dependencies 68 | 69 | You don't have to install any dependency to build SniffCraft, everything that is not already on your system will be automatically downloaded and locally built during the build process. 70 | 71 | - [asio](https://think-async.com/Asio/) 72 | - [zlib](https://github.com/madler/zlib) 73 | - [openssl](https://www.openssl.org/) (optional, only if cmake option SNIFFCRAFT_WITH_ENCRYPTION is set) 74 | - [botcraft](https://github.com/adepierre/botcraft) 75 | 76 | GUI dependencies (only if cmake option SNIFFCRAFT_WITH_GUI is set) 77 | - [glad](https://github.com/Dav1dde/glad) 78 | - [glfw](https://github.com/glfw/glfw) 79 | - [Dear ImGui](https://github.com/ocornut/imgui) 80 | 81 | ## Build and launch 82 | 83 | Precompiled binaries for the latest game version with encryption and GUI support can be found in the [latest release](https://github.com/adepierre/SniffCraft/releases/tag/latest). If you want to build it yourself: 84 | ``` 85 | git clone https://github.com/adepierre/SniffCraft.git 86 | cd SniffCraft 87 | mkdir build 88 | cd build 89 | cmake -DGAME_VERSION=latest -DSNIFFCRAFT_WITH_ENCRYPTION=ON -DSNIFFCRAFT_WITH_GUI=ON .. 90 | cmake --build . --config Release 91 | ``` 92 | 93 | If you need more help, you can join the Sniffcraft/Botcraft community [discord server](https://discord.gg/wECVsTbjA9). 94 | 95 | Once built, you can start SniffCraft by double clicking the executable (by default, compiled executable file can be found in ``bin`` folder next to the source code), or with the following command line: 96 | 97 | ``` 98 | sniffcraft 99 | ``` 100 | 101 | conf/file/path is the path to a json file, and can be used to set authentication information and filter out the packets. Examples can be found in the [conf](conf/) directory. If no path is given, a default conf.json file will be created. With the default configuration, only the names of the packets are logged. When a packet is added to an ignored list, it won't appear in the logs, when it's in a detail list, its full content will be logged. Packets can be added either by id or by name (as registered in protocolCraft), but as id can vary from one version to another, using names is safer. 102 | 103 | ServerAddress should match the address of the server you want to connect to, with the same format as in a regular minecraft client. Custom URL with DNS SRV records are supported (like MyServer.Example.net for example). You can then connect your official minecraft client to SniffCraft as if it were a regular server using . If you are running SniffCraft on the same computer as your client, something like 127.0.0.1:LocalPort should work. 104 | 105 | ## Replay Mod 106 | 107 | If ``LogToReplay`` is present and set to true in the configuration file when the session starts, all packets will also be logged in a format compatible with [replay mod](https://github.com/ReplayMod/ReplayMod). When the capture stops, you'll get a ``XXXX.mcpr`` file that can be opened by the replay mod viewer inside minecraft. Note that this is a compressed format. It may take a few seconds after the connection is closed for this file to be created correctly. Make sure you don't close SniffCraft during this time. 108 | 109 | The current player will **not** appear on this capture, as the replay mod artificially adds some packets to display it. 110 | 111 | ## License 112 | 113 | GPL v3 114 | -------------------------------------------------------------------------------- /cmake/asio.cmake: -------------------------------------------------------------------------------- 1 | # Check if asio folder is empty and clone submodule if needed 2 | file(GLOB RESULT "${CMAKE_CURRENT_SOURCE_DIR}/3rdparty/asio/asio/include") 3 | list(LENGTH RESULT RES_LEN) 4 | if(RES_LEN EQUAL 0) 5 | message(STATUS "Asio not found, cloning it...") 6 | execute_process(COMMAND git submodule update --init -- 3rdparty/asio WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}") 7 | endif() 8 | 9 | add_library(asio INTERFACE IMPORTED) 10 | set_property(TARGET asio PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/3rdparty/asio/asio/include") 11 | -------------------------------------------------------------------------------- /cmake/botcraft.cmake: -------------------------------------------------------------------------------- 1 | # Download botcraft library 2 | 3 | file(GLOB RESULT "${CMAKE_CURRENT_SOURCE_DIR}/3rdparty/botcraft/protocolCraft") 4 | list(LENGTH RESULT RES_LEN) 5 | if(RES_LEN EQUAL 0) 6 | message(STATUS "Botcraft not found, cloning it...") 7 | execute_process(COMMAND git submodule update --init -- 3rdparty/botcraft WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}") 8 | endif() 9 | 10 | set(BOTCRAFT_OUTPUT_DIR "${CMAKE_SOURCE_DIR}" CACHE PATH "Base output build path for protocolCraft") 11 | set(PROTOCOLCRAFT_STATIC ON) 12 | if(SNIFFCRAFT_WITH_GUI) 13 | set(PROTOCOLCRAFT_DETAILED_PARSING ON) 14 | else() 15 | set(PROTOCOLCRAFT_DETAILED_PARSING OFF) 16 | endif() 17 | -------------------------------------------------------------------------------- /cmake/glad.cmake: -------------------------------------------------------------------------------- 1 | add_library(glad STATIC ${CMAKE_CURRENT_SOURCE_DIR}/3rdparty/glad/src/glad.c) 2 | target_include_directories(glad PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/3rdparty/glad/include) 3 | if(MSVC) 4 | set_target_properties(glad PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded") 5 | endif() 6 | -------------------------------------------------------------------------------- /cmake/glfw.cmake: -------------------------------------------------------------------------------- 1 | set(GLFW_BUILD_DOCS FALSE) 2 | set(GLFW_BUILD_EXAMPLES FALSE) 3 | set(GLFW_BUILD_TESTS FALSE) 4 | set(GLFW_INSTALL FALSE) 5 | set(USE_MSVC_RUNTIME_LIBRARY_DLL FALSE) 6 | 7 | FetchContent_Declare( 8 | glfw 9 | GIT_REPOSITORY https://github.com/glfw/glfw.git 10 | GIT_TAG 3.4 11 | GIT_SHALLOW TRUE 12 | GIT_PROGRESS TRUE 13 | ) 14 | 15 | FetchContent_MakeAvailable(glfw) 16 | -------------------------------------------------------------------------------- /cmake/imgui.cmake: -------------------------------------------------------------------------------- 1 | FetchContent_Declare( 2 | imgui 3 | GIT_REPOSITORY https://github.com/ocornut/imgui 4 | GIT_TAG v1.90.4 5 | GIT_SHALLOW TRUE 6 | GIT_PROGRESS TRUE 7 | ) 8 | 9 | FetchContent_MakeAvailable(imgui) 10 | 11 | add_library(imgui STATIC 12 | ${imgui_SOURCE_DIR}/imgui.cpp 13 | ${imgui_SOURCE_DIR}/imgui_draw.cpp 14 | ${imgui_SOURCE_DIR}/imgui_tables.cpp 15 | ${imgui_SOURCE_DIR}/imgui_widgets.cpp 16 | 17 | ${imgui_SOURCE_DIR}/misc/cpp/imgui_stdlib.cpp 18 | 19 | ${imgui_SOURCE_DIR}/backends/imgui_impl_glfw.cpp 20 | ${imgui_SOURCE_DIR}/backends/imgui_impl_opengl3.cpp 21 | ) 22 | set_property(TARGET imgui PROPERTY CXX_STANDARD 11) 23 | target_include_directories(imgui PUBLIC ${imgui_SOURCE_DIR}) 24 | target_link_libraries(imgui PUBLIC glfw OpenGL::GL) 25 | 26 | if(MSVC) 27 | set_target_properties(imgui PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded") 28 | endif() 29 | -------------------------------------------------------------------------------- /cmake/opengl.cmake: -------------------------------------------------------------------------------- 1 | find_package(OpenGL REQUIRED) 2 | -------------------------------------------------------------------------------- /cmake/openssl.cmake: -------------------------------------------------------------------------------- 1 | # We first try to find OpenSSL in the system 2 | if (NOT SNIFFCRAFT_FORCE_LOCAL_OPENSSL) 3 | find_package(OpenSSL QUIET) 4 | endif(NOT SNIFFCRAFT_FORCE_LOCAL_OPENSSL) 5 | 6 | set(OPENSSL_SRC_PATH "${CMAKE_CURRENT_SOURCE_DIR}/3rdparty/openssl") 7 | set(OPENSSL_BUILD_PATH "${CMAKE_CURRENT_BINARY_DIR}/3rdparty/openssl") 8 | 9 | file(GLOB RESULT "${OPENSSL_BUILD_PATH}/install/lib/*") 10 | list(LENGTH RESULT RES_LEN) 11 | 12 | # If not found, build from sources 13 | if (NOT OPENSSL_FOUND AND RES_LEN EQUAL 0) 14 | message(STATUS "OpenSSL not found, cloning and building it from sources...") 15 | 16 | file(GLOB RESULT "${CMAKE_CURRENT_SOURCE_DIR}/3rdparty/openssl/include") 17 | list(LENGTH RESULT RES_LEN) 18 | if(RES_LEN EQUAL 0) 19 | execute_process(COMMAND git submodule update --init -- 3rdparty/openssl WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}") 20 | endif() 21 | 22 | file(MAKE_DIRECTORY "${OPENSSL_BUILD_PATH}") 23 | 24 | execute_process( 25 | COMMAND "${CMAKE_COMMAND}" "${OPENSSL_SRC_PATH}" "-G" "${CMAKE_GENERATOR}" "-A" "${CMAKE_GENERATOR_PLATFORM}" "-DCMAKE_MAKE_PROGRAM=${CMAKE_MAKE_PROGRAM}" "-DCMAKE_BUILD_TYPE=Release" "-DCMAKE_INSTALL_PREFIX=install" "-DWITH_APPS=OFF" "-DCPACK_SOURCE_7Z=OFF" "-DCPACK_SOURCE_ZIP=OFF" "-DMSVC_DYNAMIC_RUNTIME=OFF" "-DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded" "-DCMAKE_POSITION_INDEPENDENT_CODE=ON" 26 | WORKING_DIRECTORY "${OPENSSL_BUILD_PATH}") 27 | 28 | execute_process(COMMAND "${CMAKE_COMMAND}" "--build" "." "--target" "install" "--config" "Release" "--parallel" "2" WORKING_DIRECTORY "${OPENSSL_BUILD_PATH}") 29 | 30 | set(OPENSSL_FOUND ON CACHE INTERNAL "") 31 | endif() 32 | 33 | if(NOT TARGET OpenSSL::SSL OR NOT TARGET OpenSSL::Crypto) 34 | # Create imported targets 35 | file(GLOB ssl_lib_file "${OPENSSL_BUILD_PATH}/install/lib/*libssl*") 36 | add_library(OpenSSL::SSL STATIC IMPORTED) 37 | set_property(TARGET OpenSSL::SSL PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${OPENSSL_BUILD_PATH}/install/include") 38 | set_target_properties(OpenSSL::SSL PROPERTIES IMPORTED_LOCATION "${ssl_lib_file}") 39 | 40 | file(GLOB crypto_lib_file "${OPENSSL_BUILD_PATH}/install/lib/*libcrypto*") 41 | add_library(OpenSSL::Crypto STATIC IMPORTED) 42 | set_property(TARGET OpenSSL::Crypto PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${OPENSSL_BUILD_PATH}/install/include") 43 | set_target_properties(OpenSSL::Crypto PROPERTIES IMPORTED_LOCATION "${crypto_lib_file}") 44 | target_link_libraries(OpenSSL::Crypto INTERFACE ${CMAKE_DL_LIBS}) 45 | endif() 46 | -------------------------------------------------------------------------------- /cmake/zlib.cmake: -------------------------------------------------------------------------------- 1 | #Add zlib library 2 | 3 | # We first try to find zlib in the system 4 | if (NOT SNIFFCRAFT_FORCE_LOCAL_ZLIB) 5 | find_package(ZLIB QUIET) 6 | endif(NOT SNIFFCRAFT_FORCE_LOCAL_ZLIB) 7 | 8 | # If not found, build from sources 9 | if(NOT TARGET ZLIB::ZLIB) 10 | set(ZLIB_SRC_PATH "${CMAKE_CURRENT_SOURCE_DIR}/3rdparty/zlib/") 11 | set(ZLIB_BUILD_PATH "${CMAKE_CURRENT_BINARY_DIR}/3rdparty/zlib") 12 | 13 | file(GLOB RESULT "${ZLIB_BUILD_PATH}/install") 14 | list(LENGTH RESULT RES_LEN) 15 | if(RES_LEN EQUAL 0) 16 | message(STATUS "Can't find Zlib, cloning and building it from sources") 17 | 18 | file(GLOB RESULT "${ZLIB_SRC_PATH}") 19 | list(LENGTH RESULT RES_LEN) 20 | if(RES_LEN EQUAL 0) 21 | execute_process(COMMAND git submodule update --init -- 3rdparty/zlib WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}") 22 | endif() 23 | 24 | file(MAKE_DIRECTORY "${ZLIB_BUILD_PATH}") 25 | 26 | execute_process( 27 | COMMAND "${CMAKE_COMMAND}" "${ZLIB_SRC_PATH}" "-G" "${CMAKE_GENERATOR}" "-DCMAKE_BUILD_TYPE=Release" "-A" "${CMAKE_GENERATOR_PLATFORM}" "-DCMAKE_MAKE_PROGRAM=${CMAKE_MAKE_PROGRAM}" "-DCMAKE_INSTALL_PREFIX=install" "-DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded" "-DCMAKE_POLICY_DEFAULT_CMP0091=NEW" "-DZLIB_BUILD_SHARED=OFF" 28 | WORKING_DIRECTORY "${ZLIB_BUILD_PATH}") 29 | 30 | execute_process(COMMAND "${CMAKE_COMMAND}" "--build" "." "--target" "install" "--config" "Release" "--parallel" "2" WORKING_DIRECTORY "${ZLIB_BUILD_PATH}") 31 | endif() 32 | 33 | # Find the freshly built library 34 | 35 | # From 3.24 there is a cmake option to find zlib static 36 | # but before, we need to do it in a more manual way 37 | if(${CMAKE_VERSION} VERSION_LESS "3.24.0") 38 | set(_CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES}) 39 | set(CMAKE_FIND_LIBRARY_SUFFIXES "static.lib" "s.lib" ".a") 40 | else() 41 | set(ZLIB_USE_STATIC_LIBS "ON") 42 | endif() 43 | 44 | find_package(ZLIB QUIET NO_DEFAULT_PATH PATHS "${ZLIB_BUILD_PATH}/install") 45 | 46 | # We link to ZLIB::ZLIB so we need an alias if we're using the static local version 47 | add_library(ZLIB::ZLIB ALIAS ZLIB::ZLIBSTATIC) 48 | 49 | if(${CMAKE_VERSION} VERSION_LESS "3.24.0") 50 | set(CMAKE_FIND_LIBRARY_SUFFIXES ${_CMAKE_FIND_LIBRARY_SUFFIXES}) 51 | unset(_CMAKE_FIND_LIBRARY_SUFFIXES) 52 | endif() 53 | endif() 54 | -------------------------------------------------------------------------------- /conf/custom.json: -------------------------------------------------------------------------------- 1 | { 2 | "ServerAddress": "127.0.0.1:25565", 3 | "LocalPort": 25555, 4 | "LogToTxtFile": true, 5 | "LogToBinFile": false, 6 | "LogToConsole": true, 7 | "LogToReplay": false, 8 | "LogRawBytes": false, 9 | "Online": false, 10 | "NetworkRecapToConsole": false, 11 | "MicrosoftAccountCacheKey": "", 12 | "Handshaking": { 13 | "ignored_clientbound" : [ 14 | 15 | ], 16 | "ignored_serverbound" : [ 17 | 18 | ], 19 | "detailed_clientbound": [ 20 | 21 | ], 22 | "detailed_serverbound": [ 23 | 24 | ] 25 | }, 26 | "Status": { 27 | "ignored_clientbound" : [ 28 | 29 | ], 30 | "ignored_serverbound" : [ 31 | 32 | ], 33 | "detailed_clientbound": [ 34 | 35 | ], 36 | "detailed_serverbound": [ 37 | 38 | ] 39 | }, 40 | "Configuration": { 41 | "ignored_clientbound" : [ 42 | 43 | ], 44 | "ignored_serverbound" : [ 45 | 46 | ], 47 | "detailed_clientbound": [ 48 | 49 | ], 50 | "detailed_serverbound": [ 51 | 52 | ] 53 | }, 54 | "Login": { 55 | "ignored_clientbound" : [ 56 | 57 | ], 58 | "ignored_serverbound" : [ 59 | 60 | ], 61 | "detailed_clientbound": [ 62 | "Hello" 63 | ], 64 | "detailed_serverbound": [ 65 | "Key" 66 | ] 67 | }, 68 | "Play": { 69 | "ignored_clientbound" : [ 70 | "Move Entity Pos", 71 | "Move Entity PosRot", 72 | "Move Entity Rot", 73 | "Entity Event", 74 | "Player Position", 75 | "Rotate Head", 76 | "Level Chunk", 77 | "Section Blocks Update", 78 | "Light Update", 79 | "Forget Level Chunk", 80 | "Set Entity Data", 81 | "Update Attributes", 82 | "Add Entity", 83 | "Set Entity Motion", 84 | "Teleport Entity", 85 | "Set Equipment", 86 | "Add Mob", 87 | "Remove Entity", 88 | "Block Update", 89 | "Animate", 90 | "Keep Alive", 91 | "Set Time", 92 | "Block Event", 93 | "Sound" 94 | ], 95 | "ignored_serverbound" : [ 96 | "Move Player Pos", 97 | "Move Player PosRot", 98 | "Move Player Rot", 99 | "Move Player Status Only", 100 | "Keep Alive" 101 | ], 102 | "detailed_clientbound": [ 103 | "Container Set Content", 104 | "Container Set Slot" 105 | ], 106 | "detailed_serverbound": [ 107 | "Container Click", 108 | "Container Close" 109 | ] 110 | } 111 | } -------------------------------------------------------------------------------- /conf/default.json: -------------------------------------------------------------------------------- 1 | { 2 | "ServerAddress": "127.0.0.1:25565", 3 | "LocalPort": 25555, 4 | "LogToTxtFile": true, 5 | "LogToBinFile": false, 6 | "LogToConsole": true, 7 | "LogToReplay": false, 8 | "LogRawBytes": false, 9 | "Online": false, 10 | "NetworkRecapToConsole": false, 11 | "MicrosoftAccountCacheKey": "", 12 | "Handshaking": { 13 | "ignored_clientbound" : [ 14 | 15 | ], 16 | "ignored_serverbound" : [ 17 | 18 | ], 19 | "detailed_clientbound": [ 20 | 21 | ], 22 | "detailed_serverbound": [ 23 | 24 | ] 25 | }, 26 | "Status": { 27 | "ignored_clientbound" : [ 28 | 29 | ], 30 | "ignored_serverbound" : [ 31 | 32 | ], 33 | "detailed_clientbound": [ 34 | 35 | ], 36 | "detailed_serverbound": [ 37 | 38 | ] 39 | }, 40 | "Configuration": { 41 | "ignored_clientbound" : [ 42 | 43 | ], 44 | "ignored_serverbound" : [ 45 | 46 | ], 47 | "detailed_clientbound": [ 48 | 49 | ], 50 | "detailed_serverbound": [ 51 | 52 | ] 53 | }, 54 | "Login": { 55 | "ignored_clientbound" : [ 56 | 57 | ], 58 | "ignored_serverbound" : [ 59 | 60 | ], 61 | "detailed_clientbound": [ 62 | 63 | ], 64 | "detailed_serverbound": [ 65 | 66 | ] 67 | }, 68 | "Play": { 69 | "ignored_clientbound" : [ 70 | 71 | ], 72 | "ignored_serverbound" : [ 73 | 74 | ], 75 | "detailed_clientbound": [ 76 | 77 | ], 78 | "detailed_serverbound": [ 79 | 80 | ] 81 | } 82 | } -------------------------------------------------------------------------------- /conf/no_spam.json: -------------------------------------------------------------------------------- 1 | { 2 | "ServerAddress": "127.0.0.1:25565", 3 | "LocalPort": 25555, 4 | "LogToTxtFile": true, 5 | "LogToBinFile": false, 6 | "LogToConsole": true, 7 | "LogToReplay": false, 8 | "LogRawBytes": false, 9 | "Online": false, 10 | "NetworkRecapToConsole": false, 11 | "MicrosoftAccountCacheKey": "", 12 | "Handshaking": { 13 | "ignored_clientbound" : [ 14 | 15 | ], 16 | "ignored_serverbound" : [ 17 | 18 | ], 19 | "detailed_clientbound": [ 20 | 21 | ], 22 | "detailed_serverbound": [ 23 | 24 | ] 25 | }, 26 | "Status": { 27 | "ignored_clientbound" : [ 28 | 29 | ], 30 | "ignored_serverbound" : [ 31 | 32 | ], 33 | "detailed_clientbound": [ 34 | 35 | ], 36 | "detailed_serverbound": [ 37 | 38 | ] 39 | }, 40 | "Configuration": { 41 | "ignored_clientbound" : [ 42 | 43 | ], 44 | "ignored_serverbound" : [ 45 | 46 | ], 47 | "detailed_clientbound": [ 48 | 49 | ], 50 | "detailed_serverbound": [ 51 | 52 | ] 53 | }, 54 | "Login": { 55 | "ignored_clientbound" : [ 56 | 57 | ], 58 | "ignored_serverbound" : [ 59 | 60 | ], 61 | "detailed_clientbound": [ 62 | 63 | ], 64 | "detailed_serverbound": [ 65 | 66 | ] 67 | }, 68 | "Play": { 69 | "ignored_clientbound" : [ 70 | "Move Entity Pos", 71 | "Move Entity PosRot", 72 | "Move Entity Rot", 73 | "Entity Event", 74 | "Player Position", 75 | "Rotate Head", 76 | "Level Chunk", 77 | "Section Blocks Update", 78 | "Light Update", 79 | "Forget Level Chunk", 80 | "Set Entity Data", 81 | "Update Attributes", 82 | "Add Entity", 83 | "Set Entity Motion", 84 | "Teleport Entity", 85 | "Set Equipment", 86 | "Add Mob", 87 | "Remove Entity", 88 | "Block Update", 89 | "Animate", 90 | "Keep Alive", 91 | "Set Time", 92 | "Block Event", 93 | "Sound" 94 | ], 95 | "ignored_serverbound" : [ 96 | "Move Player Pos", 97 | "Move Player PosRot", 98 | "Move Player Rot", 99 | "Move Player Status Only", 100 | "Keep Alive" 101 | ], 102 | "detailed_clientbound": [ 103 | 104 | ], 105 | "detailed_serverbound": [ 106 | 107 | ] 108 | } 109 | } -------------------------------------------------------------------------------- /sniffcraft/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | project(sniffcraft) 2 | 3 | set(sniffcraft_PUBLIC_HDR 4 | include/sniffcraft/BaseProxy.hpp 5 | include/sniffcraft/Compression.hpp 6 | include/sniffcraft/conf.hpp 7 | include/sniffcraft/Connection.hpp 8 | include/sniffcraft/DataProcessor.hpp 9 | include/sniffcraft/enums.hpp 10 | include/sniffcraft/Logger.hpp 11 | include/sniffcraft/LogItem.hpp 12 | include/sniffcraft/MinecraftEncryptionDataProcessor.hpp 13 | include/sniffcraft/MinecraftProxy.hpp 14 | include/sniffcraft/NetworkRecapItem.hpp 15 | include/sniffcraft/PacketUtilities.hpp 16 | include/sniffcraft/ReplayModLogger.hpp 17 | include/sniffcraft/server.hpp 18 | 19 | ../3rdparty/botcraft/botcraft/private_include/botcraft/Network/DNS/DNSMessage.hpp 20 | ../3rdparty/botcraft/botcraft/private_include/botcraft/Network/DNS/DNSQuestion.hpp 21 | ../3rdparty/botcraft/botcraft/private_include/botcraft/Network/DNS/DNSResourceRecord.hpp 22 | ../3rdparty/botcraft/botcraft/private_include/botcraft/Network/DNS/DNSSrvData.hpp 23 | 24 | ../3rdparty/botcraft/botcraft/private_include/botcraft/Network/Authentifier.hpp 25 | ../3rdparty/botcraft/botcraft/private_include/botcraft/Network/AESEncrypter.hpp 26 | ../3rdparty/botcraft/botcraft/include/botcraft/Network/LastSeenMessagesTracker.hpp 27 | 28 | ../3rdparty/botcraft/botcraft/include/botcraft/Utilities/Logger.hpp 29 | ../3rdparty/botcraft/botcraft/private_include/botcraft/Utilities/StringUtilities.hpp 30 | 31 | include/sniffcraft/Zip/DosTime.hpp 32 | include/sniffcraft/Zip/ZeptoZip.hpp 33 | ) 34 | 35 | set(sniffcraft_SRC 36 | src/BaseProxy.cpp 37 | src/Compression.cpp 38 | src/conf.cpp 39 | src/Connection.cpp 40 | src/Logger.cpp 41 | src/MinecraftEncryptionDataProcessor.cpp 42 | src/MinecraftProxy.cpp 43 | src/ReplayModLogger.cpp 44 | src/server.cpp 45 | src/main.cpp 46 | 47 | src/Zip/ZeptoZip.cpp 48 | 49 | ../3rdparty/botcraft/botcraft/src/Network/Authentifier.cpp 50 | ../3rdparty/botcraft/botcraft/src/Network/AESEncrypter.cpp 51 | ../3rdparty/botcraft/botcraft/src/Network/LastSeenMessagesTracker.cpp 52 | ../3rdparty/botcraft/botcraft/src/Utilities/Logger.cpp 53 | ../3rdparty/botcraft/botcraft/src/Utilities/StringUtilities.cpp 54 | ) 55 | 56 | # To have a nice files structure in Visual Studio 57 | if(MSVC) 58 | foreach(source IN LISTS sniffcraft_PUBLIC_HDR) 59 | get_filename_component(source_path_header "${source}" PATH) 60 | string(REPLACE "../3rdparty/botcraft/botcraft/private_include/botcraft/Network" "Header Files/public/botcraft" source_path_header "${source_path_header}") 61 | string(REPLACE "../3rdparty/botcraft/botcraft/private_include/botcraft/Utilities" "Header Files/public/botcraft" source_path_header "${source_path_header}") 62 | string(REPLACE "../3rdparty/botcraft/botcraft/include/botcraft/Utilities" "Header Files/public/botcraft" source_path_header "${source_path_header}") 63 | string(REPLACE "../3rdparty/botcraft/botcraft/include/botcraft/Network" "Header Files/public/botcraft" source_path_header "${source_path_header}") 64 | string(REPLACE "include/sniffcraft" "Header Files/public" source_path_header "${source_path_header}") 65 | string(REPLACE "/" "\\" source_path_msvc "${source_path_header}") 66 | source_group("${source_path_msvc}" FILES "${source}") 67 | endforeach() 68 | 69 | foreach(source IN LISTS sniffcraft_SRC) 70 | get_filename_component(source_path "${source}" PATH) 71 | string(REPLACE "../3rdparty/botcraft/botcraft/src" "Source Files/botcraft" source_path "${source_path}") 72 | string(REPLACE "src" "Source Files" source_path "${source_path}") 73 | string(REPLACE "/" "\\" source_path_msvc "${source_path}") 74 | source_group("${source_path_msvc}" FILES "${source}") 75 | endforeach() 76 | endif() 77 | 78 | add_executable(${PROJECT_NAME} ${sniffcraft_SRC} ${sniffcraft_PUBLIC_HDR}) 79 | set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 17) 80 | set_target_properties(${PROJECT_NAME} PROPERTIES DEBUG_POSTFIX "_d") 81 | set_target_properties(${PROJECT_NAME} PROPERTIES RELWITHDEBINFO_POSTFIX "_rd") 82 | 83 | if(MSVC) 84 | # To avoid having folder for each configuration when building with Visual 85 | set_target_properties(${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY_DEBUG "${CMAKE_SOURCE_DIR}/bin") 86 | set_target_properties(${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_SOURCE_DIR}/bin") 87 | set_target_properties(${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO "${CMAKE_SOURCE_DIR}/bin") 88 | set_target_properties(${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL "${CMAKE_SOURCE_DIR}/bin") 89 | set_target_properties(${PROJECT_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY_DEBUG "${CMAKE_SOURCE_DIR}/bin") 90 | set_target_properties(${PROJECT_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY_RELEASE "${CMAKE_SOURCE_DIR}/bin") 91 | set_target_properties(${PROJECT_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY_RELWITHDEBINFO "${CMAKE_SOURCE_DIR}/bin") 92 | set_target_properties(${PROJECT_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY_MINSIZEREL "${CMAKE_SOURCE_DIR}/bin") 93 | set_target_properties(${PROJECT_NAME} PROPERTIES ARCHIVE_OUTPUT_DIRECTORY_DEBUG "${CMAKE_SOURCE_DIR}/lib") 94 | set_target_properties(${PROJECT_NAME} PROPERTIES ARCHIVE_OUTPUT_DIRECTORY_RELEASE "${CMAKE_SOURCE_DIR}/lib") 95 | set_target_properties(${PROJECT_NAME} PROPERTIES ARCHIVE_OUTPUT_DIRECTORY_RELWITHDEBINFO "${CMAKE_SOURCE_DIR}/lib") 96 | set_target_properties(${PROJECT_NAME} PROPERTIES ARCHIVE_OUTPUT_DIRECTORY_MINSIZEREL "${CMAKE_SOURCE_DIR}/lib") 97 | 98 | set_property(TARGET ${PROJECT_NAME} PROPERTY VS_DEBUGGER_WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}/bin") 99 | else() 100 | set_target_properties(${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/bin") 101 | set_target_properties(${PROJECT_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/bin") 102 | set_target_properties(${PROJECT_NAME} PROPERTIES ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib") 103 | endif(MSVC) 104 | 105 | target_include_directories(${PROJECT_NAME} PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") 106 | target_include_directories(${PROJECT_NAME} PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/../3rdparty/botcraft/botcraft/private_include") 107 | target_include_directories(${PROJECT_NAME} PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/../3rdparty/botcraft/botcraft/include") 108 | 109 | if (MSVC) 110 | set_target_properties(${PROJECT_NAME} PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded") 111 | endif(MSVC) 112 | 113 | # Add Asio 114 | target_link_libraries(${PROJECT_NAME} PUBLIC asio) 115 | target_compile_definitions(${PROJECT_NAME} PUBLIC ASIO_STANDALONE) 116 | 117 | # Add Zlib 118 | target_link_libraries(${PROJECT_NAME} PUBLIC ZLIB::ZLIB) 119 | 120 | # Add OpenSSL 121 | if(SNIFFCRAFT_WITH_ENCRYPTION) 122 | target_link_libraries(${PROJECT_NAME} PUBLIC OpenSSL::SSL) 123 | target_link_libraries(${PROJECT_NAME} PUBLIC OpenSSL::Crypto) 124 | target_compile_definitions(${PROJECT_NAME} PUBLIC USE_ENCRYPTION=1) 125 | endif(SNIFFCRAFT_WITH_ENCRYPTION) 126 | 127 | # Add threads support 128 | target_link_libraries(${PROJECT_NAME} PUBLIC Threads::Threads) 129 | 130 | # Add protocolCraft 131 | target_link_libraries(${PROJECT_NAME} PUBLIC protocolCraft) 132 | 133 | if (SNIFFCRAFT_WITH_GUI) 134 | target_link_libraries(${PROJECT_NAME} PRIVATE glfw ${OPENGL_LIBRARIES} glad imgui) 135 | target_compile_definitions(${PROJECT_NAME} PRIVATE WITH_GUI) 136 | endif() 137 | -------------------------------------------------------------------------------- /sniffcraft/include/sniffcraft/BaseProxy.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include 10 | 11 | #include "sniffcraft/Connection.hpp" 12 | #include "sniffcraft/enums.hpp" 13 | 14 | /// @brief A base proxy class that will transfer all data 15 | /// both way without changing anything. Can be overriden by 16 | class BaseProxy 17 | { 18 | public: 19 | BaseProxy(asio::io_context& io_context); 20 | virtual ~BaseProxy(); 21 | 22 | /// @brief Starts the connection process to a given server 23 | /// @param server_address IP address of the server 24 | /// @param server_port port to connect to 25 | virtual void Start(const std::string& server_address, const unsigned short server_port); 26 | 27 | /// @brief Get the client connection underlying socket 28 | /// @return A reference to the client socket 29 | asio::ip::tcp::socket& ClientSocket(); 30 | 31 | bool Started(); 32 | bool Running(); 33 | 34 | protected: 35 | /// @brief Function called when new data are available. On BaseProxy, just 36 | /// send the data to the other endpoint without any other processing. Override 37 | /// to do more advanced stuff. It will always be called by one thread at the same 38 | /// time, and you don't need to worry about any thread locking stuff. 39 | /// @param data Iterator to the first element of the data 40 | /// @param length Size of the available data 41 | /// @param source Where the data are coming from 42 | /// @return The size of data that have been processed and should 43 | /// be removed from the incoming buffer 44 | virtual size_t ProcessData(const std::vector::const_iterator& data, const size_t length, const Endpoint source); 45 | 46 | /// @brief Close both client and server connections 47 | void Close(); 48 | 49 | private: 50 | /// @brief Use as callback when server connection has new data 51 | void NotifyServerData(const size_t length); 52 | /// @brief Use as callback when client connection has new data 53 | void NotifyClientData(const size_t length); 54 | 55 | /// @brief Function running in data_processing_thread 56 | void ReadIncomingData(); 57 | 58 | protected: 59 | /// @brief In/Out connection to the client 60 | Connection client_connection; 61 | /// @brief In/Out connection to the server 62 | Connection server_connection; 63 | 64 | std::string server_ip_; 65 | unsigned short server_port_; 66 | 67 | private: 68 | asio::io_context& io_context_; 69 | 70 | /// @brief Running thread to process incoming data from 71 | /// both client and server 72 | std::thread data_processing_thread; 73 | 74 | /// @brief Everytime one connection has data, 75 | /// it adds the source Endpoint in this queue 76 | /// and the number of bytes transferred this time 77 | std::list > data_sources; 78 | /// @brief Mutex to protect the data_sources 79 | std::mutex data_sources_mutex; 80 | /// @brief Condition variable notified everytime 81 | /// there is a new entry in data_sources 82 | std::condition_variable data_source_cv; 83 | 84 | /// @brief History of data received by the client connection 85 | std::vector client_received_data; 86 | /// @brief History of data received by the server connection 87 | std::vector server_received_data; 88 | 89 | std::atomic process_data_ready; 90 | std::atomic closed; 91 | std::atomic started; 92 | }; 93 | -------------------------------------------------------------------------------- /sniffcraft/include/sniffcraft/Compression.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | 9 | std::vector Compress(const std::vector &data); 10 | std::vector Decompress(const unsigned char* compressed, const size_t size); 11 | 12 | /// @brief Compress an input file directly to an output, without loading it in memory 13 | /// @param src_file Source file to compress 14 | /// @param dst_file Destination file to write to 15 | /// @return Tuple of 16 | std::tuple CompressRawDeflateFile(std::ifstream& src_file, std::ofstream& dst_file); 17 | -------------------------------------------------------------------------------- /sniffcraft/include/sniffcraft/Connection.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #include 11 | 12 | constexpr size_t BUFFER_SIZE = 1024; 13 | 14 | class DataProcessor; 15 | 16 | class Connection 17 | { 18 | public: 19 | Connection(asio::io_context& io_context); 20 | ~Connection(); 21 | 22 | /// @brief Setter for the callback called on data reception 23 | /// @param callback a function to call 24 | void SetCallback(const std::function& callback); 25 | 26 | /// @brief Setter for the data processor 27 | /// @param processor The processor this connection will take ownership of 28 | void SetDataProcessor(std::unique_ptr& processor); 29 | 30 | /// @brief Get all available ready data in ready_received_data and clear the vector 31 | /// @param dst Vector to which the data will be pushed to 32 | void RetreiveData(std::vector& dst); 33 | 34 | /// @brief Start writing/reading data to/from this socket 35 | void StartListeningAndWriting(); 36 | 37 | /// @brief Push given data to the buffer to be sent through the socket 38 | /// @param data Pointer to the first data element 39 | /// @param length Size of the data in bytes 40 | void WriteData(const unsigned char* const data, const size_t length); 41 | 42 | /// @brief Getter for this connection underlying socket 43 | /// @return A reference to asio socket 44 | asio::ip::tcp::socket& GetSocket(); 45 | 46 | /// @brief Close the underlying socket 47 | void Close(); 48 | 49 | /// @brief Get the state of this connection 50 | /// @return True if closed, false otherwise 51 | bool Closed() const; 52 | 53 | private: 54 | void WriteLoop(); 55 | void handle_read(const asio::error_code& ec, const size_t bytes_transferred); 56 | void handle_timeout(const asio::error_code& ec); 57 | 58 | private: 59 | std::atomic closed; 60 | /// @brief Function called when N new bytes were added in ready_received_data 61 | std::function data_callback; 62 | 63 | /// @brief Connection underlying socket 64 | asio::ip::tcp::socket socket; 65 | asio::steady_timer timeout_timer; 66 | 67 | /// @brief BUFFER_SIZE vector used to store incoming bytes 68 | std::vector read_buffer; 69 | /// @brief Growing buffer storing all the received bytes ready to be processed. Protected by received_mutex 70 | std::vector ready_received_data; 71 | /// @brief mutex protecting ready_received_data 72 | std::mutex received_mutex; 73 | 74 | /// @brief Thread running the sync writing loop 75 | std::thread write_thread; 76 | std::atomic write_thread_started; 77 | /// @brief A deque of data to send. If second parameter bool is set to true, means that we need to apply data_processor to it before sending 78 | std::deque, bool>> data_to_write; 79 | /// @brief mutex protecting data_to_write 80 | std::mutex write_mutex; 81 | /// @brief condition variable notified when a new data is added to data_to_write 82 | std::condition_variable write_cv; 83 | 84 | /// @brief Optional DataProcessor applied to all incoming and outgoing data 85 | std::unique_ptr data_processor; 86 | }; 87 | -------------------------------------------------------------------------------- /sniffcraft/include/sniffcraft/DataProcessor.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | class DataProcessor 6 | { 7 | public: 8 | DataProcessor() {}; 9 | virtual ~DataProcessor() {}; 10 | 11 | virtual std::vector ProcessIncomingData(const std::vector& data) const = 0; 12 | virtual std::vector ProcessOutgoingData(const std::vector& data) const = 0; 13 | }; 14 | -------------------------------------------------------------------------------- /sniffcraft/include/sniffcraft/LogItem.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "sniffcraft/enums.hpp" 4 | 5 | #include "protocolCraft/enums.hpp" 6 | #include "protocolCraft/Packet.hpp" 7 | 8 | #include 9 | #include 10 | 11 | struct LogItem 12 | { 13 | std::shared_ptr packet; 14 | std::chrono::time_point date; 15 | ProtocolCraft::ConnectionState connection_state; 16 | Endpoint origin; 17 | size_t bandwidth_bytes; 18 | }; 19 | -------------------------------------------------------------------------------- /sniffcraft/include/sniffcraft/Logger.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "sniffcraft/enums.hpp" 4 | #include "sniffcraft/LogItem.hpp" 5 | #include "sniffcraft/NetworkRecapItem.hpp" 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | 24 | class Logger 25 | { 26 | public: 27 | Logger(); 28 | #ifdef WITH_GUI 29 | Logger(const std::filesystem::path& path); 30 | #endif 31 | ~Logger(); 32 | void Log(const std::shared_ptr& packet, const ProtocolCraft::ConnectionState connection_state, const Endpoint origin, const size_t bandwidth_bytes); 33 | const std::string& GetBaseFilename() const; 34 | void LoadConfig(); 35 | void Stop(); 36 | #ifdef WITH_GUI 37 | /// @brief Render this Logger packets 38 | /// @return A tuple to add to ignored, if first element is nullptr, nothing to add 39 | std::tuple, ProtocolCraft::ConnectionState, Endpoint> Render(); 40 | #endif 41 | 42 | private: 43 | void LogConsume(); 44 | void LoadPacketsFromJson(const ProtocolCraft::Json::Value& value, const ProtocolCraft::ConnectionState connection_state); 45 | std::string_view OriginToString(const Endpoint origin) const; 46 | std::string_view ConnectionStateToString(const ProtocolCraft::ConnectionState connection_state) const; 47 | /// @brief Get packet name (default packet name + identifier if it's a custom payload) 48 | /// @param item LogItem 49 | /// @return Displayable packet name 50 | std::string GetPacketName(const LogItem& item) const; 51 | Endpoint SimpleOrigin(const Endpoint origin) const; 52 | std::string GenerateNetworkRecap(const int max_entry = -1, const int max_name_size = -1) const; 53 | 54 | private: 55 | std::chrono::time_point start_time; 56 | 57 | std::thread log_thread; 58 | std::mutex log_mutex; 59 | std::condition_variable log_condition; 60 | std::queue logging_queue; 61 | 62 | std::string base_filename; 63 | std::ofstream log_file; 64 | std::ofstream binary_file; 65 | std::atomic is_running; 66 | bool log_to_file; 67 | bool log_to_binary_file; 68 | bool log_to_console; 69 | bool log_raw_bytes; 70 | bool log_network_recap_console; 71 | #ifdef WITH_GUI 72 | bool in_gui; 73 | #endif 74 | 75 | std::time_t last_time_checked_conf_file; 76 | std::time_t last_time_conf_file_loaded; 77 | std::time_t last_time_network_recap_printed; 78 | 79 | std::map, std::set > ignored_packets; 80 | std::mutex ignored_packets_mutex; 81 | std::map, std::set > detailed_packets; 82 | 83 | std::map clientbound_network_recap_data; 84 | std::map serverbound_network_recap_data; 85 | mutable std::mutex network_recap_mutex; 86 | NetworkRecapItem clientbound_total_network_recap; 87 | NetworkRecapItem serverbound_total_network_recap; 88 | 89 | #ifdef WITH_GUI 90 | std::vector packets_history; 91 | std::vector packets_history_filtered_indices; 92 | std::mutex packets_history_mutex; 93 | long long int selected_index = -1; 94 | std::vector selected_bytes; 95 | ProtocolCraft::Json::Value selected_json; 96 | #endif 97 | }; 98 | -------------------------------------------------------------------------------- /sniffcraft/include/sniffcraft/MinecraftEncryptionDataProcessor.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #ifdef USE_ENCRYPTION 4 | #include 5 | 6 | #include "sniffcraft/DataProcessor.hpp" 7 | 8 | namespace Botcraft 9 | { 10 | class AESEncrypter; 11 | } 12 | 13 | class MinecraftEncryptionDataProcessor : public DataProcessor 14 | { 15 | public: 16 | MinecraftEncryptionDataProcessor(std::unique_ptr& encrypter_); 17 | virtual ~MinecraftEncryptionDataProcessor(); 18 | 19 | virtual std::vector ProcessIncomingData(const std::vector& data) const override; 20 | virtual std::vector ProcessOutgoingData(const std::vector& data) const override; 21 | 22 | private: 23 | std::unique_ptr encrypter; 24 | }; 25 | #endif -------------------------------------------------------------------------------- /sniffcraft/include/sniffcraft/MinecraftProxy.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | #include "sniffcraft/BaseProxy.hpp" 7 | 8 | #ifdef USE_ENCRYPTION 9 | #if PROTOCOL_VERSION > 760 /* > 1.19.1/2 */ 10 | #include 11 | #endif 12 | namespace Botcraft 13 | { 14 | class Authentifier; 15 | } 16 | #endif 17 | 18 | class Logger; 19 | class ReplayModLogger; 20 | 21 | class MinecraftProxy : public BaseProxy, public ProtocolCraft::Handler 22 | { 23 | public: 24 | MinecraftProxy(asio::io_context& io_context); 25 | virtual ~MinecraftProxy(); 26 | 27 | virtual void Start(const std::string& server_address, const unsigned short server_port) override; 28 | 29 | std::shared_ptr GetLogger() const; 30 | 31 | protected: 32 | virtual size_t ProcessData(const std::vector::const_iterator& data, const size_t length, const Endpoint source) override; 33 | 34 | private: 35 | /// @brief Check the size of the next MC packet 36 | /// @param data iterator to the data start 37 | /// @param length number of available bytes 38 | /// @return The size of the next packet, or 0 if not enough bytes to read the size 39 | size_t Peek(std::vector::const_iterator& data, size_t& length); 40 | 41 | /// @brief Convert a MC packet to bytes vector 42 | /// @param packet Packet to convert 43 | /// @return Bytes representation of the packet 44 | std::vector PacketToBytes(const ProtocolCraft::Packet& packet) const; 45 | 46 | virtual void Handle(ProtocolCraft::ServerboundClientIntentionPacket& packet) override; 47 | virtual void Handle(ProtocolCraft::ServerboundHelloPacket& packet) override; 48 | #if PROTOCOL_VERSION < 764 /* < 1.20.2 */ 49 | virtual void Handle(ProtocolCraft::ClientboundGameProfilePacket& packet) override; 50 | #endif 51 | virtual void Handle(ProtocolCraft::ClientboundLoginCompressionPacket& packet) override; 52 | virtual void Handle(ProtocolCraft::ClientboundHelloPacket& packet) override; 53 | #if USE_ENCRYPTION && PROTOCOL_VERSION > 760 /* > 1.19.1/2 */ 54 | virtual void Handle(ProtocolCraft::ClientboundLoginPacket& packet) override; 55 | virtual void Handle(ProtocolCraft::ServerboundChatPacket& packet) override; 56 | #if PROTOCOL_VERSION < 766 /* < 1.20.5 */ 57 | virtual void Handle(ProtocolCraft::ServerboundChatCommandPacket& packet) override; 58 | #else 59 | virtual void Handle(ProtocolCraft::ServerboundChatCommandSignedPacket& packet) override; 60 | #endif 61 | virtual void Handle(ProtocolCraft::ClientboundPlayerChatPacket& packet) override; 62 | #endif 63 | #if PROTOCOL_VERSION > 763 /* > 1.20.1 */ 64 | virtual void Handle(ProtocolCraft::ServerboundLoginAcknowledgedPacket& packet) override; 65 | virtual void Handle(ProtocolCraft::ServerboundFinishConfigurationPacket& packet) override; 66 | virtual void Handle(ProtocolCraft::ServerboundConfigurationAcknowledgedPacket& packet) override; 67 | #endif 68 | 69 | private: 70 | std::shared_ptr logger; 71 | std::unique_ptr replay_logger; 72 | 73 | ProtocolCraft::ConnectionState connection_state; 74 | bool transmit_original_packet; 75 | int compression_threshold; 76 | #ifdef USE_ENCRYPTION 77 | std::unique_ptr authentifier; 78 | #if PROTOCOL_VERSION > 760 /* > 1.19.1/2 */ 79 | Botcraft::LastSeenMessagesTracker chat_context; 80 | ProtocolCraft::UUID chat_session_uuid; 81 | int message_sent_index; 82 | #endif 83 | #endif 84 | }; 85 | -------------------------------------------------------------------------------- /sniffcraft/include/sniffcraft/NetworkRecapItem.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | struct NetworkRecapItem 4 | { 5 | unsigned long long int count = 0; 6 | unsigned long long int bandwidth_bytes = 0; 7 | }; 8 | -------------------------------------------------------------------------------- /sniffcraft/include/sniffcraft/PacketUtilities.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | struct NameID 8 | { 9 | std::string_view name; 10 | int id; 11 | }; 12 | 13 | template 14 | constexpr std::array GetNameIds(std::integer_sequence seq) 15 | { 16 | return { NameID{std::tuple_element_t::packet_name, Indices} ... }; 17 | } 18 | 19 | template 20 | struct PacketNameIdExtractor{ 21 | static constexpr auto name_ids = GetNameIds(std::make_integer_sequence>{}); 22 | }; 23 | -------------------------------------------------------------------------------- /sniffcraft/include/sniffcraft/ReplayModLogger.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "sniffcraft/enums.hpp" 4 | #include "sniffcraft/LogItem.hpp" 5 | 6 | #include 7 | #include 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | class ReplayModLogger 20 | { 21 | public: 22 | ReplayModLogger(); 23 | ~ReplayModLogger(); 24 | void Log(const std::shared_ptr packet, const ProtocolCraft::ConnectionState connection_state, const Endpoint origin); 25 | void SetServerName(const std::string& server_name_); 26 | 27 | private: 28 | void LogConsume(); 29 | void SaveReplayMetadataFile() const; 30 | void WrapMCPRFile() const; 31 | 32 | private: 33 | std::chrono::time_point start_time; 34 | 35 | std::thread log_thread; 36 | std::mutex log_mutex; 37 | std::condition_variable log_condition; 38 | std::queue logging_queue; 39 | 40 | std::string session_prefix; 41 | std::ofstream replay_file; 42 | bool is_running; 43 | 44 | std::string server_name; 45 | }; 46 | -------------------------------------------------------------------------------- /sniffcraft/include/sniffcraft/Zip/DosTime.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class DosTime 5 | { 6 | public: 7 | static const unsigned int Now() 8 | { 9 | auto now = std::chrono::system_clock::now(); 10 | time_t tt = std::chrono::system_clock::to_time_t(now); 11 | tm local_tm = *localtime(&tt); 12 | 13 | int year = local_tm.tm_year + 1900; 14 | int month = local_tm.tm_mon + 1; 15 | int day = local_tm.tm_mday; 16 | int hour = local_tm.tm_hour; 17 | int min = local_tm.tm_min; 18 | int sec = local_tm.tm_sec; 19 | 20 | return ((year - 1980) << 25) 21 | | (month << 21) 22 | | (day << 16) 23 | | (hour << 11) 24 | | (min << 5) 25 | | (sec >> 1); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /sniffcraft/include/sniffcraft/Zip/ZeptoZip.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | // Can we have a Zip library? 7 | // We already have a Zip library at home 8 | // Zip library at home: 9 | class ZeptoZip 10 | { 11 | public: 12 | // Pack a list of files into a zip archive at outpath. 13 | // File content is compressed using zlib. 14 | // This is a very very very simple zip implementation 15 | // barely sufficient for sniffcraft use. Might not be 16 | // suitable for anything else 17 | static void CreateZipArchive(const std::string& outpath, const std::vector& inputs, const std::vector& filenames); 18 | }; 19 | -------------------------------------------------------------------------------- /sniffcraft/include/sniffcraft/conf.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | class Conf 10 | { 11 | public: 12 | static const std::string server_address_key; 13 | static const std::string local_port_key; 14 | static const std::string text_file_log_key; 15 | static const std::string binary_file_log_key; 16 | static const std::string console_log_key; 17 | static const std::string replay_log_key; 18 | static const std::string raw_bytes_log_key; 19 | static const std::string online_key; 20 | static const std::string network_recap_to_console_key; 21 | static const std::string account_cache_key_key; 22 | static const std::string handshaking_key; 23 | static const std::string status_key; 24 | static const std::string login_key; 25 | static const std::string configuration_key; 26 | static const std::string play_key; 27 | static const std::string ignored_clientbound_key; 28 | static const std::string ignored_serverbound_key; 29 | static const std::string detailed_clientbound_key; 30 | static const std::string detailed_serverbound_key; 31 | 32 | static bool headless; 33 | static std::string conf_path; 34 | static std::shared_mutex conf_mutex; 35 | 36 | public: 37 | static ProtocolCraft::Json::Value LoadConf(); 38 | static void SaveConf(const ProtocolCraft::Json::Value& conf); 39 | static std::time_t GetModifiedTimestamp(); 40 | }; 41 | -------------------------------------------------------------------------------- /sniffcraft/include/sniffcraft/enums.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | enum class Endpoint 4 | { 5 | Server, 6 | Client, 7 | SniffcraftToServer, 8 | SniffcraftToClient, 9 | ServerToSniffcraft, 10 | ClientToSniffcraft 11 | }; 12 | -------------------------------------------------------------------------------- /sniffcraft/include/sniffcraft/server.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include 10 | 11 | #include "protocolCraft/Utilities/Json.hpp" 12 | 13 | class BaseProxy; 14 | #ifdef WITH_GUI 15 | struct GLFWwindow; 16 | class Logger; 17 | #endif 18 | 19 | class Server 20 | { 21 | public: 22 | Server(); 23 | ~Server(); 24 | void run(); 25 | 26 | private: 27 | void run_iocontext(); 28 | void listen_connection(); 29 | void handle_accept(BaseProxy* new_proxy, const asio::error_code &ec); 30 | void ResolveIpPortFromAddress(); 31 | 32 | BaseProxy* GetNewMinecraftProxy(); 33 | void CleanProxies(); 34 | 35 | #ifdef WITH_GUI 36 | void Render(); 37 | void InternalRenderLoop(GLFWwindow* window); 38 | #endif 39 | 40 | private: 41 | std::string server_address; 42 | std::string server_ip; 43 | unsigned short server_port; 44 | unsigned short client_port; 45 | 46 | asio::io_context io_context; 47 | std::unique_ptr acceptor; 48 | 49 | std::vector> proxies; 50 | std::mutex proxies_mutex; 51 | std::thread proxies_cleaning_thread; 52 | std::atomic proxies_cleaning_thread_running; 53 | 54 | #ifdef WITH_GUI 55 | std::thread iocontext_thread; 56 | std::mutex loggers_mutex; 57 | std::vector> loggers; 58 | #endif 59 | }; 60 | -------------------------------------------------------------------------------- /sniffcraft/src/BaseProxy.cpp: -------------------------------------------------------------------------------- 1 | #include "sniffcraft/BaseProxy.hpp" 2 | 3 | #include 4 | 5 | BaseProxy::BaseProxy(asio::io_context& io_context) : 6 | io_context_(io_context), 7 | client_connection(io_context), 8 | server_connection(io_context) 9 | { 10 | started = false; 11 | closed = true; 12 | } 13 | 14 | BaseProxy::~BaseProxy() 15 | { 16 | Close(); 17 | data_source_cv.notify_one(); 18 | if (data_processing_thread.joinable()) 19 | { 20 | data_processing_thread.join(); 21 | } 22 | } 23 | 24 | void BaseProxy::Start(const std::string& server_address, const unsigned short server_port) 25 | { 26 | std::cout << "Starting new proxy to " << server_address << ":" << server_port << std::endl; 27 | server_ip_ = server_address; 28 | server_port_ = server_port; 29 | 30 | // Try to connect to remote server 31 | asio::ip::tcp::resolver resolver(io_context_); 32 | asio::ip::tcp::resolver::results_type results = resolver.resolve(server_ip_, std::to_string(server_port_)); 33 | 34 | asio::error_code ec; 35 | asio::connect(server_connection.GetSocket(), results, ec); 36 | 37 | if (ec) 38 | { 39 | Close(); 40 | std::cerr << "Error trying to establish connection to " 41 | << server_address << ":" << server_port 42 | << ": " << ec 43 | << std::endl; 44 | return; 45 | } 46 | 47 | closed = false; 48 | started = true; 49 | 50 | // Once connected, we can start the processing thread 51 | process_data_ready = false; 52 | data_processing_thread = std::thread(&BaseProxy::ReadIncomingData, this); 53 | 54 | // Wait for the thread to be launched and ready to process incoming data 55 | while (!process_data_ready) 56 | { 57 | 58 | } 59 | 60 | client_connection.SetCallback( 61 | std::bind( 62 | &BaseProxy::NotifyClientData, this, 63 | std::placeholders::_1 64 | ) 65 | ); 66 | 67 | server_connection.SetCallback( 68 | std::bind( 69 | &BaseProxy::NotifyServerData, this, 70 | std::placeholders::_1 71 | ) 72 | ); 73 | 74 | client_connection.StartListeningAndWriting(); 75 | server_connection.StartListeningAndWriting(); 76 | } 77 | 78 | void BaseProxy::Close() 79 | { 80 | client_connection.Close(); 81 | server_connection.Close(); 82 | closed = true; 83 | } 84 | 85 | bool BaseProxy::Started() 86 | { 87 | return started; 88 | } 89 | 90 | bool BaseProxy::Running() 91 | { 92 | if (!closed && (client_connection.Closed() || server_connection.Closed())) 93 | { 94 | Close(); 95 | } 96 | return !closed; 97 | } 98 | 99 | asio::ip::tcp::socket& BaseProxy::ClientSocket() 100 | { 101 | return client_connection.GetSocket(); 102 | } 103 | 104 | size_t BaseProxy::ProcessData(const std::vector::const_iterator& data, const size_t length, const Endpoint source) 105 | { 106 | Connection& dst_connection = source == Endpoint::Server ? client_connection : server_connection; 107 | 108 | // Transfer the data to the other endpoint 109 | dst_connection.WriteData(&(*data), length); 110 | return length; 111 | } 112 | 113 | void BaseProxy::NotifyServerData(const size_t length) 114 | { 115 | { 116 | std::lock_guard data_sources_lock(data_sources_mutex); 117 | data_sources.push_back({ Endpoint::Server, length }); 118 | } 119 | data_source_cv.notify_one(); 120 | } 121 | 122 | void BaseProxy::NotifyClientData(const size_t length) 123 | { 124 | { 125 | std::lock_guard data_sources_lock(data_sources_mutex); 126 | data_sources.push_back({ Endpoint::Client, length }); 127 | } 128 | data_source_cv.notify_one(); 129 | } 130 | 131 | void BaseProxy::ReadIncomingData() 132 | { 133 | // Run indefinitely 134 | while (!closed) 135 | { 136 | if (server_connection.Closed() && client_connection.Closed()) 137 | { 138 | Close(); 139 | break; 140 | } 141 | 142 | // Wait for some data 143 | { 144 | std::unique_lock data_source_lock(data_sources_mutex); 145 | process_data_ready = true; 146 | data_source_cv.wait(data_source_lock); 147 | } 148 | 149 | if (closed) 150 | { 151 | break; 152 | } 153 | 154 | try 155 | { 156 | while (!data_sources.empty()) 157 | { 158 | Endpoint data_source = Endpoint::Server; 159 | // Retrieve the origin of the data, but don't remove it in case we need 160 | // to wait for more data to get a full packet 161 | { 162 | std::lock_guard data_source_lock(data_sources_mutex); 163 | data_source = data_sources.front().first; 164 | } 165 | 166 | // Process the data coming from this endpoint 167 | Connection& src_connection = data_source == Endpoint::Server ? server_connection : client_connection; 168 | std::vector& received_data = data_source == Endpoint::Server ? server_received_data : client_received_data; 169 | // Read all new data from this connection 170 | src_connection.RetreiveData(received_data); 171 | 172 | // Do something with the data 173 | size_t data_to_remove = ProcessData(received_data.cbegin(), received_data.size(), data_source); 174 | 175 | if (data_to_remove == 0) 176 | { 177 | continue; 178 | } 179 | 180 | if (data_to_remove > received_data.size()) 181 | { 182 | std::cerr << "Warning, asked to remove more data than possible" << std::endl; 183 | data_to_remove = received_data.size(); 184 | } 185 | 186 | // Remove the data from the buffer 187 | received_data.erase(received_data.begin(), received_data.begin() + data_to_remove); 188 | 189 | // Remove all data_sources elements that refers to data we already removed 190 | { 191 | std::lock_guard data_source_lock(data_sources_mutex); 192 | std::list>::iterator it = data_sources.begin(); 193 | size_t already_removed = 0; 194 | while (it != data_sources.end()) 195 | { 196 | // If this is from the endpoint we processed 197 | if (it->first == data_source) 198 | { 199 | // If we cleared all the data from this update, remove this entry 200 | // as it's fully processed, and increment the iterator to next item 201 | if (already_removed + it->second <= data_to_remove) 202 | { 203 | already_removed += it->second; 204 | data_sources.erase(it++); 205 | } 206 | // We only used part of the data from this update, so set it's new size 207 | else 208 | { 209 | it->second = it->second - (data_to_remove - already_removed); 210 | already_removed = data_to_remove; 211 | } 212 | 213 | // If we removed the right amount of elements, we can stop iterating the list 214 | if (already_removed == data_to_remove) 215 | { 216 | break; 217 | } 218 | } 219 | else 220 | { 221 | ++it; 222 | } 223 | } 224 | } 225 | 226 | if (server_connection.Closed()) 227 | { 228 | client_connection.Close(); 229 | } 230 | if (client_connection.Closed()) 231 | { 232 | server_connection.Close(); 233 | } 234 | } 235 | } 236 | catch (const std::exception& e) 237 | { 238 | std::cerr << "Exception when reading the data: " << e.what() << std::endl; 239 | client_connection.Close(); 240 | server_connection.Close(); 241 | } 242 | } 243 | } 244 | -------------------------------------------------------------------------------- /sniffcraft/src/Compression.cpp: -------------------------------------------------------------------------------- 1 | #include "sniffcraft/Compression.hpp" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | std::vector Compress(const std::vector &data) 10 | { 11 | unsigned long compressed_size = compressBound(data.size()); 12 | 13 | std::vector compressed_data(compressed_size); 14 | int status = compress2(compressed_data.data(), &compressed_size, data.data(), data.size(), Z_DEFAULT_COMPRESSION); 15 | 16 | if (status != Z_OK) 17 | { 18 | throw(std::runtime_error("Error compressing packet")); 19 | } 20 | 21 | // Shrink to keep only real data 22 | compressed_data.resize(compressed_size); 23 | return compressed_data; 24 | } 25 | 26 | std::vector Decompress(const unsigned char* compressed, const size_t size) 27 | { 28 | std::vector decompressed_data; 29 | decompressed_data.reserve(size); 30 | 31 | std::vector buffer(64 * 1024); 32 | 33 | z_stream strm; 34 | memset(&strm, 0, sizeof(strm)); 35 | strm.next_in = const_cast(compressed); 36 | strm.avail_in = size; 37 | strm.next_out = buffer.data(); 38 | strm.avail_out = buffer.size(); 39 | 40 | int res = inflateInit(&strm); 41 | if (res != Z_OK) 42 | { 43 | throw(std::runtime_error("inflateInit failed: " + std::string(strm.msg))); 44 | } 45 | 46 | for (;;) 47 | { 48 | res = inflate(&strm, Z_NO_FLUSH); 49 | switch (res) 50 | { 51 | case Z_OK: 52 | decompressed_data.insert(decompressed_data.end(), buffer.begin(), buffer.end() - strm.avail_out); 53 | strm.next_out = buffer.data(); 54 | strm.avail_out = buffer.size(); 55 | if (strm.avail_in == 0) 56 | { 57 | inflateEnd(&strm); 58 | return decompressed_data; 59 | } 60 | break; 61 | case Z_STREAM_END: 62 | decompressed_data.insert(decompressed_data.end(), buffer.begin(), buffer.end() - strm.avail_out); 63 | inflateEnd(&strm); 64 | return decompressed_data; 65 | break; 66 | default: 67 | inflateEnd(&strm); 68 | throw(std::runtime_error("Inflate decompression failed: " + std::string(strm.msg))); 69 | break; 70 | } 71 | } 72 | } 73 | 74 | std::tuple CompressRawDeflateFile(std::ifstream& src_file, std::ofstream& dst_file) 75 | { 76 | z_stream strm; 77 | memset(&strm, 0, sizeof(strm)); 78 | int res = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); 79 | if (res != Z_OK) 80 | { 81 | throw(std::runtime_error("deflateInit failed: " + std::string(strm.msg))); 82 | } 83 | 84 | std::vector src_buffer(8192); 85 | std::vector dst_buffer(8192); 86 | 87 | size_t src_size = 0; 88 | size_t dst_size = 0; 89 | uLong crc = crc32(0L, Z_NULL, 0); 90 | 91 | do 92 | { 93 | src_file.read(src_buffer.data(), src_buffer.size()); 94 | strm.avail_in = src_file.gcount(); 95 | strm.next_in = reinterpret_cast(src_buffer.data()); 96 | 97 | crc = crc32(crc, reinterpret_cast(src_buffer.data()), strm.avail_in); 98 | 99 | do 100 | { 101 | strm.avail_out = dst_buffer.size(); 102 | strm.next_out = reinterpret_cast(dst_buffer.data()); 103 | deflate(&strm, src_file.eof() ? Z_FINISH : Z_NO_FLUSH); 104 | const std::streamsize out_count = dst_buffer.size() - strm.avail_out; 105 | dst_file.write(dst_buffer.data(), out_count); 106 | dst_size += out_count; 107 | } while (strm.avail_out == 0); 108 | src_size += strm.avail_in; 109 | } while (!src_file.eof()); 110 | 111 | deflateEnd(&strm); 112 | 113 | return { src_size, dst_size, crc }; 114 | } 115 | -------------------------------------------------------------------------------- /sniffcraft/src/Connection.cpp: -------------------------------------------------------------------------------- 1 | #include "sniffcraft/Connection.hpp" 2 | #include "sniffcraft/DataProcessor.hpp" 3 | 4 | Connection::Connection(asio::io_context& io_context) : 5 | socket(io_context), 6 | timeout_timer(io_context) 7 | { 8 | read_buffer = std::vector(BUFFER_SIZE); 9 | closed = false; 10 | } 11 | 12 | Connection::~Connection() 13 | { 14 | Close(); 15 | } 16 | 17 | void Connection::SetCallback(const std::function& callback) 18 | { 19 | data_callback = callback; 20 | } 21 | 22 | void Connection::SetDataProcessor(std::unique_ptr& processor) 23 | { 24 | // Lock mutex to prevent any race condition issue in WriteData 25 | std::lock_guard write_lock(write_mutex); 26 | data_processor = std::move(processor); 27 | } 28 | 29 | void Connection::RetreiveData(std::vector& dst) 30 | { 31 | std::lock_guard received_lock(received_mutex); 32 | dst.insert(dst.end(), ready_received_data.begin(), ready_received_data.end()); 33 | ready_received_data.clear(); 34 | } 35 | 36 | void Connection::StartListeningAndWriting() 37 | { 38 | write_thread_started = false; 39 | write_thread = std::thread(&Connection::WriteLoop, this); 40 | while (!write_thread_started) 41 | { 42 | 43 | } 44 | timeout_timer.expires_after(std::chrono::seconds(15)); 45 | timeout_timer.async_wait( 46 | std::bind(&Connection::handle_timeout, this, std::placeholders::_1) 47 | ); 48 | socket.async_read_some(asio::buffer(read_buffer.data(), BUFFER_SIZE), 49 | std::bind(&Connection::handle_read, this, 50 | std::placeholders::_1, std::placeholders::_2)); 51 | } 52 | 53 | void Connection::WriteData(const unsigned char* const data, const size_t length) 54 | { 55 | { 56 | std::lock_guard write_lock(write_mutex); 57 | data_to_write.push_back({ std::vector(data, data + length), data_processor != nullptr }); 58 | } 59 | write_cv.notify_one(); 60 | } 61 | 62 | asio::ip::tcp::socket& Connection::GetSocket() 63 | { 64 | return socket; 65 | } 66 | 67 | void Connection::Close() 68 | { 69 | closed = true; 70 | if (socket.is_open()) 71 | { 72 | socket.close(); 73 | } 74 | write_cv.notify_one(); 75 | if (write_thread.joinable()) 76 | { 77 | write_thread.join(); 78 | } 79 | } 80 | 81 | bool Connection::Closed() const 82 | { 83 | return closed; 84 | } 85 | 86 | void Connection::WriteLoop() 87 | { 88 | write_thread_started = true; 89 | // Run indefinitely 90 | while (!closed) 91 | { 92 | // Wait for some data 93 | { 94 | std::unique_lock write_lock(write_mutex); 95 | write_cv.wait(write_lock); 96 | } 97 | 98 | if (closed) 99 | { 100 | break; 101 | } 102 | 103 | while (!data_to_write.empty()) 104 | { 105 | std::pair, bool> next_written; 106 | { 107 | std::lock_guard write_lock(write_mutex); 108 | next_written = data_to_write.front(); 109 | data_to_write.pop_front(); 110 | } 111 | 112 | 113 | const unsigned char* data_ptr = next_written.first.data(); 114 | size_t data_length = next_written.first.size(); 115 | 116 | std::vector processed_data; 117 | if (next_written.second) 118 | { 119 | processed_data = data_processor->ProcessOutgoingData(next_written.first); 120 | data_ptr = processed_data.data(); 121 | data_length = processed_data.size(); 122 | } 123 | 124 | asio::error_code ec; 125 | asio::write(socket, asio::buffer(data_ptr, data_length), ec); 126 | if (ec) 127 | { 128 | closed = true; 129 | return; 130 | } 131 | } 132 | } 133 | } 134 | 135 | void Connection::handle_read(const asio::error_code& ec, const size_t bytes_transferred) 136 | { 137 | if (closed) 138 | { 139 | return; 140 | } 141 | 142 | if (ec) 143 | { 144 | closed = true; 145 | return; 146 | } 147 | 148 | const std::vector* data = &read_buffer; 149 | size_t length = bytes_transferred; 150 | 151 | std::vector processed_data; 152 | if (data_processor != nullptr) 153 | { 154 | processed_data = data_processor->ProcessIncomingData({ data->begin(), data->begin() + length }); 155 | data = &processed_data; 156 | length = processed_data.size(); 157 | } 158 | 159 | { 160 | std::lock_guard received_lock(received_mutex); 161 | ready_received_data.insert(ready_received_data.end(), data->begin(), data->begin() + length); 162 | 163 | // We need to protect the callback call in the mutex scope 164 | // otherwise we could have data in the buffer without the 165 | // data length being transmitted correctly 166 | if (data_callback) 167 | { 168 | data_callback(length); 169 | } 170 | } 171 | 172 | timeout_timer.cancel(); 173 | timeout_timer.expires_after(std::chrono::seconds(15)); 174 | timeout_timer.async_wait( 175 | std::bind(&Connection::handle_timeout, this, std::placeholders::_1) 176 | ); 177 | 178 | socket.async_read_some(asio::buffer(read_buffer.data(), BUFFER_SIZE), 179 | std::bind(&Connection::handle_read, this, 180 | std::placeholders::_1, std::placeholders::_2)); 181 | } 182 | 183 | void Connection::handle_timeout(const asio::error_code& ec) 184 | { 185 | if (ec == asio::error::operation_aborted) 186 | { 187 | return; 188 | } 189 | 190 | Close(); 191 | } 192 | -------------------------------------------------------------------------------- /sniffcraft/src/MinecraftEncryptionDataProcessor.cpp: -------------------------------------------------------------------------------- 1 | #ifdef USE_ENCRYPTION 2 | #include 3 | 4 | #include "sniffcraft/MinecraftEncryptionDataProcessor.hpp" 5 | 6 | MinecraftEncryptionDataProcessor::MinecraftEncryptionDataProcessor(std::unique_ptr& encrypter_) 7 | { 8 | encrypter = std::move(encrypter_); 9 | } 10 | 11 | MinecraftEncryptionDataProcessor::~MinecraftEncryptionDataProcessor() 12 | { 13 | } 14 | 15 | std::vector MinecraftEncryptionDataProcessor::ProcessIncomingData(const std::vector& data) const 16 | { 17 | return encrypter->Decrypt(data); 18 | } 19 | 20 | std::vector MinecraftEncryptionDataProcessor::ProcessOutgoingData(const std::vector& data) const 21 | { 22 | return encrypter->Encrypt(data); 23 | } 24 | #endif 25 | -------------------------------------------------------------------------------- /sniffcraft/src/MinecraftProxy.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #ifdef USE_ENCRYPTION 8 | #include 9 | #include 10 | #if PROTOCOL_VERSION > 758 /* > 1.18.2 */ 11 | #include 12 | #endif 13 | #endif 14 | 15 | #include "sniffcraft/Compression.hpp" 16 | #include "sniffcraft/conf.hpp" 17 | #include "sniffcraft/MinecraftProxy.hpp" 18 | #include "sniffcraft/Logger.hpp" 19 | #include "sniffcraft/ReplayModLogger.hpp" 20 | #ifdef USE_ENCRYPTION 21 | #include "sniffcraft/MinecraftEncryptionDataProcessor.hpp" 22 | #endif 23 | 24 | using namespace ProtocolCraft; 25 | 26 | MinecraftProxy::MinecraftProxy(asio::io_context& io_context) : BaseProxy(io_context) 27 | { 28 | connection_state = ConnectionState::Handshake; 29 | compression_threshold = -1; 30 | } 31 | 32 | MinecraftProxy::~MinecraftProxy() 33 | { 34 | if (logger != nullptr) 35 | { 36 | logger->Stop(); 37 | } 38 | } 39 | 40 | void MinecraftProxy::Start(const std::string& server_address, const unsigned short server_port) 41 | { 42 | logger = std::make_shared(); 43 | 44 | std::shared_lock lock(Conf::conf_mutex); 45 | const ProtocolCraft::Json::Value conf = Conf::LoadConf(); 46 | if (conf.contains(Conf::replay_log_key) && conf[Conf::replay_log_key].get()) 47 | { 48 | replay_logger = std::make_unique(); 49 | replay_logger->SetServerName(server_address + ":" + std::to_string(server_port)); 50 | } 51 | 52 | #ifdef USE_ENCRYPTION 53 | if (conf.contains(Conf::online_key) && conf[Conf::online_key].get()) 54 | { 55 | authentifier = std::make_unique(); 56 | 57 | const std::string credentials_cache_key = conf.contains(Conf::account_cache_key_key) ? conf[Conf::account_cache_key_key].get() : ""; 58 | 59 | std::cout << "Trying to authenticate using Microsoft account" << std::endl; 60 | if (!authentifier->AuthMicrosoft(credentials_cache_key)) 61 | { 62 | std::cerr << "Error trying to authenticate with Microsoft account" << std::endl; 63 | throw std::runtime_error("Error trying to authenticate with Microsoft account"); 64 | } 65 | } 66 | #endif 67 | 68 | BaseProxy::Start(server_address, server_port); 69 | } 70 | 71 | std::shared_ptr MinecraftProxy::GetLogger() const 72 | { 73 | return logger; 74 | } 75 | 76 | size_t MinecraftProxy::ProcessData(const std::vector::const_iterator& data, const size_t length, const Endpoint source) 77 | { 78 | Connection& dst_connection = source == Endpoint::Server ? client_connection : server_connection; 79 | 80 | std::vector::const_iterator data_iterator = data; 81 | size_t max_length = length; 82 | 83 | const size_t packet_length = Peek(data_iterator, max_length); 84 | const size_t packet_length_length = length - max_length; 85 | 86 | // We don't have enough data to get packet size 87 | if (packet_length == 0) 88 | { 89 | return 0; 90 | } 91 | // We don't have enough data to get a full packet 92 | if (packet_length > max_length) 93 | { 94 | return 0; 95 | } 96 | 97 | size_t remaining_packet_bytes = packet_length; 98 | std::vector uncompressed; 99 | if (compression_threshold > -1) 100 | { 101 | const int data_length = ReadData(data_iterator, remaining_packet_bytes); 102 | if (data_length != 0) 103 | { 104 | uncompressed = Decompress(&(*data_iterator), remaining_packet_bytes); 105 | data_iterator = uncompressed.begin(); 106 | remaining_packet_bytes = uncompressed.size(); 107 | } 108 | } 109 | 110 | const int minecraft_id = ReadData(data_iterator, remaining_packet_bytes); 111 | 112 | std::shared_ptr packet = source == Endpoint::Client ? 113 | CreateServerboundPacket(connection_state, minecraft_id) : 114 | CreateClientboundPacket(connection_state, minecraft_id); 115 | 116 | // Clear the replacement bytes vector 117 | bool error_parsing = false; 118 | if (packet != nullptr) 119 | { 120 | try 121 | { 122 | packet->Read(data_iterator, remaining_packet_bytes); 123 | } 124 | catch (const std::exception& ex) 125 | { 126 | std::cout << ((source == Endpoint::Server) ? "Server --> Client: " : "Client --> Server: ") << 127 | "PARSING EXCEPTION for message " << packet->GetName() << "(: " << minecraft_id << ")" << ex.what() << std::endl; 128 | error_parsing = true; 129 | } 130 | } 131 | else 132 | { 133 | std::cout << ((source == Endpoint::Server) ? "Server --> Client: " : "Client --> Server: ") << 134 | "NULL MESSAGE WITH ID: " << minecraft_id << std::endl; 135 | error_parsing = true; 136 | } 137 | 138 | transmit_original_packet = true; 139 | const ConnectionState old_connection_state = connection_state; 140 | if (!error_parsing) 141 | { 142 | // React to the message if necessary 143 | packet->Dispatch(this); 144 | } 145 | 146 | // Transfer the data as they came 147 | if (transmit_original_packet) 148 | { 149 | // The packet is transmitted, log it as it is 150 | if (!error_parsing) 151 | { 152 | logger->Log(packet, old_connection_state, source, packet_length + packet_length_length); 153 | if (replay_logger) 154 | { 155 | replay_logger->Log(packet, old_connection_state, source); 156 | } 157 | } 158 | 159 | dst_connection.WriteData(&(*data), packet_length + packet_length_length); 160 | } 161 | // The packet has been replaced by something else, log it as intercepted by sniffcraft 162 | else if (!error_parsing) 163 | { 164 | // The packet has been replaced, log it as intercepted by sniffcraft 165 | logger->Log(packet, old_connection_state, source == Endpoint::Server ? Endpoint::ServerToSniffcraft : Endpoint::ClientToSniffcraft, packet_length + packet_length_length); 166 | } 167 | 168 | // Return the number of bytes we read (or rather should have read in case of error) 169 | return packet_length + packet_length_length; 170 | } 171 | 172 | size_t MinecraftProxy::Peek(std::vector::const_iterator& data, size_t& length) 173 | { 174 | try 175 | { 176 | return static_cast(ReadData(data, length)); 177 | } 178 | catch (const std::exception&) 179 | { 180 | return 0; 181 | } 182 | } 183 | 184 | std::vector MinecraftProxy::PacketToBytes(const Packet& packet) const 185 | { 186 | std::vector content; 187 | packet.Write(content); 188 | 189 | if (compression_threshold > -1) 190 | { 191 | if (content.size() < compression_threshold) 192 | { 193 | content.insert(content.begin(), 0x00); 194 | 195 | } 196 | else 197 | { 198 | std::vector compressed_data = Compress(content); 199 | const int decompressed_size = static_cast(content.size()); 200 | content.clear(); 201 | WriteData(decompressed_size, content); 202 | content.insert(content.end(), compressed_data.begin(), compressed_data.end()); 203 | } 204 | } 205 | 206 | std::vector sized_packet; 207 | WriteData(static_cast(content.size()), sized_packet); 208 | sized_packet.insert(std::end(sized_packet), std::cbegin(content), std::cend(content)); 209 | return sized_packet; 210 | } 211 | 212 | void MinecraftProxy::Handle(ServerboundClientIntentionPacket& packet) 213 | { 214 | if (packet.GetProtocolVersion() != PROTOCOL_VERSION) 215 | { 216 | std::cout << "WARNING, Client and Sniffcraft protocol versions are different (" 217 | << packet.GetProtocolVersion() << " VS " << PROTOCOL_VERSION 218 | << "). Logged packet details may be wrong" 219 | << std::endl; 220 | } 221 | transmit_original_packet = false; 222 | 223 | const ConnectionState old_connection_state = connection_state; 224 | connection_state = static_cast(packet.GetIntention()); 225 | 226 | std::shared_ptr replacement_intention_packet = std::make_shared(); 227 | replacement_intention_packet->SetIntention(packet.GetIntention()); 228 | replacement_intention_packet->SetProtocolVersion(packet.GetProtocolVersion()); 229 | std::string new_hostname = server_ip_; 230 | const size_t old_hostname_strlen = strlen(packet.GetHostName().c_str()); 231 | // Forge adds \0FML\0, \0FML2\0 or \0FML3\0 to the hostname 232 | // strlen will only count the size until the fist \0 233 | if (packet.GetHostName().size() > old_hostname_strlen) 234 | { 235 | new_hostname += packet.GetHostName().substr(old_hostname_strlen); 236 | } 237 | replacement_intention_packet->SetHostName(new_hostname); 238 | replacement_intention_packet->SetPort(server_port_); 239 | 240 | std::vector replacement_bytes = PacketToBytes(*replacement_intention_packet); 241 | server_connection.WriteData(replacement_bytes.data(), replacement_bytes.size()); 242 | 243 | // We don't log packet size as it's not really part of the network data 244 | logger->Log(replacement_intention_packet, old_connection_state, Endpoint::SniffcraftToServer, 0); 245 | // Don't replay log it as it's serverbound 246 | } 247 | 248 | void MinecraftProxy::Handle(ServerboundHelloPacket& packet) 249 | { 250 | #ifdef USE_ENCRYPTION 251 | if (authentifier == nullptr) 252 | { 253 | return; 254 | } 255 | 256 | transmit_original_packet = false; 257 | 258 | // Make sure we use the name and the signature key 259 | // of the profile we auth with 260 | std::shared_ptr replacement_hello_packet = std::make_shared(); 261 | #if PROTOCOL_VERSION < 759 /* < 1.19 */ 262 | replacement_hello_packet->SetGameProfile(authentifier->GetPlayerDisplayName()); 263 | #else 264 | replacement_hello_packet->SetName_(authentifier->GetPlayerDisplayName()); 265 | 266 | #if PROTOCOL_VERSION < 761 /* < 1.19.3 */ 267 | ProfilePublicKey key; 268 | key.SetTimestamp(authentifier->GetKeyTimestamp()); 269 | const std::vector key_bytes = Botcraft::Utilities::RSAToBytes(authentifier->GetPublicKey()); 270 | if (!packet.GetPublicKey().has_value() || key_bytes != packet.GetPublicKey().value().GetKey()) 271 | { 272 | std::cerr << "WARNING, public key mismatch between client and sniffcraft.\n" 273 | << "You might get kicked out if you send a chat message" << std::endl; 274 | } 275 | key.SetKey(key_bytes); 276 | key.SetSignature(Botcraft::Utilities::DecodeBase64(authentifier->GetKeySignature())); 277 | replacement_hello_packet->SetPublicKey(key); 278 | #endif 279 | #if PROTOCOL_VERSION > 759 /* > 1.19 */ 280 | replacement_hello_packet->SetProfileId(authentifier->GetPlayerUUID()); 281 | #endif 282 | #endif 283 | 284 | std::vector replacement_bytes = PacketToBytes(*replacement_hello_packet); 285 | server_connection.WriteData(replacement_bytes.data(), replacement_bytes.size()); 286 | // We don't log packet size as it's not really part of the network data 287 | logger->Log(replacement_hello_packet, connection_state, Endpoint::SniffcraftToServer, 0); 288 | // Don't replay log it as it's serverbound 289 | #endif 290 | } 291 | 292 | #if PROTOCOL_VERSION < 764 /* < 1.20.2 */ 293 | void MinecraftProxy::Handle(ClientboundGameProfilePacket& packet) 294 | { 295 | connection_state = ConnectionState::Play; 296 | } 297 | #endif 298 | 299 | void MinecraftProxy::Handle(ClientboundLoginCompressionPacket& packet) 300 | { 301 | compression_threshold = packet.GetCompressionThreshold(); 302 | } 303 | 304 | void MinecraftProxy::Handle(ClientboundHelloPacket& packet) 305 | { 306 | #ifdef USE_ENCRYPTION 307 | if (authentifier == nullptr) 308 | { 309 | std::cerr << "WARNING, trying to connect to a server with encryption enabled\n" 310 | << "but impossible without being authenticated.\n" 311 | << "Try changing Online to true in sniffcraft conf json file\n" 312 | << "or check Authenticated in the GUI\n" 313 | << std::endl; 314 | throw std::runtime_error("Not authenticated"); 315 | } 316 | 317 | transmit_original_packet = false; 318 | 319 | std::unique_ptr encrypter = std::make_unique(); 320 | 321 | std::vector raw_shared_secret; 322 | std::vector encrypted_shared_secret; 323 | 324 | #if PROTOCOL_VERSION < 759 /* < 1.19 */ 325 | std::vector encrypted_nonce; 326 | encrypter->Init(packet.GetPublicKey(), packet.GetNonce(), 327 | raw_shared_secret, encrypted_nonce, encrypted_shared_secret); 328 | #elif PROTOCOL_VERSION < 761 /* < 1.19.3 */ 329 | std::vector salted_nonce_signature; 330 | long long int salt; 331 | encrypter->Init(packet.GetPublicKey(), packet.GetNonce(), authentifier->GetPrivateKey(), 332 | raw_shared_secret, encrypted_shared_secret, 333 | salt, salted_nonce_signature); 334 | #else 335 | std::vector encrypted_challenge; 336 | encrypter->Init(packet.GetPublicKey(), packet.GetChallenge(), 337 | raw_shared_secret, encrypted_shared_secret, encrypted_challenge); 338 | #endif 339 | 340 | authentifier->JoinServer(packet.GetServerId(), raw_shared_secret, packet.GetPublicKey()); 341 | 342 | std::shared_ptr response_packet = std::make_shared(); 343 | response_packet->SetKeyBytes(encrypted_shared_secret); 344 | #if PROTOCOL_VERSION < 759 /* < 1.19 */ 345 | // Pre-1.19 behaviour, send encrypted nonce 346 | response_packet->SetNonce(encrypted_nonce); 347 | #elif PROTOCOL_VERSION < 761 /* < 1.19.3 */ 348 | // 1.19 - 1.19.2 behaviour, send salted nonce signature 349 | SaltSignature salt_signature; 350 | salt_signature.SetSalt(salt); 351 | salt_signature.SetSignature(salted_nonce_signature); 352 | response_packet->SetSaltSignature(salt_signature); 353 | #else 354 | // 1.19.3+ behaviour, back to sending encrypted challenge only 355 | response_packet->SetEncryptedChallenge(encrypted_challenge); 356 | #endif 357 | 358 | // Send additional packet only to server on behalf of the client 359 | const std::vector replacement_bytes = PacketToBytes(*response_packet); 360 | server_connection.WriteData(replacement_bytes.data(), replacement_bytes.size()); 361 | 362 | // We don't log packet size as it's not really part of the network data 363 | logger->Log(response_packet, connection_state, Endpoint::SniffcraftToServer, 0); 364 | 365 | // Set the encrypter for any future message from the server 366 | std::unique_ptr encryption_data_processor = std::make_unique(encrypter); 367 | server_connection.SetDataProcessor(encryption_data_processor); 368 | 369 | #else 370 | std::cerr << "WARNING, trying to connect to a server with encryption enabled\n" << 371 | "but sniffcraft was built without encryption support." << std::endl; 372 | throw std::runtime_error("Not authenticated"); 373 | #endif 374 | } 375 | 376 | #if USE_ENCRYPTION && PROTOCOL_VERSION > 760 /* > 1.19.1/2 */ 377 | void MinecraftProxy::Handle(ClientboundLoginPacket& packet) 378 | { 379 | if (authentifier == nullptr) 380 | { 381 | return; 382 | } 383 | 384 | std::shared_ptr chat_session_packet = std::make_shared(); 385 | RemoteChatSessionData chat_session_data; 386 | 387 | ProfilePublicKey key; 388 | key.SetTimestamp(authentifier->GetKeyTimestamp()); 389 | key.SetKey(Botcraft::Utilities::RSAToBytes(authentifier->GetPublicKey())); 390 | key.SetSignature(Botcraft::Utilities::DecodeBase64(authentifier->GetKeySignature())); 391 | 392 | chat_session_data.SetProfilePublicKey(key); 393 | chat_session_uuid = UUID(); 394 | std::mt19937 rnd = std::mt19937(static_cast(std::chrono::duration_cast(std::chrono::high_resolution_clock::now().time_since_epoch()).count())); 395 | std::uniform_int_distribution distrib(std::numeric_limits::min(), std::numeric_limits::max()); 396 | for (size_t i = 0; i < chat_session_uuid.size(); ++i) 397 | { 398 | chat_session_uuid[i] = static_cast(distrib(rnd)); 399 | } 400 | chat_session_data.SetUuid(chat_session_uuid); 401 | 402 | chat_session_packet->SetChatSession(chat_session_data); 403 | std::vector chat_session_packet_bytes = PacketToBytes(*chat_session_packet); 404 | 405 | server_connection.WriteData(chat_session_packet_bytes.data(), chat_session_packet_bytes.size()); 406 | 407 | // We don't log packet size as it's not really part of the network data 408 | logger->Log(chat_session_packet, connection_state, Endpoint::SniffcraftToServer, 0); 409 | } 410 | 411 | void MinecraftProxy::Handle(ServerboundChatPacket& packet) 412 | { 413 | if (authentifier == nullptr) 414 | { 415 | return; 416 | } 417 | 418 | transmit_original_packet = false; 419 | 420 | // Ugly stuff because there is a GetMessage macro in Windows API somewhere :) 421 | #if _MSC_VER || __MINGW32__ 422 | #pragma push_macro("GetMessage") 423 | #undef GetMessage 424 | #endif 425 | 426 | std::shared_ptr replacement_chat_packet = std::make_shared(); 427 | replacement_chat_packet->SetMessage(packet.GetMessage()); 428 | 429 | long long int salt, timestamp; 430 | std::vector signature; 431 | 432 | const auto [signatures, updates] = chat_context.GetLastSeenMessagesUpdate(); 433 | const int current_message_sent_index = message_sent_index++; 434 | signature = authentifier->GetMessageSignature(packet.GetMessage(), current_message_sent_index, chat_session_uuid, signatures, salt, timestamp); 435 | replacement_chat_packet->SetLastSeenMessages(updates); 436 | 437 | #if _MSC_VER || __MINGW32__ 438 | #pragma pop_macro("GetMessage") 439 | #endif 440 | 441 | if (signature.empty()) 442 | { 443 | throw std::runtime_error("Empty chat message signature."); 444 | } 445 | replacement_chat_packet->SetTimestamp(timestamp); 446 | replacement_chat_packet->SetSalt(salt); 447 | replacement_chat_packet->SetSignature(signature); 448 | 449 | const std::vector replacement_bytes = PacketToBytes(*replacement_chat_packet); 450 | server_connection.WriteData(replacement_bytes.data(), replacement_bytes.size()); 451 | // We don't log packet size as it's not really part of the network data 452 | logger->Log(replacement_chat_packet, connection_state, Endpoint::SniffcraftToServer, 0); 453 | } 454 | 455 | #if PROTOCOL_VERSION < 766 /* < 1.20.5 */ 456 | void MinecraftProxy::Handle(ServerboundChatCommandPacket& packet) 457 | #else 458 | void MinecraftProxy::Handle(ServerboundChatCommandSignedPacket& packet) 459 | #endif 460 | { 461 | if (authentifier == nullptr) 462 | { 463 | return; 464 | } 465 | 466 | transmit_original_packet = false; 467 | 468 | #if PROTOCOL_VERSION < 766 /* < 1.20.5 */ 469 | std::shared_ptr replacement_chat_command = std::make_shared(); 470 | #else 471 | std::shared_ptr replacement_chat_command = std::make_shared(); 472 | #endif 473 | replacement_chat_command->SetCommand(packet.GetCommand()); 474 | replacement_chat_command->SetTimestamp(packet.GetTimestamp()); 475 | replacement_chat_command->SetSalt(packet.GetSalt()); 476 | const auto [signatures, updates] = chat_context.GetLastSeenMessagesUpdate(); 477 | replacement_chat_command->SetLastSeenMessages(updates); 478 | replacement_chat_command->SetArgumentSignatures(packet.GetArgumentSignatures()); 479 | 480 | const std::vector replacement_bytes = PacketToBytes(*replacement_chat_command); 481 | server_connection.WriteData(replacement_bytes.data(), replacement_bytes.size()); 482 | // We don't log packet size as it's not really part of the network data 483 | logger->Log(replacement_chat_command, connection_state, Endpoint::SniffcraftToServer, 0); 484 | } 485 | 486 | void MinecraftProxy::Handle(ClientboundPlayerChatPacket& packet) 487 | { 488 | if (authentifier == nullptr) 489 | { 490 | return; 491 | } 492 | 493 | if (packet.GetSignature().has_value()) 494 | { 495 | chat_context.AddSeenMessage(std::vector(packet.GetSignature().value().begin(), packet.GetSignature().value().end())); 496 | 497 | if (chat_context.GetOffset() > 64) 498 | { 499 | std::shared_ptr ack_packet = std::make_shared(); 500 | ack_packet->SetOffset(chat_context.GetAndResetOffset()); 501 | 502 | const std::vector replacement_bytes_ack = PacketToBytes(*ack_packet); 503 | server_connection.WriteData(replacement_bytes_ack.data(), replacement_bytes_ack.size()); 504 | // We don't log packet size as it's not really part of the network data 505 | logger->Log(ack_packet, connection_state, Endpoint::SniffcraftToServer, 0); 506 | } 507 | } 508 | } 509 | #endif 510 | 511 | #if PROTOCOL_VERSION > 763 /* > 1.20.1 */ 512 | void MinecraftProxy::Handle(ServerboundLoginAcknowledgedPacket& packet) 513 | { 514 | connection_state = ConnectionState::Configuration; 515 | } 516 | 517 | void MinecraftProxy::Handle(ServerboundFinishConfigurationPacket& packet) 518 | { 519 | connection_state = ConnectionState::Play; 520 | } 521 | 522 | void MinecraftProxy::Handle(ServerboundConfigurationAcknowledgedPacket& packet) 523 | { 524 | connection_state = ConnectionState::Configuration; 525 | } 526 | #endif 527 | -------------------------------------------------------------------------------- /sniffcraft/src/ReplayModLogger.cpp: -------------------------------------------------------------------------------- 1 | #include "sniffcraft/ReplayModLogger.hpp" 2 | #include "sniffcraft/Zip/ZeptoZip.hpp" 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace ProtocolCraft; 9 | 10 | ReplayModLogger::ReplayModLogger() 11 | { 12 | is_running = true; 13 | log_thread = std::thread(&ReplayModLogger::LogConsume, this); 14 | } 15 | 16 | ReplayModLogger::~ReplayModLogger() 17 | { 18 | if (is_running) 19 | { 20 | is_running = false; 21 | log_condition.notify_all(); 22 | 23 | while (!logging_queue.empty()) 24 | { 25 | std::this_thread::sleep_for(std::chrono::milliseconds(50)); 26 | } 27 | 28 | if (log_thread.joinable()) 29 | { 30 | log_thread.join(); 31 | } 32 | replay_file.close(); 33 | 34 | SaveReplayMetadataFile(); 35 | WrapMCPRFile(); 36 | } 37 | } 38 | 39 | void ReplayModLogger::Log(const std::shared_ptr packet, const ConnectionState connection_state, const Endpoint origin) 40 | { 41 | if (!is_running) 42 | { 43 | return; 44 | } 45 | 46 | std::lock_guard log_guard(log_mutex); 47 | if (!replay_file.is_open()) 48 | { 49 | start_time = std::chrono::system_clock::now(); 50 | auto in_time_t = std::chrono::system_clock::to_time_t(start_time); 51 | 52 | std::stringstream ss; 53 | ss << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d-%H-%M-%S"); 54 | session_prefix = ss.str(); 55 | replay_file = std::ofstream(session_prefix + "_recording.tmcpr", std::ios::out | std::ios::binary); 56 | } 57 | 58 | logging_queue.push({ packet, std::chrono::system_clock::now(), connection_state, origin }); 59 | log_condition.notify_all(); 60 | } 61 | 62 | void ReplayModLogger::SetServerName(const std::string& server_name_) 63 | { 64 | server_name = server_name_; 65 | } 66 | 67 | void ReplayModLogger::LogConsume() 68 | { 69 | while (is_running) 70 | { 71 | { 72 | std::unique_lock lock(log_mutex); 73 | log_condition.wait(lock); 74 | } 75 | while (!logging_queue.empty()) 76 | { 77 | LogItem item; 78 | { 79 | std::lock_guard log_guard(log_mutex); 80 | item = logging_queue.front(); 81 | logging_queue.pop(); 82 | } 83 | 84 | if (item.origin == Endpoint::Server || item.origin == Endpoint::SniffcraftToClient) 85 | { 86 | std::vector packet; 87 | // Write ID + Packet data 88 | item.packet->Write(packet); 89 | 90 | // Get timestamp in ms 91 | std::vector header; 92 | WriteData(static_cast(std::chrono::duration_cast(item.date - start_time).count()), header); 93 | // Get total size 94 | WriteData(static_cast(packet.size()), header); 95 | 96 | replay_file.write(reinterpret_cast(header.data()), header.size()); 97 | replay_file.write(reinterpret_cast(packet.data()), packet.size()); 98 | } 99 | } 100 | } 101 | } 102 | 103 | void ReplayModLogger::SaveReplayMetadataFile() const 104 | { 105 | std::ofstream metadata(session_prefix + "_metaData.json", std::ios::out); 106 | auto now = std::chrono::system_clock::now(); 107 | 108 | metadata << "{\"singleplayer\":false," 109 | << "\"serverName\":\"" << server_name << "\"," 110 | << "\"duration\":" << std::chrono::duration_cast(now - start_time).count() << "," 111 | << "\"date\":" << std::chrono::duration_cast(now.time_since_epoch()).count() << "," 112 | << "\"fileFormat\":\"MCPR\"," 113 | << "\"fileFormatVersion\":14," 114 | << "\"protocol\":\"" << PROTOCOL_VERSION << "\"," 115 | << "\"generator\":\"SniffCraft\"}"; 116 | metadata.close(); 117 | } 118 | 119 | void ReplayModLogger::WrapMCPRFile() const 120 | { 121 | ZeptoZip::CreateZipArchive(session_prefix + ".mcpr", { session_prefix + "_metaData.json", session_prefix + "_recording.tmcpr" }, 122 | { "metaData.json", "recording.tmcpr" }); 123 | std::remove((session_prefix + "_metaData.json").c_str()); 124 | std::remove((session_prefix + "_recording.tmcpr").c_str()); 125 | } 126 | -------------------------------------------------------------------------------- /sniffcraft/src/Zip/ZeptoZip.cpp: -------------------------------------------------------------------------------- 1 | #include "sniffcraft/Zip/ZeptoZip.hpp" 2 | #include "sniffcraft/Zip/DosTime.hpp" 3 | #include "sniffcraft/Compression.hpp" 4 | 5 | #include 6 | #include 7 | 8 | void ZeptoZip::CreateZipArchive(const std::string& outpath, const std::vector& inputs, const std::vector& filenames) 9 | { 10 | // We assume inputs.size() == filenames.size() 11 | 12 | std::ofstream out_file(outpath, std::ios::out | std::ios::binary); 13 | const unsigned int msdos_now = DosTime::Now(); 14 | 15 | std::vector crcs(inputs.size()); 16 | std::vector compressed_sizes(inputs.size()); 17 | std::vector raw_sizes(inputs.size()); 18 | std::vector filename_sizes(inputs.size()); 19 | std::vector header_offsets(inputs.size()); 20 | 21 | unsigned short number_of_records = inputs.size(); 22 | 23 | unsigned int bytes_added_files = 0; 24 | unsigned int bytes_added_central_directory = 0; 25 | 26 | // All files 27 | for (int i = 0; i < inputs.size(); ++i) 28 | { 29 | filename_sizes[i] = filenames[i].size(); 30 | header_offsets[i] = bytes_added_files; 31 | 32 | // Write all data to file 33 | 34 | // Signature 35 | out_file << (char)0x50 << (char)0x4b << (char)0x03 << (char)0x04; 36 | bytes_added_files += 4; 37 | // Version needed to extract (minimum) 38 | out_file << (char)0x14 << (char)0x00; 39 | bytes_added_files += 2; 40 | // General purpose flag 41 | out_file << (char)0x00 << (char)0x00; 42 | bytes_added_files += 2; 43 | // Compression method 44 | out_file << (char)0x08 << (char)0x00; 45 | bytes_added_files += 2; 46 | // Last modification time 47 | out_file << ((char*)(&msdos_now))[0] << ((char*)(&msdos_now))[1]; 48 | bytes_added_files += 2; 49 | // Last modification date 50 | out_file << ((char*)(&msdos_now))[2] << ((char*)(&msdos_now))[3]; 51 | bytes_added_files += 2; 52 | // CRC-32 of raw data 53 | const unsigned int crc_offset = bytes_added_files; 54 | out_file << (char)0x00 << (char)0x00 << (char)0x00 << (char)0x00; // temp value, will be set later 55 | bytes_added_files += 4; 56 | // Compressed size 57 | const unsigned int compressed_size_offset = bytes_added_files; 58 | out_file << (char)0x00 << (char)0x00 << (char)0x00 << (char)0x00; // temp value, will be set later 59 | bytes_added_files += 4; 60 | // Uncompressed size 61 | const unsigned int uncompressed_size_offset = bytes_added_files; 62 | out_file << (char)0x00 << (char)0x00 << (char)0x00 << (char)0x00; // temp value, will be set later 63 | bytes_added_files += 4; 64 | // File name length 65 | out_file << ((char*)filename_sizes.data())[i * 2 + 0] << ((char*)filename_sizes.data())[i * 2 + 1]; 66 | bytes_added_files += 2; 67 | // Extra field length 68 | out_file << (char)0x00 << (char)0x00; 69 | bytes_added_files += 2; 70 | // File name 71 | out_file << filenames[i]; 72 | bytes_added_files += filename_sizes[i]; 73 | // File Content 74 | std::ifstream in_file(inputs[i], std::ios::binary); 75 | std::tuple compression_output = CompressRawDeflateFile(in_file, out_file); 76 | in_file.close(); 77 | raw_sizes[i] = std::get<0>(compression_output); 78 | compressed_sizes[i] = std::get<1>(compression_output); 79 | crcs[i] = std::get<2>(compression_output); 80 | bytes_added_files += compressed_sizes[i]; 81 | 82 | // Replace temp values now that we have the correct ones 83 | out_file.seekp(crc_offset); 84 | out_file << ((char*)crcs.data())[i * 4 + 0] << ((char*)crcs.data())[i * 4 + 1] << ((char*)crcs.data())[i * 4 + 2] << ((char*)crcs.data())[i * 4 + 3]; 85 | out_file.seekp(compressed_size_offset); 86 | out_file << ((char*)compressed_sizes.data())[i * 4 + 0] << ((char*)compressed_sizes.data())[i * 4 + 1] << ((char*)compressed_sizes.data())[i * 4 + 2] << ((char*)compressed_sizes.data())[i * 4 + 3]; 87 | out_file.seekp(uncompressed_size_offset); 88 | out_file << ((char*)raw_sizes.data())[i * 4 + 0] << ((char*)raw_sizes.data())[i * 4 + 1] << ((char*)raw_sizes.data())[i * 4 + 2] << ((char*)raw_sizes.data())[i * 4 + 3]; 89 | 90 | // Go back at the end of the file for the next file 91 | out_file.seekp(0, std::ios_base::end); 92 | } 93 | 94 | // Central directory file header 95 | for (int i = 0; i < inputs.size(); i++) 96 | { 97 | // Signature 98 | out_file << (char)0x50 << (char)0x4b << (char)0x01 << (char)0x02; 99 | bytes_added_central_directory += 4; 100 | // Version made by 101 | out_file << (char)0x14 << (char)0x00; 102 | bytes_added_central_directory += 2; 103 | // Version needed to extract (minimum) 104 | out_file << (char)0x14 << (char)0x00; 105 | bytes_added_central_directory += 2; 106 | // General purpose flag 107 | out_file << (char)0x00 << (char)0x00; 108 | bytes_added_central_directory += 2; 109 | // Compression method 110 | out_file << (char)0x08 << (char)0x00; 111 | bytes_added_central_directory += 2; 112 | // Last modification time 113 | out_file << ((char*)(&msdos_now))[0] << ((char*)(&msdos_now))[1]; 114 | bytes_added_central_directory += 2; 115 | // Last modification date 116 | out_file << ((char*)(&msdos_now))[2] << ((char*)(&msdos_now))[3]; 117 | bytes_added_central_directory += 2; 118 | // CRC-32 of raw data 119 | out_file << ((char*)crcs.data())[i * 4 + 0] << ((char*)crcs.data())[i * 4 + 1] << ((char*)crcs.data())[i * 4 + 2] << ((char*)crcs.data())[i * 4 + 3]; 120 | bytes_added_central_directory += 4; 121 | // Compressed size 122 | out_file << ((char*)compressed_sizes.data())[i * 4 + 0] << ((char*)compressed_sizes.data())[i * 4 + 1] << ((char*)compressed_sizes.data())[i * 4 + 2] << ((char*)compressed_sizes.data())[i * 4 + 3]; 123 | bytes_added_central_directory += 4; 124 | // Uncompressed size 125 | out_file << ((char*)raw_sizes.data())[i * 4 + 0] << ((char*)raw_sizes.data())[i * 4 + 1] << ((char*)raw_sizes.data())[i * 4 + 2] << ((char*)raw_sizes.data())[i * 4 + 3]; 126 | bytes_added_central_directory += 4; 127 | // File name length 128 | out_file << ((char*)filename_sizes.data())[i * 2 + 0] << ((char*)filename_sizes.data())[i * 2 + 1]; 129 | bytes_added_central_directory += 2; 130 | // Extra field length 131 | out_file << (char)0x00 << (char)0x00; 132 | bytes_added_central_directory += 2; 133 | // File comment length 134 | out_file << (char)0x00 << (char)0x00; 135 | bytes_added_central_directory += 2; 136 | // Disk number where file starts 137 | out_file << (char)0x00 << (char)0x00; 138 | bytes_added_central_directory += 2; 139 | // Internal file attributes 140 | out_file << (char)0x01 << (char)0x00; 141 | bytes_added_central_directory += 2; 142 | // External file attributes 143 | out_file << (char)0x20 << (char)0x00 << (char)0x00 << (char)0x00; 144 | bytes_added_central_directory += 4; 145 | // Relative offset of local file header 146 | out_file << ((char*)header_offsets.data())[i * 4 + 0] << ((char*)header_offsets.data())[i * 4 + 1] << ((char*)header_offsets.data())[i * 4 + 2] << ((char*)header_offsets.data())[i * 4 + 3]; 147 | bytes_added_central_directory += 4; 148 | // File name 149 | out_file << filenames[i]; 150 | bytes_added_central_directory += filename_sizes[i]; 151 | } 152 | 153 | // End of central directory record 154 | // Signature 155 | out_file << (char)0x50 << (char)0x4b << (char)0x05 << (char)0x06; 156 | // Number of this disk 157 | out_file << (char)0x00 << (char)0x00; 158 | // Disk where central directory starts 159 | out_file << (char)0x00 << (char)0x00; 160 | // Number of central directory records on this disk 161 | out_file << ((char*)(&number_of_records))[0] << ((char*)(&number_of_records))[1]; 162 | // Total number of central directory records 163 | out_file << ((char*)(&number_of_records))[0] << ((char*)(&number_of_records))[1]; 164 | // Size of central directory (51x2) 165 | out_file << ((char*)(&bytes_added_central_directory))[0] << ((char*)(&bytes_added_central_directory))[1] << ((char*)(&bytes_added_central_directory))[2] << ((char*)(&bytes_added_central_directory))[3]; 166 | // Offset of start of central directory 167 | out_file << ((char*)(&bytes_added_files))[0] << ((char*)(&bytes_added_files))[1] << ((char*)(&bytes_added_files))[2] << ((char*)(&bytes_added_files))[3]; 168 | // Comment length 169 | out_file << (char)0x00 << (char)0x00; 170 | 171 | out_file.close(); 172 | } 173 | -------------------------------------------------------------------------------- /sniffcraft/src/conf.cpp: -------------------------------------------------------------------------------- 1 | #include "sniffcraft/conf.hpp" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #ifndef WIN32 9 | #include 10 | #else 11 | #define stat _stat 12 | #endif 13 | 14 | const std::string Conf::server_address_key = "ServerAddress"; 15 | const std::string Conf::local_port_key = "LocalPort"; 16 | const std::string Conf::text_file_log_key = "LogToTxtFile"; 17 | const std::string Conf::binary_file_log_key = "LogToBinFile"; 18 | const std::string Conf::console_log_key = "LogToConsole"; 19 | const std::string Conf::replay_log_key = "LogToReplay"; 20 | const std::string Conf::raw_bytes_log_key = "LogRawBytes"; 21 | const std::string Conf::online_key = "Online"; 22 | const std::string Conf::network_recap_to_console_key = "NetworkRecapToConsole"; 23 | const std::string Conf::account_cache_key_key = "MicrosoftAccountCacheKey"; 24 | const std::string Conf::handshaking_key = "Handshaking"; 25 | const std::string Conf::status_key = "Status"; 26 | const std::string Conf::login_key = "Login"; 27 | const std::string Conf::configuration_key = "Configuration"; 28 | const std::string Conf::play_key = "Play"; 29 | const std::string Conf::ignored_clientbound_key = "ignored_clientbound"; 30 | const std::string Conf::ignored_serverbound_key = "ignored_serverbound"; 31 | const std::string Conf::detailed_clientbound_key = "detailed_clientbound"; 32 | const std::string Conf::detailed_serverbound_key = "detailed_serverbound"; 33 | 34 | #ifdef WITH_GUI 35 | bool Conf::headless = false; 36 | #else 37 | bool Conf::headless = true; 38 | #endif 39 | 40 | std::string Conf::conf_path = ""; 41 | 42 | std::shared_mutex Conf::conf_mutex; 43 | 44 | ProtocolCraft::Json::Value Conf::LoadConf() 45 | { 46 | if (conf_path.empty()) 47 | { 48 | conf_path = "conf.json"; 49 | } 50 | 51 | // Create file if it doesn't exist 52 | if (!std::filesystem::exists(conf_path)) 53 | { 54 | std::ofstream outfile(conf_path, std::ios::out); 55 | outfile << ProtocolCraft::Json::Value().Dump(4); 56 | } 57 | 58 | std::ifstream file = std::ifstream(conf_path, std::ios::in); 59 | if (!file.is_open()) 60 | { 61 | throw std::runtime_error("Error trying to open conf file at: " + conf_path); 62 | } 63 | ProtocolCraft::Json::Value json; 64 | file >> json; 65 | file.close(); 66 | 67 | if (!json.is_object()) 68 | json = ProtocolCraft::Json::Object(); 69 | // Set default values if missing 70 | if (!json.contains(server_address_key)) 71 | json[server_address_key] = "127.0.0.1:25565"; 72 | if (!json.contains(local_port_key)) 73 | json[local_port_key] = 25555; 74 | if (!json.contains(text_file_log_key)) 75 | json[text_file_log_key] = true; 76 | if (!json.contains(binary_file_log_key)) 77 | json[binary_file_log_key] = false; 78 | if (!json.contains(console_log_key)) 79 | json[console_log_key] = true; 80 | if (!json.contains(replay_log_key)) 81 | json[replay_log_key] = false; 82 | if (!json.contains(raw_bytes_log_key)) 83 | json[raw_bytes_log_key] = false; 84 | if (!json.contains(online_key)) 85 | json[online_key] = false; 86 | if (!json.contains(account_cache_key_key)) 87 | json[account_cache_key_key] = ""; 88 | if (!json.contains(network_recap_to_console_key)) 89 | json[network_recap_to_console_key] = false; 90 | ProtocolCraft::Json::Value packet_lists = { 91 | { ignored_clientbound_key, ProtocolCraft::Json::Array() }, 92 | { ignored_serverbound_key, ProtocolCraft::Json::Array() }, 93 | { detailed_clientbound_key, ProtocolCraft::Json::Array() }, 94 | { detailed_serverbound_key, ProtocolCraft::Json::Array() }, 95 | }; 96 | if (!json.contains(handshaking_key)) 97 | json[handshaking_key] = packet_lists; 98 | if (!json.contains(status_key)) 99 | json[status_key] = packet_lists; 100 | if (!json.contains(login_key)) 101 | json[login_key] = packet_lists; 102 | if (!json.contains(play_key)) 103 | json[play_key] = packet_lists; 104 | if (!json.contains(configuration_key)) 105 | json[configuration_key] = packet_lists; 106 | 107 | return json; 108 | } 109 | 110 | void Conf::SaveConf(const ProtocolCraft::Json::Value& conf) 111 | { 112 | std::ofstream file = std::ofstream(conf_path, std::ios::out); 113 | if (!file.is_open()) 114 | { 115 | throw std::runtime_error("Error trying to open conf file at: " + conf_path); 116 | } 117 | 118 | file << conf.Dump(4); 119 | file.close(); 120 | } 121 | 122 | std::time_t Conf::GetModifiedTimestamp() 123 | { 124 | struct stat result; 125 | if (stat(conf_path.c_str(), &result) == 0) 126 | { 127 | return result.st_mtime; 128 | } 129 | return -1; 130 | } 131 | -------------------------------------------------------------------------------- /sniffcraft/src/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "sniffcraft/conf.hpp" 4 | #include "sniffcraft/server.hpp" 5 | 6 | int main(int argc, char* argv[]) 7 | { 8 | if (argc < 1) 9 | { 10 | std::cerr << "usage: sniffcraft " << std::endl; 11 | } 12 | 13 | if (argc > 1) 14 | { 15 | for (int i = 1; i < argc; ++i) 16 | { 17 | if (std::string_view(argv[i]) == "--headless") 18 | { 19 | Conf::headless = true; 20 | } 21 | else 22 | { 23 | Conf::conf_path = argv[i]; 24 | } 25 | } 26 | } 27 | 28 | try 29 | { 30 | Server server = Server(); 31 | server.run(); 32 | } 33 | catch(std::exception& e) 34 | { 35 | std::cerr << "Error: " << e.what() << std::endl; 36 | return 1; 37 | } 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /sniffcraft/src/server.cpp: -------------------------------------------------------------------------------- 1 | #include "sniffcraft/conf.hpp" 2 | #include "sniffcraft/MinecraftProxy.hpp" 3 | #include "sniffcraft/Logger.hpp" 4 | #include "sniffcraft/PacketUtilities.hpp" 5 | #include "sniffcraft/server.hpp" 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | #ifdef WITH_GUI 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #endif 25 | 26 | Server::Server() 27 | { 28 | std::shared_lock conf_lock(Conf::conf_mutex); 29 | const ProtocolCraft::Json::Value conf = Conf::LoadConf(); 30 | client_port = conf[Conf::local_port_key].get_number(); 31 | server_address = conf[Conf::server_address_key].get_string(); 32 | ResolveIpPortFromAddress(); 33 | 34 | proxies_cleaning_thread = std::thread(&Server::CleanProxies, this); 35 | } 36 | 37 | Server::~Server() 38 | { 39 | #ifdef WITH_GUI 40 | io_context.stop(); 41 | if (iocontext_thread.joinable()) 42 | { 43 | iocontext_thread.join(); 44 | } 45 | #endif 46 | 47 | if (proxies_cleaning_thread_running) 48 | { 49 | proxies_cleaning_thread_running = false; 50 | proxies_cleaning_thread.join(); 51 | } 52 | } 53 | 54 | void Server::run() 55 | { 56 | #ifdef WITH_GUI 57 | if (Conf::headless) 58 | { 59 | run_iocontext(); 60 | } 61 | else 62 | { 63 | Render(); 64 | } 65 | #else 66 | run_iocontext(); 67 | #endif 68 | } 69 | 70 | void Server::run_iocontext() 71 | { 72 | acceptor = std::make_unique(io_context, asio::ip::tcp::endpoint(asio::ip::tcp::v4(), client_port)); 73 | listen_connection(); 74 | std::cout << "Starting redirection of any connection on 127.0.0.1:" << client_port << " to " << server_ip << ":" << server_port << std::endl; 75 | io_context.run(); 76 | } 77 | 78 | void Server::listen_connection() 79 | { 80 | BaseProxy* proxy = GetNewMinecraftProxy(); 81 | 82 | acceptor->async_accept(proxy->ClientSocket(), 83 | std::bind(&Server::handle_accept, this, proxy, 84 | std::placeholders::_1)); 85 | } 86 | 87 | void Server::handle_accept(BaseProxy* new_proxy, const asio::error_code& ec) 88 | { 89 | if (!ec) 90 | { 91 | new_proxy->Start(server_ip, server_port); 92 | #ifdef WITH_GUI 93 | if (MinecraftProxy* casted_proxy = dynamic_cast(new_proxy)) 94 | { 95 | std::scoped_lock lock(loggers_mutex); 96 | loggers.push_back(casted_proxy->GetLogger()); 97 | } 98 | #endif 99 | } 100 | else 101 | { 102 | std::cerr << "Failed to start new proxy" << std::endl; 103 | } 104 | listen_connection(); 105 | } 106 | 107 | void Server::ResolveIpPortFromAddress() 108 | { 109 | std::string addressOnly; 110 | 111 | const std::vector splitted_port = Botcraft::Utilities::SplitString(server_address, ':'); 112 | // address:port format 113 | if (splitted_port.size() > 1) 114 | { 115 | try 116 | { 117 | server_port = std::stoi(splitted_port[1]); 118 | server_ip = splitted_port[0]; 119 | return; 120 | } 121 | catch (const std::exception&) 122 | { 123 | server_port = 0; 124 | } 125 | addressOnly = splitted_port[0]; 126 | } 127 | // address only format 128 | else 129 | { 130 | addressOnly = server_address; 131 | server_port = 0; 132 | } 133 | 134 | // If port is unknown we first try a SRV DNS lookup 135 | std::cout << "Performing SRV DNS lookup on " << "_minecraft._tcp." << addressOnly << " to find an endpoint" << std::endl; 136 | asio::ip::udp::socket udp_socket(io_context); 137 | 138 | // Create the query 139 | Botcraft::DNSMessage query; 140 | // Random identification 141 | query.SetIdentification({ 0x42, 0x42 }); 142 | query.SetFlagQR(0); 143 | query.SetFlagOPCode(0); 144 | query.SetFlagAA(0); 145 | query.SetFlagTC(0); 146 | query.SetFlagRD(1); 147 | query.SetFlagRA(0); 148 | query.SetFlagZ(0); 149 | query.SetFlagRCode(0); 150 | query.SetNumberQuestion(1); 151 | query.SetNumberAnswer(0); 152 | query.SetNumberAuthority(0); 153 | query.SetNumberAdditionalRR(0); 154 | Botcraft::DNSQuestion question; 155 | // SRV type 156 | question.SetTypeCode(33); 157 | question.SetClassCode(1); 158 | question.SetNameLabels(Botcraft::Utilities::SplitString("_minecraft._tcp." + server_address, '.')); 159 | query.SetQuestions({ question }); 160 | 161 | // Write the request and send it to google DNS 162 | std::vector encoded_query; 163 | query.Write(encoded_query); 164 | udp_socket.open(asio::ip::udp::v4()); 165 | asio::ip::udp::endpoint endpoint(asio::ip::make_address("8.8.8.8"), 53); 166 | udp_socket.send_to(asio::buffer(encoded_query), endpoint); 167 | 168 | // Wait for the answer 169 | std::vector answer_buffer(512); 170 | asio::ip::udp::endpoint sender_endpoint; 171 | const size_t len = udp_socket.receive_from(asio::buffer(answer_buffer), sender_endpoint); 172 | 173 | ProtocolCraft::ReadIterator iter = answer_buffer.begin(); 174 | size_t remaining = len; 175 | 176 | // Read answer 177 | Botcraft::DNSMessage answer; 178 | answer.Read(iter, remaining); 179 | 180 | // If there is an answer and it's a SRV one (as it should be) 181 | if (answer.GetNumberAnswer() > 0 182 | && answer.GetAnswers()[0].GetTypeCode() == 0x21) 183 | { 184 | Botcraft::DNSSrvData data; 185 | auto iter2 = answer.GetAnswers()[0].GetRData().begin(); 186 | size_t len2 = answer.GetAnswers()[0].GetRDLength(); 187 | data.Read(iter2, len2); 188 | server_ip = ""; 189 | for (int i = 0; i < data.GetNameLabels().size(); ++i) 190 | { 191 | server_ip += data.GetNameLabels()[i] + (i == data.GetNameLabels().size() - 1 ? "" : "."); 192 | } 193 | server_port = data.GetPort(); 194 | 195 | std::cout << "SRV DNS lookup successful!" << std::endl; 196 | return; 197 | } 198 | std::cout << "SRV DNS lookup failed to find an address" << std::endl; 199 | 200 | // If we are here either the port was given or the SRV failed 201 | // In both cases we need to assume the given address is the correct one 202 | server_port = (server_port == 0) ? 25565 : server_port; 203 | server_ip = addressOnly; 204 | } 205 | 206 | BaseProxy* Server::GetNewMinecraftProxy() 207 | { 208 | std::lock_guard lock(proxies_mutex); 209 | // Create a new proxy 210 | std::unique_ptr proxy = std::make_unique(io_context); 211 | proxies.push_back(std::move(proxy)); 212 | 213 | return proxies.back().get(); 214 | } 215 | 216 | void Server::CleanProxies() 217 | { 218 | proxies_cleaning_thread_running = true; 219 | while (proxies_cleaning_thread_running) 220 | { 221 | { 222 | std::lock_guard lock(proxies_mutex); 223 | // Clean old proxies 224 | for (int i = static_cast(proxies.size()) - 1; i > -1; --i) 225 | { 226 | if (proxies[i]->Started() && !proxies[i]->Running()) 227 | { 228 | proxies.erase(proxies.begin() + i); 229 | } 230 | } 231 | } 232 | std::this_thread::sleep_for(std::chrono::seconds(1)); 233 | } 234 | } 235 | 236 | #ifdef WITH_GUI 237 | void Server::Render() 238 | { 239 | glfwInit(); 240 | glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); 241 | glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); 242 | glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); 243 | #ifdef __APPLE__ 244 | glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); 245 | #endif 246 | 247 | glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); 248 | GLFWwindow* window = glfwCreateWindow(1200, 960, "SniffCraft", NULL, NULL); 249 | if (window == NULL) 250 | { 251 | std::cerr << "Failed to create GLFW window, you can launch SniffCraft without GUI with the --headless argument" << std::endl; 252 | glfwTerminate(); 253 | return; 254 | } 255 | 256 | glfwSetWindowUserPointer(window, this); 257 | glfwMakeContextCurrent(window); 258 | glfwSwapInterval(1); 259 | glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); 260 | glfwSetDropCallback(window, [](GLFWwindow* w, int count, const char** paths) 261 | { 262 | Server* server = static_cast(glfwGetWindowUserPointer(w)); 263 | std::scoped_lock lock(server->loggers_mutex); 264 | for (int i = 0; i < count; ++i) 265 | { 266 | try 267 | { 268 | server->loggers.push_back(std::make_shared(std::filesystem::path(paths[i]))); 269 | } 270 | catch (std::runtime_error& e) 271 | { 272 | std::cerr << "Error trying to load binary file: " << e.what() << std::endl; 273 | } 274 | } 275 | }); 276 | 277 | // glad: load all OpenGL function pointers 278 | // --------------------------------------- 279 | if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) 280 | { 281 | std::cerr << "Failed to initialize GLAD" << std::endl; 282 | return; 283 | } 284 | 285 | // imgui: setup context 286 | // --------------------------------------- 287 | IMGUI_CHECKVERSION(); 288 | ImGui::CreateContext(); 289 | 290 | // Style 291 | ImGui::StyleColorsDark(); 292 | ImGui::GetIO().IniFilename = NULL; 293 | ImGui::GetIO().LogFilename = NULL; 294 | 295 | // Setup platform/renderer 296 | ImGui_ImplGlfw_InitForOpenGL(window, true); 297 | ImGui_ImplOpenGL3_Init("#version 330"); 298 | 299 | InternalRenderLoop(window); 300 | 301 | // ImGui cleaning 302 | ImGui_ImplOpenGL3_Shutdown(); 303 | ImGui_ImplGlfw_Shutdown(); 304 | ImGui::DestroyContext(); 305 | 306 | glfwDestroyWindow(window); 307 | glfwTerminate(); 308 | } 309 | 310 | void HelpMarker(const char* tooltip); 311 | 312 | void Server::InternalRenderLoop(GLFWwindow* window) 313 | { 314 | int width, height; 315 | glfwGetWindowSize(window, &width, &height); 316 | 317 | // A bunch of variables used as display data during one frame 318 | // App parameters 319 | bool started = false; 320 | std::string local_port_str = std::to_string(client_port); 321 | bool is_online = false; 322 | std::string cache_key = ""; 323 | bool log_to_console = false; 324 | bool network_recap_to_console = false; 325 | bool log_to_text_file = false; 326 | bool log_to_bin_file = false; 327 | bool log_raw_bytes = false; 328 | bool log_to_replay_file = false; 329 | 330 | // Display filter 331 | const std::vector connection_state_str = { 332 | "Handshake", 333 | "Status", 334 | "Login", 335 | "Play", 336 | #if PROTOCOL_VERSION > 763 /* > 1.20.1 */ 337 | "Configuration" 338 | #endif 339 | }; 340 | int selected_connection_state = 3; 341 | const std::vector direction_str = { 342 | "Server --> Client", 343 | "Client --> Server" 344 | }; 345 | int selected_direction = 0; 346 | std::vector displayed; 347 | std::vector hidden; 348 | 349 | const auto on_display_changed = [&]() 350 | { 351 | std::shared_lock lock(Conf::conf_mutex); 352 | const ProtocolCraft::Json::Value conf = Conf::LoadConf(); 353 | const ConnectionState state = static_cast(selected_connection_state); 354 | displayed.clear(); 355 | hidden.clear(); 356 | // Clientbound 357 | if (selected_direction == 0) 358 | { 359 | switch (state) 360 | { 361 | case ConnectionState::None: 362 | return; 363 | case ConnectionState::Handshake: 364 | return; 365 | case ConnectionState::Status: 366 | for (const auto& s : PacketNameIdExtractor::name_ids) 367 | { 368 | bool ignored = false; 369 | for (const auto& v : conf[Conf::status_key][Conf::ignored_clientbound_key].get_array()) 370 | { 371 | if ((v.is_number() && v.get_number() == s.id) || 372 | (v.is_string() && v.get_string() == s.name)) 373 | { 374 | ignored = true; 375 | break; 376 | } 377 | } 378 | (ignored ? hidden : displayed).push_back(s); 379 | } 380 | break; 381 | case ConnectionState::Login: 382 | for (const auto& s : PacketNameIdExtractor::name_ids) 383 | { 384 | bool ignored = false; 385 | for (const auto& v : conf[Conf::login_key][Conf::ignored_clientbound_key].get_array()) 386 | { 387 | if ((v.is_number() && v.get_number() == s.id) || 388 | (v.is_string() && v.get_string() == s.name)) 389 | { 390 | ignored = true; 391 | break; 392 | } 393 | } 394 | (ignored ? hidden : displayed).push_back(s); 395 | } 396 | break; 397 | case ConnectionState::Play: 398 | for (const auto& s : PacketNameIdExtractor::name_ids) 399 | { 400 | bool ignored = false; 401 | for (const auto& v : conf[Conf::play_key][Conf::ignored_clientbound_key].get_array()) 402 | { 403 | if ((v.is_number() && v.get_number() == s.id) || 404 | (v.is_string() && v.get_string() == s.name)) 405 | { 406 | ignored = true; 407 | break; 408 | } 409 | } 410 | (ignored ? hidden : displayed).push_back(s); 411 | } 412 | break; 413 | #if PROTOCOL_VERSION > 763 /* > 1.20.1 */ 414 | case ConnectionState::Configuration: 415 | for (const auto& s : PacketNameIdExtractor::name_ids) 416 | { 417 | bool ignored = false; 418 | for (const auto& v : conf[Conf::configuration_key][Conf::ignored_clientbound_key].get_array()) 419 | { 420 | if ((v.is_number() && v.get_number() == s.id) || 421 | (v.is_string() && v.get_string() == s.name)) 422 | { 423 | ignored = true; 424 | break; 425 | } 426 | } 427 | (ignored ? hidden : displayed).push_back(s); 428 | } 429 | break; 430 | #endif 431 | } 432 | } 433 | // Serverbound 434 | else 435 | { 436 | switch (state) 437 | { 438 | case ConnectionState::None: 439 | return; 440 | case ConnectionState::Handshake: 441 | for (const auto& s : PacketNameIdExtractor::name_ids) 442 | { 443 | bool ignored = false; 444 | for (const auto& v : conf[Conf::handshaking_key][Conf::ignored_serverbound_key].get_array()) 445 | { 446 | if ((v.is_number() && v.get_number() == s.id) || 447 | (v.is_string() && v.get_string() == s.name)) 448 | { 449 | ignored = true; 450 | break; 451 | } 452 | } 453 | (ignored ? hidden : displayed).push_back(s); 454 | } 455 | break; 456 | case ConnectionState::Status: 457 | for (const auto& s : PacketNameIdExtractor::name_ids) 458 | { 459 | bool ignored = false; 460 | for (const auto& v : conf[Conf::status_key][Conf::ignored_serverbound_key].get_array()) 461 | { 462 | if ((v.is_number() && v.get_number() == s.id) || 463 | (v.is_string() && v.get_string() == s.name)) 464 | { 465 | ignored = true; 466 | break; 467 | } 468 | } 469 | (ignored ? hidden : displayed).push_back(s); 470 | } 471 | break; 472 | case ConnectionState::Login: 473 | for (const auto& s : PacketNameIdExtractor::name_ids) 474 | { 475 | bool ignored = false; 476 | for (const auto& v : conf[Conf::login_key][Conf::ignored_serverbound_key].get_array()) 477 | { 478 | if ((v.is_number() && v.get_number() == s.id) || 479 | (v.is_string() && v.get_string() == s.name)) 480 | { 481 | ignored = true; 482 | break; 483 | } 484 | } 485 | (ignored ? hidden : displayed).push_back(s); 486 | } 487 | break; 488 | case ConnectionState::Play: 489 | for (const auto& s : PacketNameIdExtractor::name_ids) 490 | { 491 | bool ignored = false; 492 | for (const auto& v : conf[Conf::play_key][Conf::ignored_serverbound_key].get_array()) 493 | { 494 | if ((v.is_number() && v.get_number() == s.id) || 495 | (v.is_string() && v.get_string() == s.name)) 496 | { 497 | ignored = true; 498 | break; 499 | } 500 | } 501 | (ignored ? hidden : displayed).push_back(s); 502 | } 503 | break; 504 | #if PROTOCOL_VERSION > 763 /* > 1.20.1 */ 505 | case ConnectionState::Configuration: 506 | for (const auto& s : PacketNameIdExtractor::name_ids) 507 | { 508 | bool ignored = false; 509 | for (const auto& v : conf[Conf::configuration_key][Conf::ignored_serverbound_key].get_array()) 510 | { 511 | if ((v.is_number() && v.get_number() == s.id) || 512 | (v.is_string() && v.get_string() == s.name)) 513 | { 514 | ignored = true; 515 | break; 516 | } 517 | } 518 | (ignored ? hidden : displayed).push_back(s); 519 | } 520 | break; 521 | #endif 522 | } 523 | } 524 | 525 | std::sort(displayed.begin(), displayed.end(), [](const NameID& a, const NameID& b) { return a.name < b.name; }); 526 | std::sort(hidden.begin(), hidden.end(), [](const NameID& a, const NameID& b) { return a.name < b.name; }); 527 | }; 528 | const auto on_ignored_changed = [&]() 529 | { 530 | const ConnectionState state = static_cast(selected_connection_state); 531 | std::string conf_key = ""; 532 | 533 | switch (state) 534 | { 535 | case ConnectionState::None: 536 | return; 537 | case ConnectionState::Handshake: 538 | conf_key = Conf::handshaking_key; 539 | break; 540 | case ConnectionState::Status: 541 | conf_key = Conf::status_key; 542 | break; 543 | case ConnectionState::Login: 544 | conf_key = Conf::login_key; 545 | break; 546 | case ConnectionState::Play: 547 | conf_key = Conf::play_key; 548 | break; 549 | #if PROTOCOL_VERSION > 763 /* > 1.20.1 */ 550 | case ConnectionState::Configuration: 551 | conf_key = Conf::configuration_key; 552 | break; 553 | #endif 554 | } 555 | std::sort(displayed.begin(), displayed.end(), [](const NameID& a, const NameID& b) { return a.name < b.name; }); 556 | std::sort(hidden.begin(), hidden.end(), [](const NameID& a, const NameID& b) { return a.name < b.name; }); 557 | 558 | { 559 | std::scoped_lock lock(Conf::conf_mutex); 560 | ProtocolCraft::Json::Value conf = Conf::LoadConf(); 561 | std::vector ignored_names(hidden.size()); 562 | for (size_t i = 0; i < hidden.size(); ++i) 563 | { 564 | ignored_names[i] = hidden[i].name; 565 | } 566 | conf[conf_key][selected_direction == 0 ? Conf::ignored_clientbound_key : Conf::ignored_serverbound_key] = ignored_names; 567 | Conf::SaveConf(conf); 568 | } 569 | { 570 | // Triger a load config for all associated loggers 571 | std::scoped_lock lock(loggers_mutex); 572 | for (auto& l : loggers) 573 | { 574 | l->LoadConfig(); 575 | } 576 | } 577 | }; 578 | 579 | // Init the values with actual conf values 580 | { 581 | std::shared_lock lock(Conf::conf_mutex); 582 | const ProtocolCraft::Json::Value conf = Conf::LoadConf(); 583 | is_online = conf.contains(Conf::online_key) && conf[Conf::online_key].is_bool() && conf[Conf::online_key].get(); 584 | cache_key = (conf.contains(Conf::account_cache_key_key) && conf[Conf::account_cache_key_key].is_string()) ? conf[Conf::account_cache_key_key].get_string() : ""; 585 | log_to_console = conf.contains(Conf::console_log_key) && conf[Conf::console_log_key].is_bool() && conf[Conf::console_log_key].get(); 586 | network_recap_to_console = conf.contains(Conf::network_recap_to_console_key) && conf[Conf::network_recap_to_console_key].is_bool() && conf[Conf::network_recap_to_console_key].get(); 587 | log_to_text_file = conf.contains(Conf::text_file_log_key) && conf[Conf::text_file_log_key].is_bool() && conf[Conf::text_file_log_key].get(); 588 | log_to_bin_file = conf.contains(Conf::binary_file_log_key) && conf[Conf::binary_file_log_key].is_bool() && conf[Conf::binary_file_log_key].get(); 589 | log_raw_bytes = conf.contains(Conf::raw_bytes_log_key) && conf[Conf::raw_bytes_log_key].is_bool() && conf[Conf::raw_bytes_log_key].get(); 590 | log_to_replay_file = conf.contains(Conf::replay_log_key) && conf[Conf::replay_log_key].is_bool() && conf[Conf::replay_log_key].get(); 591 | } 592 | on_display_changed(); 593 | 594 | 595 | while (glfwWindowShouldClose(window) == 0) 596 | { 597 | // clear the window 598 | glClear(GL_COLOR_BUFFER_BIT); 599 | 600 | // Init imgui frame 601 | ImGui_ImplOpenGL3_NewFrame(); 602 | ImGui_ImplGlfw_NewFrame(); 603 | ImGui::NewFrame(); 604 | 605 | { 606 | ImGui::SetNextWindowPos(ImVec2(0, 0)); 607 | ImGui::SetNextWindowSize(ImVec2(static_cast(width), static_cast(height))); 608 | 609 | ImGui::Begin("SniffCraft Main Window", NULL, 610 | ImGuiWindowFlags_NoResize | 611 | ImGuiWindowFlags_NoMove | 612 | ImGuiWindowFlags_NoCollapse | 613 | ImGuiWindowFlags_NoSavedSettings | 614 | ImGuiWindowFlags_NoTitleBar | 615 | ImGuiWindowFlags_NoScrollbar | 616 | ImGuiWindowFlags_NoScrollWithMouse 617 | ); 618 | ImGui::SeparatorText("Application parameters"); 619 | { 620 | ImGui::TextUnformatted("Server address"); 621 | ImGui::SameLine(); 622 | HelpMarker("Server address, as you would enter it in a minecraft client"); 623 | ImGui::SameLine(); 624 | ImGui::SetNextItemWidth(500.0f); 625 | ImGui::InputText("##server_address", &server_address); 626 | if (ImGui::IsItemDeactivatedAfterEdit()) 627 | { 628 | std::scoped_lock lock(Conf::conf_mutex); 629 | ProtocolCraft::Json::Value conf = Conf::LoadConf(); 630 | conf[Conf::server_address_key] = server_address; 631 | Conf::SaveConf(conf); 632 | ResolveIpPortFromAddress(); 633 | } 634 | 635 | ImGui::BeginDisabled(started); 636 | ImGui::SameLine(0.0f, 10.0f); 637 | ImGui::TextUnformatted("Local port"); 638 | ImGui::SameLine(); 639 | HelpMarker("Local port clients will use to connect to this Sniffcraft instance, should be between 1024 and 65535"); 640 | ImGui::SameLine(); 641 | ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x); 642 | ImGui::InputText("##local_port", &local_port_str, ImGuiInputTextFlags_::ImGuiInputTextFlags_CharsDecimal); 643 | if (ImGui::IsItemDeactivatedAfterEdit()) 644 | { 645 | try 646 | { 647 | client_port = static_cast(std::stoul(local_port_str)); 648 | } 649 | catch (std::exception&) 650 | { 651 | local_port_str = std::to_string(client_port); 652 | } 653 | std::scoped_lock lock(Conf::conf_mutex); 654 | ProtocolCraft::Json::Value conf = Conf::LoadConf(); 655 | conf[Conf::local_port_key] = client_port; 656 | Conf::SaveConf(conf); 657 | } 658 | ImGui::EndDisabled(); 659 | 660 | if (ImGui::Checkbox("Authenticated", &is_online)) 661 | { 662 | std::scoped_lock lock(Conf::conf_mutex); 663 | ProtocolCraft::Json::Value conf = Conf::LoadConf(); 664 | conf[Conf::online_key] = is_online; 665 | Conf::SaveConf(conf); 666 | } 667 | ImGui::SameLine(); 668 | HelpMarker("If checked, you will have to connect with a valid Minecraft account"); 669 | if (is_online) 670 | { 671 | ImGui::SameLine(0.0f, 10.0f); 672 | ImGui::TextUnformatted("Credentials cache key"); 673 | ImGui::SameLine(); 674 | ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x); 675 | ImGui::InputTextWithHint("##cache_key", "Key used to select an account in the credentials cache file", &cache_key); 676 | if (ImGui::IsItemDeactivatedAfterEdit()) 677 | { 678 | std::scoped_lock lock(Conf::conf_mutex); 679 | ProtocolCraft::Json::Value conf = Conf::LoadConf(); 680 | conf[Conf::account_cache_key_key] = cache_key; 681 | Conf::SaveConf(conf); 682 | } 683 | } 684 | 685 | if (ImGui::Checkbox("Console", &log_to_console)) 686 | { 687 | std::scoped_lock lock(Conf::conf_mutex); 688 | ProtocolCraft::Json::Value conf = Conf::LoadConf(); 689 | conf[Conf::console_log_key] = log_to_console; 690 | Conf::SaveConf(conf); 691 | } 692 | ImGui::SameLine(); 693 | HelpMarker("If checked, logs will be printed in the console"); 694 | ImGui::SameLine(0.0f, 10.0f); 695 | if (ImGui::Checkbox("Network recap", &network_recap_to_console)) 696 | { 697 | std::scoped_lock lock(Conf::conf_mutex); 698 | ProtocolCraft::Json::Value conf = Conf::LoadConf(); 699 | conf[Conf::network_recap_to_console_key] = network_recap_to_console; 700 | Conf::SaveConf(conf); 701 | } 702 | ImGui::SameLine(); 703 | HelpMarker("If checked, a network usage recap will be printed in the console every ~10 seconds"); 704 | ImGui::SameLine(0.0f, 10.0f); 705 | if (ImGui::Checkbox("Raw bytes", &log_raw_bytes)) 706 | { 707 | std::scoped_lock lock(Conf::conf_mutex); 708 | ProtocolCraft::Json::Value conf = Conf::LoadConf(); 709 | conf[Conf::raw_bytes_log_key] = log_raw_bytes; 710 | Conf::SaveConf(conf); 711 | } 712 | ImGui::SameLine(); 713 | HelpMarker("If checked, raw bytes will be added in the console and text file"); 714 | ImGui::SameLine(0.0f, 10.0f); 715 | if (ImGui::Checkbox("Text file", &log_to_text_file)) 716 | { 717 | std::scoped_lock lock(Conf::conf_mutex); 718 | ProtocolCraft::Json::Value conf = Conf::LoadConf(); 719 | conf[Conf::text_file_log_key] = log_to_text_file; 720 | Conf::SaveConf(conf); 721 | } 722 | ImGui::SameLine(); 723 | HelpMarker("If checked, logs will be sent to a text file"); 724 | ImGui::SameLine(0.0f, 10.0f); 725 | if (ImGui::Checkbox("Binary file", &log_to_bin_file)) 726 | { 727 | std::scoped_lock lock(Conf::conf_mutex); 728 | ProtocolCraft::Json::Value conf = Conf::LoadConf(); 729 | conf[Conf::binary_file_log_key] = log_to_bin_file; 730 | Conf::SaveConf(conf); 731 | } 732 | ImGui::SameLine(); 733 | HelpMarker("If checked, packets will be saved in a binary file that can be reimported into Sniffcraft GUI"); 734 | ImGui::SameLine(0.0f, 10.0f); 735 | if (ImGui::Checkbox("Replay file", &log_to_replay_file)) 736 | { 737 | std::scoped_lock lock(Conf::conf_mutex); 738 | ProtocolCraft::Json::Value conf = Conf::LoadConf(); 739 | conf[Conf::replay_log_key] = log_to_replay_file; 740 | Conf::SaveConf(conf); 741 | } 742 | ImGui::SameLine(); 743 | HelpMarker("If checked, the session will be saved as a replay file compatible with replay mod. /!\\ Current player will NOT be visible in it, as replay mod artificially adds some packets to display it."); 744 | 745 | if (!started) 746 | { 747 | ImGui::PushStyleColor(ImGuiCol_::ImGuiCol_Button, ImVec4(1.0f, 0.0f, 0.0f, 1.0f)); 748 | if (ImGui::Button("Start")) 749 | { 750 | started = true; 751 | iocontext_thread = std::thread(&Server::run_iocontext, this); 752 | } 753 | ImGui::PopStyleColor(); 754 | } 755 | else 756 | { 757 | ImGui::Text("Any connection on 127.0.0.1:%i will be redirected to %s:%i", client_port, server_ip.c_str(), server_port); 758 | } 759 | } 760 | 761 | 762 | ImGui::SeparatorText("Display filter"); 763 | { 764 | if (ImGui::BeginCombo("##connection_state", connection_state_str[selected_connection_state].c_str(), ImGuiComboFlags_WidthFitPreview)) 765 | { 766 | for (size_t n = 0; n < connection_state_str.size(); ++n) 767 | { 768 | const bool is_selected = selected_connection_state == n; 769 | if (ImGui::Selectable(connection_state_str[n].c_str(), is_selected)) 770 | { 771 | selected_connection_state = static_cast(n); 772 | if (!is_selected) 773 | { 774 | on_display_changed(); 775 | } 776 | } 777 | if (is_selected) 778 | { 779 | ImGui::SetItemDefaultFocus(); 780 | } 781 | } 782 | ImGui::EndCombo(); 783 | } 784 | ImGui::SameLine(); 785 | if (ImGui::BeginCombo("##network_direction", direction_str[selected_direction].c_str(), ImGuiComboFlags_WidthFitPreview)) 786 | { 787 | for (size_t n = 0; n < direction_str.size(); ++n) 788 | { 789 | const bool is_selected = selected_direction == n; 790 | if (ImGui::Selectable(direction_str[n].c_str(), is_selected)) 791 | { 792 | selected_direction = static_cast(n); 793 | if (!is_selected) 794 | { 795 | on_display_changed(); 796 | } 797 | } 798 | if (is_selected) 799 | { 800 | ImGui::SetItemDefaultFocus(); 801 | } 802 | } 803 | ImGui::EndCombo(); 804 | } 805 | 806 | const float half_size = 0.5f * (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x); 807 | ImGui::TextUnformatted("Displayed packets (double click to ignore)"); 808 | const float displayed_size = ImGui::GetItemRectSize().x; 809 | ImGui::SameLine(); 810 | ImGui::Dummy(ImVec2(half_size - displayed_size - ImGui::GetStyle().ItemSpacing.x, ImGui::GetTextLineHeightWithSpacing())); 811 | ImGui::SameLine(); 812 | ImGui::TextUnformatted("Hidden packets"); 813 | if (ImGui::BeginListBox("##displayed_packets", ImVec2(half_size, 7 * ImGui::GetTextLineHeightWithSpacing()))) 814 | { 815 | for (size_t i = 0; i < displayed.size(); ++i) 816 | { 817 | ImGui::Selectable(displayed[i].name.data(), false, ImGuiSelectableFlags_AllowDoubleClick); 818 | if (ImGui::IsItemHovered()) 819 | { 820 | if (ImGui::BeginTooltip()) 821 | { 822 | ImGui::Text("ID: %i", displayed[i].id); 823 | ImGui::EndTooltip(); 824 | } 825 | if (ImGui::IsMouseDoubleClicked(0)) 826 | { 827 | hidden.push_back(displayed[i]); 828 | displayed.erase(displayed.begin() + i); 829 | --i; 830 | on_ignored_changed(); 831 | } 832 | } 833 | } 834 | ImGui::EndListBox(); 835 | } 836 | ImGui::SameLine(); 837 | if (ImGui::BeginListBox("##hidden_packets", ImVec2(half_size, 7 * ImGui::GetTextLineHeightWithSpacing()))) 838 | { 839 | for (size_t i = 0; i < hidden.size(); ++i) 840 | { 841 | ImGui::Selectable(hidden[i].name.data(), false, ImGuiSelectableFlags_AllowDoubleClick); 842 | if (ImGui::IsItemHovered()) 843 | { 844 | if (ImGui::BeginTooltip()) 845 | { 846 | ImGui::Text("ID: %i", hidden[i].id); 847 | ImGui::EndTooltip(); 848 | } 849 | if (ImGui::IsMouseDoubleClicked(0)) 850 | { 851 | displayed.push_back(hidden[i]); 852 | hidden.erase(hidden.begin() + i); 853 | --i; 854 | on_ignored_changed(); 855 | } 856 | } 857 | } 858 | ImGui::EndListBox(); 859 | } 860 | } 861 | 862 | ImGui::SeparatorText("Sessions"); 863 | std::tuple, ConnectionState, Endpoint> additional_ignored_packet = { nullptr, ConnectionState::None, Endpoint::Client }; 864 | { 865 | std::scoped_lock lock(loggers_mutex); 866 | if (loggers.size() > 0 && ImGui::BeginTabBar("loggers", ImGuiTabBarFlags_AutoSelectNewTabs | ImGuiTabBarFlags_FittingPolicyScroll)) 867 | { 868 | int index = 0; 869 | for (auto it = loggers.begin(); it != loggers.end(); ) 870 | { 871 | ImGui::PushID(index); 872 | bool open = true; 873 | if (ImGui::BeginTabItem((*it)->GetBaseFilename().c_str(), &open, ImGuiTabItemFlags_None)) 874 | { 875 | // If a packet ignore button has been pressed, save it to update display later 876 | auto ignored_pressed = (*it)->Render(); 877 | if (std::get<0>(ignored_pressed) != nullptr) 878 | { 879 | additional_ignored_packet = ignored_pressed; 880 | } 881 | ImGui::EndTabItem(); 882 | } 883 | if (!open) 884 | { 885 | it = loggers.erase(it); 886 | } 887 | else 888 | { 889 | ++it; 890 | } 891 | index += 1; 892 | ImGui::PopID(); 893 | } 894 | ImGui::EndTabBar(); 895 | } 896 | } 897 | 898 | // Update display afterward because the loggers are locked while rendered 899 | const auto& [message, connection_state, origin] = additional_ignored_packet; 900 | if (message != nullptr) 901 | { 902 | const int current_selected_connection_state = selected_connection_state; 903 | const int current_selected_direction = selected_direction; 904 | // Switch display to the one matching the message 905 | selected_connection_state = static_cast(connection_state); 906 | selected_direction = static_cast(origin); 907 | on_display_changed(); 908 | // Add this message to hidden 909 | hidden.push_back(NameID{ message->GetName(), message->GetId() }); 910 | for (int i = static_cast(displayed.size()) - 1; i > -1; --i) 911 | { 912 | if (displayed[i].id == message->GetId()) 913 | { 914 | displayed.erase(displayed.begin() + i); 915 | } 916 | } 917 | on_ignored_changed(); 918 | // Switch back to the previously selected display 919 | selected_connection_state = current_selected_connection_state; 920 | selected_direction = current_selected_direction; 921 | on_display_changed(); 922 | } 923 | ImGui::End(); 924 | } 925 | 926 | // Render ImGui 927 | ImGui::Render(); 928 | ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); 929 | 930 | // swap buffer 931 | glfwSwapBuffers(window); 932 | 933 | // process user events 934 | glfwPollEvents(); 935 | } 936 | } 937 | 938 | void HelpMarker(const char* tooltip) 939 | { 940 | ImGui::TextDisabled("(?)"); 941 | if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) && ImGui::BeginTooltip()) 942 | { 943 | ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); 944 | ImGui::TextUnformatted(tooltip); 945 | ImGui::PopTextWrapPos(); 946 | ImGui::EndTooltip(); 947 | } 948 | } 949 | #endif 950 | --------------------------------------------------------------------------------