├── .devcontainer ├── Dockerfile └── devcontainer.json ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── images │ ├── dns_cname.png │ ├── dns_txt.png │ └── minecraft_localhost_connect.png └── workflows │ └── build_publish.yml ├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── common ├── build.gradle └── src │ └── main │ ├── java │ └── de │ │ └── rafael │ │ └── modflared │ │ ├── Modflared.java │ │ ├── ModflaredPlatform.java │ │ ├── binary │ │ ├── Cloudflared.java │ │ ├── download │ │ │ ├── CloudflaredDownload.java │ │ │ └── DownloadedCloudflared.java │ │ └── local │ │ │ └── LocalCloudflared.java │ │ ├── github │ │ └── GithubAPI.java │ │ ├── interfaces │ │ └── mixin │ │ │ ├── IClientConnection.java │ │ │ ├── IConnectScreen.java │ │ │ └── IServerInfo.java │ │ ├── methods │ │ └── ConnectScreenMethods.java │ │ ├── mixin │ │ ├── ClientConnectionMixin.java │ │ ├── ConnectScreenMixin.java │ │ └── client │ │ │ ├── MultiplayerServerListPingerMixin.java │ │ │ ├── ServerEntryMixin.java │ │ │ └── ServerInfoMixin.java │ │ ├── platform │ │ └── LoaderPlatform.java │ │ └── tunnel │ │ ├── RunningTunnel.java │ │ ├── TunnelStatus.java │ │ └── manager │ │ └── TunnelManager.java │ └── resources │ ├── architectury.common.json │ ├── assets │ └── modflared │ │ ├── lang │ │ └── en_us.json │ │ └── textures │ │ └── gui │ │ └── sprites │ │ └── icon │ │ └── indicator.png │ ├── forced_tunnels.json │ ├── modflared-common.mixins.json │ └── modflared.accesswidener ├── fabric ├── build.gradle └── src │ └── main │ ├── java │ └── de │ │ └── rafael │ │ └── modflared │ │ └── fabric │ │ ├── ModflaredFabricClient.java │ │ ├── ModflaredPlatformImpl.java │ │ └── mixin │ │ └── ConnectScreenThreadRunMixin.java │ └── resources │ ├── assets │ └── modflared │ │ └── icon.png │ ├── fabric.mod.json │ └── modflared.mixins.json ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── neoforge ├── build.gradle ├── gradle.properties └── src │ └── main │ ├── java │ └── de │ │ └── rafael │ │ └── modflared │ │ └── neoforge │ │ ├── ModflaredNeoForge.java │ │ ├── ModflaredPlatformImpl.java │ │ └── mixin │ │ └── ConnectScreenThreadRunMixin.java │ └── resources │ ├── META-INF │ └── neoforge.mods.toml │ ├── icon.png │ ├── modflared.mixins.json │ └── pack.mcmeta └── settings.gradle /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | # Use the official ArchLinux image with a AUR helper installed 2 | FROM ghcr.io/greyltc-org/archlinux-aur:paru 3 | 4 | RUN pacman-key --init 5 | RUN pacman -Syu --noconfirm 6 | 7 | # Install required packages 8 | RUN pacman -S base-devel git openssh nano jdk21-openjdk gradle --noconfirm 9 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Development Container", 3 | "dockerFile": "Dockerfile", 4 | "customizations": { 5 | "vscode": { 6 | "settings": { 7 | "terminal.integrated.shell.linux": "/bin/bash" 8 | }, 9 | "extensions": [] 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: 'bug' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **Which version of the mod/game are you using?** 14 | Where did you get the version from? Which Minecraft version do you use? Which mod version are you using? 15 | 16 | **To Reproduce** 17 | Steps to reproduce the behavior: 18 | 1. Start game 19 | 2. Click on '....' 20 | 3. Type '....' 21 | 4. See error 22 | 23 | **Expected behavior** 24 | A clear and concise description of what you expected to happen. 25 | 26 | **Screenshots** 27 | If applicable, add screenshots to help explain your problem. 28 | 29 | **Additional context** 30 | Add any other context about the problem here. 31 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: 'enhancement' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/images/dns_cname.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HttpRafa/modflared/fc8180410fe28c7e948d25cec082b02466847416/.github/images/dns_cname.png -------------------------------------------------------------------------------- /.github/images/dns_txt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HttpRafa/modflared/fc8180410fe28c7e948d25cec082b02466847416/.github/images/dns_txt.png -------------------------------------------------------------------------------- /.github/images/minecraft_localhost_connect.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HttpRafa/modflared/fc8180410fe28c7e948d25cec082b02466847416/.github/images/minecraft_localhost_connect.png -------------------------------------------------------------------------------- /.github/workflows/build_publish.yml: -------------------------------------------------------------------------------- 1 | name: build_publish 2 | on: 3 | pull_request: 4 | push: 5 | paths: 6 | - fabric/** 7 | - neoforge/** 8 | - common/** 9 | - build.gradle 10 | - gradle.properties 11 | jobs: 12 | build_publish: 13 | strategy: 14 | matrix: 15 | # Use these Java versions 16 | java: [ 17 | 21, # Current Java LTS & minimum supported by Minecraft 18 | ] 19 | os: [ubuntu-22.04] 20 | runs-on: ${{ matrix.os }} 21 | if: "!contains(github.event.head_commit.message, 'ci skip')" 22 | steps: 23 | - name: checkout repository 24 | uses: actions/checkout@v3 25 | - name: setup jdk ${{ matrix.java }} 26 | uses: actions/setup-java@v3 27 | with: 28 | java-version: ${{ matrix.java }} 29 | distribution: 'microsoft' 30 | cache: gradle 31 | - name: make gradle wrapper executable 32 | if: "${{ runner.os != 'Windows' }}" 33 | run: chmod +x ./gradlew 34 | - name: build 35 | run: ./gradlew build 36 | - name: upload to modrinth 37 | if: "github.ref == 'refs/heads/multi/latest' && !contains(github.event.head_commit.message, 'upload skip')" 38 | run: ./gradlew modrinth 39 | env: 40 | MODRINTH_TOKEN: ${{ secrets.MODRINTH_UPLOAD_TOKEN }} 41 | GITHUB_RUN_NUMBER: ${{ github.run_number }} 42 | GITHUB_EVENT_RAW_PATH: ${{ github.event_path }} 43 | - name: upload to curseforge 44 | if: "github.ref == 'refs/heads/multi/latest' && !contains(github.event.head_commit.message, 'upload skip')" 45 | run: ./gradlew publishCurseForge 46 | env: 47 | CURSEFORGE_TOKEN: ${{ secrets.CURSEFORGE_UPLOAD_TOKEN }} 48 | GITHUB_RUN_NUMBER: ${{ github.run_number }} 49 | GITHUB_EVENT_RAW_PATH: ${{ github.event_path }} 50 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | *.ipr 3 | run/ 4 | *.iws 5 | out/ 6 | *.iml 7 | .gradle/ 8 | output/ 9 | bin/ 10 | libs/ 11 | 12 | .classpath 13 | .project 14 | .idea/ 15 | classes/ 16 | .metadata 17 | .vscode 18 | .settings 19 | *.launch -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Rafael 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Modflared 2 | Automatically connects you to a [Cloudflare tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/) without having to install [cloudflared](https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation/) separately. 3 | #### This mod has not yet been fully tested! 4 | 5 | ## How to use 6 | To be able to use the mod you have to be on the operating system Windows, Linux, or MacOS. 7 | 8 | ## Other resources 9 | For more detailed instructions, you can also read Varun A's blog post. The blog post can be found [here](https://dacubeking.com/2024/02/28/Proxying-Minecraft.html). 10 | 11 | ## Configuring Cloudflared 12 | You need to set up cloudflare on your server for this to work. There's plenty of guides on how to do this elsewhere. 13 | Make sure in your config file (possibly in `/etc/cloudflared/config.yml`) you have the lines: 14 | ```YML 15 | - hostname: example.domain.net 16 | service: tcp://localhost:25565 17 | ``` 18 | Replace `example.domain.net` with the correct subdomain you want to use. If you're running multiple instances (eg. with docker), change the port 25565 to whatever port you're using. 19 | Restart the cloudflare daemon (`sudo systemctl restart cloudflared`) to apply the changes. 20 | Add the correct DNS entry: go to [Cloudflare dashboard](https://dash.cloudflare.net), go to your website and DNS entries, then add a new CNAME DNS entry with your subdomain and set the target to `.cfargotunnel.com`, with the tunnel ID found in the cloudflare config.yml file. 21 | ### Example DNS Entries 22 | ![Example CNAME](https://raw.githubusercontent.com/HttpRafa/modflared/multi/latest/.github/images/dns_cname.png) 23 | ![Example TXT](https://raw.githubusercontent.com/HttpRafa/modflared/multi/latest/.github/images/dns_txt.png) 24 | 25 | ### For Players 26 | If your server admin has properly configured their server you should be able to connect to the server as usual. 27 | No extra configuration is needed. 28 | 29 | If your server admin has not properly configured their server, you will need to add their server to the `forced_tunnels.json` file in the modflared config folder. 30 | #### Example configuration (modflared/forced_tunnels.json) 31 | ```JSON 32 | ["example.domain.net", "example2.domain.net"] 33 | ``` 34 | 35 | ### Server Admins (Setting Up cloudflared) 36 | Install Cloudflared as described in the “Configuring Cloudflared” part above. 37 | 38 | #### Telling modflared to use connect to your server using cloudflared 39 | For the hostname that you want your players to connect to (eg. `example.domain.net`), create a TXT dns record with either of the following values: 40 | - `cloudflared-use-tunnel` - This will make modflared connect to the tunnel on the hostname itself (eg. `example.domain.net`) 41 | - `cloudflared-route=` - This will make modflared connect to the tunnel under the hostname of ``. 42 | (ex. setting `cloudflared-route=example2.domain.net` will make modflared connect to the tunnel on `example2.domain.net` instead of `example.domain.net`) -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id "architectury-plugin" version "3.4-SNAPSHOT" 3 | id "dev.architectury.loom" version "1.10-SNAPSHOT" apply false 4 | } 5 | 6 | architectury { 7 | minecraft = rootProject.minecraft_version 8 | } 9 | 10 | subprojects { 11 | apply plugin: "dev.architectury.loom" 12 | 13 | loom { 14 | silentMojangMappingsLicense() 15 | } 16 | 17 | dependencies { 18 | minecraft "com.mojang:minecraft:${rootProject.minecraft_version}" 19 | // The following line declares the mojmap mappings, you may use other mappings as well 20 | // mappings loom.officialMojangMappings() 21 | // The following line declares the yarn mappings you may select this one as well. 22 | mappings loom.layered { 23 | it.mappings("net.fabricmc:yarn:${rootProject.yarn_version}:v2") 24 | it.mappings("dev.architectury:yarn-mappings-patch-neoforge:${rootProject.yarn_mappings_patch}") 25 | } 26 | } 27 | } 28 | 29 | allprojects { 30 | apply plugin: "java" 31 | apply plugin: "architectury-plugin" 32 | apply plugin: "maven-publish" 33 | 34 | base { 35 | archivesName = rootProject.archives_base_name 36 | } 37 | 38 | version = "${rootProject.mod_version}+${rootProject.mod_version_type}.${System.getenv("GITHUB_RUN_NUMBER") == null ? "dev" : System.getenv("GITHUB_RUN_NUMBER")}" 39 | group = rootProject.maven_group 40 | 41 | repositories { 42 | // Add repositories to retrieve artifacts from in here. 43 | // You should only use this when depending on other mods because 44 | // Loom adds the essential maven repositories to download Minecraft and libraries from automatically. 45 | // See https://docs.gradle.org/current/userguide/declaring_repositories.html 46 | // for more information about repositories. 47 | } 48 | 49 | tasks.withType(JavaCompile) { 50 | options.encoding = "UTF-8" 51 | options.release = 21 52 | } 53 | 54 | java { 55 | withSourcesJar() 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /common/build.gradle: -------------------------------------------------------------------------------- 1 | architectury { 2 | common(rootProject.enabled_platforms.split(",")) 3 | } 4 | 5 | loom { 6 | accessWidenerPath = file("src/main/resources/modflared.accesswidener") 7 | } 8 | 9 | dependencies { 10 | // We depend on fabric loader here to use the fabric @Environment annotations and get the mixin dependencies 11 | // Do NOT use other classes from fabric loader 12 | modImplementation "net.fabricmc:fabric-loader:${rootProject.fabric_loader_version}" 13 | } 14 | 15 | publishing { 16 | publications { 17 | mavenCommon(MavenPublication) { 18 | artifactId = rootProject.archives_base_name 19 | from components.java 20 | } 21 | } 22 | 23 | // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. 24 | repositories { 25 | // Add repositories to publish to here. 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /common/src/main/java/de/rafael/modflared/Modflared.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared; 2 | 3 | import com.google.gson.Gson; 4 | import com.google.gson.GsonBuilder; 5 | import de.rafael.modflared.platform.LoaderPlatform; 6 | import de.rafael.modflared.tunnel.manager.TunnelManager; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | 10 | import java.util.concurrent.ExecutorService; 11 | import java.util.concurrent.Executors; 12 | 13 | public class Modflared { 14 | 15 | public static final ExecutorService EXECUTOR = Executors.newCachedThreadPool(); 16 | public static final Gson GSON = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().serializeNulls().create(); 17 | 18 | public static final String MOD_ID = "modflared"; 19 | public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID); 20 | public static final LoaderPlatform PLATFORM = ModflaredPlatform.getPlatform(); 21 | 22 | public static final TunnelManager TUNNEL_MANAGER = new TunnelManager(); 23 | 24 | public static void init() { 25 | TUNNEL_MANAGER.prepareBinary(); 26 | TUNNEL_MANAGER.loadForcedTunnels(); 27 | 28 | Runtime.getRuntime().addShutdownHook(new Thread(() -> { 29 | TUNNEL_MANAGER.closeTunnels(); 30 | EXECUTOR.shutdownNow(); 31 | })); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /common/src/main/java/de/rafael/modflared/ModflaredPlatform.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared; 2 | 3 | import de.rafael.modflared.platform.LoaderPlatform; 4 | import dev.architectury.injectables.annotations.ExpectPlatform; 5 | 6 | import java.nio.file.Path; 7 | 8 | public class ModflaredPlatform { 9 | 10 | @ExpectPlatform 11 | public static Path getGameDir() { 12 | throw new AssertionError(); 13 | } 14 | 15 | @ExpectPlatform 16 | public static LoaderPlatform getPlatform() { 17 | throw new AssertionError(); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /common/src/main/java/de/rafael/modflared/binary/Cloudflared.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.binary; 2 | 3 | import de.rafael.modflared.Modflared; 4 | import de.rafael.modflared.binary.download.DownloadedCloudflared; 5 | import de.rafael.modflared.binary.local.LocalCloudflared; 6 | import de.rafael.modflared.tunnel.RunningTunnel; 7 | 8 | import java.util.concurrent.CompletableFuture; 9 | 10 | public abstract class Cloudflared { 11 | 12 | protected volatile String version; 13 | 14 | public Cloudflared(String version) { 15 | this.version = version; 16 | } 17 | 18 | public abstract CompletableFuture prepare(); 19 | 20 | public abstract String[] buildCommand(RunningTunnel.Access access); 21 | 22 | public static CompletableFuture create() { 23 | var local = LocalCloudflared.tryCreate(); 24 | if(local != null) return CompletableFuture.completedFuture(local); 25 | 26 | return DownloadedCloudflared.tryCreate(); 27 | } 28 | 29 | public RunningTunnel createTunnel(RunningTunnel.Access access) { 30 | try { 31 | return RunningTunnel.createTunnel(this, access).get(); 32 | } catch (Exception exception) { 33 | Modflared.LOGGER.error("Failed to create tunnel", exception); 34 | return null; 35 | } 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /common/src/main/java/de/rafael/modflared/binary/download/CloudflaredDownload.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.binary.download; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | 5 | import java.util.Arrays; 6 | 7 | public enum CloudflaredDownload { 8 | 9 | WINDOW_32("windows", "x86", "cloudflared-windows-386.exe", "cloudflared-windows-386.exe"), 10 | WINDOW_64("windows", "amd64", "cloudflared-windows-amd64.exe", "cloudflared-windows-amd64.exe"), 11 | LINUX_32("linux", "x86", "cloudflared-linux-386", "cloudflared-linux-386"), 12 | LINUX_64("linux", "amd64", "cloudflared-linux-amd64", "cloudflared-linux-amd64"), 13 | MAC_OS_X_64("mac os x", "x86_64", "cloudflared-darwin-amd64", "cloudflared-darwin-amd64.tgz"), 14 | 15 | MAC_OS_ARM("mac os x", "aarch64", "cloudflared-darwin-amd64", "cloudflared-darwin-amd64.tgz"); 16 | 17 | private final String osName; 18 | private final String arch; 19 | private final String fileName; 20 | private final String downloadFile; 21 | 22 | CloudflaredDownload(String osName, String arch, String fileName, String downloadFile) { 23 | this.osName = osName; 24 | this.arch = arch; 25 | this.fileName = fileName; 26 | this.downloadFile = downloadFile; 27 | } 28 | 29 | public static @NotNull CloudflaredDownload find() { 30 | String osName = System.getProperty("os.name").toLowerCase(); 31 | String arch = System.getProperty("os.arch").toLowerCase(); 32 | var download = Arrays.stream(CloudflaredDownload.values()).filter(item -> osName.contains(item.osName) && arch.contains(item.arch)).findFirst(); 33 | if(download.isPresent()) { 34 | return download.get(); 35 | } else { 36 | throw new IllegalStateException("Cloudflared could not be downloaded because no binary file was found for the current operating system"); 37 | } 38 | } 39 | 40 | public String osName() { 41 | return osName; 42 | } 43 | 44 | public String arch() { 45 | return arch; 46 | } 47 | 48 | public String fileName() { 49 | return fileName; 50 | } 51 | 52 | public String downloadFile() { 53 | return downloadFile; 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /common/src/main/java/de/rafael/modflared/binary/download/DownloadedCloudflared.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.binary.download; 2 | 3 | //------------------------------ 4 | // 5 | // This class was developed by Rafael K. 6 | // On 10/31/2022 at 11:17 PM 7 | // In the project cloudflared 8 | // 9 | //------------------------------ 10 | 11 | import de.rafael.modflared.Modflared; 12 | import de.rafael.modflared.binary.Cloudflared; 13 | import de.rafael.modflared.github.GithubAPI; 14 | import de.rafael.modflared.tunnel.RunningTunnel; 15 | import de.rafael.modflared.tunnel.manager.TunnelManager; 16 | import net.minecraft.util.Pair; 17 | import org.jetbrains.annotations.Contract; 18 | import org.jetbrains.annotations.NotNull; 19 | import org.jetbrains.annotations.Nullable; 20 | import org.lwjgl.system.Platform; 21 | 22 | import java.io.*; 23 | import java.net.URI; 24 | import java.nio.charset.StandardCharsets; 25 | import java.nio.file.Files; 26 | import java.util.Arrays; 27 | import java.util.concurrent.CompletableFuture; 28 | 29 | public class DownloadedCloudflared extends Cloudflared { 30 | 31 | private final CloudflaredDownload download; 32 | 33 | private static final File VERSION_FILE = new File(TunnelManager.DATA_FOLDER, "version.json"); 34 | 35 | private static final String GITHUB_DOWNLOAD_ENDPOINT = "https://github.com/cloudflare/cloudflared/releases/download/"; 36 | 37 | public DownloadedCloudflared(CloudflaredDownload download, String version) { 38 | super(version); 39 | this.download = download; 40 | } 41 | 42 | public static CompletableFuture tryCreate() { 43 | if(VERSION_FILE.exists()) { 44 | try { 45 | var version = Modflared.GSON.fromJson(new InputStreamReader(new FileInputStream(VERSION_FILE)), DownloadedCloudflared.class); 46 | if(version != null) return CompletableFuture.completedFuture(version); 47 | } catch (Throwable throwable) { 48 | Modflared.LOGGER.error("Failed to load existing version file creating new one...", throwable); 49 | } 50 | } 51 | return GithubAPI.requestLatestVersion().thenApply(latestVersion -> new DownloadedCloudflared(CloudflaredDownload.find(), latestVersion)); 52 | } 53 | 54 | @Override 55 | public CompletableFuture prepare() { 56 | if(isInstalled()) { 57 | CompletableFuture completableFuture = new CompletableFuture<>(); 58 | isUptoDate().whenComplete((pair, throwable) -> { 59 | if (throwable != null) { 60 | Modflared.LOGGER.error("Failed to check for updates", throwable); 61 | TunnelManager.displayErrorToast(); 62 | completableFuture.complete(null); 63 | } else { 64 | if(!pair.getLeft()) { 65 | Modflared.LOGGER.info("Update detected updating..."); 66 | version = pair.getRight(); 67 | downloadAndSaveInfo().whenComplete((unused, throwable1) -> { 68 | if (throwable1 != null) Modflared.LOGGER.error("Failed to download update", throwable1); 69 | TunnelManager.displayErrorToast(); 70 | completableFuture.complete(null); 71 | }); 72 | } else { 73 | Modflared.LOGGER.info("Cloudflared has no updates :)"); 74 | completableFuture.complete(null); 75 | } 76 | } 77 | }); 78 | return completableFuture; 79 | } else { 80 | return downloadAndSaveInfo(); 81 | } 82 | } 83 | 84 | @Override 85 | public String[] buildCommand(RunningTunnel.@NotNull Access access) { 86 | var command = access.command(createBinaryRef().getName(), true); 87 | Modflared.LOGGER.info(Arrays.toString(command).replace(",","")); 88 | if (Platform.get() == Platform.WINDOWS) { 89 | command[0] = "\"" + TunnelManager.DATA_FOLDER.getAbsolutePath() + "\\" + command[0] + "\""; 90 | } 91 | return command; 92 | } 93 | 94 | private CompletableFuture downloadAndSaveInfo() { 95 | return downloadFile().thenAccept(unused -> { 96 | try { 97 | save(); 98 | } catch (Throwable throwable) { 99 | Modflared.LOGGER.error("Failed to save current installed version", throwable); 100 | TunnelManager.displayErrorToast(); 101 | } 102 | }); 103 | } 104 | 105 | public boolean isInstalled() { 106 | return createBinaryRef().exists() && VERSION_FILE.exists(); 107 | } 108 | 109 | @Contract(" -> new") 110 | public @NotNull File createBinaryRef() { 111 | return new File(TunnelManager.DATA_FOLDER, download.fileName()); 112 | } 113 | 114 | public CompletableFuture> isUptoDate() { 115 | return GithubAPI.requestLatestVersion().thenApply(latestVersion -> new Pair<>(latestVersion.equals(version), latestVersion)); 116 | } 117 | 118 | public @NotNull CompletableFuture downloadFile() { 119 | return GithubAPI.requestFileHash(download.downloadFile()).thenAcceptAsync(fileHash -> { 120 | try { 121 | for (int i = 0; i < 5; i++) { 122 | Modflared.LOGGER.info("Downloading cloudflared version {} from github. Attempt: {}", version, i + 1); 123 | File file = syncDownloadFile(); 124 | 125 | // Check if file is corrupt 126 | if(fileHash.compareTo(file)) { 127 | Modflared.LOGGER.info("Download finished of cloudflared version {}!", version); 128 | return; 129 | } else { 130 | file.delete(); 131 | } 132 | } 133 | } catch (InterruptedException exception) { 134 | throw new IllegalStateException("Error while unpacking MacOS cloudflared download", exception); 135 | } catch (Exception exception) { 136 | throw new IllegalStateException("Failed to download cloudflared binary", exception); 137 | } 138 | throw new IllegalStateException("Modflared failed 5 times to download cloudflared from github. Please check your internet connection"); 139 | }, Modflared.EXECUTOR); 140 | } 141 | 142 | private @NotNull File syncDownloadFile() throws IOException, InterruptedException { 143 | File output = new File(TunnelManager.DATA_FOLDER, download.fileName()); 144 | if(!output.getParentFile().exists()) output.getParentFile().mkdirs(); 145 | if(!output.exists()) output.createNewFile(); 146 | try (BufferedInputStream in = new BufferedInputStream(URI.create(GITHUB_DOWNLOAD_ENDPOINT + version + "/" + download.downloadFile()).toURL().openStream()); BufferedOutputStream fileOutputStream = new BufferedOutputStream(new FileOutputStream(output))) { 147 | byte[] dataBuffer = new byte[1024]; 148 | int bytesRead; 149 | while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) { 150 | fileOutputStream.write(dataBuffer, 0, bytesRead); 151 | } 152 | fileOutputStream.flush(); 153 | } 154 | 155 | switch (Platform.get()) { 156 | case MACOSX: 157 | new ProcessBuilder("tar", "-xzf", output.getName()).directory(output.getParentFile()).start().waitFor(); 158 | new ProcessBuilder("mv", "cloudflared", output.getName()).directory(output.getParentFile()).start().waitFor(); 159 | //Fallthrough 160 | case LINUX: 161 | new ProcessBuilder("chmod", "+x", output.getName()).directory(output.getParentFile()).start(); 162 | break; 163 | default: 164 | break; 165 | } 166 | return output; 167 | } 168 | 169 | private void save() throws IOException { 170 | Files.writeString(VERSION_FILE.toPath(), Modflared.GSON.toJson(this), StandardCharsets.UTF_8); 171 | } 172 | 173 | } 174 | -------------------------------------------------------------------------------- /common/src/main/java/de/rafael/modflared/binary/local/LocalCloudflared.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.binary.local; 2 | 3 | import de.rafael.modflared.Modflared; 4 | import de.rafael.modflared.binary.Cloudflared; 5 | import de.rafael.modflared.tunnel.RunningTunnel; 6 | import org.jetbrains.annotations.NotNull; 7 | import org.jetbrains.annotations.Nullable; 8 | 9 | import java.io.BufferedReader; 10 | import java.io.InputStreamReader; 11 | import java.util.concurrent.CompletableFuture; 12 | 13 | public class LocalCloudflared extends Cloudflared { 14 | 15 | public LocalCloudflared(String version) { 16 | super(version); 17 | } 18 | 19 | @Override 20 | public CompletableFuture prepare() { 21 | return CompletableFuture.completedFuture(null); 22 | } 23 | 24 | @Override 25 | public String[] buildCommand(RunningTunnel.@NotNull Access access) { 26 | return access.command("cloudflared", false); 27 | } 28 | 29 | public static @Nullable Cloudflared tryCreate() { 30 | // Check if cloudflared is already installed on the system 31 | try { 32 | var builder = new ProcessBuilder("cloudflared", "--version"); 33 | var process = builder.start(); 34 | var reader = new BufferedReader(new InputStreamReader(process.getInputStream())); 35 | String versionString = reader.readLine(); 36 | String version = versionString.split(" ")[2]; 37 | Modflared.LOGGER.info("Cloudflared output: {}", versionString); 38 | Modflared.LOGGER.info("Cloudflared version {} is already installed on the system", version); 39 | return new LocalCloudflared(version); 40 | } catch (Throwable ignored) { 41 | Modflared.LOGGER.info("Cloudflared is not installed on the system. Downloading it if necessary..."); 42 | } 43 | return null; 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /common/src/main/java/de/rafael/modflared/github/GithubAPI.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.github; 2 | 3 | import com.google.common.hash.HashCode; 4 | import com.google.common.hash.Hashing; 5 | import com.google.common.io.ByteSource; 6 | import com.google.common.io.Files; 7 | import com.google.gson.JsonObject; 8 | import com.google.gson.JsonParser; 9 | import de.rafael.modflared.Modflared; 10 | import org.jetbrains.annotations.Contract; 11 | import org.jetbrains.annotations.NotNull; 12 | 13 | import java.io.File; 14 | import java.io.IOException; 15 | import java.io.InputStream; 16 | import java.io.InputStreamReader; 17 | import java.net.MalformedURLException; 18 | import java.net.URI; 19 | import java.net.URL; 20 | import java.net.URLConnection; 21 | import java.util.Arrays; 22 | import java.util.List; 23 | import java.util.Objects; 24 | import java.util.concurrent.CompletableFuture; 25 | 26 | public class GithubAPI { 27 | 28 | private static final String GITHUB_USER = "cloudflare"; 29 | private static final String GITHUB_REPOSITORY = "cloudflared"; 30 | 31 | private static URL GITHUB_API_ENDPOINT = null; 32 | 33 | static { 34 | try { 35 | GITHUB_API_ENDPOINT = URI.create("https://api.github.com/repos/" + GITHUB_USER + "/" + GITHUB_REPOSITORY + "/releases/latest").toURL(); 36 | } catch (MalformedURLException exception) { 37 | Modflared.LOGGER.error("Failed to create url object of github endpoint.", exception); 38 | } 39 | } 40 | 41 | @Contract(" -> new") 42 | public static @NotNull CompletableFuture requestLatestVersion() { 43 | return CompletableFuture.supplyAsync(() -> { 44 | try { 45 | return getJsonFromEndpoint(GITHUB_API_ENDPOINT).get("tag_name").getAsString(); 46 | } catch (Throwable throwable) { 47 | throw new IllegalStateException("Failed to get latest cloudflared version from github", throwable); 48 | } 49 | }, Modflared.EXECUTOR); 50 | } 51 | 52 | @Contract("_ -> new") 53 | public static @NotNull CompletableFuture requestFileHash(String filename) { 54 | return CompletableFuture.supplyAsync(() -> { 55 | try { 56 | return extractHashes(getJsonFromEndpoint(GITHUB_API_ENDPOINT)).stream().filter(item -> item.file.equals(filename)).findFirst().orElseThrow(); 57 | } catch (Throwable throwable) { 58 | throw new IllegalStateException("Failed to get file hash from github", throwable); 59 | } 60 | }, Modflared.EXECUTOR); 61 | } 62 | 63 | private static List extractHashes(@NotNull JsonObject data) { 64 | return Arrays.stream(data.get("body").getAsString().split("\n")).filter(item -> item.startsWith("cloudflared-") && item.contains(":")).map(item -> { 65 | var fileData = item.split(":"); 66 | return new FileHash(fileData[0].trim(), fileData[1].trim()); 67 | }).toList(); 68 | } 69 | 70 | private static JsonObject getJsonFromEndpoint(@NotNull URL url) throws IOException { 71 | URLConnection connection = url.openConnection(); 72 | InputStream inputStream = connection.getInputStream(); 73 | return JsonParser.parseReader(new InputStreamReader(inputStream)).getAsJsonObject(); 74 | } 75 | 76 | public record FileHash(String file, String hash) { 77 | 78 | public boolean compareTo(File file) throws IOException { 79 | ByteSource byteSource = Files.asByteSource(file); 80 | HashCode hashCode = byteSource.hash(Hashing.sha256()); 81 | return compareTo(hashCode.toString()); 82 | } 83 | 84 | public boolean compareTo(String hash) { 85 | return Objects.equals(this.hash, hash); 86 | } 87 | 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /common/src/main/java/de/rafael/modflared/interfaces/mixin/IClientConnection.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.interfaces.mixin; 2 | 3 | import de.rafael.modflared.tunnel.RunningTunnel; 4 | 5 | public interface IClientConnection { 6 | 7 | void setRunningTunnel(RunningTunnel runningTunnel); 8 | 9 | } 10 | -------------------------------------------------------------------------------- /common/src/main/java/de/rafael/modflared/interfaces/mixin/IConnectScreen.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.interfaces.mixin; 2 | 3 | import de.rafael.modflared.tunnel.TunnelStatus; 4 | 5 | public interface IConnectScreen { 6 | 7 | void setStatus(TunnelStatus status); 8 | 9 | } -------------------------------------------------------------------------------- /common/src/main/java/de/rafael/modflared/interfaces/mixin/IServerInfo.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.interfaces.mixin; 2 | 3 | import de.rafael.modflared.tunnel.TunnelStatus; 4 | 5 | public interface IServerInfo { 6 | 7 | void setTunnelStatus(TunnelStatus status); 8 | TunnelStatus getTunnelStatus(); 9 | 10 | } 11 | -------------------------------------------------------------------------------- /common/src/main/java/de/rafael/modflared/methods/ConnectScreenMethods.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.methods; 2 | 3 | import de.rafael.modflared.Modflared; 4 | import de.rafael.modflared.interfaces.mixin.IConnectScreen; 5 | import de.rafael.modflared.tunnel.TunnelStatus; 6 | import io.netty.channel.ChannelFuture; 7 | import net.minecraft.client.MinecraftClient; 8 | import net.minecraft.client.gui.screen.multiplayer.ConnectScreen; 9 | import net.minecraft.network.ClientConnection; 10 | import org.jetbrains.annotations.NotNull; 11 | 12 | import java.net.InetSocketAddress; 13 | 14 | public class ConnectScreenMethods { 15 | 16 | public static ChannelFuture connect(@NotNull InetSocketAddress address, boolean useEpoll, ClientConnection connection) { 17 | var status = Modflared.TUNNEL_MANAGER.handleConnect(address); 18 | Modflared.TUNNEL_MANAGER.prepareConnection(status, connection); 19 | 20 | var currentScreen = MinecraftClient.getInstance().currentScreen; 21 | if (currentScreen instanceof ConnectScreen connectScreen) { 22 | ((IConnectScreen) connectScreen).setStatus(status); 23 | } 24 | 25 | return ClientConnection.connect(status.state() == TunnelStatus.State.USE ? status.runningTunnel().access().tunnelAddress() : address, useEpoll, connection); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /common/src/main/java/de/rafael/modflared/mixin/ClientConnectionMixin.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.mixin; 2 | 3 | import de.rafael.modflared.Modflared; 4 | import de.rafael.modflared.interfaces.mixin.IClientConnection; 5 | import de.rafael.modflared.tunnel.RunningTunnel; 6 | import net.minecraft.network.ClientConnection; 7 | import net.minecraft.text.Text; 8 | import org.spongepowered.asm.mixin.*; 9 | import org.spongepowered.asm.mixin.injection.At; 10 | import org.spongepowered.asm.mixin.injection.Inject; 11 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; 12 | 13 | @Implements(@Interface(iface = IClientConnection.class, prefix = "connection$")) 14 | @Mixin(ClientConnection.class) 15 | public abstract class ClientConnectionMixin implements IClientConnection { 16 | 17 | @Unique 18 | private RunningTunnel modflared$runningTunnel = null; 19 | 20 | /* Replaced by MultiplayerServerListPingerMixin 21 | @Redirect(method = "connect(Ljava/net/InetSocketAddress;ZLnet/minecraft/util/profiler/PerformanceLog;)Lnet/minecraft/network/ClientConnection;", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/ClientConnection;connect(Ljava/net/InetSocketAddress;ZLnet/minecraft/network/ClientConnection;)Lio/netty/channel/ChannelFuture;")) 22 | private static ChannelFuture connect(@NotNull InetSocketAddress address, boolean useEpoll, ClientConnection connection) { 23 | return ClientConnection.connect(Modflared.TUNNEL_MANAGER.handleConnect(address, connection).address(), useEpoll, connection); 24 | }*/ 25 | 26 | @Inject(method = "disconnect", at = @At("TAIL")) 27 | public void disconnect(Text disconnectReason, CallbackInfo callbackInfo) { 28 | synchronized(this) { 29 | if(this.modflared$runningTunnel != null) { 30 | Modflared.TUNNEL_MANAGER.closeTunnel(this.modflared$runningTunnel); 31 | this.modflared$runningTunnel = null; 32 | } 33 | } 34 | } 35 | 36 | @Intrinsic 37 | public void connection$setRunningTunnel(RunningTunnel runningTunnel) { 38 | this.modflared$runningTunnel = runningTunnel; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /common/src/main/java/de/rafael/modflared/mixin/ConnectScreenMixin.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.mixin; 2 | 3 | import de.rafael.modflared.interfaces.mixin.IConnectScreen; 4 | import de.rafael.modflared.tunnel.TunnelStatus; 5 | import net.minecraft.client.gui.DrawContext; 6 | import net.minecraft.client.gui.screen.Screen; 7 | import net.minecraft.client.gui.screen.multiplayer.ConnectScreen; 8 | import net.minecraft.text.Text; 9 | import org.jetbrains.annotations.Nullable; 10 | import org.spongepowered.asm.mixin.*; 11 | import org.spongepowered.asm.mixin.injection.At; 12 | import org.spongepowered.asm.mixin.injection.Inject; 13 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; 14 | 15 | @Implements(@Interface(iface = IConnectScreen.class, prefix = "connectScreen$")) 16 | @Mixin(ConnectScreen.class) 17 | public abstract class ConnectScreenMixin extends Screen implements IConnectScreen { 18 | 19 | protected ConnectScreenMixin(Text title) { 20 | super(title); 21 | } 22 | 23 | @Unique 24 | @Nullable 25 | public TunnelStatus modflared$status; 26 | 27 | @Intrinsic 28 | public void connectScreen$setStatus(TunnelStatus status) { 29 | this.modflared$status = status; 30 | } 31 | 32 | @Shadow 33 | private Text status; 34 | 35 | @Inject(method = "render", at = @At("TAIL")) 36 | public void render(DrawContext context, int mouseX, int mouseY, float delta, CallbackInfo ci) { 37 | // This screen starts drawing before the connection is established, so we need to check if the status is null 38 | // We're also checking if the status is the default "Connecting..." status, because we know we've connected to the server 39 | // when the status changes 40 | if (this.modflared$status == null || !status.equals(Text.translatable("connect.connecting"))) return; 41 | 42 | int y = this.height / 2 - 50; 43 | // Connecting Text is drawn at y = this.height / 2 - 50 44 | y += 10; 45 | 46 | for (Text status : this.modflared$status.generateFeedback()) { 47 | y += 10; 48 | context.drawCenteredTextWithShadow(this.textRenderer, status, this.width / 2, y, 16777215); 49 | } 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /common/src/main/java/de/rafael/modflared/mixin/client/MultiplayerServerListPingerMixin.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.mixin.client; 2 | 3 | import de.rafael.modflared.Modflared; 4 | import de.rafael.modflared.interfaces.mixin.IServerInfo; 5 | import de.rafael.modflared.tunnel.TunnelStatus; 6 | import net.minecraft.client.network.MultiplayerServerListPinger; 7 | import net.minecraft.client.network.ServerInfo; 8 | import net.minecraft.network.ClientConnection; 9 | import net.minecraft.util.profiler.MultiValueDebugSampleLogImpl; 10 | import org.spongepowered.asm.mixin.Mixin; 11 | import org.spongepowered.asm.mixin.injection.At; 12 | import org.spongepowered.asm.mixin.injection.Redirect; 13 | 14 | import java.net.InetSocketAddress; 15 | 16 | @Mixin(MultiplayerServerListPinger.class) 17 | public abstract class MultiplayerServerListPingerMixin { 18 | 19 | @Redirect(method = "add", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/ClientConnection;connect(Ljava/net/InetSocketAddress;ZLnet/minecraft/util/profiler/MultiValueDebugSampleLogImpl;)Lnet/minecraft/network/ClientConnection;")) 20 | public ClientConnection connect(InetSocketAddress address, boolean useEpoll, MultiValueDebugSampleLogImpl packetSizeLog, ServerInfo entry) { 21 | var result = Modflared.TUNNEL_MANAGER.handleConnect(address); 22 | if(result.state() == TunnelStatus.State.USE) { 23 | var connection = ClientConnection.connect(result.runningTunnel().access().tunnelAddress(), useEpoll, packetSizeLog); 24 | Modflared.TUNNEL_MANAGER.prepareConnection(result, connection); 25 | ((IServerInfo) entry).setTunnelStatus(result); 26 | return connection; 27 | } 28 | return ClientConnection.connect(address, useEpoll, packetSizeLog); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /common/src/main/java/de/rafael/modflared/mixin/client/ServerEntryMixin.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.mixin.client; 2 | 3 | import de.rafael.modflared.Modflared; 4 | import de.rafael.modflared.interfaces.mixin.IServerInfo; 5 | import de.rafael.modflared.tunnel.TunnelStatus; 6 | import net.minecraft.client.gui.DrawContext; 7 | import net.minecraft.client.gui.screen.multiplayer.MultiplayerScreen; 8 | import net.minecraft.client.gui.screen.multiplayer.MultiplayerServerListWidget; 9 | import net.minecraft.client.network.ServerInfo; 10 | import net.minecraft.client.render.RenderLayer; 11 | import net.minecraft.text.Text; 12 | import net.minecraft.util.Formatting; 13 | import net.minecraft.util.Identifier; 14 | import org.jetbrains.annotations.NotNull; 15 | import org.spongepowered.asm.mixin.Final; 16 | import org.spongepowered.asm.mixin.Mixin; 17 | import org.spongepowered.asm.mixin.Shadow; 18 | import org.spongepowered.asm.mixin.Unique; 19 | import org.spongepowered.asm.mixin.injection.At; 20 | import org.spongepowered.asm.mixin.injection.Inject; 21 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; 22 | 23 | import java.util.Collections; 24 | 25 | @Mixin(MultiplayerServerListWidget.ServerEntry.class) 26 | public abstract class ServerEntryMixin { 27 | 28 | @Shadow @Final private ServerInfo server; 29 | @Shadow @Final private MultiplayerScreen screen; 30 | 31 | @Unique 32 | private static final Identifier MODFLARED_INDICATOR_TEXTURE = Identifier.of(Modflared.MOD_ID, "icon/indicator"); 33 | 34 | @Inject(method = "render", at = @At("TAIL")) 35 | public void render(@NotNull DrawContext context, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float tickDelta, CallbackInfo ci) { 36 | var tunnelStatus = ((IServerInfo) server).getTunnelStatus(); 37 | if(tunnelStatus != null && tunnelStatus.state() == TunnelStatus.State.USE) { 38 | int xOffset = entryWidth - 15; 39 | int yOffset = 10 + 1; 40 | context.drawGuiTexture(RenderLayer::getGuiTextured, MODFLARED_INDICATOR_TEXTURE, x + xOffset, y + yOffset, 10, 10); 41 | 42 | // Tooltip 43 | int l = mouseX - x; 44 | int m = mouseY - y; 45 | if (l >= entryWidth - 15 && l <= entryWidth - 5 && m >= 9 && m <= 9 + 10) { 46 | this.screen.setTooltip(Collections.singletonList(Text.translatable("gui.multiplayer.tunnel.status.0").formatted(Formatting.AQUA).asOrderedText())); 47 | } 48 | } 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /common/src/main/java/de/rafael/modflared/mixin/client/ServerInfoMixin.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.mixin.client; 2 | 3 | import de.rafael.modflared.interfaces.mixin.IServerInfo; 4 | import de.rafael.modflared.tunnel.TunnelStatus; 5 | import net.minecraft.client.network.ServerInfo; 6 | import org.spongepowered.asm.mixin.*; 7 | 8 | @Implements(@Interface(iface = IServerInfo.class, prefix = "serverInfo$")) 9 | @Mixin(ServerInfo.class) 10 | public abstract class ServerInfoMixin implements IServerInfo { 11 | 12 | @Unique 13 | private TunnelStatus modflared$tunnelStatus; 14 | 15 | @Intrinsic 16 | public void serverInfo$setTunnelStatus(TunnelStatus status) { 17 | this.modflared$tunnelStatus = status; 18 | } 19 | 20 | @Intrinsic 21 | public TunnelStatus serverInfo$getTunnelStatus() { 22 | return modflared$tunnelStatus; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /common/src/main/java/de/rafael/modflared/platform/LoaderPlatform.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.platform; 2 | 3 | public enum LoaderPlatform { 4 | 5 | FABRIC, 6 | NEOFORGE; 7 | 8 | public boolean isNeoForge() { 9 | return this == NEOFORGE; 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /common/src/main/java/de/rafael/modflared/tunnel/RunningTunnel.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.tunnel; 2 | 3 | //------------------------------ 4 | // 5 | // This class was developed by Rafael K. 6 | // On 10/31/2022 at 11:29 PM 7 | // In the project cloudflared 8 | // 9 | //------------------------------ 10 | 11 | import de.rafael.modflared.Modflared; 12 | import de.rafael.modflared.binary.Cloudflared; 13 | import de.rafael.modflared.tunnel.manager.TunnelManager; 14 | import org.jetbrains.annotations.Contract; 15 | import org.jetbrains.annotations.NotNull; 16 | import org.lwjgl.system.Platform; 17 | 18 | import java.io.*; 19 | import java.net.InetSocketAddress; 20 | import java.util.concurrent.CompletableFuture; 21 | import java.util.zip.CRC32; 22 | 23 | public record RunningTunnel(Access access, Process process) { 24 | 25 | public static @NotNull CompletableFuture createTunnel(@NotNull Cloudflared binary, @NotNull Access access) { 26 | var future = new CompletableFuture(); 27 | Modflared.EXECUTOR.execute(() -> { 28 | try { 29 | ProcessBuilder processBuilder = new ProcessBuilder(binary.buildCommand(access)); 30 | // Since LINUX, MACOSX, and WINDOWS are the only options, this will work to only set the directory for Linux and MacOS 31 | if (Platform.get() != Platform.WINDOWS) { 32 | processBuilder.directory(TunnelManager.DATA_FOLDER); 33 | } 34 | processBuilder.redirectErrorStream(true); 35 | var process = processBuilder.start(); 36 | 37 | var reader = new BufferedReader(new InputStreamReader(process.getInputStream())); 38 | 39 | String line; 40 | while ((line = reader.readLine()) != null) { 41 | TunnelManager.CLOUDFLARE_LOGGER.info(line); 42 | if (line.contains("Start Websocket listener")) { 43 | // Wait for the websocket to start (this is a hacky solution, but I don't really see a better way) 44 | Thread.sleep(250); 45 | future.complete(new RunningTunnel(access, process)); // Tunnel was started. Return running tunnel to minecraft client 46 | } 47 | } 48 | } catch (IOException | InterruptedException exception) { 49 | Modflared.LOGGER.error("Failed to start cloudflared", exception); 50 | future.completeExceptionally(exception); 51 | } 52 | }); 53 | return future; 54 | } 55 | 56 | public void closeTunnel() { 57 | process.destroy(); 58 | } 59 | 60 | public record Access(String protocol, String hostname, InetSocketAddress tunnelAddress) { 61 | @Contract("_ -> new") 62 | public static @NotNull Access localWithRandomPort(String host) { 63 | return new Access("tcp", host, new InetSocketAddress("127.0.0.1", computePort(host))); 64 | } 65 | 66 | public String @NotNull [] command(@NotNull String fileName, boolean prefix) { 67 | return new String[] {(prefix && Platform.get() != Platform.WINDOWS ? "./" : "") + fileName, "access", protocol, "--hostname", hostname, "--url", tunnelAddress.getHostString() + ":" + tunnelAddress.getPort()}; 68 | } 69 | 70 | public static int computePort(@NotNull String host) { 71 | final int MIN_PORT = 25565; 72 | final int MAX_PORT = 65530; 73 | final int RANGE = MAX_PORT - MIN_PORT + 1; 74 | 75 | CRC32 crc32 = new CRC32(); 76 | crc32.update(host.getBytes()); 77 | long hash = crc32.getValue(); 78 | 79 | return (int) ((hash % RANGE) + MIN_PORT); 80 | } 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /common/src/main/java/de/rafael/modflared/tunnel/TunnelStatus.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.tunnel; 2 | 3 | import net.minecraft.text.Text; 4 | import net.minecraft.util.Formatting; 5 | import org.jetbrains.annotations.Unmodifiable; 6 | 7 | import java.util.List; 8 | 9 | public record TunnelStatus(RunningTunnel runningTunnel, State state) { 10 | 11 | public @Unmodifiable List generateFeedback() { 12 | return switch (state) { 13 | case USE -> List.of( 14 | Text.translatable("gui.tunnel.status.use").formatted(Formatting.AQUA) 15 | ); 16 | case DONT_USE -> List.of(); 17 | case FAILED_TO_DETERMINE -> List.of( 18 | Text.translatable("gui.tunnel.status.failed.0").formatted(Formatting.RED), 19 | Text.translatable("gui.tunnel.status.failed.1").formatted(Formatting.RED), 20 | Text.translatable("gui.tunnel.status.failed.2").formatted(Formatting.RED) 21 | ); 22 | }; 23 | } 24 | 25 | public enum State { 26 | USE, 27 | DONT_USE, 28 | FAILED_TO_DETERMINE 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /common/src/main/java/de/rafael/modflared/tunnel/manager/TunnelManager.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.tunnel.manager; 2 | 3 | import com.google.gson.JsonArray; 4 | import com.google.gson.JsonElement; 5 | import com.google.gson.JsonParser; 6 | import de.rafael.modflared.Modflared; 7 | import de.rafael.modflared.ModflaredPlatform; 8 | import de.rafael.modflared.binary.Cloudflared; 9 | import de.rafael.modflared.interfaces.mixin.IClientConnection; 10 | import de.rafael.modflared.tunnel.RunningTunnel; 11 | import de.rafael.modflared.tunnel.TunnelStatus; 12 | import net.minecraft.client.MinecraftClient; 13 | import net.minecraft.client.network.ServerAddress; 14 | import net.minecraft.client.toast.SystemToast; 15 | import net.minecraft.network.ClientConnection; 16 | import net.minecraft.text.Text; 17 | import org.jetbrains.annotations.NotNull; 18 | import org.jetbrains.annotations.Nullable; 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | 22 | import javax.naming.NamingException; 23 | import javax.naming.directory.Attribute; 24 | import javax.naming.directory.Attributes; 25 | import javax.naming.directory.InitialDirContext; 26 | import java.io.*; 27 | import java.net.InetAddress; 28 | import java.net.InetSocketAddress; 29 | import java.net.UnknownHostException; 30 | import java.util.ArrayList; 31 | import java.util.List; 32 | import java.util.Properties; 33 | import java.util.concurrent.atomic.AtomicReference; 34 | 35 | public class TunnelManager { 36 | 37 | public static final File BASE_FOLDER = ModflaredPlatform.getGameDir().resolve("modflared/").toFile(); 38 | public static final File DATA_FOLDER = new File(BASE_FOLDER, "bin/"); 39 | public static final File FORCED_TUNNELS_FILE = new File(BASE_FOLDER, "forced_tunnels.json"); 40 | 41 | public static final Logger CLOUDFLARE_LOGGER = LoggerFactory.getLogger("Cloudflared"); 42 | 43 | private final AtomicReference cloudflared = new AtomicReference<>(); 44 | private final List forcedTunnels = new ArrayList<>(); 45 | 46 | private final List runningTunnels = new ArrayList<>(); 47 | 48 | public RunningTunnel createTunnel(String host) { 49 | var binary = this.cloudflared.get(); 50 | if (binary != null) { 51 | Modflared.LOGGER.info("Starting tunnel to {}", host); 52 | var process = binary.createTunnel(RunningTunnel.Access.localWithRandomPort(host)); 53 | if (process == null) return null; 54 | this.runningTunnels.add(process); 55 | return process; 56 | } else { 57 | return null; 58 | } 59 | } 60 | 61 | public void closeTunnel(@NotNull RunningTunnel runningTunnel) { 62 | Modflared.LOGGER.info("Stopping tunnel to {}", runningTunnel.access().tunnelAddress()); 63 | this.runningTunnels.remove(runningTunnel); 64 | runningTunnel.closeTunnel(); 65 | } 66 | 67 | public void closeTunnels() { 68 | for (RunningTunnel runningTunnel : this.runningTunnels) { 69 | runningTunnel.closeTunnel(); 70 | } 71 | } 72 | 73 | /** 74 | * Check the TXT records for the server to see if it should use a tunnel We check for a TXT record on the same subdomain as 75 | * the server we are connecting to. 76 | *

77 | * This is done by checking if the server has a TXT record with the value "cloudflared-use-tunnel" or 78 | * "cloudflared-route=" 79 | *

  • 80 | * If the server has the TXT record "cloudflared-route=", it will use the route as the route for the tunnel. 81 | *
  • 82 | *
  • 83 | * If the server has the TXT record "cloudflared-use-tunnel", it will use the server address as the route for the tunnel 84 | *
  • 85 | *
  • 86 | * If the server has neither of the TXT records, it will not use a tunnel (unless it is in the forced tunnels list) 87 | *
  • 88 | * 89 | * @return The route to use for the tunnel, or null if the tunnel should not be used 90 | * @throws IOException If an error occurs while resolving the DNS TXT records 91 | */ 92 | public @Nullable String shouldUseTunnel(String host) throws IOException { 93 | if (forcedTunnels.stream().anyMatch(serverAddress -> serverAddress.getAddress().equalsIgnoreCase(host))) { 94 | return host; 95 | } 96 | 97 | // Check if the host is an IP address 98 | if (!isHost(host)) { 99 | return null; 100 | } 101 | try { 102 | var properties = new Properties(); 103 | properties.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); 104 | InitialDirContext dirContext = new InitialDirContext(properties); 105 | Attributes attributes = dirContext.getAttributes(host, new String[]{"TXT"}); 106 | Attribute txtRecords = attributes.get("TXT"); 107 | 108 | if (txtRecords != null) { 109 | var iterator = txtRecords.getAll(); 110 | while (iterator.hasMore()) { 111 | var record = ((String) iterator.next()).replaceAll("\"", ""); 112 | if (record.startsWith("cloudflared-route=")) { 113 | return record.replace("cloudflared-route=", ""); 114 | } else if (record.equals("cloudflared-use-tunnel")) { 115 | return host; 116 | } 117 | } 118 | } 119 | } catch (NamingException | UncheckedIOException exception) { 120 | Modflared.LOGGER.error("Failed to resolve DNS TXT entries: " + exception.getMessage(), exception); 121 | 122 | Modflared.LOGGER.error( 123 | "Modflared was unable to determine if a tunnel should be used for {} and is defaulting to not " + 124 | "using a tunnel", host); 125 | Modflared.LOGGER.error( 126 | "If you believe you need a tunnel for this server, please add it to the forced tunnels list in " + 127 | "the modflared folder in your game directory."); 128 | Modflared.LOGGER.error("For more information, please see the modflared documentation at " + 129 | "https://github.com/HttpRafa/modflared?tab=readme-ov-file#versions-100-and-onward"); 130 | 131 | throw new IOException(exception); 132 | } 133 | 134 | return null; 135 | } 136 | 137 | /** 138 | * @param ip The IP address or hostname 139 | * @return Whether the string is a hostname 140 | * @see How do you tell whether a string is an IP or a hostname 141 | */ 142 | private boolean isHost(String ip) { 143 | if (ip.strip().equalsIgnoreCase("localhost")) return false; 144 | try { 145 | InetAddress[] ips = InetAddress.getAllByName(ip); 146 | // #getAllByName will return an InetAddress that is the same as the input if it is an IP address, 147 | // so we can check if the input is an IP address by comparing the InetAddress to the input 148 | return !(ips.length == 1 && ips[0].getHostAddress().equals(ip)); 149 | } catch (UnknownHostException e) { 150 | return true; 151 | } 152 | } 153 | 154 | public void prepareConnection(@NotNull TunnelStatus status, ClientConnection connection) { 155 | var tunnelConnection = (IClientConnection) connection; 156 | if (status.runningTunnel() != null) { 157 | tunnelConnection.setRunningTunnel(status.runningTunnel()); 158 | } 159 | } 160 | 161 | public TunnelStatus handleConnect(@NotNull InetSocketAddress address) { 162 | if(this.cloudflared.get() == null) { 163 | Modflared.LOGGER.warn("Modflared is not ready yet, ignoring all connections."); 164 | return new TunnelStatus(null, TunnelStatus.State.DONT_USE); 165 | } 166 | 167 | RunningTunnel runningTunnel = null; 168 | TunnelStatus.State state = TunnelStatus.State.DONT_USE; 169 | 170 | String route = null; 171 | try { 172 | route = Modflared.TUNNEL_MANAGER.shouldUseTunnel(address.getHostName()); 173 | } catch (IOException ignored) { 174 | state = TunnelStatus.State.FAILED_TO_DETERMINE; 175 | } 176 | 177 | if (route != null) { 178 | runningTunnel = Modflared.TUNNEL_MANAGER.createTunnel(route); 179 | state = TunnelStatus.State.USE; 180 | } 181 | return new TunnelStatus(runningTunnel, state); 182 | } 183 | 184 | public void prepareBinary() { 185 | Cloudflared.create().whenComplete((version, throwable) -> { 186 | if (throwable != null) { 187 | Modflared.LOGGER.error(throwable.getMessage(), throwable); 188 | } else { 189 | version.prepare().whenComplete((unused, throwable1) -> { 190 | if (throwable1 != null) { 191 | Modflared.LOGGER.error(throwable1.getMessage(), throwable1); 192 | displayErrorToast(); 193 | } else { 194 | this.cloudflared.set(version); 195 | } 196 | }); 197 | } 198 | }); 199 | } 200 | 201 | public void loadForcedTunnels() { 202 | this.forcedTunnels.clear(); 203 | if (!FORCED_TUNNELS_FILE.exists()) { 204 | return; 205 | } 206 | 207 | try { 208 | JsonArray entriesArray = JsonParser.parseReader( 209 | new InputStreamReader(new FileInputStream(FORCED_TUNNELS_FILE))).getAsJsonArray(); 210 | for (JsonElement jsonElement : entriesArray) { 211 | var serverString = jsonElement.getAsString(); 212 | 213 | if (!ServerAddress.isValid(serverString)) { 214 | Modflared.LOGGER.error("Invalid server address: {}", serverString); 215 | continue; 216 | } 217 | forcedTunnels.add(ServerAddress.parse(serverString)); 218 | } 219 | } catch (Exception exception) { 220 | Modflared.LOGGER.error("Failed to load forced tunnels", exception); 221 | } 222 | 223 | Modflared.LOGGER.info("Loaded {} forced tunnels", forcedTunnels.size()); 224 | for (ServerAddress serverAddress : forcedTunnels) { 225 | Modflared.LOGGER.info(" - {}", serverAddress.getAddress()); 226 | } 227 | } 228 | 229 | public static void displayErrorToast() { 230 | MinecraftClient.getInstance().getToastManager().add(new SystemToast(SystemToast.Type.PERIODIC_NOTIFICATION, Text.translatable("gui.toast.title.error"), Text.translatable("gui.toast.body.error"))); 231 | } 232 | 233 | } 234 | -------------------------------------------------------------------------------- /common/src/main/resources/architectury.common.json: -------------------------------------------------------------------------------- 1 | { 2 | "accessWidener": "modflared.accesswidener" 3 | } -------------------------------------------------------------------------------- /common/src/main/resources/assets/modflared/lang/en_us.json: -------------------------------------------------------------------------------- 1 | { 2 | "gui.tunnel.status.use": "Modflared has created a tunnel to the server...", 3 | "gui.tunnel.status.failed.0": "Modflared failed to determine if tunnel should be used.", 4 | "gui.tunnel.status.failed.1": "Assuming a tunnel should not be used...", 5 | "gui.tunnel.status.failed.2": "See logs for more information.", 6 | "gui.multiplayer.tunnel.status.0": "Modflared in use", 7 | "gui.toast.title.error": "Modflared encountered an error.", 8 | "gui.toast.body.error": "See logs for more information." 9 | } -------------------------------------------------------------------------------- /common/src/main/resources/assets/modflared/textures/gui/sprites/icon/indicator.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HttpRafa/modflared/fc8180410fe28c7e948d25cec082b02466847416/common/src/main/resources/assets/modflared/textures/gui/sprites/icon/indicator.png -------------------------------------------------------------------------------- /common/src/main/resources/forced_tunnels.json: -------------------------------------------------------------------------------- 1 | ["example.domain.net", "example2.domain.net"] -------------------------------------------------------------------------------- /common/src/main/resources/modflared-common.mixins.json: -------------------------------------------------------------------------------- 1 | { 2 | "required": true, 3 | "package": "de.rafael.modflared.mixin", 4 | "compatibilityLevel": "JAVA_17", 5 | "minVersion": "0.8", 6 | "client": [ 7 | "client.MultiplayerServerListPingerMixin", 8 | "client.ServerEntryMixin", 9 | "client.ServerInfoMixin" 10 | ], 11 | "mixins": [ 12 | "ClientConnectionMixin", 13 | "ConnectScreenMixin" 14 | ], 15 | "injectors": { 16 | "defaultRequire": 1 17 | } 18 | } -------------------------------------------------------------------------------- /common/src/main/resources/modflared.accesswidener: -------------------------------------------------------------------------------- 1 | accessWidener v2 named -------------------------------------------------------------------------------- /fabric/build.gradle: -------------------------------------------------------------------------------- 1 | import com.google.gson.Gson 2 | import com.google.gson.JsonArray 3 | import com.google.gson.JsonElement 4 | import com.google.gson.JsonObject 5 | import net.darkhax.curseforgegradle.TaskPublishCurseForge 6 | 7 | import java.nio.file.Files 8 | 9 | plugins { 10 | id "com.gradleup.shadow" version "9.0.0-beta11" 11 | id "com.modrinth.minotaur" version "2.+" 12 | id 'net.darkhax.curseforgegradle' version '1.1.15' 13 | } 14 | 15 | architectury { 16 | platformSetupLoomIde() 17 | fabric() 18 | } 19 | 20 | loom { 21 | accessWidenerPath = project(":common").loom.accessWidenerPath 22 | } 23 | 24 | configurations { 25 | common 26 | shadowCommon // Don't use shadow from the shadow plugin since it *excludes* files. 27 | compileClasspath.extendsFrom common 28 | runtimeClasspath.extendsFrom common 29 | developmentFabric.extendsFrom common 30 | } 31 | 32 | dependencies { 33 | modImplementation "net.fabricmc:fabric-loader:${rootProject.fabric_loader_version}" 34 | modApi "net.fabricmc.fabric-api:fabric-api:${rootProject.fabric_api_version}" 35 | 36 | common(project(path: ":common", configuration: "namedElements")) { transitive false } 37 | shadowCommon(project(path: ":common", configuration: "transformProductionFabric")) { transitive false } 38 | } 39 | 40 | def replacements = [ 41 | "version": project.version, 42 | "minecraft_version": project.mod_minecraft_version, 43 | "fabric_loader_version": project.fabric_loader_version 44 | ] 45 | 46 | processResources { 47 | inputs.properties(replacements) 48 | 49 | filesMatching("fabric.mod.json") { 50 | expand replacements 51 | } 52 | } 53 | 54 | // Configure the modrinth publication 55 | modrinth { 56 | token = System.getenv("MODRINTH_TOKEN") 57 | projectId = "${modrinth_project_id}" 58 | versionNumber = "${version}+${minecraft_version}" 59 | versionName = "${version} for ${minecraft_version}" 60 | versionType = "${mod_version_type}" 61 | changelog = generateChangelog() 62 | uploadFile = remapJar 63 | gameVersions = ["${minecraft_version}"] 64 | 65 | syncBodyFrom = rootProject.file("README.md").text; 66 | } 67 | 68 | tasks.modrinth.dependsOn(tasks.modrinthSyncBody) 69 | 70 | // Configure the curseforge publication 71 | tasks.register('publishCurseForge', TaskPublishCurseForge) { 72 | apiToken = System.getenv("CURSEFORGE_TOKEN") 73 | 74 | // The main file to upload 75 | def mainFile = upload(curseforge_project_id, remapJar) 76 | mainFile.displayName = "${version} for ${minecraft_version}" 77 | mainFile.releaseType = mod_version_type 78 | mainFile.changelog = generateChangelog() 79 | mainFile.changelogType = 'markdown' 80 | mainFile.addGameVersion(minecraft_version) 81 | mainFile.addModLoader("fabric") 82 | } 83 | 84 | shadowJar { 85 | exclude "architectury.common.json" 86 | 87 | configurations = [project.configurations.shadowCommon] 88 | archiveClassifier = "dev-shadow" 89 | } 90 | 91 | remapJar { 92 | injectAccessWidener = true 93 | input.set shadowJar.archiveFile 94 | dependsOn shadowJar 95 | } 96 | 97 | sourcesJar { 98 | def commonSources = project(":common").sourcesJar 99 | dependsOn commonSources 100 | from commonSources.archiveFile.map { zipTree(it) } 101 | } 102 | 103 | components.java { 104 | withVariantsFromConfiguration(project.configurations.shadowRuntimeElements) { 105 | skip() 106 | } 107 | } 108 | 109 | publishing { 110 | publications { 111 | mavenFabric(MavenPublication) { 112 | artifactId = rootProject.archives_base_name + "-" + project.name 113 | from components.java 114 | } 115 | } 116 | 117 | // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. 118 | repositories { 119 | // Add repositories to publish to here. 120 | } 121 | } 122 | 123 | // Credits: https://github.com/RelativityMC/VMP-fabric 124 | static String generateChangelog() { 125 | final String path = System.getenv("GITHUB_EVENT_RAW_PATH"); 126 | if (path == null || path.isBlank()) return "No changelog was specified. "; 127 | final JsonObject jsonObject = new Gson().fromJson(Files.readString(java.nio.file.Path.of(path)), JsonObject.class); 128 | 129 | StringBuilder builder = new StringBuilder(); 130 | builder.append("This version is uploaded automatically by GitHub Actions. \n\n") 131 | .append("Changelog: \n"); 132 | final JsonArray commits = jsonObject.getAsJsonArray("commits"); 133 | if (commits.isEmpty()) { 134 | builder.append("No changes detected. \n"); 135 | } else { 136 | for (JsonElement commit : commits) { 137 | JsonObject object = commit.getAsJsonObject(); 138 | builder.append("- "); 139 | builder.append('[').append(object.get("id").getAsString(), 0, 8).append(']').append('(').append(object.get("url").getAsString()).append(')'); 140 | builder.append(' '); 141 | builder.append(object.get("message").getAsString().split("\n")[0]); 142 | builder.append(" - "); 143 | builder.append(object.get("author").getAsJsonObject().get("name").getAsString()); 144 | builder.append(" ").append('\n'); 145 | } 146 | } 147 | return builder.toString(); 148 | } -------------------------------------------------------------------------------- /fabric/src/main/java/de/rafael/modflared/fabric/ModflaredFabricClient.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.fabric; 2 | 3 | import de.rafael.modflared.Modflared; 4 | import net.fabricmc.api.ClientModInitializer; 5 | 6 | public class ModflaredFabricClient implements ClientModInitializer { 7 | 8 | @Override 9 | public void onInitializeClient() { 10 | Modflared.init(); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /fabric/src/main/java/de/rafael/modflared/fabric/ModflaredPlatformImpl.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.fabric; 2 | 3 | import de.rafael.modflared.platform.LoaderPlatform; 4 | import net.fabricmc.loader.api.FabricLoader; 5 | 6 | import java.nio.file.Path; 7 | 8 | public class ModflaredPlatformImpl { 9 | 10 | public static Path getGameDir() { 11 | return FabricLoader.getInstance().getGameDir(); 12 | } 13 | 14 | public static LoaderPlatform getPlatform() { 15 | return LoaderPlatform.FABRIC; 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /fabric/src/main/java/de/rafael/modflared/fabric/mixin/ConnectScreenThreadRunMixin.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.fabric.mixin; 2 | 3 | import de.rafael.modflared.methods.ConnectScreenMethods; 4 | import io.netty.channel.ChannelFuture; 5 | import net.minecraft.network.ClientConnection; 6 | import org.jetbrains.annotations.NotNull; 7 | import org.spongepowered.asm.mixin.Mixin; 8 | import org.spongepowered.asm.mixin.injection.At; 9 | import org.spongepowered.asm.mixin.injection.Redirect; 10 | 11 | import java.net.InetSocketAddress; 12 | 13 | @Mixin(targets = "net.minecraft.client.gui.screen.multiplayer.ConnectScreen$1") 14 | public abstract class ConnectScreenThreadRunMixin implements Runnable { 15 | 16 | @Redirect(method = "run", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/ClientConnection;connect" + 17 | "(Ljava/net/InetSocketAddress;ZLnet/minecraft/network/ClientConnection;)Lio/netty/channel/ChannelFuture;")) 18 | private ChannelFuture connect(@NotNull InetSocketAddress address, boolean useEpoll, ClientConnection connection) { 19 | return ConnectScreenMethods.connect(address, useEpoll, connection); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /fabric/src/main/resources/assets/modflared/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HttpRafa/modflared/fc8180410fe28c7e948d25cec082b02466847416/fabric/src/main/resources/assets/modflared/icon.png -------------------------------------------------------------------------------- /fabric/src/main/resources/fabric.mod.json: -------------------------------------------------------------------------------- 1 | { 2 | "schemaVersion": 1, 3 | "id": "modflared", 4 | "version": "${version}", 5 | "name": "Modflared", 6 | "description": "Automatically connects you to a Cloudflare tunnel without having to install cloudflared separately.", 7 | "authors": [ 8 | "HttpRafa", 9 | "Contributers" 10 | ], 11 | "contact": { 12 | "homepage": "https://modrinth.com/mod/modflared", 13 | "sources": "https://github.com/HttpRafa/modflared" 14 | }, 15 | "license": "MIT", 16 | "icon": "assets/modflared/icon.png", 17 | "environment": "client", 18 | "entrypoints": { 19 | "client": [ 20 | "de.rafael.modflared.fabric.ModflaredFabricClient" 21 | ] 22 | }, 23 | "depends": { 24 | "java": ">=17", 25 | "minecraft": ">=${minecraft_version}", 26 | "fabricloader": ">=${fabric_loader_version}", 27 | "fabric-api": "*" 28 | }, 29 | "mixins": [ 30 | "modflared.mixins.json", 31 | "modflared-common.mixins.json" 32 | ] 33 | } -------------------------------------------------------------------------------- /fabric/src/main/resources/modflared.mixins.json: -------------------------------------------------------------------------------- 1 | { 2 | "required": true, 3 | "package": "de.rafael.modflared.fabric.mixin", 4 | "compatibilityLevel": "JAVA_17", 5 | "minVersion": "0.8", 6 | "client": [ 7 | ], 8 | "mixins": [ 9 | "ConnectScreenThreadRunMixin" 10 | ], 11 | "injectors": { 12 | "defaultRequire": 1 13 | } 14 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Done to increase the memory available to gradle. 2 | org.gradle.jvmargs=-Xmx4G 3 | org.gradle.parallel=true 4 | 5 | # Game Properties 6 | minecraft_version=1.21.5 7 | yarn_version=1.21.5+build.1 8 | yarn_mappings_patch=1.21+build.4 9 | enabled_platforms=fabric,neoforge 10 | 11 | # Mod Properties 12 | archives_base_name=modflared 13 | mod_version=1.3.0 14 | maven_group=de.rafael 15 | mod_minecraft_version=1.21.5 16 | 17 | # Loader Properties 18 | fabric_loader_version=0.16.10 19 | fabric_api_version=0.119.6+1.21.5 20 | neoforge_version=21.5.8-beta 21 | 22 | # Modrinth Properties 23 | modrinth_project_id=modflared 24 | 25 | # Curseforge Properties 26 | curseforge_project_id=997330 27 | 28 | # Publish Properties 29 | mod_version_type=release -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HttpRafa/modflared/fc8180410fe28c7e948d25cec082b02466847416/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.12.1-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | if ! command -v java >/dev/null 2>&1 137 | then 138 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 139 | 140 | Please set the JAVA_HOME variable in your environment to match the 141 | location of your Java installation." 142 | fi 143 | fi 144 | 145 | # Increase the maximum file descriptors if we can. 146 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 147 | case $MAX_FD in #( 148 | max*) 149 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 150 | # shellcheck disable=SC2039,SC3045 151 | MAX_FD=$( ulimit -H -n ) || 152 | warn "Could not query maximum file descriptor limit" 153 | esac 154 | case $MAX_FD in #( 155 | '' | soft) :;; #( 156 | *) 157 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 158 | # shellcheck disable=SC2039,SC3045 159 | ulimit -n "$MAX_FD" || 160 | warn "Could not set maximum file descriptor limit to $MAX_FD" 161 | esac 162 | fi 163 | 164 | # Collect all arguments for the java command, stacking in reverse order: 165 | # * args from the command line 166 | # * the main class name 167 | # * -classpath 168 | # * -D...appname settings 169 | # * --module-path (only if needed) 170 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 171 | 172 | # For Cygwin or MSYS, switch paths to Windows format before running java 173 | if "$cygwin" || "$msys" ; then 174 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 175 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 176 | 177 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 178 | 179 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 180 | for arg do 181 | if 182 | case $arg in #( 183 | -*) false ;; # don't mess with options #( 184 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 185 | [ -e "$t" ] ;; #( 186 | *) false ;; 187 | esac 188 | then 189 | arg=$( cygpath --path --ignore --mixed "$arg" ) 190 | fi 191 | # Roll the args list around exactly as many times as the number of 192 | # args, so each arg winds up back in the position where it started, but 193 | # possibly modified. 194 | # 195 | # NB: a `for` loop captures its iteration list before it begins, so 196 | # changing the positional parameters here affects neither the number of 197 | # iterations, nor the values presented in `arg`. 198 | shift # remove old arg 199 | set -- "$@" "$arg" # push replacement arg 200 | done 201 | fi 202 | 203 | 204 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 205 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 206 | 207 | # Collect all arguments for the java command: 208 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 209 | # and any embedded shellness will be escaped. 210 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 211 | # treated as '${Hostname}' itself on the command line. 212 | 213 | set -- \ 214 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 215 | -classpath "$CLASSPATH" \ 216 | org.gradle.wrapper.GradleWrapperMain \ 217 | "$@" 218 | 219 | # Stop when "xargs" is not available. 220 | if ! command -v xargs >/dev/null 2>&1 221 | then 222 | die "xargs is not available" 223 | fi 224 | 225 | # Use "xargs" to parse quoted args. 226 | # 227 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 228 | # 229 | # In Bash we could simply go: 230 | # 231 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 232 | # set -- "${ARGS[@]}" "$@" 233 | # 234 | # but POSIX shell has neither arrays nor command substitution, so instead we 235 | # post-process each arg (as a line of input to sed) to backslash-escape any 236 | # character that might be a shell metacharacter, then use eval to reverse 237 | # that process (while maintaining the separation between arguments), and wrap 238 | # the whole thing up as a single "set" statement. 239 | # 240 | # This will of course break if any of these variables contains a newline or 241 | # an unmatched quote. 242 | # 243 | 244 | eval "set -- $( 245 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 246 | xargs -n1 | 247 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 248 | tr '\n' ' ' 249 | )" '"$@"' 250 | 251 | exec "$JAVACMD" "$@" 252 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /neoforge/build.gradle: -------------------------------------------------------------------------------- 1 | import com.google.gson.Gson 2 | import com.google.gson.JsonArray 3 | import com.google.gson.JsonElement 4 | import com.google.gson.JsonObject 5 | import net.darkhax.curseforgegradle.TaskPublishCurseForge 6 | 7 | import java.nio.file.Files 8 | 9 | plugins { 10 | id "com.gradleup.shadow" version "9.0.0-beta11" 11 | id "com.modrinth.minotaur" version "2.+" 12 | id 'net.darkhax.curseforgegradle' version '1.1.15' 13 | } 14 | 15 | architectury { 16 | platformSetupLoomIde() 17 | neoForge() 18 | } 19 | 20 | loom { 21 | accessWidenerPath = project(":common").loom.accessWidenerPath 22 | } 23 | 24 | configurations { 25 | common 26 | shadowCommon // Don't use shadow from the shadow plugin since it *excludes* files. 27 | compileClasspath.extendsFrom common 28 | runtimeClasspath.extendsFrom common 29 | developmentNeoForge.extendsFrom common 30 | } 31 | 32 | repositories { 33 | maven { 34 | url "https://maven.neoforged.net/releases/" 35 | } 36 | } 37 | 38 | dependencies { 39 | neoForge "net.neoforged:neoforge:${rootProject.neoforge_version}" 40 | 41 | common(project(path: ":common", configuration: "namedElements")) { transitive false } 42 | shadowCommon(project(path: ":common", configuration: "transformProductionNeoForge")) { transitive = false } 43 | } 44 | 45 | def replacements = [ 46 | "version": project.version, 47 | "minecraft_version": project.mod_minecraft_version, 48 | ] 49 | 50 | processResources { 51 | inputs.properties(replacements) 52 | 53 | filesMatching("META-INF/neoforge.mods.toml") { 54 | expand replacements 55 | } 56 | } 57 | 58 | // Configure the modrinth publication 59 | modrinth { 60 | token = System.getenv("MODRINTH_TOKEN") 61 | projectId = "${modrinth_project_id}" 62 | versionNumber = "${version}+${minecraft_version}" 63 | versionName = "${version} for ${minecraft_version}" 64 | versionType = "${mod_version_type}" 65 | changelog = generateChangelog() 66 | uploadFile = remapJar 67 | gameVersions = ["${minecraft_version}"] 68 | 69 | syncBodyFrom = rootProject.file("README.md").text; 70 | } 71 | 72 | tasks.modrinth.dependsOn(tasks.modrinthSyncBody) 73 | 74 | // Configure the curseforge publication 75 | tasks.register('publishCurseForge', TaskPublishCurseForge) { 76 | apiToken = System.getenv("CURSEFORGE_TOKEN") 77 | 78 | // The main file to upload 79 | def mainFile = upload(curseforge_project_id, remapJar) 80 | mainFile.displayName = "${version} for ${minecraft_version}" 81 | mainFile.releaseType = mod_version_type 82 | mainFile.changelog = generateChangelog() 83 | mainFile.changelogType = 'markdown' 84 | mainFile.addGameVersion(minecraft_version) 85 | mainFile.addModLoader("neoforge") 86 | } 87 | 88 | shadowJar { 89 | exclude "fabric.mod.json" 90 | exclude "architectury.common.json" 91 | 92 | configurations = [project.configurations.shadowCommon] 93 | archiveClassifier = "dev-shadow" 94 | } 95 | 96 | remapJar { 97 | input.set shadowJar.archiveFile 98 | dependsOn shadowJar 99 | } 100 | 101 | sourcesJar { 102 | def commonSources = project(":common").sourcesJar 103 | dependsOn commonSources 104 | from commonSources.archiveFile.map { zipTree(it) } 105 | } 106 | 107 | components.java { 108 | withVariantsFromConfiguration(project.configurations.shadowRuntimeElements) { 109 | skip() 110 | } 111 | } 112 | 113 | publishing { 114 | publications { 115 | mavenForge(MavenPublication) { 116 | artifactId = rootProject.archives_base_name + "-" + project.name 117 | from components.java 118 | } 119 | } 120 | 121 | // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. 122 | repositories { 123 | // Add repositories to publish to here. 124 | } 125 | } 126 | 127 | // Credits: https://github.com/RelativityMC/VMP-fabric 128 | static String generateChangelog() { 129 | final String path = System.getenv("GITHUB_EVENT_RAW_PATH"); 130 | if (path == null || path.isBlank()) return "No changelog was specified. "; 131 | final JsonObject jsonObject = new Gson().fromJson(Files.readString(java.nio.file.Path.of(path)), JsonObject.class); 132 | 133 | StringBuilder builder = new StringBuilder(); 134 | builder.append("This version is uploaded automatically by GitHub Actions. \n\n") 135 | .append("Changelog: \n"); 136 | final JsonArray commits = jsonObject.getAsJsonArray("commits"); 137 | if (commits.isEmpty()) { 138 | builder.append("No changes detected. \n"); 139 | } else { 140 | for (JsonElement commit : commits) { 141 | JsonObject object = commit.getAsJsonObject(); 142 | builder.append("- "); 143 | builder.append('[').append(object.get("id").getAsString(), 0, 8).append(']').append('(').append(object.get("url").getAsString()).append(')'); 144 | builder.append(' '); 145 | builder.append(object.get("message").getAsString().split("\n")[0]); 146 | builder.append(" - "); 147 | builder.append(object.get("author").getAsJsonObject().get("name").getAsString()); 148 | builder.append(" ").append('\n'); 149 | } 150 | } 151 | return builder.toString(); 152 | } -------------------------------------------------------------------------------- /neoforge/gradle.properties: -------------------------------------------------------------------------------- 1 | loom.platform=neoforge -------------------------------------------------------------------------------- /neoforge/src/main/java/de/rafael/modflared/neoforge/ModflaredNeoForge.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.neoforge; 2 | 3 | import de.rafael.modflared.Modflared; 4 | import net.neoforged.bus.api.IEventBus; 5 | import net.neoforged.bus.api.SubscribeEvent; 6 | import net.neoforged.fml.common.Mod; 7 | import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent; 8 | import org.jetbrains.annotations.NotNull; 9 | 10 | @Mod(Modflared.MOD_ID) 11 | public class ModflaredNeoForge { 12 | 13 | public ModflaredNeoForge(@NotNull IEventBus eventBus) { 14 | eventBus.register(this); 15 | } 16 | 17 | @SubscribeEvent 18 | public void onClientSetup(FMLClientSetupEvent event) { 19 | Modflared.init(); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /neoforge/src/main/java/de/rafael/modflared/neoforge/ModflaredPlatformImpl.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.neoforge; 2 | 3 | import de.rafael.modflared.platform.LoaderPlatform; 4 | import net.neoforged.fml.loading.FMLPaths; 5 | 6 | import java.nio.file.Path; 7 | 8 | public class ModflaredPlatformImpl { 9 | 10 | public static Path getGameDir() { 11 | return FMLPaths.GAMEDIR.get(); 12 | } 13 | 14 | public static LoaderPlatform getPlatform() { 15 | return LoaderPlatform.NEOFORGE; 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /neoforge/src/main/java/de/rafael/modflared/neoforge/mixin/ConnectScreenThreadRunMixin.java: -------------------------------------------------------------------------------- 1 | package de.rafael.modflared.neoforge.mixin; 2 | 3 | import de.rafael.modflared.methods.ConnectScreenMethods; 4 | import io.netty.channel.ChannelFuture; 5 | import net.minecraft.network.ClientConnection; 6 | import org.jetbrains.annotations.NotNull; 7 | import org.spongepowered.asm.mixin.Mixin; 8 | import org.spongepowered.asm.mixin.injection.At; 9 | import org.spongepowered.asm.mixin.injection.Redirect; 10 | 11 | import java.net.InetSocketAddress; 12 | 13 | @Mixin(targets = "net.minecraft.client.gui.screen.multiplayer.ConnectScreen$1") 14 | public abstract class ConnectScreenThreadRunMixin implements Runnable { 15 | 16 | @Redirect(method = "run", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/ClientConnection;connect" + 17 | "(Ljava/net/InetSocketAddress;ZLnet/minecraft/network/ClientConnection;)Lio/netty/channel/ChannelFuture;")) 18 | private ChannelFuture connect(@NotNull InetSocketAddress address, boolean useEpoll, ClientConnection connection) { 19 | return ConnectScreenMethods.connect(address, useEpoll, connection); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /neoforge/src/main/resources/META-INF/neoforge.mods.toml: -------------------------------------------------------------------------------- 1 | modLoader="javafml" 2 | loaderVersion="[2,)" 3 | license="MIT" 4 | 5 | [[mods]] 6 | modId="modflared" 7 | version="${version}" 8 | displayName="Modflared" 9 | logoFile="icon.png" 10 | authors="HttpRafa, Contributers" 11 | description='''Automatically connects you to a Cloudflare tunnel without having to install cloudflared separately.''' 12 | 13 | [[dependencies.modflared]] 14 | modId="neoforge" 15 | type="required" 16 | versionRange="[20.4,)" 17 | ordering="NONE" 18 | side="CLIENT" 19 | 20 | [[dependencies.modflared]] 21 | modId="minecraft" 22 | type="required" 23 | versionRange="[${minecraft_version},)" 24 | ordering="NONE" 25 | side="CLIENT" 26 | 27 | [[mixins]] 28 | config = "modflared-common.mixins.json" 29 | 30 | [[mixins]] 31 | config = "modflared.mixins.json" -------------------------------------------------------------------------------- /neoforge/src/main/resources/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HttpRafa/modflared/fc8180410fe28c7e948d25cec082b02466847416/neoforge/src/main/resources/icon.png -------------------------------------------------------------------------------- /neoforge/src/main/resources/modflared.mixins.json: -------------------------------------------------------------------------------- 1 | { 2 | "required": true, 3 | "package": "de.rafael.modflared.neoforge.mixin", 4 | "compatibilityLevel": "JAVA_17", 5 | "minVersion": "0.8", 6 | "client": [ 7 | ], 8 | "mixins": [ 9 | "ConnectScreenThreadRunMixin" 10 | ], 11 | "injectors": { 12 | "defaultRequire": 1 13 | } 14 | } -------------------------------------------------------------------------------- /neoforge/src/main/resources/pack.mcmeta: -------------------------------------------------------------------------------- 1 | { 2 | "pack": { 3 | "description": "Modflared", 4 | "pack_format": 15 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | maven { url "https://maven.fabricmc.net/" } 4 | maven { url "https://maven.architectury.dev/" } 5 | maven { url "https://maven.minecraftforge.net/" } 6 | gradlePluginPortal() 7 | } 8 | } 9 | 10 | include("common") 11 | include("fabric") 12 | include("neoforge") 13 | 14 | rootProject.name = "modflared" 15 | --------------------------------------------------------------------------------