├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src └── main │ ├── resources │ ├── mcwifipnp.png │ ├── pack.mcmeta │ ├── mcwifipnp.mixins.json │ └── assets │ │ └── mcwifipnp │ │ └── lang │ │ ├── zh_hk.json │ │ ├── zh_tw.json │ │ ├── zh_cn.json │ │ ├── es_es.json │ │ ├── en_us.json │ │ └── ru_ru.json │ └── java │ ├── io │ └── github │ │ └── satxm │ │ └── mcwifipnp │ │ ├── network │ │ ├── IUPnPProvider.java │ │ ├── UPnPModule.java │ │ └── GlobalIPs.java │ │ ├── mixin │ │ ├── AccessorGridLayout.java │ │ ├── MixinMinecraftServer.java │ │ ├── MixinUUIDUtil.java │ │ ├── MixinIntegratedServer.java │ │ └── MixinPauseScreen.java │ │ ├── OnlineMode.java │ │ ├── client │ │ ├── GuiUtils.java │ │ ├── OptionsList.java │ │ ├── EditBoxEx.java │ │ └── ShareToLanScreenNew.java │ │ ├── commands │ │ ├── OnlineModeCommand.java │ │ ├── UPnPCommand.java │ │ ├── EnumArgument.java │ │ ├── UUIDFixerCommand.java │ │ └── IpCommand.java │ │ ├── ReadListFile.java │ │ ├── MCWiFiPnPUnit.java │ │ ├── Config.java │ │ └── UUIDFixer.java │ └── com │ └── dosse │ └── upnp │ ├── GatewayFinder.java │ ├── UPnP.java │ └── Gateway.java ├── .gitignore ├── .github ├── ISSUE_TEMPLATE │ └── bug-report.md └── workflows │ ├── build.yml │ └── publish.yaml ├── forge ├── src │ └── main │ │ ├── resources │ │ └── META-INF │ │ │ └── mods.toml │ │ └── java │ │ └── io │ │ └── github │ │ └── satxm │ │ └── mcwifipnp │ │ └── MCWiFiPnP.java └── build.gradle ├── neoforge ├── src │ └── main │ │ ├── resources │ │ └── META-INF │ │ │ └── neoforge.mods.toml │ │ └── java │ │ └── io │ │ └── github │ │ └── satxm │ │ └── mcwifipnp │ │ └── MCWiFiPnP.java └── build.gradle ├── fabric ├── src │ └── main │ │ ├── java │ │ └── io │ │ │ └── github │ │ │ └── satxm │ │ │ └── mcwifipnp │ │ │ └── MCWiFiPnP.java │ │ └── resources │ │ └── fabric.mod.json └── build.gradle ├── settings.gradle ├── quilt ├── src │ └── main │ │ ├── java │ │ └── io │ │ │ └── github │ │ │ └── satxm │ │ │ └── mcwifipnp │ │ │ └── MCWiFiPnP.java │ │ └── resources │ │ └── quilt.mod.json └── build.gradle ├── gradle.properties ├── gradlew.bat ├── README.zh-CN.md ├── README.md ├── gradlew └── LICENSE /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Satxm/mcwifipnp/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/resources/mcwifipnp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Satxm/mcwifipnp/HEAD/src/main/resources/mcwifipnp.png -------------------------------------------------------------------------------- /src/main/resources/pack.mcmeta: -------------------------------------------------------------------------------- 1 | { 2 | "pack": { 3 | "description": "LAN World Plug-n-Play Mod Resources", 4 | "pack_format": ${pack_format_number}, 5 | "min_format": 1, 6 | "max_format": 999, 7 | "supported_formats": [1, 999] 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /src/main/java/io/github/satxm/mcwifipnp/network/IUPnPProvider.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp.network; 2 | 3 | import javax.annotation.Nullable; 4 | 5 | public interface IUPnPProvider { 6 | @Nullable 7 | UPnPModule getUPnPInstance(); 8 | 9 | void setUPnPInstance(@Nullable UPnPModule uPnPInstance); 10 | } 11 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Gradle 2 | .gradle/ 3 | build/ 4 | out/ 5 | classes/ 6 | run/ 7 | runs/ 8 | 9 | # Eclipse 10 | *.launch 11 | 12 | # IntelliJ Idea 13 | .idea/ 14 | *.iml 15 | *.ipr 16 | *.iws 17 | 18 | # Visual Studio Code 19 | .settings/ 20 | .vscode/ 21 | bin/ 22 | .classpath 23 | .project 24 | .factorypath 25 | 26 | # Eclipse JDT LS 27 | workspace/ 28 | 29 | # macOS 30 | *.DS_Store 31 | -------------------------------------------------------------------------------- /src/main/resources/mcwifipnp.mixins.json: -------------------------------------------------------------------------------- 1 | { 2 | "required": true, 3 | "minVersion": "0.8", 4 | "package": "io.github.satxm.mcwifipnp.mixin", 5 | "compatibilityLevel": "JAVA_21", 6 | "refmap": "mcwifipnp-refmap.json", 7 | "client": [ 8 | "AccessorGridLayout", 9 | "MixinIntegratedServer", 10 | "MixinPauseScreen" 11 | ], 12 | "mixins": [ 13 | "MixinMinecraftServer", 14 | "MixinUUIDUtil" 15 | ], 16 | "injectors": { 17 | "defaultRequire": 1 18 | } 19 | } -------------------------------------------------------------------------------- /src/main/java/io/github/satxm/mcwifipnp/mixin/AccessorGridLayout.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp.mixin; 2 | 3 | import java.util.List; 4 | 5 | import org.spongepowered.asm.mixin.Mixin; 6 | import org.spongepowered.asm.mixin.gen.Accessor; 7 | 8 | import net.minecraft.client.gui.layouts.GridLayout; 9 | import net.minecraft.client.gui.layouts.LayoutElement; 10 | 11 | @Mixin(GridLayout.class) 12 | public interface AccessorGridLayout { 13 | @Accessor 14 | List getChildren(); 15 | } -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug-report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug Report 3 | about: Create a report to help us clearly find bug 4 | title: BUG 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **MC Information** 11 | - MC Version: [e.g. 1.21.5] 12 | - Mod Loder: [e.g. fabric] 13 | - Loder Version: [e.g. 0.16.14] 14 | 15 | **Bug Describtion** 16 | A clear and concise description of what the bug is. 17 | 18 | **Log File** 19 | Upload your log file(gamedir\logs\latest.log). 20 | 21 | **Crash Report** 22 | Upload your crash reports file(gamedir\crash-reports\crash-2025-06-09_16.15.26-fml.txt). 23 | -------------------------------------------------------------------------------- /src/main/java/io/github/satxm/mcwifipnp/mixin/MixinMinecraftServer.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp.mixin; 2 | 3 | import javax.annotation.Nullable; 4 | 5 | import org.spongepowered.asm.mixin.Mixin; 6 | import org.spongepowered.asm.mixin.Unique; 7 | 8 | import io.github.satxm.mcwifipnp.network.IUPnPProvider; 9 | import io.github.satxm.mcwifipnp.network.UPnPModule; 10 | import net.minecraft.server.MinecraftServer; 11 | 12 | @Mixin(MinecraftServer.class) 13 | public abstract class MixinMinecraftServer implements IUPnPProvider { 14 | @Unique 15 | @Nullable 16 | private UPnPModule uPnPInstance; 17 | 18 | @Override 19 | public UPnPModule getUPnPInstance() { 20 | return this.uPnPInstance; 21 | } 22 | 23 | @Override 24 | public void setUPnPInstance(UPnPModule uPnPInstance) { 25 | this.uPnPInstance = uPnPInstance; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/io/github/satxm/mcwifipnp/mixin/MixinUUIDUtil.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp.mixin; 2 | 3 | import java.util.UUID; 4 | 5 | import org.spongepowered.asm.mixin.Mixin; 6 | import org.spongepowered.asm.mixin.injection.At; 7 | import org.spongepowered.asm.mixin.injection.Inject; 8 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; 9 | 10 | import io.github.satxm.mcwifipnp.UUIDFixer; 11 | import net.minecraft.core.UUIDUtil; 12 | 13 | @Mixin(UUIDUtil.class) 14 | public abstract class MixinUUIDUtil { 15 | @Inject(method = "createOfflinePlayerUUID", at = @At("HEAD"), cancellable = true, require = 1, allow = 1) 16 | private static void detour_createOfflinePlayerUUID(String playerName, CallbackInfoReturnable ci) { 17 | UUID uuid = UUIDFixer.hookEntry(playerName); 18 | 19 | if (uuid != null) { 20 | ci.setReturnValue(uuid); 21 | ci.cancel(); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | permissions: 9 | contents: read 10 | 11 | steps: 12 | - uses: actions/checkout@v4 13 | 14 | - name: Set up JDK 21 15 | uses: actions/setup-java@v4 16 | with: 17 | java-version: '21' 18 | distribution: 'temurin' 19 | 20 | - name: Setup Gradle 21 | uses: gradle/actions/setup-gradle@v4 22 | with: 23 | cache-read-only: false 24 | cache-cleanup: always 25 | 26 | - name: Make Gradle Wrapper Executable 27 | if: ${{ runner.os != 'Windows' }} 28 | run: chmod +x ./gradlew 29 | 30 | - name: Build with Gradle Wrapper 31 | run: ./gradlew build 32 | 33 | - name: Upload Artifacts 34 | uses: actions/upload-artifact@v4 35 | with: 36 | name: mcwifipnp-artifacts 37 | path: '**/build/libs/*.jar' 38 | -------------------------------------------------------------------------------- /src/main/java/io/github/satxm/mcwifipnp/mixin/MixinIntegratedServer.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp.mixin; 2 | 3 | import org.spongepowered.asm.mixin.Mixin; 4 | import org.spongepowered.asm.mixin.injection.At; 5 | import org.spongepowered.asm.mixin.injection.Inject; 6 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; 7 | 8 | import io.github.satxm.mcwifipnp.Config; 9 | import net.minecraft.client.Minecraft; 10 | import net.minecraft.client.server.IntegratedServer; 11 | 12 | @Mixin(IntegratedServer.class) 13 | public abstract class MixinIntegratedServer { 14 | 15 | @Inject(method = "getMaxPlayers", at = @At("HEAD"), cancellable = true, require = 1, allow = 1) 16 | private void setMaxPlayers(CallbackInfoReturnable ci) { 17 | IntegratedServer server = Minecraft.getInstance().getSingleplayerServer(); 18 | if (Minecraft.getInstance().hasSingleplayerServer()) { 19 | int i = Config.read(server).maxPlayers; 20 | ci.setReturnValue(i); 21 | ci.cancel(); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /forge/src/main/resources/META-INF/mods.toml: -------------------------------------------------------------------------------- 1 | modLoader="javafml" 2 | loaderVersion="${forge_loader_version_range}" 3 | license="Apache License 2.0" 4 | issueTrackerURL="https://github.com/satxm/mcwifipnp/issues" 5 | clientSideOnly=true 6 | 7 | [[mods]] 8 | modId="mcwifipnp" 9 | version="${mod_version}" 10 | displayName="LAN World Plug-n-Play" 11 | #updateJSONURL="" 12 | displayURL="https://github.com/satxm/mcwifipnp" 13 | logoFile="mcwifipnp.png" 14 | authors="Satxm, Rikka0w0" 15 | description=''' 16 | Provides a better UI than the vanilla Minecraft \"Open to LAN\" screen, which now also: 17 | 1. Allows for a port customization 18 | 2. Allows a user to disable the online mode, so that unauthenticated players can also join. 19 | 3. UPnP support. 20 | ''' 21 | 22 | [[dependencies.mcwifipnp]] 23 | modId="forge" 24 | mandatory=true 25 | versionRange="${forge_version_range}" 26 | ordering="NONE" 27 | side="CLIENT" 28 | 29 | [[dependencies.mcwifipnp]] 30 | modId="minecraft" 31 | mandatory=true 32 | versionRange="[${minecraft_version_min}, ${minecraft_version_max})" 33 | ordering="NONE" 34 | side="CLIENT" 35 | -------------------------------------------------------------------------------- /neoforge/src/main/resources/META-INF/neoforge.mods.toml: -------------------------------------------------------------------------------- 1 | modLoader="javafml" 2 | loaderVersion="${neo_loader_version_range}" 3 | license="Apache License 2.0" 4 | issueTrackerURL="https://github.com/satxm/mcwifipnp/issues" 5 | 6 | [[mods]] 7 | modId="mcwifipnp" 8 | version="${mod_version}" 9 | displayName="LAN World Plug-n-Play" 10 | #updateJSONURL="" 11 | displayURL="https://github.com/satxm/mcwifipnp" 12 | logoFile="mcwifipnp.png" 13 | authors="Satxm, Rikka0w0" 14 | description=''' 15 | Provides a better UI than the vanilla Minecraft \"Open to LAN\" screen, which now also: 16 | 1. Allows for a port customization 17 | 2. Allows a user to disable the online mode, so that unauthenticated players can also join. 18 | 3. UPnP support. 19 | ''' 20 | 21 | [[mixins]] 22 | config="mcwifipnp.mixins.json" 23 | 24 | [[dependencies.mcwifipnp]] 25 | modId="neoforge" 26 | type="required" 27 | versionRange="${neo_version_range}" 28 | ordering="NONE" 29 | side="CLIENT" 30 | 31 | [[dependencies.mcwifipnp]] 32 | modId="minecraft" 33 | type="required" 34 | versionRange="[${minecraft_version_min}, ${minecraft_version_max})" 35 | ordering="NONE" 36 | side="CLIENT" 37 | -------------------------------------------------------------------------------- /src/main/java/io/github/satxm/mcwifipnp/OnlineMode.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp; 2 | 3 | import net.minecraft.network.chat.Component; 4 | 5 | public enum OnlineMode { 6 | ONLINE(true, false, "online"), 7 | OFFLINE(false, false, "offline"), 8 | FIX_UUID(false, true, "fixuuid"); 9 | 10 | public final boolean onlineMode, fixUUID; 11 | private final Component displayName, toolTip; 12 | 13 | OnlineMode(boolean onlineModeEnabled, boolean tryOnlineUUIDFirst, final String name) { 14 | this.onlineMode = onlineModeEnabled; 15 | this.fixUUID = tryOnlineUUIDFirst; 16 | this.displayName = Component.translatable("mcwifipnp.gui.OnlineMode." + name); 17 | this.toolTip = Component.translatable("mcwifipnp.gui.OnlineMode." + name + ".info"); 18 | } 19 | 20 | public Component getDisplayName() { 21 | return this.displayName; 22 | } 23 | 24 | public Component gettoolTip() { 25 | return this.toolTip; 26 | } 27 | 28 | public static OnlineMode of(boolean onlineModeEnabled, boolean tryOnlineUUIDFirst) { 29 | if (onlineModeEnabled) { 30 | return ONLINE; 31 | } else { 32 | return tryOnlineUUIDFirst ? FIX_UUID : OFFLINE; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /forge/src/main/java/io/github/satxm/mcwifipnp/MCWiFiPnP.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp; 2 | 3 | import net.minecraftforge.common.MinecraftForge; 4 | import net.minecraftforge.event.RegisterCommandsEvent; 5 | import net.minecraftforge.event.server.ServerStartingEvent; 6 | import net.minecraftforge.event.server.ServerStoppingEvent; 7 | import net.minecraftforge.eventbus.api.listener.SubscribeEvent; 8 | import net.minecraftforge.fml.common.Mod; 9 | import net.minecraftforge.fml.loading.FMLEnvironment; 10 | 11 | @Mod(MCWiFiPnPUnit.MODID) 12 | public class MCWiFiPnP { 13 | public MCWiFiPnP() { 14 | MinecraftForge.EVENT_BUS.register(this); 15 | } 16 | 17 | @SubscribeEvent 18 | public void onRegisterCommands(RegisterCommandsEvent event) { 19 | MCWiFiPnPUnit.registerCommands(event.getDispatcher(), FMLEnvironment.dist.isDedicatedServer()); 20 | } 21 | 22 | @SubscribeEvent 23 | public void onServerStarting(ServerStartingEvent event) { 24 | MCWiFiPnPUnit.onServerStarting(event.getServer()); 25 | } 26 | 27 | @SubscribeEvent 28 | public void onServerStopping(ServerStoppingEvent event) { 29 | MCWiFiPnPUnit.onServerStopping(event.getServer()); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /fabric/src/main/java/io/github/satxm/mcwifipnp/MCWiFiPnP.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp; 2 | 3 | import net.fabricmc.api.ClientModInitializer; 4 | import net.fabricmc.api.DedicatedServerModInitializer; 5 | import net.fabricmc.api.ModInitializer; 6 | import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; 7 | import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; 8 | 9 | public class MCWiFiPnP implements ModInitializer, ClientModInitializer, DedicatedServerModInitializer { 10 | @Override 11 | public void onInitialize() { 12 | ServerLifecycleEvents.SERVER_STOPPING.register(MCWiFiPnPUnit::onServerStopping); 13 | ServerLifecycleEvents.SERVER_STARTING.register(MCWiFiPnPUnit::onServerStarting); 14 | } 15 | 16 | @Override 17 | public void onInitializeClient() { 18 | CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> { 19 | MCWiFiPnPUnit.registerCommands(dispatcher, false); 20 | }); 21 | } 22 | 23 | @Override 24 | public void onInitializeServer() { 25 | CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> { 26 | MCWiFiPnPUnit.registerCommands(dispatcher, true); 27 | }); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /neoforge/src/main/java/io/github/satxm/mcwifipnp/MCWiFiPnP.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp; 2 | 3 | import net.neoforged.bus.api.IEventBus; 4 | import net.neoforged.bus.api.SubscribeEvent; 5 | import net.neoforged.fml.common.Mod; 6 | import net.neoforged.fml.loading.FMLEnvironment; 7 | import net.neoforged.neoforge.common.NeoForge; 8 | import net.neoforged.neoforge.event.RegisterCommandsEvent; 9 | import net.neoforged.neoforge.event.server.ServerStartingEvent; 10 | import net.neoforged.neoforge.event.server.ServerStoppingEvent; 11 | 12 | @Mod(MCWiFiPnPUnit.MODID) 13 | public class MCWiFiPnP { 14 | public MCWiFiPnP(IEventBus modEventBus) { 15 | NeoForge.EVENT_BUS.register(this); 16 | } 17 | 18 | @SubscribeEvent 19 | public void onRegisterCommands(RegisterCommandsEvent event) { 20 | MCWiFiPnPUnit.registerCommands(event.getDispatcher(), FMLEnvironment.getDist().isDedicatedServer()); 21 | } 22 | 23 | @SubscribeEvent 24 | public void onServerStarting(ServerStartingEvent event) { 25 | MCWiFiPnPUnit.onServerStarting(event.getServer()); 26 | } 27 | 28 | @SubscribeEvent 29 | public void onServerStopping(ServerStoppingEvent event) { 30 | MCWiFiPnPUnit.onServerStopping(event.getServer()); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | mavenLocal() 4 | maven { 5 | name = 'Fabric' 6 | url = 'https://maven.fabricmc.net/' 7 | } 8 | maven { 9 | name = 'MinecraftForge' 10 | url = 'https://maven.minecraftforge.net/' 11 | } 12 | maven { 13 | name = 'NeoForge' 14 | url = 'https://maven.neoforged.net/releases' 15 | } 16 | maven { 17 | name = 'Quilt' 18 | url = 'https://maven.quiltmc.org/repository/release' 19 | } 20 | maven { 21 | name = 'Minecraft libraries' 22 | url = 'https://libraries.minecraft.net' 23 | } 24 | exclusiveContent { 25 | forRepository { 26 | maven { 27 | name = 'Sponge' 28 | url = 'https://repo.spongepowered.org/repository/maven-public' 29 | } 30 | } 31 | filter { 32 | includeGroupAndSubgroups('org.spongepowered') 33 | } 34 | } 35 | mavenCentral() 36 | gradlePluginPortal() 37 | } 38 | } 39 | 40 | plugins { 41 | id 'org.gradle.toolchains.foojay-resolver-convention' version '0.10.0' 42 | } 43 | 44 | rootProject.name = "mcwifipnp" 45 | 46 | include("fabric") 47 | include("forge") 48 | include("neoforge") 49 | // include("quilt") 50 | -------------------------------------------------------------------------------- /fabric/src/main/resources/fabric.mod.json: -------------------------------------------------------------------------------- 1 | { 2 | "schemaVersion": 1, 3 | "id": "mcwifipnp", 4 | "version": "${version}", 5 | "name": "LAN World Plug-n-Play", 6 | "description": "Provides a better UI than the vanilla Minecraft \"Open to LAN\" screen, which now also:\\n1. Allows for a port customization\\n2. Allows a user to disable the online mode, so that unauthenticated players can also join.\\n3. UPnP support.", 7 | "authors": [ 8 | "Satxm", 9 | "Rikka0w0" 10 | ], 11 | "contact": { 12 | "homepage": "https://github.com/satxm/mcwifipnp", 13 | "issues": "https://github.com/satxm/mcwifipnp/issues", 14 | "sources": "https://github.com/satxm/mcwifipnp" 15 | }, 16 | "license": "Apache License 2.0", 17 | "icon": "mcwifipnp.png", 18 | "environment": "*", 19 | "entrypoints": { 20 | "main": [ "io.github.satxm.mcwifipnp.MCWiFiPnP" ], 21 | "client": [ "io.github.satxm.mcwifipnp.MCWiFiPnP" ], 22 | "server": [ "io.github.satxm.mcwifipnp.MCWiFiPnP" ] 23 | }, 24 | "mixins": [ 25 | "mcwifipnp.mixins.json" 26 | ], 27 | "depends": { 28 | "fabric": "${fabric_version_range}", 29 | "minecraft": ">=${minecraft_version_min} <${minecraft_version_max}", 30 | "fabricloader": "${fabric_loader_version_range}", 31 | "java": ">=21" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /quilt/src/main/java/io/github/satxm/mcwifipnp/MCWiFiPnP.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp; 2 | 3 | import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; 4 | import org.quiltmc.loader.api.ModContainer; 5 | import org.quiltmc.qsl.base.api.entrypoint.ModInitializer; 6 | import org.quiltmc.qsl.base.api.entrypoint.client.ClientModInitializer; 7 | import org.quiltmc.qsl.base.api.entrypoint.server.DedicatedServerModInitializer; 8 | 9 | import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; 10 | 11 | public class MCWiFiPnP implements ModInitializer, ClientModInitializer, DedicatedServerModInitializer { 12 | @Override 13 | public void onInitialize(ModContainer mod) { 14 | ServerLifecycleEvents.SERVER_STOPPING.register(MCWiFiPnPUnit::onServerStopping); 15 | ServerLifecycleEvents.SERVER_STARTING.register(MCWiFiPnPUnit::onServerStarting); 16 | } 17 | 18 | @Override 19 | public void onInitializeClient(ModContainer mod) { 20 | CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> { 21 | MCWiFiPnPUnit.registerCommands(dispatcher, false); 22 | }); 23 | } 24 | 25 | @Override 26 | public void onInitializeServer(ModContainer mod) { 27 | CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> { 28 | MCWiFiPnPUnit.registerCommands(dispatcher, true); 29 | }); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /quilt/src/main/resources/quilt.mod.json: -------------------------------------------------------------------------------- 1 | { 2 | "schema_version": 1, 3 | "quilt_loader": { 4 | "group": "io.github.satxm.mcwifipnp", 5 | "id": "mcwifipnp", 6 | "version": "${version}", 7 | "metadata": { 8 | "name": "LAN World Plug-n-Play", 9 | "description": "Provides a better UI than the vanilla Minecraft \"Open to LAN\" screen, which now also:\\n1. Allows for a port customization\\n2. Allows a user to disable the online mode, so that unauthenticated players can also join.\\n3. UPnP support.", 10 | "contributors": { 11 | "Satxm": "Owner", 12 | "Rikka0w0": "Contributor" 13 | }, 14 | "contact": { 15 | "homepage": "https://github.com/satxm/mcwifipnp", 16 | "issues": "https://github.com/satxm/mcwifipnp/issues", 17 | "sources": "https://github.com/satxm/mcwifipnp" 18 | }, 19 | "icon": "mcwifipnp.png" 20 | }, 21 | "intermediate_mappings": "net.fabricmc:intermediary", 22 | "entrypoints": { 23 | "init": "io.github.satxm.mcwifipnp.MCWiFiPnP", 24 | "client": "io.github.satxm.mcwifipnp.MCWiFiPnP", 25 | "server": "io.github.satxm.mcwifipnp.MCWiFiPnP" 26 | }, 27 | "depends": [ 28 | { 29 | "id": "quilt_loader", 30 | "versions": "${quilt_loader_version_range}" 31 | }, 32 | { 33 | "id": "quilted_fabric_api", 34 | "versions": "${quilt_qsl_version_range}" 35 | }, 36 | { 37 | "id": "minecraft", 38 | "versions": ">=${minecraft_version_min} <${minecraft_version_max}" 39 | } 40 | ] 41 | }, 42 | "mixin": "mcwifipnp.mixins.json" 43 | } 44 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.jvmargs = -Xmx4G 2 | org.gradle.daemon = false 3 | org.gradle.debug = false 4 | 5 | # Mod Properties 6 | mod_id = mcwifipnp 7 | mod_version = 1.9.8 8 | mod_group_id = io.github.satxm.mcwifipnp 9 | 10 | # The Minecraft version in the development environment 11 | minecraft_version = 1.21.9 12 | 13 | # Fabric Properties on https://fabricmc.net/develop/ 14 | fabric_loader_version = 0.17.2 15 | fabric_version = 0.134.0+1.21.9 16 | 17 | # Forge Properties on https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json 18 | forge_version = 59.0.5 19 | 20 | # NeoForge Properties on https://maven.neoforged.net/api/maven/versions/releases/net/neoforged/neoforge 21 | neo_version = 21.9.16-beta 22 | 23 | # Quilt Properties on https://quiltmc.org/en/usage/latest-versions/ 24 | quilt_loader_version = 0.26.3 25 | qfapi_version = 11.0.0-alpha.3+0.102.0-1.21 26 | # QSL on https://maven.quiltmc.org/repository/release/org/quiltmc/qsl/maven-metadata.xml 27 | qsl_version = 10.0.0-alpha.1+1.21 28 | 29 | # Mod Config 30 | # Minecraft 31 | # The minimum minecraft version (inclusive) to run this Mod 32 | minecraft_version_min=1.21.9 33 | # The maximum minecraft version (exclusive) to run this Mod 34 | minecraft_version_max=1.22 35 | 36 | # Fabric 37 | fabric_version_range = >=0.120.0 38 | fabric_loader_version_range = >=0.15.0 39 | 40 | # Forge 41 | forge_version_range = [59,) 42 | forge_loader_version_range = [59,) 43 | 44 | # NeoForge 45 | neo_version_range = [21.9.0-beta,) 46 | neo_loader_version_range = [2,) 47 | 48 | # Quilt 49 | quilt_loader_version_range = >=0.26.0 50 | quilt_qsl_version_range = >=10.0.0- 51 | 52 | # Resource Pack 53 | pack_format_number = 65 54 | -------------------------------------------------------------------------------- /src/main/java/io/github/satxm/mcwifipnp/client/GuiUtils.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp.client; 2 | 3 | import java.util.List; 4 | 5 | import net.minecraft.client.gui.components.AbstractWidget; 6 | import net.minecraft.network.chat.Component; 7 | import net.minecraft.network.chat.MutableComponent; 8 | import net.minecraft.network.chat.contents.TranslatableContents; 9 | 10 | public class GuiUtils { 11 | @SuppressWarnings("unchecked") 12 | public static T findWidget(List list, Class cls, String vanillaLangKey) { 13 | for (Object child : list) { 14 | if (!(child instanceof AbstractWidget widget)) 15 | continue; 16 | 17 | // We only look for AbstractWidget 18 | if (cls.isAssignableFrom(widget.getClass())) { 19 | Component component = widget.getMessage(); 20 | if (component.getContents() instanceof TranslatableContents) { 21 | TranslatableContents content = (TranslatableContents) component.getContents(); 22 | if (content.getKey().equals(vanillaLangKey)) { 23 | return (T) widget; 24 | } else { 25 | Object[] args = content.getArgs(); 26 | if (args.length == 0) 27 | continue; 28 | 29 | if (!(args[0] instanceof MutableComponent)) 30 | continue; 31 | 32 | MutableComponent mutableComponent = (MutableComponent) args[0]; 33 | if (!(component.getContents() instanceof TranslatableContents)) 34 | continue; 35 | 36 | if (!(mutableComponent.getContents() instanceof TranslatableContents)) 37 | continue; 38 | 39 | content = (TranslatableContents) mutableComponent.getContents(); 40 | if (content.getKey().equals(vanillaLangKey)) { 41 | return (T) widget; 42 | } 43 | } 44 | } 45 | } 46 | } 47 | 48 | return null; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /fabric/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'fabric-loom' version '1.11+' 3 | } 4 | 5 | sourceCompatibility = targetCompatibility = JavaVersion.VERSION_21 6 | 7 | println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" 8 | 9 | version = project.mod_version + "-" + project.minecraft_version + "-fabric" 10 | group = project.mod_group_id 11 | 12 | base { 13 | archivesName = project.mod_id 14 | } 15 | 16 | dependencies { 17 | minecraft "com.mojang:minecraft:${project.minecraft_version}" 18 | mappings loom.officialMojangMappings() 19 | modImplementation "net.fabricmc:fabric-loader:${project.fabric_loader_version}" 20 | modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" 21 | modImplementation "com.google.code.findbugs:jsr305:3.0.2" 22 | } 23 | 24 | sourceSets { 25 | main { 26 | java { 27 | srcDir "../src/main/java" 28 | } 29 | resources { 30 | srcDir "../src/main/resources" 31 | srcDir "src/generated/resources" 32 | } 33 | } 34 | } 35 | 36 | tasks.withType(ProcessResources).configureEach { 37 | var replaceProperties = [ 38 | minecraft_version_min : project.minecraft_version_min, 39 | minecraft_version_max : project.minecraft_version_max, 40 | fabric_version_range : project.fabric_version_range, 41 | fabric_loader_version_range : project.fabric_loader_version_range, 42 | version: project.mod_version, 43 | pack_format_number: project.pack_format_number, 44 | ] 45 | inputs.properties replaceProperties 46 | filesMatching(['fabric.mod.json', 'pack.mcmeta']) { 47 | expand replaceProperties + [project: project] 48 | } 49 | } 50 | 51 | tasks.withType(JavaCompile).configureEach { 52 | it.options.encoding = "UTF-8" 53 | it.options.release = 21 54 | } 55 | 56 | java.withSourcesJar() 57 | 58 | jar { 59 | from("../LICENSE") { 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/io/github/satxm/mcwifipnp/commands/OnlineModeCommand.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp.commands; 2 | 3 | import com.mojang.brigadier.CommandDispatcher; 4 | import com.mojang.brigadier.arguments.BoolArgumentType; 5 | import com.mojang.brigadier.builder.LiteralArgumentBuilder; 6 | 7 | import io.github.satxm.mcwifipnp.Config; 8 | import net.minecraft.commands.CommandSourceStack; 9 | import net.minecraft.commands.Commands; 10 | import net.minecraft.network.chat.CommonComponents; 11 | import net.minecraft.network.chat.Component; 12 | import net.minecraft.server.MinecraftServer; 13 | 14 | public class OnlineModeCommand { 15 | public static void register(CommandDispatcher commandDispatcher) { 16 | LiteralArgumentBuilder cmdBuilder = Commands.literal("onlinemode") 17 | .requires((cmdStack) -> cmdStack.hasPermission(3)); 18 | 19 | cmdBuilder = cmdBuilder.then( 20 | Commands.argument("enabled", BoolArgumentType.bool()).executes(commandContext -> { 21 | return setEnabled(commandContext.getSource(), BoolArgumentType.getBool(commandContext, "enabled")); 22 | }) 23 | ).executes(commandContext -> { 24 | return showEnabled(commandContext.getSource()); 25 | }); 26 | 27 | commandDispatcher.register(cmdBuilder); 28 | } 29 | 30 | private static int setEnabled(CommandSourceStack commandSourceStack, boolean enabled) { 31 | MinecraftServer server = commandSourceStack.getServer(); 32 | Config cfg = Config.readFromPublishedServer(server); 33 | cfg.onlineMode = enabled; 34 | cfg.saveAndApply(server); 35 | 36 | return showEnabled(commandSourceStack); 37 | } 38 | 39 | private static int showEnabled(CommandSourceStack commandSourceStack) { 40 | MinecraftServer server = commandSourceStack.getServer(); 41 | Config cfg = Config.readFromPublishedServer(server); 42 | 43 | Component status = Component.translatable("mcwifipnp.gui.OnlineMode") 44 | .append(": ").append(cfg.onlineMode ? CommonComponents.OPTION_ON : CommonComponents.OPTION_OFF); 45 | commandSourceStack.sendSuccess(()->status, false); 46 | return 1; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /quilt/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.quiltmc.loom' version '1.8+' 3 | } 4 | 5 | sourceCompatibility = targetCompatibility = JavaVersion.VERSION_21 6 | 7 | println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" 8 | 9 | version = project.mod_version + "-" + project.minecraft_version + "-quilt" 10 | group = project.mod_group_id 11 | 12 | base { 13 | archivesName = project.mod_id 14 | } 15 | 16 | loom { 17 | mods { 18 | "${project.mod_id}" { 19 | sourceSet("main") 20 | } 21 | } 22 | } 23 | 24 | dependencies { 25 | minecraft "com.mojang:minecraft:${project.minecraft_version}" 26 | mappings loom.layered { 27 | officialMojangMappings() 28 | } 29 | modImplementation "org.quiltmc:quilt-loader:${project.quilt_loader_version}" 30 | modImplementation "org.quiltmc:qsl:${project.qsl_version}" 31 | modImplementation "org.quiltmc.quilted-fabric-api:quilted-fabric-api:${project.qfapi_version}" 32 | modImplementation "com.google.code.findbugs:jsr305:3.0.2" 33 | } 34 | 35 | sourceSets { 36 | main { 37 | java { 38 | srcDir "../src/main/java" 39 | } 40 | resources { 41 | srcDir "../src/main/resources" 42 | srcDir "src/generated/resources" 43 | } 44 | } 45 | } 46 | 47 | tasks.withType(ProcessResources).configureEach { 48 | var replaceProperties = [ 49 | minecraft_version_min : project.minecraft_version_min, 50 | minecraft_version_max : project.minecraft_version_max, 51 | quilt_qsl_version_range : project.quilt_qsl_version_range, 52 | quilt_loader_version_range : project.quilt_loader_version_range, 53 | version: project.mod_version, 54 | pack_format_number: project.pack_format_number, 55 | ] 56 | inputs.properties replaceProperties 57 | filesMatching(['quilt.mod.json', 'pack.mcmeta']) { 58 | expand replaceProperties + [project: project] 59 | } 60 | } 61 | 62 | tasks.withType(JavaCompile).configureEach { 63 | it.options.encoding = "UTF-8" 64 | it.options.release = 21 65 | } 66 | 67 | java.withSourcesJar() 68 | 69 | jar { 70 | from("../LICENSE") { 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/io/github/satxm/mcwifipnp/commands/UPnPCommand.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp.commands; 2 | 3 | import com.mojang.brigadier.CommandDispatcher; 4 | import com.mojang.brigadier.arguments.BoolArgumentType; 5 | import com.mojang.brigadier.builder.LiteralArgumentBuilder; 6 | 7 | import io.github.satxm.mcwifipnp.Config; 8 | import io.github.satxm.mcwifipnp.network.UPnPModule; 9 | import net.minecraft.commands.CommandSourceStack; 10 | import net.minecraft.commands.Commands; 11 | import net.minecraft.network.chat.CommonComponents; 12 | import net.minecraft.network.chat.Component; 13 | import net.minecraft.server.MinecraftServer; 14 | 15 | public class UPnPCommand { 16 | public static void register(CommandDispatcher commandDispatcher) { 17 | LiteralArgumentBuilder cmdBuilder = Commands.literal("upnp") 18 | .requires((cmdStack) -> cmdStack.hasPermission(3)); 19 | 20 | cmdBuilder = cmdBuilder.then( 21 | Commands.argument("enabled", BoolArgumentType.bool()).executes(commandContext -> { 22 | return setEnabled(commandContext.getSource(), BoolArgumentType.getBool(commandContext, "enabled")); 23 | }) 24 | ).executes(commandContext -> { 25 | return showEnabled(commandContext.getSource()); 26 | }); 27 | 28 | commandDispatcher.register(cmdBuilder); 29 | } 30 | 31 | private static int setEnabled(CommandSourceStack commandSourceStack, boolean enabled) { 32 | MinecraftServer server = commandSourceStack.getServer(); 33 | Config cfg = Config.readFromPublishedServer(server); 34 | 35 | if (cfg.useUPnP ^ enabled) { 36 | cfg.useUPnP = enabled; 37 | cfg.saveAndApply(server); 38 | 39 | if (enabled) { 40 | if (server.isPublished()) 41 | UPnPModule.startIfEnabled(server, cfg); 42 | } else { 43 | UPnPModule.stop(server); 44 | } 45 | } 46 | 47 | return showEnabled(commandSourceStack); 48 | } 49 | 50 | private static int showEnabled(CommandSourceStack commandSourceStack) { 51 | MinecraftServer server = commandSourceStack.getServer(); 52 | Config cfg = Config.readFromPublishedServer(server); 53 | 54 | Component status = Component.literal("UPnP: ") 55 | .append(cfg.useUPnP ? CommonComponents.OPTION_ON : CommonComponents.OPTION_OFF); 56 | commandSourceStack.sendSuccess(()->status, false); 57 | return 1; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/io/github/satxm/mcwifipnp/network/UPnPModule.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp.network; 2 | 3 | import com.dosse.upnp.UPnP; 4 | import io.github.satxm.mcwifipnp.Config; 5 | import io.github.satxm.mcwifipnp.MCWiFiPnPUnit; 6 | import net.minecraft.client.Minecraft; 7 | import net.minecraft.network.chat.Component; 8 | import net.minecraft.server.MinecraftServer; 9 | import net.minecraft.server.level.ServerPlayer; 10 | import org.apache.logging.log4j.Logger; 11 | 12 | public record UPnPModule(int port, String displayName) implements Runnable { 13 | private static final Logger LOGGER = MCWiFiPnPUnit.LOGGER; 14 | 15 | public static void startIfEnabled(MinecraftServer server, Config cfg) { 16 | if (!cfg.useUPnP) { 17 | ((IUPnPProvider) server).setUPnPInstance(null); 18 | return; 19 | } 20 | 21 | UPnPModule instance = new UPnPModule(cfg.port, cfg.motd); 22 | ((IUPnPProvider) server).setUPnPInstance(instance); 23 | new Thread(instance, "MCWiFiPnP_UPnP").start(); 24 | } 25 | 26 | public static boolean has(MinecraftServer server) { 27 | return ((IUPnPProvider) server).getUPnPInstance() != null; 28 | } 29 | 30 | public static void stop(MinecraftServer server) { 31 | UPnPModule uPnPModule = ((IUPnPProvider) server).getUPnPInstance(); 32 | if (uPnPModule != null) { 33 | uPnPModule.stop(); 34 | } 35 | ((IUPnPProvider) server).setUPnPInstance(null); 36 | } 37 | 38 | public void stop() { 39 | UPnP.closePortTCP(this.port); 40 | LOGGER.info("Stopped forwarding port " + this.port + "."); 41 | } 42 | 43 | @Override 44 | public void run() { 45 | MinecraftServer server = Minecraft.getInstance().getSingleplayerServer(); 46 | ServerPlayer player = server.getPlayerList().getPlayer(server.getSingleplayerProfile().id()); 47 | 48 | if (UPnP.isUPnPAvailable()) { 49 | if (UPnP.isMappedTCP(this.port)) { 50 | player.sendSystemMessage(Component.translatable("mcwifipnp.upnp.failed.mapped", this.port)); 51 | } else if (UPnP.openPortTCP(this.port, this.displayName)) { 52 | player.sendSystemMessage(Component.translatable("mcwifipnp.upnp.success", this.port)); 53 | LOGGER.info("Started forwarded port " + this.port + "."); 54 | } else { 55 | player.sendSystemMessage(Component.translatable("mcwifipnp.upnp.failed", this.port)); 56 | } 57 | } else { 58 | player.sendSystemMessage(Component.translatable("mcwifipnp.upnp.failed.disabled", this.port)); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/resources/assets/mcwifipnp/lang/zh_hk.json: -------------------------------------------------------------------------------- 1 | { 2 | "mcwifipnp.gui.port.info": "局域網遊戲端口碼。\n請闕之,抑再入 1024 至 65535 間之數。", 3 | "mcwifipnp.gui.port.invalid": "端口碼不可用。\n請闕之,抑再入 1024 至 65535 間之數。", 4 | "mcwifipnp.gui.port.unavailable": "端口碼不可用。\n請闕之,抑再入 1024 至 65535 間之另數。", 5 | "mcwifipnp.gui.players": "允許玩家數", 6 | "mcwifipnp.gui.players.info": "伺服器同時能容納的最大玩家數量。", 7 | "mcwifipnp.gui.lanServerOptions": "伺服器設定", 8 | "mcwifipnp.gui.otherOptions": "更多設定", 9 | "mcwifipnp.gui.backToVanillaScreen": "返回原版伺服器設定", 10 | "mcwifipnp.gui.motd": "伺服器信息", 11 | "mcwifipnp.gui.motd.info": "玩家客戶端的多人遊戲服務器列錶中顯示於名稱下方的服務器信息。", 12 | "mcwifipnp.gui.AllPlayersCheats": "其他玩家作弊", 13 | "mcwifipnp.gui.AllPlayersCheats.info": "是否允許其他玩家作弊,你可以使用 /op 命令開放某人的作弊權限。", 14 | "mcwifipnp.gui.Whitelist": "白名单", 15 | "mcwifipnp.gui.Whitelist.info": "是否伺服器的白名單。當啓用時,隻有白名單上的用戶才能連接服務器。", 16 | "mcwifipnp.gui.OnlineMode": "正版驗證", 17 | "mcwifipnp.gui.OnlineMode.info": "是否讓服務器對比 Mojang 伺服器賬戶數據庫驗證登入信息。", 18 | "mcwifipnp.gui.OnlineMode.online": "啟用", 19 | "mcwifipnp.gui.OnlineMode.online.info": "啟用正版驗證將只允許使用微軟帳戶登入的玩家加入本服務器。", 20 | "mcwifipnp.gui.OnlineMode.offline": "禁用", 21 | "mcwifipnp.gui.OnlineMode.offline.info": "禁用正版驗證將允許使用離線模式登入的玩家加入本服務器。", 22 | "mcwifipnp.gui.OnlineMode.fixuuid": "禁用+修復UUID", 23 | "mcwifipnp.gui.OnlineMode.fixuuid.info": "嘗試使用離線模式登入的玩家名匹配Mojang服務器用戶名稱以獲取唯一UUID。\n同時為使用微軟帳戶登入的用戶保留UUID。\n它也可以防止背包和物品欄內容遺失。", 24 | "mcwifipnp.gui.PvP": "PvP", 25 | "mcwifipnp.gui.PvP.info": "是否允許 PvP。也隻有在允許 PvP 時玩家自己的箭才會受到傷害。", 26 | "mcwifipnp.gui.UseUPnP": "映射端口", 27 | "mcwifipnp.gui.UseUPnP.info": "是否使用 UPnP 功能映射局域網遊戲端口號。", 28 | "mcwifipnp.gui.localIP": "內網%s", 29 | "mcwifipnp.gui.globalIP": "公網%s", 30 | "mcwifipnp.gui.CopyIP": "獲取 IP", 31 | "mcwifipnp.gui.CopyIP.info": "取得內網 IP 地址及公網 IP 地址,以便於你直接複製。", 32 | "mcwifipnp.gui.removePlayerReportingButton": "替換 舉報玩家 按鈕", 33 | "mcwifipnp.upnp.success": "成功轉發端口 %s", 34 | "mcwifipnp.upnp.clipboard": "成功獲取到 %s,由於NAT等因素,這些 IP 可能仍舊無法直接聯機。", 35 | "mcwifipnp.upnp.cantgetip": "無法獲取 IP!請檢查你嘅網路設置。你嘅 IPv4 可能包含多級 NAT 或者你無 IPv6。", 36 | "mcwifipnp.upnp.failed.mapped": "無法轉發端口 %s:端口 %s 已被另一個 UPnP 服務映射,請更換端口。", 37 | "mcwifipnp.upnp.failed.disabled": "無法轉發端口 %s:路由器上未啟用 UPnP,你可能需要端口映射軟件。", 38 | "mcwifipnp.upnp.failed.unknownerror": "無法轉發端口 %s:添加端口映射時出現未知錯誤,請使用端口映射軟件。", 39 | "mcwifipnp.upnp.failed": "無法轉發端口 %s!請使用端口映射軟件。", 40 | "mcwifipnp.commands.forceoffline.add.failed": "玩家已在強制離線模式清單內", 41 | "mcwifipnp.commands.forceoffline.add.success": "已將 %s 加入強制離線模式清單", 42 | "mcwifipnp.commands.forceoffline.list": "強制離線模式清單中共有%s名玩家:%s", 43 | "mcwifipnp.commands.forceoffline.none": "強制離線模式清單中沒有玩家", 44 | "mcwifipnp.commands.forceoffline.remove.failed": "玩家不在強制離線模式清單內", 45 | "mcwifipnp.commands.forceoffline.remove.success": "已將 %s 移出強制離線模式清單" 46 | } 47 | -------------------------------------------------------------------------------- /src/main/resources/assets/mcwifipnp/lang/zh_tw.json: -------------------------------------------------------------------------------- 1 | { 2 | "mcwifipnp.gui.port.info": "區域網路世界的連接埠號碼。\n請將編輯欄留空,或是輸入一個 1024 到 65535 之間的數值。", 3 | "mcwifipnp.gui.port.invalid": "無效的連接埠。\n請將編輯欄留空,或是輸入一個 1024 到 65535 之間的數值。", 4 | "mcwifipnp.gui.port.unavailable": "無法使用這個連接埠。\n請將編輯欄留空,或是輸入一個 1024 到 65535 之間的新數值。", 5 | "mcwifipnp.gui.players": "最大玩家數", 6 | "mcwifipnp.gui.players.info": "可以加入伺服器的最大玩家數量。", 7 | "mcwifipnp.gui.lanServerOptions": "伺服器設定", 8 | "mcwifipnp.gui.otherOptions": "更多設定", 9 | "mcwifipnp.gui.backToVanillaScreen": "返回原版伺服器設定", 10 | "mcwifipnp.gui.motd": "伺服器資訊", 11 | "mcwifipnp.gui.motd.info": "在多人遊戲伺服器清單中名稱下方顯示的伺服器資訊。", 12 | "mcwifipnp.gui.AllPlayersCheats": "其他玩家作弊", 13 | "mcwifipnp.gui.AllPlayersCheats.info": "啟用後,其他玩家加入伺服器時將自動成為管理員。您也可以使用 /op 指令使某人成為管理員。", 14 | "mcwifipnp.gui.Whitelist": "白名單", 15 | "mcwifipnp.gui.Whitelist.info": "強制執行白名單。啟用後,只有白名單上的玩家才能連線到伺服器。使用 /whitelist 指令將玩家新增到清單中。", 16 | "mcwifipnp.gui.OnlineMode": "線上模式", 17 | "mcwifipnp.gui.OnlineMode.info": "是否讓伺服器將登入資訊與 Mojang 伺服器資料庫進行比較和驗證。", 18 | "mcwifipnp.gui.OnlineMode.online": "啟用", 19 | "mcwifipnp.gui.OnlineMode.online.info": "啟用線上模式將只允許使用 Microsoft 帳號登入的玩家加入這個伺服器。", 20 | "mcwifipnp.gui.OnlineMode.offline": "停用", 21 | "mcwifipnp.gui.OnlineMode.offline.info": "停用線上模式將允許以離線模式登入的玩家加入這個伺服器。", 22 | "mcwifipnp.gui.OnlineMode.fixuuid": "停用 + UUID 修正", 23 | "mcwifipnp.gui.OnlineMode.fixuuid.info": "嘗試將 Mojang 伺服器使用者名稱與離線模式玩家的玩家名稱相符,以取得唯一的 UUID。\n同時,使用 Microsoft 帳號登入的使用者將保留其 UUID。\n它還可以防止背包和物品欄物品的遺失。", 24 | "mcwifipnp.gui.PvP": "玩家對戰", 25 | "mcwifipnp.gui.PvP.info": "切換玩家對戰。停用玩家對戰也會阻止您自己受到投射物的傷害。", 26 | "mcwifipnp.gui.UseUPnP": "連接埠轉發", 27 | "mcwifipnp.gui.UseUPnP.info": "是否使用 UPnP 功能映射區域網路遊戲連接埠號碼。", 28 | "mcwifipnp.gui.localIP": "區域網路%s", 29 | "mcwifipnp.gui.globalIP": "全域%s", 30 | "mcwifipnp.gui.CopyIP": "取得 IP", 31 | "mcwifipnp.gui.CopyIP.info": "取得 IP 並複製到剪貼簿", 32 | "mcwifipnp.gui.removePlayerReportingButton": "替換 檢舉玩家 按鈕", 33 | "mcwifipnp.upnp.success": "成功連接埠轉發 %s", 34 | "mcwifipnp.upnp.clipboard": "成功取得 %s,由於 NAT 等因素,這些 IP 可能仍然無法直接連線。", 35 | "mcwifipnp.upnp.cantgetip": "無法取得公網 IP!請檢查您的網路設定。您的 IPv4 可能包含多個 NAT 或您沒有 IPv6。", 36 | "mcwifipnp.upnp.failed.mapped": "無法連接埠轉發 %s:連接埠已被其他 UPnP 服務映射,請變更連接埠號碼。", 37 | "mcwifipnp.upnp.failed.disabled": "無法連接埠轉發 %s:您的路由器上未啟用 UPnP,您可能需要使用連接埠映射軟體。", 38 | "mcwifipnp.upnp.failed.unknownerror": "無法連接埠轉發 %s:新增連接埠映射時發生未知錯誤,請使用連接埠映射軟體。", 39 | "mcwifipnp.upnp.failed": "無法連接埠轉發 %s!", 40 | "mcwifipnp.commands.forceoffline.add.failed": "玩家已在強制離線清單中", 41 | "mcwifipnp.commands.forceoffline.add.success": "已將 %s 新增到強制離線清單", 42 | "mcwifipnp.commands.forceoffline.list": "強制離線清單中有 %s 個玩家:%s", 43 | "mcwifipnp.commands.forceoffline.none": "強制離線清單中沒有玩家", 44 | "mcwifipnp.commands.forceoffline.remove.failed": "玩家不在強制離線清單中", 45 | "mcwifipnp.commands.forceoffline.remove.success": "已將 %s 從強制離線清單中移除" 46 | } 47 | -------------------------------------------------------------------------------- /neoforge/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java-library' 3 | id 'eclipse' 4 | id 'idea' 5 | id 'net.neoforged.moddev' version '2.+' 6 | } 7 | 8 | java.toolchain.languageVersion = JavaLanguageVersion.of(21) 9 | 10 | println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" 11 | 12 | version = project.mod_version + "-" + project.minecraft_version + "-neoforge" 13 | group = project.mod_group_id 14 | 15 | base { 16 | archivesName = project.mod_id 17 | } 18 | 19 | repositories { 20 | mavenLocal() 21 | } 22 | 23 | neoForge { 24 | version = project.neo_version 25 | 26 | runs { 27 | client { 28 | client() 29 | systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id 30 | } 31 | 32 | server { 33 | server() 34 | programArgument '--nogui' 35 | systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id 36 | } 37 | 38 | gameTestServer { 39 | type = "gameTestServer" 40 | systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id 41 | } 42 | 43 | data { 44 | clientData() 45 | programArguments.addAll '--mod', project.mod_id, '--all', '--output', file('src/generated/resources/').getAbsolutePath(), '--existing', file('src/main/resources/').getAbsolutePath() 46 | } 47 | 48 | configureEach { 49 | systemProperty 'forge.logging.markers', 'REGISTRIES' 50 | logLevel = org.slf4j.event.Level.DEBUG 51 | } 52 | } 53 | 54 | mods { 55 | "${mod_id}" { 56 | sourceSet(sourceSets.main) 57 | } 58 | } 59 | } 60 | 61 | sourceSets { 62 | main { 63 | java { 64 | srcDir "../src/main/java" 65 | } 66 | resources { 67 | srcDir "../src/main/resources" 68 | srcDir "src/generated/resources" 69 | } 70 | } 71 | } 72 | 73 | configurations { 74 | runtimeClasspath.extendsFrom localRuntime 75 | } 76 | 77 | tasks.withType(ProcessResources).configureEach { 78 | var replaceProperties = [ 79 | minecraft_version_min : project.minecraft_version_min, 80 | minecraft_version_max : project.minecraft_version_max, 81 | neo_version_range : project.neo_version_range, 82 | neo_loader_version_range : project.neo_loader_version_range, 83 | mod_version: project.mod_version, 84 | pack_format_number: project.pack_format_number, 85 | ] 86 | inputs.properties replaceProperties 87 | filesMatching(['META-INF/neoforge.mods.toml', 'pack.mcmeta']) { 88 | expand replaceProperties + [project: project] 89 | } 90 | } 91 | 92 | tasks.withType(JavaCompile).configureEach { 93 | it.options.encoding = 'UTF-8' 94 | it.options.release = 21 95 | } 96 | 97 | java.withSourcesJar() 98 | 99 | jar { 100 | from("../LICENSE") { 101 | } 102 | } 103 | 104 | idea { 105 | module { 106 | downloadSources = true 107 | downloadJavadoc = true 108 | } 109 | } -------------------------------------------------------------------------------- /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 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 1>&2 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 48 | echo. 1>&2 49 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 50 | echo location of your Java installation. 1>&2 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 1>&2 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 62 | echo. 1>&2 63 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 64 | echo location of your Java installation. 1>&2 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /src/main/resources/assets/mcwifipnp/lang/zh_cn.json: -------------------------------------------------------------------------------- 1 | { 2 | "mcwifipnp.gui.port.info": "监听端口号。", 3 | "mcwifipnp.gui.port.invalid": "端口无效。\n请输入一个介于§41024至65535§之间的数字。", 4 | "mcwifipnp.gui.port.unavailable": "§4端口不可用。", 5 | "mcwifipnp.gui.players": "最大允许玩家数", 6 | "mcwifipnp.gui.players.info": "服务器同时能容纳的最大玩家数量。", 7 | "mcwifipnp.gui.lanServerOptions": "局域网游戏设置", 8 | "mcwifipnp.gui.otherOptions": "更多设置", 9 | "mcwifipnp.gui.backToVanillaScreen": "返回原版局域网设置", 10 | "mcwifipnp.gui.motd": "服务器信息", 11 | "mcwifipnp.gui.motd.info": "玩家客户端的多人游戏服务器列表中显示于名称下方的服务器信息。", 12 | "mcwifipnp.gui.AllPlayersCheats": "其他玩家作弊", 13 | "mcwifipnp.gui.AllPlayersCheats.info": "是否允许其他玩家作弊,你可以使用/op命令开放某人的作弊权限。", 14 | "mcwifipnp.gui.Whitelist": "白名单", 15 | "mcwifipnp.gui.Whitelist.info": "是否服务器的白名单。当启用时,只有白名单上的用户才能连接服务器。", 16 | "mcwifipnp.gui.OnlineMode": "正版验证", 17 | "mcwifipnp.gui.OnlineMode.info": "是否让服务器比对Mojang服务器数据库验证登录信息。", 18 | "mcwifipnp.gui.OnlineMode.online": "启用", 19 | "mcwifipnp.gui.OnlineMode.online.info": "启用正版验证将只允许使用微软帐户登录的玩家加入本服务器。", 20 | "mcwifipnp.gui.OnlineMode.offline": "禁用", 21 | "mcwifipnp.gui.OnlineMode.offline.info": "禁用正版验证将允许使用离线模式登录的玩家加入本服务器。", 22 | "mcwifipnp.gui.OnlineMode.fixuuid": "禁用 + 修复UUID", 23 | "mcwifipnp.gui.OnlineMode.fixuuid.info": "尝试使用离线模式登录的玩家名匹配Mojang服务器用户名称以获取唯一UUID。\n同时为使用微软帐户登录的用户保留UUID。\n§b它也可以防止背包和物品栏内容丢失。", 24 | "mcwifipnp.gui.PvP": "PvP", 25 | "mcwifipnp.gui.PvP.info": "是否允许PvP。也只有在允许PvP时玩家自己的箭才会受到伤害。", 26 | "mcwifipnp.gui.UseUPnP": "UPnP映射端口", 27 | "mcwifipnp.gui.UseUPnP.info": "是否使用UPnP功能映射局域网游戏端口号。", 28 | "mcwifipnp.gui.localIP": "内网%s", 29 | "mcwifipnp.gui.globalIP": "公网%s", 30 | "mcwifipnp.gui.CopyIP": "获取IP", 31 | "mcwifipnp.gui.CopyIP.info": "是否获取你当前设备的IP地址,以便于你直接复制。", 32 | "mcwifipnp.gui.removePlayerReportingButton": "替换 举报玩家 按钮", 33 | "mcwifipnp.upnp.success": "成功转发端口%s", 34 | "mcwifipnp.upnp.clipboard": "成功获取到%s,由于NAT等因素,这些IP可能仍旧无法直接联机。", 35 | "mcwifipnp.upnp.cantgetip": "无法获取IP!请检查你的网络设置。你的IPv4可能包含多级NAT或者你无IPv6。", 36 | "mcwifipnp.upnp.failed.mapped": "无法转发端口%s:端口%s已被另一个UPnP服务映射,请更换端口。", 37 | "mcwifipnp.upnp.failed.disabled": "无法转发端口%s:路由器上未启用UPnP,你可能需要端口映射软件。", 38 | "mcwifipnp.upnp.failed.unknownerror": "无法转发端口%s:添加端口映射时出现未知错误,请使用端口映射软件。", 39 | "mcwifipnp.upnp.failed": "无法转发端口%s!请使用端口映射软件。", 40 | "mcwifipnp.commands.uuidfixer.name": "修复UUID", 41 | "mcwifipnp.commands.uuidfixer.policy.online": "正版验证", 42 | "mcwifipnp.commands.uuidfixer.policy.offline": "离线模式", 43 | "mcwifipnp.commands.uuidfixer.policy.invalid": "无效", 44 | "mcwifipnp.commands.uuidfixer.default.show": "修复UUID的默认方式为%s.", 45 | "mcwifipnp.commands.uuidfixer.default.set": "将修复UUID的默认方式设为%s.", 46 | "mcwifipnp.commands.uuidfixer.set.success": "将%s的修复UUID的策略设置为%s.", 47 | "mcwifipnp.commands.uuidfixer.set.override": "强制%s使用指定的UUID: %s.", 48 | "mcwifipnp.commands.uuidfixer.set.bad-policy": "无效的策略: %s,应为online、offline、或者一个有效的UUID.", 49 | "mcwifipnp.commands.uuidfixer.list": "修复UUID的策略列表有%s项:", 50 | "mcwifipnp.commands.uuidfixer.none": "修复UUID的策略列表为空.", 51 | "mcwifipnp.commands.uuidfixer.policy.not-exist": "%s不在修复UUID的策略列表里!", 52 | "mcwifipnp.commands.uuidfixer.remove.success": "从修复UUID的策略列表中删除%s的规则." 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/io/github/satxm/mcwifipnp/network/GlobalIPs.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp.network; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.InputStreamReader; 5 | import java.net.URI; 6 | import java.net.URL; 7 | import java.net.URLConnection; 8 | 9 | import javax.annotation.Nullable; 10 | 11 | import io.netty.channel.socket.InternetProtocolFamily; 12 | import io.netty.util.NetUtil; 13 | 14 | public enum GlobalIPs { 15 | IP_SB_4("https://api-ipv4.ip.sb/ip", InternetProtocolFamily.IPv4), 16 | IP_SB_6("https://api-ipv6.ip.sb/ip", InternetProtocolFamily.IPv6), 17 | IPW_CN_4("https://4.ipw.cn", InternetProtocolFamily.IPv4), 18 | IPW_CN_6("https://6.ipw.cn", InternetProtocolFamily.IPv6); 19 | 20 | public final String apiEndPoint; 21 | public final InternetProtocolFamily family; 22 | 23 | private GlobalIPs(String apiEndPoint, InternetProtocolFamily family) { 24 | this.apiEndPoint = apiEndPoint; 25 | this.family = family; 26 | } 27 | 28 | /** 29 | * Fetch the global IP address from the given API provider then validate the 30 | * result. 31 | * 32 | * @return the IP, or null if failed or the IP is invalid 33 | */ 34 | @Nullable 35 | public String fetch() { 36 | return GlobalIPs.fetchGlobalIP(this.apiEndPoint, this.family); 37 | } 38 | 39 | /** 40 | * Fetch the global IP address from a given API provider then validate the 41 | * result. 42 | * 43 | * @param apiProvider the API provider's URL 44 | * @param family IP family to be verify against, can be IPv4 or IPv6 45 | * @return the IP, or null if failed or the IP is invalid 46 | */ 47 | @Nullable 48 | public static String fetchGlobalIP(String apiProvider, InternetProtocolFamily family) { 49 | String ip = null; 50 | try { 51 | URL url = URI.create(apiProvider).toURL(); 52 | URLConnection URLconnection = url.openConnection(); 53 | InputStreamReader isr = new InputStreamReader(URLconnection.getInputStream()); 54 | BufferedReader bufferReader = new BufferedReader(isr); 55 | 56 | String line; 57 | while ((line = bufferReader.readLine()) != null) { 58 | ip = line; 59 | } 60 | 61 | bufferReader.close(); 62 | } catch (Exception e) { 63 | } 64 | 65 | if (ip == null) 66 | return null; 67 | 68 | switch (family) { 69 | case IPv4: 70 | if (!NetUtil.isValidIpV4Address(ip)) 71 | ip = null; 72 | break; 73 | 74 | case IPv6: 75 | if (!NetUtil.isValidIpV6Address(ip)) 76 | ip = null; 77 | break; 78 | 79 | default: 80 | ip = null; 81 | break; 82 | } 83 | 84 | return ip; 85 | } 86 | 87 | /** 88 | * Attempt to find a global IP of a given IP family by fetching each of the 89 | * known API end points defined in {@link GlobalIPs}. The order follows the enum 90 | * order. The first successful result will be returned, and no more fetch will 91 | * be performed. 92 | * 93 | * @param family the expected IP family 94 | * @return the IP, or null if failed or the IP is invalid 95 | */ 96 | @Nullable 97 | public static String fetchGlobalIP(InternetProtocolFamily family) { 98 | for (GlobalIPs api : GlobalIPs.values()) { 99 | if (api.family != family) 100 | continue; 101 | 102 | String ip = api.fetch(); 103 | if (ip != null) { 104 | return ip; 105 | } 106 | } 107 | 108 | return null; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/main/java/io/github/satxm/mcwifipnp/ReadListFile.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.nio.charset.StandardCharsets; 6 | 7 | import com.google.common.io.Files; 8 | import com.google.gson.Gson; 9 | import com.google.gson.GsonBuilder; 10 | import com.google.gson.JsonArray; 11 | import com.google.gson.JsonElement; 12 | import com.google.gson.JsonObject; 13 | import com.google.gson.JsonParseException; 14 | 15 | import net.minecraft.server.MinecraftServer; 16 | import net.minecraft.server.players.IpBanListEntry; 17 | import net.minecraft.server.players.PlayerList; 18 | import net.minecraft.server.players.ServerOpListEntry; 19 | import net.minecraft.server.players.UserBanListEntry; 20 | import net.minecraft.server.players.UserWhiteListEntry; 21 | import net.minecraft.util.GsonHelper; 22 | 23 | public class ReadListFile { 24 | private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); 25 | 26 | public static void ReadListFile(MinecraftServer server) { 27 | PlayerList playerList = server.getPlayerList(); 28 | try { 29 | BufferedReader bufferedReader = Files.newReader(PlayerList.OPLIST_FILE, StandardCharsets.UTF_8); 30 | JsonArray jsonArray = GSON.fromJson(bufferedReader, JsonArray.class); 31 | 32 | for (JsonElement jsonElement : jsonArray) { 33 | JsonObject jsonObject = GsonHelper.convertToJsonObject(jsonElement, "entry"); 34 | ServerOpListEntry entry = new ServerOpListEntry(jsonObject); 35 | if (entry.getUser() != null) { 36 | playerList.getOps().add(entry); 37 | } 38 | } 39 | } catch (IOException | JsonParseException | NullPointerException e) { 40 | } 41 | try { 42 | BufferedReader bufferedReader = Files.newReader(PlayerList.WHITELIST_FILE, StandardCharsets.UTF_8); 43 | JsonArray jsonArray = GSON.fromJson(bufferedReader, JsonArray.class); 44 | 45 | for (JsonElement jsonElement : jsonArray) { 46 | JsonObject jsonObject = GsonHelper.convertToJsonObject(jsonElement, "entry"); 47 | UserWhiteListEntry entry = new UserWhiteListEntry(jsonObject); 48 | if (entry.getUser() != null) { 49 | playerList.getWhiteList().add(entry); 50 | } 51 | } 52 | } catch (IOException | JsonParseException | NullPointerException e) { 53 | } 54 | try { 55 | BufferedReader bufferedReader = Files.newReader(PlayerList.IPBANLIST_FILE, StandardCharsets.UTF_8); 56 | JsonArray jsonArray = GSON.fromJson(bufferedReader, JsonArray.class); 57 | 58 | for (JsonElement jsonElement : jsonArray) { 59 | JsonObject jsonObject = GsonHelper.convertToJsonObject(jsonElement, "entry"); 60 | IpBanListEntry entry = new IpBanListEntry(jsonObject); 61 | if (entry.getUser() != null) { 62 | playerList.getIpBans().add(entry); 63 | } 64 | } 65 | } catch (IOException | JsonParseException | NullPointerException e) { 66 | } 67 | try { 68 | BufferedReader bufferedReader = Files.newReader(PlayerList.USERBANLIST_FILE, StandardCharsets.UTF_8); 69 | JsonArray jsonArray = GSON.fromJson(bufferedReader, JsonArray.class); 70 | 71 | for (JsonElement jsonElement : jsonArray) { 72 | JsonObject jsonObject = GsonHelper.convertToJsonObject(jsonElement, "entry"); 73 | UserBanListEntry entry = new UserBanListEntry(jsonObject); 74 | if (entry.getUser() != null) { 75 | playerList.getBans().add(entry); 76 | } 77 | } 78 | } catch (IOException | JsonParseException | NullPointerException e) { 79 | } 80 | } 81 | } -------------------------------------------------------------------------------- /src/main/java/io/github/satxm/mcwifipnp/mixin/MixinPauseScreen.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp.mixin; 2 | 3 | import java.util.List; 4 | 5 | import org.spongepowered.asm.mixin.Mixin; 6 | import org.spongepowered.asm.mixin.injection.At; 7 | import org.spongepowered.asm.mixin.injection.Inject; 8 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; 9 | import org.spongepowered.asm.mixin.injection.callback.LocalCapture; 10 | 11 | import io.github.satxm.mcwifipnp.Config; 12 | import io.github.satxm.mcwifipnp.client.GuiUtils; 13 | import io.github.satxm.mcwifipnp.client.ShareToLanScreenNew; 14 | import net.minecraft.client.gui.components.Button; 15 | import net.minecraft.client.gui.components.SpriteIconButton; 16 | import net.minecraft.client.gui.components.Tooltip; 17 | import net.minecraft.client.gui.layouts.GridLayout; 18 | import net.minecraft.client.gui.layouts.LayoutElement; 19 | import net.minecraft.client.gui.screens.PauseScreen; 20 | import net.minecraft.client.gui.screens.Screen; 21 | import net.minecraft.client.server.IntegratedServer; 22 | import net.minecraft.network.chat.Component; 23 | import net.minecraft.resources.ResourceLocation; 24 | 25 | @Mixin(PauseScreen.class) 26 | public abstract class MixinPauseScreen extends Screen { 27 | private Config cfg; 28 | 29 | protected MixinPauseScreen(Component title) { 30 | super(title); 31 | } 32 | 33 | @Inject(method = "createPauseMenu", at = @At("TAIL"), locals = LocalCapture.CAPTURE_FAILHARD) 34 | protected void addOrReplaceButton(CallbackInfo ci, GridLayout gridLayout, GridLayout.RowHelper dummy) { 35 | 36 | IntegratedServer server = this.minecraft.getSingleplayerServer(); 37 | if (this.minecraft.hasSingleplayerServer()) { 38 | this.cfg = Config.read(server); 39 | } 40 | 41 | Component MODIFY_LAN_OPTIONS = this.minecraft.hasSingleplayerServer() 42 | && this.minecraft.getSingleplayerServer().isPublished() 43 | ? Component.translatable("mcwifipnp.gui.lanServerOptions") 44 | : Component.translatable("menu.shareToLan"); 45 | 46 | // Add a new button to the pause screen to open Lan Options Screen. 47 | if (this.minecraft.hasSingleplayerServer() && this.minecraft.getSingleplayerServer().isPublished() 48 | && !cfg.removePlayerReportingButton) { 49 | Button optionButton = GuiUtils.findWidget(this.children(), Button.class, "menu.options"); 50 | 51 | if (optionButton != null) { 52 | SpriteIconButton lanServerSettings = SpriteIconButton 53 | .builder(MODIFY_LAN_OPTIONS, 54 | (button) -> this.minecraft.setScreen(new ShareToLanScreenNew(this, true)), true) 55 | .width(20).sprite(ResourceLocation.tryParse("icon/language"), 15, 15).build(); 56 | lanServerSettings.setPosition(this.width / 2 - 124, optionButton.getY()); 57 | lanServerSettings.setTooltip(Tooltip.create(MODIFY_LAN_OPTIONS)); 58 | this.addRenderableWidget(lanServerSettings); 59 | } 60 | } 61 | 62 | // Replace the vanilla "Open to Lan" or "Player Reporting" button. 63 | final List elements = ((AccessorGridLayout) gridLayout).getChildren(); 64 | Button oldButton = GuiUtils.findWidget(elements, Button.class, "menu.shareToLan"); 65 | 66 | if (this.minecraft.hasSingleplayerServer() && cfg.removePlayerReportingButton && oldButton == null) { 67 | oldButton = GuiUtils.findWidget(elements, Button.class, "menu.playerReporting"); 68 | } 69 | if (oldButton != null) { 70 | Button newButton = Button.builder(MODIFY_LAN_OPTIONS, btn -> { 71 | this.minecraft.setScreen(new ShareToLanScreenNew(this, 72 | (this.minecraft.hasSingleplayerServer() && this.minecraft.getSingleplayerServer().isPublished()))); 73 | }).bounds(oldButton.getX(), oldButton.getY(), oldButton.getWidth(), oldButton.getHeight()).build(); 74 | elements.set(elements.indexOf(oldButton), newButton); 75 | this.removeWidget(oldButton); 76 | this.addRenderableWidget(newButton); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /README.zh-CN.md: -------------------------------------------------------------------------------- 1 | [__English__![en](https://img.shields.io/badge/lang-en-red.svg)](README.md) 2 | 3 | # LAN World Plug-n-Play 4 | 5 |
6 | 7 | [![1][1]][2] [![3][3]][4] [![5][5]][6] [![7][7]][8] 8 | 9 |
10 | 11 | [1]: https://img.shields.io/modrinth/dt/RTWpcTBp?label=Modrinth%0aDownloads&logo=modrinth&style=flat&color=45A35F&labelcolor=2D2D2D 12 | [2]: https://modrinth.com/mod/mcwifipnp 13 | 14 | [3]: https://img.shields.io/curseforge/dt/450250?label=CurseForge%0aDownloads&logo=curseforge&style=flat&color=E36639&labelcolor=2D2D2D 15 | [4]: https://www.curseforge.com/minecraft/mc-mods/mcwifipnp 16 | 17 | [5]: https://img.shields.io/badge/Available%20for-%201.15%20to%201.21-47376F?logo=files&color=377BCB&labelcolor=2D2D2D 18 | [6]: https://modrinth.com/mod/mcwifipnp/versions 19 | 20 | [7]: https://img.shields.io/github/license/Satxm/mcwifipnp?label=License&logo=github&style=flat&color=E51050&labelcolor=2D2D2D 21 | [8]: https://github.com/satxm/mcwifipnp 22 | 23 | ## 依赖 24 | 25 | **Fabric: [Fabric Loader](https://fabricmc.net/use/), [Fabric API](https://modrinth.com/mod/fabric-api)**. 26 | 27 | **Quilt: [Quilt Loader](https://quiltmc.org/install/), [QFAPI/QSL](https://modrinth.com/mod/qsl)**. 28 | 29 | **Forge: [Forge](https://files.minecraftforge.net/net/minecraftforge/forge/)**. 30 | 31 | **NeoForge: [NeoForge](https://projects.neoforged.net/neoforged/neoforge/)**. 32 | 33 | ## 下载 34 | 35 | CurseForge : [https://www.curseforge.com/minecraft/mc-mods/mcwifipnp](https://www.curseforge.com/minecraft/mc-mods/mcwifipnp) 36 | 37 | Modrinth : [https://modrinth.com/mod/mcwifipnp](https://modrinth.com/mod/mcwifipnp) 38 | 39 | MC百科 : [https://www.mcmod.cn/class/4498.html](https://www.mcmod.cn/class/4498.html) 40 | 41 | GitHub : [https://github.com/Satxm/mcwifipnp](https://github.com/Satxm/mcwifipnp) 42 | 43 | ## 简介 44 | 45 | **这个分支仅适用于 Minecraft 版本 [1.21.6, 1.21.9)!** 46 | 47 | 使用Minecraft原生界面样式,使用Mojang官方混淆表。 48 | 49 | * 修改自[TheGlitch76/mcpnp](https://github.com/TheGlitch76/mcpnp)项目 50 | * UPnP模块来自[adolfintel/WaifUPnP](https://github.com/adolfintel/WaifUPnP) & [RetGal/WaifUPnP](https://github.com/RetGal/WaifUPnP)。 51 | *`正版验证`以及`UUID修复`等功能来自[Rikka0w0/LanServerProperties](https://github.com/rikka0w0/LanServerProperties). 52 | 53 | ## 界面截图 54 | 55 |
56 | 57 | ![GUI ZH-CN](https://cdn.modrinth.com/data/cached_images/289c4b460fb56d3166be341cfbd6888f8fb8e72d.jpeg) 58 | 59 |
60 | 61 | ## 用法 62 | 63 | 1. 对于`正版验证`按钮,现在有三个选项: 64 | - `启用`:启用正版验证,将会比对Mojang服务器数据库验证登录信息,即只允许使用微软帐户登录的玩家加入; 65 | - `禁用`:即不验证登录信息,允许使用离线模式登录的玩家加入; 66 | - `禁用 + 修复UUID`:尝试使用离线模式登录的玩家名匹配Mojang服务器用户名称以获取唯一UUID,同时为使用微软帐户登录的用户保留UUID,它也可以防止背包和物品栏内容丢失。 67 | - 对应的控制台命令为`/onlinemode`与`/uuidfixer enabled`。 68 | 69 | 2. 新命令 `/uuidfixer` 可以控制在`禁用 + 修复UUID`模式下用户名如何映射为UUID。 70 | - `/uuidfixer enabled`用于开启与关闭本功能。 71 | - `/uuidfixer list` 命令可以查看列表中的规则。 72 | - `/uuidfixer force` 命令可以添加新规则或替换已有规则。 73 | - `/uuidfixer remove` 命令可以从列表中移除一个已有规则。 74 | - `/uuidfixer test` 命令可用于检查一个用户名所适用的规则。 75 | 76 | 3. 允许你修改局域网世界的端口号,并选择是否映射这个端口使用UPnP映射到公网(如果你的路由器支持UPnP)。 77 | 使用图形界面或者`/upnp`命令来开启与关闭UPnP支持。 78 | 79 | 4. 允许你启用或禁用PVP。 80 | 81 | 5. 允许你自定义MOTD(是玩家客户端的多人游戏服务器列表中显示的服务器信息,显示于名称下方)。 82 | 83 | 6. 你可以控制其他玩家加入时是否有op权限、是否可以作弊,你也可以使用 `/op` `/deop` 命令进行控制。你可以使用 `/whitelist` 命令构建白名单,然后用其控制其他玩家进是否允许加入你的游戏世界。 84 | 85 | 7. 你可以使用 `/ban` 来封禁玩家、 使用 `/ban-ip` 来封禁 IP 地址、 `/banlist` 命令可以查看封禁的玩家列表;你可以使用 `/pardon` 来解封玩家、 使用 `/pardon-ip` 来解封 IP地址。 86 | 87 | 8. 本模组可以自动保存配置文件,并且下次加载世界时会自动载入配置。 88 | 89 | 9. 本模组可以获取你的IP地址(比如本地 IPv4,公网 IPv4 或 IPv6),而且你可以选择是否复制IP到剪切板,以方便联机使用。`/ip`命令可以检索更多IP信息。 90 | 91 | 10. 服务器启动后,您可以更改上述大部分设置,但某些选项仅适用于新加入的玩家。 92 | 93 | 11. 您还可以通过单击左下角的按钮返回原版的“对局域网开放”屏幕。 94 | 95 | 12. 当本模组安装在服务端上时,只有修复UUID功能可用。只有服务端工作目录下存在`uuid_fixer.json`时修复UUID才会启用。`/uuidfixer`命令在服务端上也可用。除此之外,本模组在服务端上什么也不会做。 96 | 97 | ## 开发者 98 | ### 编译 99 | ``` 100 | git clone git@github.com:Satxm/mcwifipnp.git 101 | cd mcwifipnp 102 | .\gradlew.bat :fabric:runClient 103 | ``` 104 | 将`fabric`替换为`forge`, `neoforge`, 或者 `quilt`可以构建对应的jar。 105 | 106 | ### Eclipse 107 | 在 Eclipse 中将直接将根文件夹作为gradle项目导入就以开始开发。 108 | 如果嫌慢可以在`settings.gradle`中禁用某些目标以加快初始移植/开发速度。 109 | -------------------------------------------------------------------------------- /forge/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'eclipse' 3 | id 'idea' 4 | id 'net.minecraftforge.gradle' version '[6.0.36,6.2)' 5 | id 'org.spongepowered.mixin' version '0.7.+' 6 | } 7 | 8 | java.toolchain.languageVersion = JavaLanguageVersion.of(21) 9 | 10 | println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" 11 | 12 | version = project.mod_version + "-" + project.minecraft_version + "-forge" 13 | group = project.mod_group_id 14 | 15 | base { 16 | archivesName = project.mod_id 17 | } 18 | 19 | minecraft { 20 | mappings channel: 'official', version: project.minecraft_version 21 | reobf = false 22 | copyIdeResources = true 23 | 24 | runs { 25 | configureEach { 26 | workingDirectory project.file('run') 27 | property 'forge.logging.markers', 'REGISTRIES' 28 | property 'forge.logging.console.level', 'debug' 29 | arg "-mixin.config=${mod_id}.mixins.json" 30 | mods { 31 | "${mod_id}" { 32 | source sourceSets.main 33 | } 34 | } 35 | } 36 | client { 37 | property 'forge.enabledGameTestNamespaces', project.mod_id 38 | } 39 | 40 | server { 41 | property 'forge.enabledGameTestNamespaces', project.mod_id 42 | args '--nogui' 43 | } 44 | 45 | gameTestServer { 46 | property 'forge.enabledGameTestNamespaces', project.mod_id 47 | } 48 | 49 | data { 50 | workingDirectory project.file('run-data') 51 | args '--mod', project.mod_id, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/') 52 | } 53 | } 54 | } 55 | 56 | dependencies { 57 | minecraft "net.minecraftforge:forge:${project.minecraft_version}-${project.forge_version}" 58 | annotationProcessor "org.spongepowered:mixin:0.8.5:processor" 59 | annotationProcessor 'net.minecraftforge:eventbus-validator:7.0-beta.12' 60 | implementation('net.sf.jopt-simple:jopt-simple:5.0.4') { version { strictly '5.0.4' } } 61 | } 62 | 63 | sourceSets { 64 | main { 65 | java { 66 | srcDir "../src/main/java" 67 | } 68 | resources { 69 | srcDir "../src/main/resources" 70 | srcDir "src/generated/resources" 71 | } 72 | } 73 | } 74 | 75 | mixin { 76 | // MixinGradle Settings 77 | add sourceSets.main, 'mcwifipnp-refmap.json' 78 | config 'mcwifipnp.mixins.json' 79 | 80 | debug.verbose = true 81 | debug.export = true 82 | } 83 | 84 | tasks.named('jar', Jar).configure { 85 | manifest { 86 | attributes([ 87 | "Specification-Title": "LAN World Plug-n-Play", 88 | "Specification-Vendor": "Satxm", 89 | "Specification-Version": "1", 90 | "Implementation-Title": project.name, 91 | "Implementation-Version": "${version}", 92 | "Implementation-Vendor": "Satxm", 93 | "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"), 94 | "MixinConfigs": "mcwifipnp.mixins.json" 95 | ]) 96 | } 97 | } 98 | 99 | tasks.named('processResources', ProcessResources).configure { 100 | var replaceProperties = [ 101 | mod_version : project.mod_version, 102 | forge_version_range : project.forge_version_range, 103 | minecraft_version_min : project.minecraft_version_min, 104 | minecraft_version_max : project.minecraft_version_max, 105 | forge_loader_version_range : project.forge_loader_version_range, 106 | pack_format_number: pack_format_number, 107 | ] 108 | inputs.properties replaceProperties 109 | filesMatching(['META-INF/mods.toml', 'pack.mcmeta']) { 110 | expand replaceProperties + [project: project] 111 | } 112 | } 113 | 114 | tasks.withType(JavaCompile).configureEach { 115 | it.options.encoding = 'UTF-8' 116 | it.options.release = 21 117 | } 118 | 119 | idea { 120 | module { 121 | downloadSources = true 122 | downloadJavadoc = true 123 | } 124 | } 125 | java.withSourcesJar() 126 | 127 | jar { 128 | from("../LICENSE") { 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /src/main/resources/assets/mcwifipnp/lang/es_es.json: -------------------------------------------------------------------------------- 1 | { 2 | "mcwifipnp.gui.port.info": "Número de puerto para el Mundo LAN.\nDeja el cuadro de edición vacío o ingresa un número diferente entre 1024 y 65535.", 3 | "mcwifipnp.gui.port.invalid": "Puerto no válido.\nDeja la caja de edición vacía o elige un número entre 1024 y 65535.", 4 | "mcwifipnp.gui.port.unavailable": "Puerto no disponible.\nDeja la caja de edición vacía o elige un número diferente entre 1024 y 65535.", 5 | "mcwifipnp.gui.players": "Jugadores Máximos", 6 | "mcwifipnp.gui.players.info": "El número máximo de jugadores que pueden unirse al servidor.", 7 | "mcwifipnp.gui.motd": "Mensaje del servidor", 8 | "mcwifipnp.gui.motd.info": "La información del servidor que se muestra debajo del nombre en la lista de servidores multijugador.", 9 | "mcwifipnp.gui.AllPlayersCheats": "Trucos de Otros Jugadores", 10 | "mcwifipnp.gui.AllPlayersCheats.info": "Habilita para hacer automáticamente operadores a otros jugadores cuando se unan al servidor. También puedes usar /op para hacer que alguien sea operador.", 11 | "mcwifipnp.gui.Whitelist": "Lista Blanca", 12 | "mcwifipnp.gui.Whitelist.info": "Habilita la lista blanca. Cuando estaba activada, solo los jugadores en la lista blanca pueden conectarse al servidor. Usa /whitelist para agregar jugadores a la lista.", 13 | "mcwifipnp.gui.OnlineMode": "Modo en Línea", 14 | "mcwifipnp.gui.OnlineMode.info": "Conecta a la base de datos de cuentas de Minecraft para verificar los inicios de sesión. Desactívalo para permitir que las cuentas sin conexión se unan.", 15 | "mcwifipnp.gui.OnlineMode.online": "Activado", 16 | "mcwifipnp.gui.OnlineMode.online.info": "El modo en línea enabe solo permite que los jugadores que se conecten con una cuenta de Microsoft se unan a este servidor.", 17 | "mcwifipnp.gui.OnlineMode.offline": "Desactivado", 18 | "mcwifipnp.gui.OnlineMode.offline.info": "Desactiva Modo en Línea permitirá a los jugadores que se conecten en modo offline unirse a este servidor.", 19 | "mcwifipnp.gui.OnlineMode.fixuuid": "Desactivar + Reparación uuid", 20 | "mcwifipnp.gui.OnlineMode.fixuuid.info": "Trate de coincidir el nombre de usuario del servidor mojang con el nombre del jugador del jugador en modo offline para obtener un uuid único. N al mismo tiempo, los usuarios que se conecten con una cuenta de Microsoft conservarán uuid. N también evita la pérdida de mochilas y artículos de inventario.", 21 | "mcwifipnp.gui.PvP": "PvP", 22 | "mcwifipnp.gui.PvP.info": "Activa o desactiva el PvP. Deshabilitar el PvP también evitará que recibas daño de tus propios proyectiles.", 23 | "mcwifipnp.gui.UseUPnP": "Reenviar Puerto", 24 | "mcwifipnp.gui.UseUPnP.info": "Si se debe usar la función UPnP para asignar el número de puerto del juego LAN.", 25 | "mcwifipnp.gui.localIP": "Local %s", 26 | "mcwifipnp.gui.globalIP": "Global %s", 27 | "mcwifipnp.gui.CopyIP": "Obtener IP", 28 | "mcwifipnp.gui.CopyIP.info": "Obtener IP y copiar al portapapeles", 29 | "mcwifipnp.gui.removePlayerReportingButton": "Reemplaza Reportes de jugadores Botón", 30 | "mcwifipnp.upnp.success": "Puerto %s reenviado con éxito", 31 | "mcwifipnp.upnp.clipboard": "Obtención exitosa de %s. Debido a factores como NAT, es posible que estas IP no puedan conectarse directamente.", 32 | "mcwifipnp.upnp.cantgetip": "¡No se pudo obtener la IP pública! Verifica la configuración de tu red. Tu IPv4 puede contener múltiples NAT o no tener IPv6.", 33 | "mcwifipnp.upnp.failed.mapped": "No se pudo reenviar el puerto %s: El puerto ya estaba asignado por otro servicio UPnP. Cambia el número de puerto.", 34 | "mcwifipnp.upnp.failed.disabled": "No se pudo reenviar el puerto %s: UPnP no estaba habilitado en tu enrutador. Puede que necesites usar software de asignación de puertos.", 35 | "mcwifipnp.upnp.failed.unknownerror": "No se pudo reenviar el puerto %s: Error desconocido al agregar la asignación de puertos. Usa un software de asignación de puertos.", 36 | "mcwifipnp.upnp.failed": "No se pudo reenviar el puerto %s.", 37 | "mcwifipnp.commands.forceoffline.add.failed": "El jugador ya estaba en la lista fuera de línea", 38 | "mcwifipnp.commands.forceoffline.add.success": "Se ha añadido a %s a la lista fuera de línea", 39 | "mcwifipnp.commands.forceoffline.list": "Hay %s jugador(es) en la lista fuera de línea: %s", 40 | "mcwifipnp.commands.forceoffline.none": "No hay jugadores en la lista fuera de línea", 41 | "mcwifipnp.commands.forceoffline.remove.failed": "El jugador no estaba en la lista fuera de línea", 42 | "mcwifipnp.commands.forceoffline.remove.success": "Se ha eliminado a %s de la lista fuera de línea" 43 | } 44 | -------------------------------------------------------------------------------- /src/main/resources/assets/mcwifipnp/lang/en_us.json: -------------------------------------------------------------------------------- 1 | { 2 | "mcwifipnp.gui.port.info": "The port to listen on.", 3 | "mcwifipnp.gui.port.invalid": "Not a valid port.\nMust be a number between §41024 and 65535§f.", 4 | "mcwifipnp.gui.port.unavailable": "§4Port not available!", 5 | "mcwifipnp.gui.players": "Max. Players", 6 | "mcwifipnp.gui.players.info": "The maximum number of players that the server can host.", 7 | "mcwifipnp.gui.lanServerOptions": "Lan Server Settings", 8 | "mcwifipnp.gui.otherOptions": "Other Settings", 9 | "mcwifipnp.gui.backToVanillaScreen": "Back to Vanilla Screen", 10 | "mcwifipnp.gui.motd": "The MOTD (Message of the day)", 11 | "mcwifipnp.gui.motd.info": "The server information displayed below the name in the multiplayer server list.", 12 | "mcwifipnp.gui.AllPlayersCheats": "Other Players Cheats", 13 | "mcwifipnp.gui.AllPlayersCheats.info": "Give a player permission to use administrative commands when joining the server. Alternatively, use /op to make someone an operator.", 14 | "mcwifipnp.gui.Whitelist": "Whitelist", 15 | "mcwifipnp.gui.Whitelist.info": "Enforce whitelist. Once enabled, only whitelisted players may join. Use /whitelist to add players to the list.", 16 | "mcwifipnp.gui.OnlineMode": "Online Mode", 17 | "mcwifipnp.gui.OnlineMode.info": "Whether to let the server compare and verify the login information against the Mojang server database.", 18 | "mcwifipnp.gui.OnlineMode.online": "Enable", 19 | "mcwifipnp.gui.OnlineMode.online.info": "Only allow players with valid Microsoft/Mojang accounts to join the LAN server.", 20 | "mcwifipnp.gui.OnlineMode.offline": "Disable", 21 | "mcwifipnp.gui.OnlineMode.offline.info": "Allow anyone to join the LAN server, including offline players.", 22 | "mcwifipnp.gui.OnlineMode.fixuuid": "Disable + UUID Fixer", 23 | "mcwifipnp.gui.OnlineMode.fixuuid.info": "Allow anyone to join the LAN server. Players with valid Microsoft/Mojang accounts will use their unique genuine UUID. \n§bUse this mode if you are migrating from the online mode and want to retain the inventories.", 24 | "mcwifipnp.gui.PvP": "PvP", 25 | "mcwifipnp.gui.PvP.info": "Note: disabling PvP will also prevent you from taking damage from your own projectiles.", 26 | "mcwifipnp.gui.UseUPnP": "UPnP Port Forwarding", 27 | "mcwifipnp.gui.UseUPnP.info": "Use UPnP to setup port forwarding and broadcast the game server on LAN with UPnP so that people on the same LAN can find us directly.", 28 | "mcwifipnp.gui.localIP": "Local %s", 29 | "mcwifipnp.gui.globalIP": "Global %s", 30 | "mcwifipnp.gui.CopyIP": "Get Public IP", 31 | "mcwifipnp.gui.CopyIP.info": "Get the §bPublic IP§f and allow you to copy it to clipboard", 32 | "mcwifipnp.gui.removePlayerReportingButton": "Replace Player Reporting Button", 33 | "mcwifipnp.upnp.success": "Successfully forwarded port %s", 34 | "mcwifipnp.upnp.clipboard": "Successfully got %s, Due to factors such as NAT, these IPs may still not be able to connect directly.", 35 | "mcwifipnp.upnp.cantgetip": "Couldn't get public IP! Please check your network settings. Your IPv4 may contain multiple NATs or you do not have IPv6.", 36 | "mcwifipnp.upnp.failed.mapped": "Unable to forward port %s: Port was already mapped by another UPnP service, Please change the port number.", 37 | "mcwifipnp.upnp.failed.disabled": "Unable to forward port %s: UPnP is not enabled on your router, You may need to use port mapping software.", 38 | "mcwifipnp.upnp.failed.unknownerror": "Unable to forward port %s: Unknown error while adding port mapping, Please use a port mapping software.", 39 | "mcwifipnp.upnp.failed": "Unable to forward port %s!", 40 | "mcwifipnp.commands.uuidfixer.name": "UUID Fixer", 41 | "mcwifipnp.commands.uuidfixer.policy.online": "online", 42 | "mcwifipnp.commands.uuidfixer.policy.offline": "offline", 43 | "mcwifipnp.commands.uuidfixer.policy.invalid": "invalid", 44 | "mcwifipnp.commands.uuidfixer.default.show": "UUID Fixer's default policy is %s.", 45 | "mcwifipnp.commands.uuidfixer.default.set": "Set UUID Fixer's default policy to %s.", 46 | "mcwifipnp.commands.uuidfixer.set.success": "Set %s's UUID Fixer policy to %s.", 47 | "mcwifipnp.commands.uuidfixer.set.override": "Override UUID of %s with to %s.", 48 | "mcwifipnp.commands.uuidfixer.set.bad-policy": "Invalid policy: %s, should be online, offline, or a valid UUID.", 49 | "mcwifipnp.commands.uuidfixer.list": "There are %s rules in the UUID Fixer's policy list:", 50 | "mcwifipnp.commands.uuidfixer.none": "UUID Fixer's policy list is empty.", 51 | "mcwifipnp.commands.uuidfixer.policy.not-exist": "%s is not in the UUID Fixer's policy list!", 52 | "mcwifipnp.commands.uuidfixer.remove.success": "Removed %s from the UUID Fixer's policy list." 53 | } 54 | -------------------------------------------------------------------------------- /.github/workflows/publish.yaml: -------------------------------------------------------------------------------- 1 | name: Build and Publish 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | channel: 7 | type: choice 8 | description: Release Channel 9 | options: 10 | - alpha 11 | - beta 12 | - release 13 | 14 | env: 15 | java-version: "21" 16 | modrinth-id: RTWpcTBp 17 | curseforge-id: 450250 18 | 19 | jobs: 20 | build: 21 | runs-on: ubuntu-latest 22 | 23 | permissions: 24 | contents: write 25 | packages: write 26 | 27 | steps: 28 | - name: Checkout Repository 29 | uses: actions/checkout@v4 30 | with: 31 | submodules: true 32 | 33 | - name: Set up JDK ${{ env.java-version }} 34 | uses: actions/setup-java@v3 35 | with: 36 | java-version: ${{ env.java-version }} 37 | distribution: "temurin" 38 | 39 | - name: Setup Gradle 40 | uses: gradle/actions/setup-gradle@v4 41 | with: 42 | cache-read-only: false 43 | cache-cleanup: always 44 | 45 | - name: Make Gradle Wrapper Executable 46 | if: ${{ runner.os != 'Windows' }} 47 | run: chmod +x ./gradlew 48 | 49 | - name: Build with Gradle Wrapper 50 | run: ./gradlew build 51 | 52 | - name: Check Files & Get Name form Files 53 | run: | 54 | fabric_name=$(basename fabric/build/libs/*.jar | sed 's/.jar//' | sed 's/mcwifipnp-//' | sed 's/-sources//' | sed 's/-dev//') 55 | forge_name=$(basename forge/build/libs/*.jar | sed 's/\.jar//' | sed 's/mcwifipnp-//' | sed 's/-sources//' | sed 's/-dev//') 56 | neoforge_name=$(basename neoforge/build/libs/*.jar | sed 's/\.jar//' | sed 's/mcwifipnp-//' | sed 's/-sources//' | sed 's/-dev//') 57 | quilt_name=$(basename quilt/build/libs/*.jar | sed 's/\.jar//' | sed 's/mcwifipnp-//' | sed 's/-sources//' | sed 's/-dev//') 58 | echo "FABRIC_NAME"="${fabric_name}" >> $GITHUB_ENV 59 | echo "FORGE_NAME"="${forge_name}" >> $GITHUB_ENV 60 | echo "NEOFORGE_NAME"="${neoforge_name}" >> $GITHUB_ENV 61 | echo "QUILT_NAME"="${quilt_name}" >> $GITHUB_ENV 62 | 63 | - name: Publish (Fabric) 64 | if: env.FABRIC_NAME != '*' 65 | uses: Kir-Antipov/mc-publish@v3.3 66 | with: 67 | fail-mode: warn 68 | modrinth-id: ${{ env.modrinth-id }} 69 | modrinth-token: "${{ secrets.MODRINTH_TOKEN }}" 70 | curseforge-id: ${{ env.curseforge-id }} 71 | curseforge-token: "${{ secrets.CURSEFORGE_TOKEN }}" 72 | 73 | name: ${{ env.FABRIC_NAME }} 74 | version-type: ${{ inputs.channel }} 75 | files: fabric/build/libs/!(*-@(dev|sources|javadoc)).jar 76 | java: Java ${{ env.java-version }} 77 | 78 | - name: Publish (Forge) 79 | if: env.FORGE_NAME != '*' 80 | uses: Kir-Antipov/mc-publish@v3.3 81 | with: 82 | fail-mode: warn 83 | modrinth-id: ${{ env.modrinth-id }} 84 | modrinth-token: "${{ secrets.MODRINTH_TOKEN }}" 85 | curseforge-id: ${{ env.curseforge-id }} 86 | curseforge-token: "${{ secrets.CURSEFORGE_TOKEN }}" 87 | 88 | name: ${{ env.FORGE_NAME }} 89 | version-type: ${{ inputs.channel }} 90 | files: forge/build/libs/!(*-@(dev|sources|javadoc)).jar 91 | java: Java ${{ env.java-version }} 92 | 93 | - name: Publish (NeoForge) 94 | if: env.NEOFORGE_NAME != '*' 95 | uses: Kir-Antipov/mc-publish@v3.3 96 | with: 97 | fail-mode: warn 98 | modrinth-id: ${{ env.modrinth-id }} 99 | modrinth-token: "${{ secrets.MODRINTH_TOKEN }}" 100 | curseforge-id: ${{ env.curseforge-id }} 101 | curseforge-token: "${{ secrets.CURSEFORGE_TOKEN }}" 102 | 103 | name: ${{ env.NEOFORGE_NAME }} 104 | loaders: neoforge 105 | version-type: ${{ inputs.channel }} 106 | files: neoforge/build/libs/!(*-@(dev|sources|javadoc)).jar 107 | java: Java ${{ env.java-version }} 108 | 109 | - name: Publish (Quilt) 110 | if: env.QUILT_NAME != '*' 111 | uses: Kir-Antipov/mc-publish@v3.3 112 | with: 113 | fail-mode: warn 114 | modrinth-id: ${{ env.modrinth-id }} 115 | modrinth-token: "${{ secrets.MODRINTH_TOKEN }}" 116 | curseforge-id: ${{ env.curseforge-id }} 117 | curseforge-token: "${{ secrets.CURSEFORGE_TOKEN }}" 118 | 119 | name: ${{ env.QUILT_NAME }} 120 | loaders: quilt 121 | version-type: ${{ inputs.channel }} 122 | files: quilt/build/libs/!(*-@(dev|sources|javadoc)).jar 123 | java: Java ${{ env.java-version }} 124 | -------------------------------------------------------------------------------- /src/main/java/io/github/satxm/mcwifipnp/client/OptionsList.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp.client; 2 | 3 | import java.util.List; 4 | 5 | import javax.annotation.Nullable; 6 | 7 | import com.google.common.collect.ImmutableList; 8 | 9 | import net.minecraft.client.Minecraft; 10 | import net.minecraft.client.gui.Font; 11 | import net.minecraft.client.gui.GuiGraphics; 12 | import net.minecraft.client.gui.components.AbstractWidget; 13 | import net.minecraft.client.gui.components.ContainerObjectSelectionList; 14 | import net.minecraft.client.gui.components.events.GuiEventListener; 15 | import net.minecraft.client.gui.layouts.HeaderAndFooterLayout; 16 | import net.minecraft.client.gui.narration.NarratableEntry; 17 | import net.minecraft.client.gui.screens.Screen; 18 | import net.minecraft.network.chat.Component; 19 | 20 | public class OptionsList extends ContainerObjectSelectionList { 21 | public final static int COLUMN_WIDTH = 150; 22 | public final static int GAP = 10; 23 | 24 | public final Screen screen; 25 | public final Font font; 26 | 27 | public OptionsList(Minecraft minecraft, int width, HeaderAndFooterLayout layout, Screen screen, Font font) { 28 | super(minecraft, width, layout.getContentHeight(), layout.getHeaderHeight(), 25); 29 | this.centerListVertically = false; 30 | this.screen = screen; 31 | this.font = font; 32 | } 33 | 34 | public void add(AbstractWidget widgets) { 35 | this.add(widgets, null); 36 | } 37 | 38 | public void add(AbstractWidget left, @Nullable AbstractWidget right) { 39 | this.addEntry(new OptionsList.Entry(left, right)); 40 | } 41 | 42 | public void add(Component labelLeft, AbstractWidget left) { 43 | this.addEntry(new OptionsList.LabeledEntry(labelLeft, left, null, null)); 44 | } 45 | 46 | public void add(Component labelLeft, AbstractWidget left, Component labelRight, AbstractWidget right) { 47 | this.addEntry(new OptionsList.LabeledEntry(labelLeft, left, labelRight, right)); 48 | } 49 | 50 | @Override 51 | public int getRowWidth() { 52 | return 340; 53 | } 54 | 55 | /** 56 | * One row with two widgets. 57 | * If there is only one widget, it and its label will use the entire row. 58 | */ 59 | protected class Entry extends ContainerObjectSelectionList.Entry { 60 | protected final List children; 61 | protected static final int X_OFFSET = 160; 62 | 63 | Entry(AbstractWidget left, @Nullable AbstractWidget right) { 64 | this.children = right == null ? ImmutableList.of(left) : ImmutableList.of(left, right); 65 | } 66 | 67 | @Override 68 | public void renderContent(GuiGraphics guiGraphics, int i, int j, boolean bl, float f) { 69 | int xStart = OptionsList.this.screen.width / 2 - COLUMN_WIDTH - GAP / 2; 70 | 71 | for (AbstractWidget abstractwidget : this.children) { 72 | abstractwidget.setPosition(xStart, this.getContentY()); 73 | abstractwidget.render(guiGraphics, i, j, f); 74 | xStart += COLUMN_WIDTH + GAP; 75 | } 76 | } 77 | 78 | @Override 79 | public List children() { 80 | return this.children; 81 | } 82 | 83 | @Override 84 | public List narratables() { 85 | return this.children; 86 | } 87 | } 88 | 89 | /** 90 | * One row with two widgets and their labels. 91 | * Labels are left aligned, widgets are right aligned. 92 | * If there is only one widget, it and its label will use the entire row. 93 | */ 94 | protected class LabeledEntry extends Entry { 95 | protected final AbstractWidget left, right; 96 | protected final Component labelLeft, labelRight; 97 | 98 | LabeledEntry(Component labelLeft, AbstractWidget left, Component labelRight, AbstractWidget right) { 99 | super(left, right); 100 | this.left = left; 101 | this.right = right; 102 | this.labelLeft = labelLeft; 103 | this.labelRight = labelRight; 104 | } 105 | 106 | @Override 107 | public void renderContent(GuiGraphics guiGraphics, int i, int j, boolean bl, float f) { 108 | int xStart = OptionsList.this.screen.width / 2 - COLUMN_WIDTH - GAP / 2; 109 | 110 | guiGraphics.drawString(OptionsList.this.font, this.labelLeft, xStart, 111 | this.getContentY() + (this.left.getHeight() - 9) / 2, 16777215); 112 | 113 | if (this.right == null) 114 | xStart += COLUMN_WIDTH + GAP; 115 | 116 | this.left.setPosition(xStart + (COLUMN_WIDTH - this.left.getWidth()), this.getContentY()); 117 | this.left.render(guiGraphics, i, j, f); 118 | 119 | if (this.right == null) 120 | return; 121 | 122 | xStart += COLUMN_WIDTH + GAP; 123 | guiGraphics.drawString(OptionsList.this.font, this.labelRight, xStart, 124 | this.getContentY() + (this.right.getHeight() - 9) / 2, 16777215); 125 | this.right.setPosition(xStart + (COLUMN_WIDTH - this.right.getWidth()), this.getContentY()); 126 | this.right.render(guiGraphics, i, j, f); 127 | } 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /src/main/java/io/github/satxm/mcwifipnp/MCWiFiPnPUnit.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp; 2 | 3 | import org.apache.logging.log4j.LogManager; 4 | import org.apache.logging.log4j.Logger; 5 | 6 | import com.mojang.brigadier.CommandDispatcher; 7 | 8 | import io.github.satxm.mcwifipnp.commands.*; 9 | import io.github.satxm.mcwifipnp.network.UPnPModule; 10 | import net.minecraft.commands.CommandSourceStack; 11 | import net.minecraft.server.MinecraftServer; 12 | import net.minecraft.server.commands.BanIpCommands; 13 | import net.minecraft.server.commands.BanListCommands; 14 | import net.minecraft.server.commands.BanPlayerCommands; 15 | import net.minecraft.server.commands.DeOpCommands; 16 | import net.minecraft.server.commands.OpCommand; 17 | import net.minecraft.server.commands.PardonCommand; 18 | import net.minecraft.server.commands.PardonIpCommand; 19 | import net.minecraft.server.commands.WhitelistCommand; 20 | import net.minecraft.server.players.OldUsersConverter; 21 | 22 | // This is the common entry which should not import any side-specific class 23 | public class MCWiFiPnPUnit { 24 | public static final String MODID = "mcwifipnp"; 25 | 26 | /** 27 | * The logger that should be used throughout this mod and its plugins. 28 | */ 29 | public static final Logger LOGGER = LogManager.getLogger(MCWiFiPnP.class); 30 | 31 | /** 32 | * Register commands. 33 | * Should be called from platform-specific entries. 34 | */ 35 | public static void registerCommands(CommandDispatcher cmdDispatcher, boolean isDedicatedServer) { 36 | // Register our new commands on both client and dedicated server 37 | UUIDFixerCommand.register(cmdDispatcher); 38 | 39 | if (isDedicatedServer) { 40 | enableUUIDFixerOnDedicatedServer(); 41 | return; 42 | } 43 | 44 | // Register our client-only commands 45 | IpCommand.register(cmdDispatcher); 46 | OnlineModeCommand.register(cmdDispatcher); 47 | UPnPCommand.register(cmdDispatcher); 48 | 49 | // Register missing vanilla server commands on the client-side 50 | DeOpCommands.register(cmdDispatcher); 51 | OpCommand.register(cmdDispatcher); 52 | WhitelistCommand.register(cmdDispatcher); 53 | BanIpCommands.register(cmdDispatcher); 54 | BanListCommands.register(cmdDispatcher); 55 | BanPlayerCommands.register(cmdDispatcher); 56 | PardonCommand.register(cmdDispatcher); 57 | PardonIpCommand.register(cmdDispatcher); 58 | } 59 | 60 | /** 61 | * Called by platform-specific hooks just before the server stopping. 62 | * Only runs on client-side 63 | */ 64 | public static void onServerStopping(MinecraftServer server) { 65 | if (!server.isDedicatedServer()) { 66 | UPnPModule.stop(server); 67 | } 68 | } 69 | 70 | /** 71 | * Called by platform-specific hooks just before the server starting. 72 | * Only runs on client-side 73 | */ 74 | public static void onServerStarting(MinecraftServer server) { 75 | } 76 | 77 | public static void enableUUIDFixerOnDedicatedServer() { 78 | UUIDFixer.enabled = true; 79 | LOGGER.info("UUID Fixer has been enabled on the dedicated server." 80 | + "To disable, delete mod McWifiPnP. Config file is \"uuid_fixer.json\"."); 81 | } 82 | 83 | /** 84 | * Copied from vanilla DedicatedServer 85 | * 86 | * @param server 87 | * @return 88 | */ 89 | public static boolean convertOldUsers(MinecraftServer server) { 90 | int i; 91 | boolean bl = false; 92 | for (i = 0; !bl && i <= 2; ++i) { 93 | if (i > 0) { 94 | LOGGER.warn("Encountered a problem while converting the user banlist, retrying in a few seconds"); 95 | MCWiFiPnPUnit.waitForRetry(); 96 | } 97 | bl = OldUsersConverter.convertUserBanlist(server); 98 | } 99 | boolean bl2 = false; 100 | for (i = 0; !bl2 && i <= 2; ++i) { 101 | if (i > 0) { 102 | LOGGER.warn("Encountered a problem while converting the ip banlist, retrying in a few seconds"); 103 | MCWiFiPnPUnit.waitForRetry(); 104 | } 105 | bl2 = OldUsersConverter.convertIpBanlist(server); 106 | } 107 | boolean bl3 = false; 108 | for (i = 0; !bl3 && i <= 2; ++i) { 109 | if (i > 0) { 110 | LOGGER.warn("Encountered a problem while converting the op list, retrying in a few seconds"); 111 | MCWiFiPnPUnit.waitForRetry(); 112 | } 113 | bl3 = OldUsersConverter.convertOpsList(server); 114 | } 115 | boolean bl4 = false; 116 | for (i = 0; !bl4 && i <= 2; ++i) { 117 | if (i > 0) { 118 | LOGGER.warn("Encountered a problem while converting the whitelist, retrying in a few seconds"); 119 | MCWiFiPnPUnit.waitForRetry(); 120 | } 121 | bl4 = OldUsersConverter.convertWhiteList(server); 122 | } 123 | return bl || bl2 || bl3 || bl4; 124 | } 125 | 126 | private static void waitForRetry() { 127 | try { 128 | Thread.sleep(5000L); 129 | } catch (InterruptedException interruptedException) { 130 | return; 131 | } 132 | } 133 | } -------------------------------------------------------------------------------- /src/main/java/io/github/satxm/mcwifipnp/commands/EnumArgument.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp.commands; 2 | 3 | import java.util.HashMap; 4 | import java.util.List; 5 | import java.util.Map; 6 | import java.util.function.Function; 7 | import java.util.function.UnaryOperator; 8 | 9 | import com.mojang.brigadier.builder.LiteralArgumentBuilder; 10 | import com.mojang.brigadier.context.CommandContext; 11 | import com.mojang.brigadier.context.ParsedCommandNode; 12 | import com.mojang.brigadier.tree.LiteralCommandNode; 13 | 14 | import io.netty.channel.socket.InternetProtocolFamily; 15 | import net.minecraft.commands.CommandSourceStack; 16 | import net.minecraft.commands.Commands; 17 | 18 | /** 19 | * The "Proper" Enum argument implementation (like the one in Forge) requires 20 | * registration. Here is a simple workaround. 21 | *

22 | * For simple string literals that don't have a enum backend, use 23 | * {@link EnumArgument#literals} and 24 | * {@link EnumArgument#getArgValue(CommandContext, int)}. 25 | *

26 | * Otherwise, call the constructors to create a helper class for the enum, then 27 | * use {@link EnumArgument#appendTo(LiteralArgumentBuilder, UnaryOperator)} and 28 | * {@link EnumArgument#valueOf(CommandContext, int)} 29 | *

30 | * The only drawback is that you need to find out the literal index manually. 31 | * 32 | * @param the Enum type 33 | */ 34 | public class EnumArgument> { 35 | public final static EnumArgument IP_FAMILY = 36 | new EnumArgument<>(InternetProtocolFamily.class); 37 | 38 | private final Function namingFunction; 39 | private final Map mapping = new HashMap<>(); 40 | 41 | /** 42 | * Use all lower case and replace _ with - for naming. 43 | * 44 | * @param enumClass 45 | */ 46 | public EnumArgument(Class enumClass) { 47 | this(enumClass, (t) -> t.name().toLowerCase().replace('_', '-')); 48 | } 49 | 50 | /** 51 | * @param enumClass 52 | * @param namingFunction how to map each of the enum to a string argument. An 53 | * error will be thrown if multiple enum have the same 54 | * mapped name. 55 | */ 56 | public EnumArgument(Class enumClass, Function namingFunction) { 57 | this.namingFunction = namingFunction; 58 | 59 | for (T value: enumClass.getEnumConstants()) { 60 | String name = namingFunction.apply(value); 61 | T existing = this.mapping.get(name); 62 | 63 | if (existing != null) { 64 | throw new RuntimeException(existing + " and " + value + " has the same mapped key: " + name); 65 | } 66 | 67 | this.mapping.put(name, value); 68 | } 69 | } 70 | 71 | public String nameOf(T value) { 72 | return this.namingFunction.apply(value); 73 | } 74 | 75 | public T valueOf(String argVal) { 76 | return this.mapping.get(argVal); 77 | } 78 | 79 | public T valueOf(CommandContext context, int index) { 80 | return this.mapping.get(getArgValue(context, index)); 81 | } 82 | 83 | public LiteralArgumentBuilder appendTo( 84 | LiteralArgumentBuilder parent, 85 | UnaryOperator> operation) { 86 | 87 | return literals(parent, this.mapping.keySet().toArray(new String[0])).apply(operation); 88 | } 89 | 90 | /** 91 | *

 92 | 	 *   EnumArgument.literals(parent, "enum1", "enum2").apply(enumOption -> enumOption.THE_OPERATION())
 93 | 	 * 
94 | *

is equivalent to:

95 | *
 96 | 	 *   parent
 97 | 	 *       .then(Commands.literal("enum1").THE_OPERATION())
 98 | 	 *       .then(Commands.literal("enum2").THE_OPERATION())
 99 | 	 * 
100 | * 101 | * @param parent 102 | * @param values 103 | * @return a builder function that accepts an operation (THE_OPERATION) to be performed on each enum literals 104 | */ 105 | public static Function>, LiteralArgumentBuilder> literals( 106 | LiteralArgumentBuilder parent, String... values 107 | ) { 108 | 109 | return (operation) -> { 110 | LiteralArgumentBuilder result = parent; 111 | for (String value: values) { 112 | result = result.then(operation.apply(Commands.literal(value))); 113 | } 114 | return result; 115 | }; 116 | } 117 | 118 | /** 119 | * Get the literal string value from a command context. 120 | * 121 | * @param context 122 | * @param index The index of the literal, from right to left, starting from 0. 123 | * @return the literal string value, null if not applicable. 124 | */ 125 | public static String getArgValue(CommandContext context, int index) { 126 | List> nodes = context.getNodes(); 127 | ParsedCommandNode node = nodes.get(nodes.size() - 1 - index); 128 | if (node.getNode() instanceof LiteralCommandNode literal) { 129 | return literal.getLiteral(); 130 | } else { 131 | return null; 132 | } 133 | } 134 | } -------------------------------------------------------------------------------- /src/main/resources/assets/mcwifipnp/lang/ru_ru.json: -------------------------------------------------------------------------------- 1 | { 2 | "mcwifipnp.gui.port.info": "Порт для локального мира.", 3 | "mcwifipnp.gui.port.invalid": "Неверный порт.\nОставьте это поле пустым или введите число от §41024 до 65535§.", 4 | "mcwifipnp.gui.port.unavailable": "§4Порт недоступен.", 5 | "mcwifipnp.gui.players": "Лимит игроков", 6 | "mcwifipnp.gui.players.info": "Максимальное количество игроков, которые могут присоединиться к серверу.", 7 | "mcwifipnp.gui.lanServerOptions": "Настройки сервера", 8 | "mcwifipnp.gui.motd": "Описание", 9 | "mcwifipnp.gui.motd.info": "Информация о сервере, отображаемая под названием в списке сетевой игры.", 10 | "mcwifipnp.gui.AllPlayersCheats": "Использование команд", 11 | "mcwifipnp.gui.AllPlayersCheats.info": "Включите, чтобы автоматически назначать других игроков операторами, когда они присоединяются к серверу. Вы также можете использовать /op, чтобы назначить кого-то оператором.", 12 | "mcwifipnp.gui.Whitelist": "Белый список", 13 | "mcwifipnp.gui.Whitelist.info": "Принудительный белый список. Если включено, только игроки, внесённые в этот список, смогут подключаться к серверу. Используйте /whitelist для добавления игроков в список.", 14 | "mcwifipnp.gui.OnlineMode": "Проверка лицензии", 15 | "mcwifipnp.gui.OnlineMode.info": "Подключается к базе данных учётных записей Minecraft для проверки логинов. Отключите, чтобы разрешить подключение учётных записей без лицензии.", 16 | "mcwifipnp.gui.OnlineMode.online": "Включить", 17 | "mcwifipnp.gui.OnlineMode.online.info": "Включение проверки лицензии позволит подключиться к этому серверу только игрокам, которые вошли в систему с учётной записью Microsoft.", 18 | "mcwifipnp.gui.OnlineMode.offline": "Отключить", 19 | "mcwifipnp.gui.OnlineMode.offline.info": "Отключение проверки лицензии позволит игрокам, вошедшим в систему в автономном режиме, присоединиться к этому серверу.", 20 | "mcwifipnp.gui.OnlineMode.fixuuid": "Отключить + исправитель UUID", 21 | "mcwifipnp.gui.OnlineMode.fixuuid.info": "Попытается сопоставить имя пользователя сервера Mojang с именем игрока для игроков в автономном режиме, чтобы получить уникальный UUID. \nМежду тем, UUID сохраняются для пользователей, входящих в систему с помощью учётных записей Microsoft.\n§bЭто также может предотвратить потерю рюкзака и предметов инвентаря.", 22 | "mcwifipnp.gui.PvP": "PvP", 23 | "mcwifipnp.gui.PvP.info": "Переключаетель урона между игроки, а также возможности вам получать урон от ваших собственных снарядов.", 24 | "mcwifipnp.gui.UseUPnP": "Переадресация порта", 25 | "mcwifipnp.gui.UseUPnP.info": "Следует ли использовать функцию UPnP для сопоставления номера игрового порта локальной сети.", 26 | "mcwifipnp.gui.localIP": "Локальный %s", 27 | "mcwifipnp.gui.globalIP": "Глобалный %s", 28 | "mcwifipnp.gui.CopyIP": "Получить IP", 29 | "mcwifipnp.gui.CopyIP.info": "Получить IP для копирования в буфер обмена", 30 | "mcwifipnp.gui.removePlayerReportingButton": "Заменить Жалобы Кнопка", 31 | "mcwifipnp.upnp.success": "Порт %s успешно переадресован", 32 | "mcwifipnp.upnp.clipboard": "Успешно получен %s, из-за таких факторов, как NAT, эти IP-адреса, возможно, по-прежнему не смогут подключиться напрямую.", 33 | "mcwifipnp.upnp.cantgetip": "Не удалось получить публичный IP! Пожалуйста, проверьте настройки вашей сети. Возможно, ваш IPv4 содержит несколько NAT-адресов или у вас нет IPv6.", 34 | "mcwifipnp.upnp.failed.mapped": "Не удаётся переадресовать порт %s: порт уже был сопоставлен другой службой UPnP. Пожалуйста, измените номер порта.", 35 | "mcwifipnp.upnp.failed.disabled": "Не удаётся переадресовать порт %s: UPnP на вашем маршрутизаторе не включен. Возможно, вам потребуется использовать программное обеспечение для сопоставления портов.", 36 | "mcwifipnp.upnp.failed.unknownerror": "Не удаётся переадресовать порт %s: неизвестная ошибка при добавлении сопоставления портов. Пожалуйста, используйте программное обеспечение для сопоставления портов.", 37 | "mcwifipnp.upnp.failed": "Не удаётся переадресовать порт %s!", 38 | "mcwifipnp.commands.uuidfixer.name": "исправитель UUID", 39 | "mcwifipnp.commands.uuidfixer.policy.online": "онлайн", 40 | "mcwifipnp.commands.uuidfixer.policy.offline": "автономная", 41 | "mcwifipnp.commands.uuidfixer.policy.invalid": "недействительна", 42 | "mcwifipnp.commands.uuidfixer.default.show": "Политика исправителя UUID по умолчанию: %s.", 43 | "mcwifipnp.commands.uuidfixer.default.set": "Политика исправителя UUID по умолчанию установлена на: %s.", 44 | "mcwifipnp.commands.uuidfixer.set.success": "Для %s политика исправителя UUID установлена на: %s.", 45 | "mcwifipnp.commands.uuidfixer.set.override": "Переопределение UUID %s на %s.", 46 | "mcwifipnp.commands.uuidfixer.set.bad-policy": "Недопустимая политика: %s, должна быть онлайн, автономная или иметь действительный UUID.", 47 | "mcwifipnp.commands.uuidfixer.list": "В списке политик исправителя UUID есть правила %s:", 48 | "mcwifipnp.commands.uuidfixer.none": "Список политик исправителя UUID пуст.", 49 | "mcwifipnp.commands.uuidfixer.policy.not-exist": "%s отсутствует в списке политик исправителя UUID!", 50 | "mcwifipnp.commands.uuidfixer.remove.success": "%s удалена из списка политик исправителя UUID." 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/dosse/upnp/GatewayFinder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Federico Dossena (adolfintel.com). 3 | * 4 | * This library is free software; you can redistribute it and/or 5 | * modify it under the terms of the GNU Lesser General Public 6 | * License as published by the Free Software Foundation; either 7 | * version 2.1 of the License, or (at your option) any later version. 8 | * 9 | * This library is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | * Lesser General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU Lesser General Public 15 | * License along with this library; if not, write to the Free Software 16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 17 | * MA 02110-1301 USA 18 | */ 19 | package com.dosse.upnp; 20 | 21 | import static java.nio.charset.StandardCharsets.UTF_8; 22 | 23 | import java.io.IOException; 24 | import java.net.DatagramPacket; 25 | import java.net.DatagramSocket; 26 | import java.net.Inet4Address; 27 | import java.net.InetAddress; 28 | import java.net.InetSocketAddress; 29 | import java.net.NetworkInterface; 30 | import java.net.SocketTimeoutException; 31 | import java.util.Enumeration; 32 | import java.util.LinkedList; 33 | 34 | /** 35 | * 36 | * @author Federico 37 | */ 38 | abstract class GatewayFinder { 39 | 40 | private static final String[] SEARCH_MESSAGES; 41 | 42 | static { 43 | LinkedList m = new LinkedList<>(); 44 | for (String type : new String[]{"urn:schemas-upnp-org:device:InternetGatewayDevice:1", "urn:schemas-upnp-org:service:WANIPConnection:1", "urn:schemas-upnp-org:service:WANPPPConnection:1"}) { 45 | m.add("M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nST: " + type + "\r\nMAN: \"ssdp:discover\"\r\nMX: 2\r\n\r\n"); 46 | } 47 | SEARCH_MESSAGES = m.toArray(new String[]{}); 48 | } 49 | 50 | private class GatewayListener extends Thread { 51 | 52 | private final Inet4Address ip; 53 | private final String req; 54 | 55 | public GatewayListener(Inet4Address ip, String req) { 56 | setName("WaifUPnP - Gateway Listener"); 57 | this.ip = ip; 58 | this.req = req; 59 | } 60 | 61 | @Override 62 | public void run() { 63 | byte[] req = this.req.getBytes(UTF_8); 64 | try (DatagramSocket s = new DatagramSocket(new InetSocketAddress(ip, 0))) { 65 | s.send(new DatagramPacket(req, req.length, new InetSocketAddress("239.255.255.250", 1900))); 66 | s.setSoTimeout(3000); 67 | for (; ; ) { 68 | try { 69 | DatagramPacket recv = new DatagramPacket(new byte[1536], 1536); 70 | s.receive(recv); 71 | Gateway gw = new Gateway(recv.getData(), ip, recv.getAddress()); 72 | String extIp = gw.getExternalIP(); 73 | if (isPublic(extIp)) { //Exclude gateways without a public external IP 74 | gatewayFound(gw); 75 | } 76 | } catch (SocketTimeoutException t) { 77 | break; 78 | } catch (Throwable t) { 79 | } 80 | } 81 | } catch (IOException e) { 82 | } 83 | } 84 | } 85 | 86 | private final LinkedList listeners = new LinkedList<>(); 87 | 88 | public GatewayFinder() { 89 | for (Inet4Address ip : getLocalIPs()) { 90 | for (String req : SEARCH_MESSAGES) { 91 | GatewayListener l = new GatewayListener(ip, req); 92 | l.start(); 93 | listeners.add(l); 94 | } 95 | } 96 | } 97 | 98 | public boolean isSearching() { 99 | for (GatewayListener l : listeners) { 100 | if (l.isAlive()) { 101 | return true; 102 | } 103 | } 104 | return false; 105 | } 106 | 107 | public abstract void gatewayFound(Gateway g); 108 | 109 | private static Inet4Address[] getLocalIPs() { 110 | LinkedList ret = new LinkedList<>(); 111 | try { 112 | Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); 113 | while (ifaces.hasMoreElements()) { 114 | try { 115 | NetworkInterface iface = ifaces.nextElement(); 116 | if (!iface.isUp() || iface.isLoopback() || iface.isVirtual() || iface.isPointToPoint()) { 117 | continue; 118 | } 119 | Enumeration addrs = iface.getInetAddresses(); 120 | if (!addrs.hasMoreElements()) { 121 | continue; 122 | } 123 | while (addrs.hasMoreElements()) { 124 | InetAddress addr = addrs.nextElement(); 125 | if (addr instanceof Inet4Address) { 126 | ret.add((Inet4Address) addr); 127 | } 128 | } 129 | } catch (Throwable t) { 130 | } 131 | } 132 | } catch (Throwable t) { 133 | } 134 | return ret.toArray(new Inet4Address[]{}); 135 | } 136 | 137 | private boolean isPublic(String ipAddress) { 138 | if (ipAddress == null) { 139 | return false; 140 | } 141 | if (ipAddress.equalsIgnoreCase("0.0.0.0")) { 142 | return false; 143 | } 144 | if (ipAddress.startsWith("192.168.")) { 145 | return false; 146 | } 147 | if (ipAddress.startsWith("10.")) { 148 | return false; 149 | } 150 | if (ipAddress.startsWith("172.")) { 151 | if (ipAddress.substring(4, 7).contains(".")) { 152 | return true; 153 | } 154 | final Integer bNet = Integer.getInteger(ipAddress.substring(4, 6)); 155 | return bNet < 16 || bNet > 31; 156 | } 157 | return true; 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /src/main/java/io/github/satxm/mcwifipnp/client/EditBoxEx.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp.client; 2 | 3 | import java.util.function.BiConsumer; 4 | import java.util.function.Function; 5 | import java.util.function.Predicate; 6 | 7 | import net.minecraft.client.gui.Font; 8 | import net.minecraft.client.gui.components.EditBox; 9 | import net.minecraft.client.gui.components.Tooltip; 10 | import net.minecraft.network.chat.Component; 11 | 12 | public class EditBoxEx extends EditBox { 13 | public final static int TEXT_COLOR_HINT = 0xFF707070; 14 | public final static int TEXT_COLOR_NORMAL = 0xFFE0E0E0; 15 | public final static int TEXT_COLOR_WARN = 0xFFFF5555; 16 | public final static int TEXT_COLOR_ERROR = 0xFFFF5555; 17 | 18 | protected T defaultValue; 19 | protected ValidatorResult defaultState; 20 | protected Function valueToStringMap; 21 | protected Function stringToValueMap; 22 | protected BiConsumer responder; 23 | 24 | /** 25 | * Return null to indicate ok and the tooltip specified in the defaultState will 26 | * be used. 27 | * To specify tooltip and text color, return a new custom ValidatorResult(). 28 | */ 29 | protected Function validator; 30 | protected ValidatorResult validatorFailedState; 31 | 32 | public EditBoxEx(Font font, int x, int y, int width, int height, Component name) { 33 | super(font, x, y, width, height, name); 34 | } 35 | 36 | public void onTextChanged(String newText) { 37 | T newValue; 38 | ValidatorResult newState; 39 | 40 | if (newText.isBlank()) { 41 | newValue = this.defaultValue; 42 | newState = this.defaultState; 43 | } else { 44 | newValue = null; 45 | newState = this.validatorFailedState; 46 | try { 47 | newValue = this.stringToValueMap.apply(newText); 48 | if (this.defaultValue.equals(newValue)) { 49 | newState = this.defaultState; 50 | } else { 51 | newState = this.validator.apply(newValue); 52 | 53 | if (newState == null) { 54 | newState = ValidatorResult.normal(this.defaultState.toolTip()); 55 | } 56 | } 57 | } catch (Exception e) { 58 | 59 | } 60 | } 61 | 62 | this.setTextColor(newState.textColor()); 63 | this.setTooltip(newState.toolTip()); 64 | 65 | this.responder.accept(newState, newState == this.validatorFailedState ? null : newValue); 66 | } 67 | 68 | @Override 69 | public void setFocused(boolean newValue) { 70 | super.setFocused(newValue); 71 | 72 | if (!newValue && this.getValue().isBlank()) { 73 | this.setValue(this.valueToStringMap.apply(this.defaultValue)); 74 | } 75 | } 76 | 77 | public static record ValidatorResult(int textColor, Tooltip toolTip, boolean valid, boolean updateBackendValue) { 78 | public static ValidatorResult normal(Tooltip toolTip) { 79 | return new ValidatorResult(TEXT_COLOR_NORMAL, toolTip, true, true); 80 | } 81 | } 82 | 83 | // Builder functions start 84 | public static EditBoxEx numerical(Font font, int x, int y, int width, int height, Component name) { 85 | EditBoxEx instance = new EditBoxEx(font, x, y, width, height, name); 86 | instance.valueToStringMap = (i) -> Integer.toString(i); 87 | instance.stringToValueMap = Integer::parseInt; 88 | return instance; 89 | } 90 | 91 | public static EditBoxEx text(Font font, int x, int y, int width, int height, Component name) { 92 | EditBoxEx instance = new EditBoxEx(font, x, y, width, height, name); 93 | instance.valueToStringMap = Function.identity(); 94 | instance.stringToValueMap = Function.identity(); 95 | return instance; 96 | } 97 | 98 | public EditBoxEx defaults(T defaultValue, int textColor, Tooltip toolTip) { 99 | this.defaultValue = defaultValue; 100 | this.defaultState = new ValidatorResult(textColor, toolTip, true, true); 101 | this.setValue(this.valueToStringMap.apply(defaultValue)); 102 | this.setTextColor(this.defaultState.textColor()); 103 | this.setTooltip(this.defaultState.toolTip()); 104 | return this; 105 | } 106 | 107 | public EditBoxEx invalid(int textColor, Tooltip toolTip) { 108 | this.validatorFailedState = new ValidatorResult(textColor, toolTip, false, false); 109 | return this; 110 | } 111 | 112 | public EditBoxEx validator(Function validator) { 113 | this.validator = validator; 114 | return this; 115 | } 116 | 117 | /** 118 | * Use a validator that returns a boolean so that one doesn't need to call 119 | * defaults(), invalid(), and validator() individually. 120 | * 121 | * @param defaultValue 122 | * @param toolTip this tooltip will always be displayed. 123 | * @param validator 124 | * @return 125 | */ 126 | public EditBoxEx bistate(T defaultValue, Tooltip toolTip, Predicate validator) { 127 | this.defaults(defaultValue, TEXT_COLOR_HINT, toolTip); 128 | this.invalid(TEXT_COLOR_ERROR, toolTip); 129 | this.validator((t) -> { 130 | return validator.test(t) ? new ValidatorResult(TEXT_COLOR_NORMAL, toolTip, true, true) 131 | : this.validatorFailedState; 132 | }); 133 | return this; 134 | } 135 | 136 | public EditBoxEx maxLength(int len) { 137 | this.setMaxLength(len); 138 | return this; 139 | } 140 | 141 | public EditBoxEx responder(BiConsumer responder) { 142 | this.responder = responder; 143 | this.setResponder(this::onTextChanged); 144 | return this; 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [__中文__![zh-cn](https://img.shields.io/badge/lang-zh--cn-green.svg)](README.zh-CN.md) 2 | 3 | # LAN World Plug-n-Play 4 | 5 |
6 | 7 | [![1][1]][2] [![3][3]][4] [![5][5]][6] [![7][7]][8] 8 | 9 |
10 | 11 | [1]: https://img.shields.io/modrinth/dt/RTWpcTBp?label=Modrinth%0aDownloads&logo=modrinth&style=flat&color=45A35F&labelcolor=2D2D2D 12 | [2]: https://modrinth.com/mod/mcwifipnp 13 | 14 | [3]: https://img.shields.io/curseforge/dt/450250?label=CurseForge%0aDownloads&logo=curseforge&style=flat&color=E36639&labelcolor=2D2D2D 15 | [4]: https://www.curseforge.com/minecraft/mc-mods/mcwifipnp 16 | 17 | [5]: https://img.shields.io/badge/Available%20for-%201.15%20to%201.21-47376F?logo=files&color=377BCB&labelcolor=2D2D2D 18 | [6]: https://modrinth.com/mod/mcwifipnp/versions 19 | 20 | [7]: https://img.shields.io/github/license/Satxm/mcwifipnp?label=License&logo=github&style=flat&color=E51050&labelcolor=2D2D2D 21 | [8]: https://github.com/satxm/mcwifipnp 22 | 23 | ## Dependencies 24 | 25 | **Fabric: [Fabric Loader](https://fabricmc.net/use/), [Fabric API](https://modrinth.com/mod/fabric-api)**. 26 | 27 | **Quilt: [Quilt Loader](https://quiltmc.org/install/), [QFAPI/QSL](https://modrinth.com/mod/qsl)**. 28 | 29 | **Forge: [Forge](https://files.minecraftforge.net/net/minecraftforge/forge/)**. 30 | 31 | **NeoForge: [NeoForge](https://projects.neoforged.net/neoforged/neoforge/)**. 32 | 33 | ## Download 34 | 35 | CurseForge : [https://www.curseforge.com/minecraft/mc-mods/mcwifipnp](https://www.curseforge.com/minecraft/mc-mods/mcwifipnp) 36 | 37 | Modrinth : [https://modrinth.com/mod/mcwifipnp](https://modrinth.com/mod/mcwifipnp) 38 | 39 | MC百科 : [https://www.mcmod.cn/class/4498.html](https://www.mcmod.cn/class/4498.html) 40 | 41 | GitHub : [https://github.com/Satxm/mcwifipnp](https://github.com/Satxm/mcwifipnp) 42 | 43 | ## Introduction 44 | 45 | **This Branch is for Minecraft [1.21.9, 1.22)!** 46 | 47 | Uses the vanilla Minecraft GUI style, Uses the official mojang mappings. 48 | 49 | * Modified from [TheGlitch76/mcpnp](https://github.com/TheGlitch76/mcpnp) 50 | * UPnP module from [adolfintel/WaifUPnP](https://github.com/adolfintel/WaifUPnP) & [RetGal/WaifUPnP](https://github.com/RetGal/WaifUPnP). 51 | * `Online Mode` and `UUID Fix` from[Rikka0w0/LanServerProperties](https://github.com/rikka0w0/LanServerProperties). 52 | 53 | ## Screenshots 54 | 55 |
56 | 57 | ![GUI ZH-CN](https://cdn.modrinth.com/data/cached_images/f0cc15cbe6b9f9e45736b12c036f2c28c2f4f9a0.jpeg) 58 | 59 |
60 | 61 | ## Usage 62 | 63 | 1. The `Online Mode` button has three options: 64 | - `Enable`: verify login information against the Mojang server database, only allow players with genuine Microsoft account to join. 65 | - `Disable`: no verification, allows anyone, including offline players to join. 66 | - `Disable + UUID Fixer`: Similar to above, enables the UUID Fixer. The default behavior of UUID Fixer is that, if a player has his name on the Mojang server, the official unique UUID will be used, just like in the "Online Mode". Exceptions can be added using the `/uuidfixer force` command. This mode can be useful to preserve backpacks and inventories when switching from "Online Mode" to "Offline Mode". 67 | - The corresponding commands are `/onlinemode` and `/uuidfixer enabled`. 68 | 69 | 2. The command `/uuidfixer` controls how usernames are mapped to UUIDs in the `Disable + UUID Fixer` mode. 70 | - command `/uuidfixer enabled` toggles the UUID fixer on and off. 71 | - command `/uuidfixer list` lists all mapping rules. 72 | - command `/uuidfixer force` adds a new rule or update an existing rule. 73 | - command `/uuidfixer remove` removes an existing rule. 74 | - command `/uuidfixer test` allows you to check the policy applied to a username. 75 | 76 | 3. Allows you to change server's port number and you can choose whether to map this port to the public network using UPnP (if your router supports UPnP). 77 | Use the GUI button or the `/upnp` command to toggle UPnP support on and off. 78 | 79 | 4. Allows you to enable or disable pvp. 80 | 81 | 5. Allows you to change server motd (The message displayed below the server name in the server list). 82 | 83 | 6. Allows you control other players' permissions when they join your world. Use `/op` and `/deop` commands to manipulate the OP list. You can also use command `/whitelist` to build a whitelist and use it to control players who can join your world. 84 | 85 | 7. You can use command `/ban` to blacklist players. Use command `/ban-ip` to add IP addresses to the blacklist. Use command `/banlist` to list blacklisted players. Use command `/pardon` to remove players from the blacklist, use command `/pardon-ip` to remove IP addresses from the blacklist 86 | 87 | 8. Your settings will be recorded in a file, and it will be automatically loaded next time. 88 | 89 | 9. This mod can get your IP address, and you can choose whether to copy the IP address (such as local IPv4, globe IPv4 or IPv6) to the clipboard. in order to provide the IP address to your friends. The command `/ip` can retrieve more IP information. 90 | 91 | 10. You can change most of the above settings once the server starts, but some options are only applied to newly joined players. 92 | 93 | 11. You can also go back to the vanilla `Open to Lan` screen by clicking in the button on the bottom-left corner. 94 | 95 | 12. When installed to a dedicated server, only the `UUID Fixer` function is available. It can only be enabled if `uuid_fixer.json` exists in the root server folder. The `/uuidfixer` command is available on the dedicated server side. This mod does nothing otherwise. 96 | 97 | ## For Developers 98 | ### Compile Fabric Artifacts 99 | ``` 100 | git clone git@github.com:Satxm/mcwifipnp.git 101 | cd mcwifipnp 102 | .\gradlew.bat :fabric:runClient 103 | ``` 104 | Replace `fabric` with `forge`, `neoforge`, or `quilt` to build the corresponding artifacts. 105 | 106 | ### Eclipse 107 | Import the root folder as a gradle project in Eclipse to start the development. 108 | You may want to disable some targets in `settings.gradle` to speed up the initial porting/development. 109 | -------------------------------------------------------------------------------- /src/main/java/io/github/satxm/mcwifipnp/Config.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp; 2 | 3 | import java.io.IOException; 4 | import java.lang.reflect.Type; 5 | import java.nio.charset.StandardCharsets; 6 | import java.nio.file.Files; 7 | import java.nio.file.Path; 8 | import java.nio.file.StandardOpenOption; 9 | 10 | import org.apache.logging.log4j.Logger; 11 | 12 | import com.google.gson.Gson; 13 | import com.google.gson.GsonBuilder; 14 | import com.google.gson.JsonDeserializationContext; 15 | import com.google.gson.JsonDeserializer; 16 | import com.google.gson.JsonElement; 17 | import com.google.gson.JsonParseException; 18 | import com.google.gson.JsonPrimitive; 19 | import com.google.gson.JsonSerializationContext; 20 | import com.google.gson.JsonSerializer; 21 | import com.google.gson.annotations.SerializedName; 22 | 23 | import net.minecraft.network.chat.Component; 24 | import net.minecraft.server.MinecraftServer; 25 | import net.minecraft.server.players.PlayerList; 26 | import net.minecraft.world.level.GameRules; 27 | import net.minecraft.world.level.GameType; 28 | import net.minecraft.world.level.storage.LevelResource; 29 | 30 | public class Config { 31 | // These fields require special handling and consideration 32 | public int port = 25565; 33 | 34 | @SerializedName(value = "allow-host-cheat", alternate = { "AllowCommands" }) 35 | public boolean allowHostCheat = false; 36 | 37 | // These fields are read, synced, and save as normal 38 | @SerializedName(value = "max-players", alternate = { "maxPlayers" }) 39 | public int maxPlayers = 8; 40 | 41 | @SerializedName(value = "gamemode", alternate = { "GameMode" }) 42 | public GameType gameType = GameType.SURVIVAL; 43 | 44 | public String motd = Component.translatable("lanServer.title").getString(); 45 | 46 | @SerializedName(value = "allow-everyone-cheat", alternate = { "AllPlayersCheats" }) 47 | public boolean allowEveryoneCheat = false; 48 | 49 | @SerializedName(value = "enforce-whitelist", alternate = { "Whitelist" }) 50 | public boolean enforceWhitelist = false; 51 | 52 | @SerializedName(value = "enable-upnp", alternate = { "UseUPnP" }) 53 | public boolean useUPnP = true; 54 | 55 | @SerializedName(value = "online-mode", alternate = { "OnlineMode" }) 56 | public boolean onlineMode = true; 57 | 58 | @SerializedName(value = "enable-uuid-fixer", alternate = { "EnableUUIDFixer" }) 59 | public boolean enableUUIDFixer = false; 60 | 61 | @SerializedName(value = "pvp", alternate = { "PvP" }) 62 | public boolean enablePvP = true; 63 | 64 | @SerializedName(value = "get-public-ip", alternate = { "CopyToClipboard" }) 65 | public boolean getPublicIP = true; 66 | 67 | @SerializedName(value = "remove-player-reporting", alternate = { "removePlayerReportingButton" }) 68 | public boolean removePlayerReportingButton = false; 69 | 70 | // These fields will not be serialized 71 | public transient Path location; 72 | public transient final boolean usingDefaults; 73 | 74 | public static transient final Logger LOGGER = MCWiFiPnPUnit.LOGGER; 75 | public static transient final Gson GSON = new GsonBuilder() 76 | .registerTypeAdapter(GameType.class, new EnumLowerCaseAdapter<>()).setPrettyPrinting().create(); 77 | 78 | /* 79 | * This constructor exists to be used by GSON 80 | */ 81 | private Config() { 82 | this(false); 83 | } 84 | 85 | private Config(boolean usingDefaults) { 86 | this.usingDefaults = usingDefaults; 87 | } 88 | 89 | public static Path getConfigPath(MinecraftServer server) { 90 | return server.getWorldPath(LevelResource.ROOT).resolve("mcwifipnp.json"); 91 | } 92 | 93 | /** 94 | * @param server the server instance used to get the root map path 95 | * @return the latest config instance read from the path 96 | */ 97 | public static Config read(MinecraftServer server) { 98 | return read(getConfigPath(server)); 99 | } 100 | 101 | public static Config readFromPublishedServer(MinecraftServer server) { 102 | Config cfg = read(getConfigPath(server)); 103 | if (server.isPublished()) 104 | cfg.readFromRunningServer(server); 105 | 106 | return cfg; 107 | } 108 | 109 | public static Config read(Path location) { 110 | Config cfg; 111 | 112 | try { 113 | cfg = GSON.fromJson(new String(Files.readAllBytes(location), StandardCharsets.UTF_8), Config.class); 114 | cfg.location = location; 115 | } catch (IOException | JsonParseException e) { 116 | try { 117 | Files.deleteIfExists(location); 118 | } catch (IOException ie) { 119 | LOGGER.warn("Unable to read config file!", ie); 120 | } 121 | cfg = new Config(true); 122 | cfg.location = location; 123 | } 124 | 125 | return cfg; 126 | } 127 | 128 | public void save() { 129 | try { 130 | Files.write(this.location, GSON.toJson(this).getBytes(StandardCharsets.UTF_8), StandardOpenOption.TRUNCATE_EXISTING, 131 | StandardOpenOption.CREATE); 132 | } catch (IOException e) { 133 | LOGGER.warn("Unable to write config file!", e); 134 | } 135 | } 136 | 137 | public void saveAndApply(MinecraftServer server) { 138 | if (server.isPublished()) 139 | this.applyTo(server); 140 | this.save(); 141 | } 142 | 143 | private static class EnumLowerCaseAdapter> implements JsonSerializer, JsonDeserializer { 144 | @Override 145 | public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context) { 146 | return new JsonPrimitive(src.name().toLowerCase()); 147 | } 148 | 149 | @SuppressWarnings("unchecked") 150 | @Override 151 | public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) 152 | throws JsonParseException { 153 | return Enum.valueOf((Class) typeOfT, json.getAsString().toUpperCase()); 154 | } 155 | } 156 | 157 | public void readFromRunningServer(MinecraftServer server) { 158 | PlayerList playerList = server.getPlayerList(); 159 | 160 | this.port = server.getPort(); 161 | 162 | this.allowEveryoneCheat = playerList.isAllowCommandsForAllPlayers(); 163 | this.gameType = server.getDefaultGameType(); 164 | 165 | this.maxPlayers = playerList.getMaxPlayers(); 166 | this.onlineMode = server.usesAuthentication(); 167 | this.enablePvP = server.isPvpAllowed(); 168 | this.enforceWhitelist = server.isEnforceWhitelist(); 169 | 170 | this.motd = server.getMotd(); 171 | this.enableUUIDFixer = UUIDFixer.enabled; 172 | } 173 | 174 | public void applyTo(MinecraftServer server) { 175 | PlayerList playerList = server.getPlayerList(); 176 | server.setDefaultGameType(this.gameType); 177 | playerList.setAllowCommandsForAllPlayers(this.allowEveryoneCheat); 178 | 179 | server.setUsesAuthentication(this.onlineMode); 180 | server.getGameRules().getRule(GameRules.RULE_PVP).set(this.enablePvP, server); 181 | server.setEnforceWhitelist(this.enforceWhitelist); 182 | server.setUsingWhitelist(this.enforceWhitelist); 183 | 184 | server.setMotd(this.motd); 185 | UUIDFixer.enabled = this.enableUUIDFixer; 186 | ReadListFile.ReadListFile(server); 187 | } 188 | 189 | } 190 | -------------------------------------------------------------------------------- /src/main/java/io/github/satxm/mcwifipnp/UUIDFixer.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp; 2 | 3 | import java.io.FileReader; 4 | import java.io.IOException; 5 | import java.net.URI; 6 | import java.nio.charset.Charset; 7 | import java.nio.file.Files; 8 | import java.nio.file.Path; 9 | import java.nio.file.StandardOpenOption; 10 | import java.util.Iterator; 11 | import java.util.Map; 12 | import java.util.Set; 13 | import java.util.TreeSet; 14 | import java.util.UUID; 15 | 16 | import javax.annotation.Nullable; 17 | 18 | import org.apache.commons.io.IOUtils; 19 | import org.apache.logging.log4j.LogManager; 20 | import org.apache.logging.log4j.Logger; 21 | 22 | import com.google.gson.Gson; 23 | import com.google.gson.GsonBuilder; 24 | import com.google.gson.JsonElement; 25 | import com.google.gson.JsonObject; 26 | import com.google.gson.JsonParser; 27 | import com.google.gson.JsonSyntaxException; 28 | 29 | public class UUIDFixer { 30 | private static final Logger LOGGER = LogManager.getLogger(UUIDFixer.class); 31 | 32 | public static boolean enabled = false; 33 | 34 | public static class PolicyHolder { 35 | private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); 36 | private static final String UUID_MAP_FILE = "uuid_fixer.json"; 37 | private static final String POLICY_ONLINE = "online"; 38 | private static final String POLICY_OFFLINE = "offline"; 39 | 40 | public final Path location; 41 | 42 | private final JsonObject rootNode; 43 | 44 | public PolicyHolder() { 45 | this(Path.of(UUID_MAP_FILE)); 46 | } 47 | 48 | public PolicyHolder(Path filePath) { 49 | this.location = filePath; 50 | 51 | JsonObject rootNode = null; 52 | try (FileReader reader = new FileReader(filePath.toFile())) { 53 | rootNode = JsonParser.parseReader(reader).getAsJsonObject(); 54 | } catch (IOException e) { 55 | rootNode = new JsonObject(); 56 | } 57 | this.rootNode = rootNode; 58 | } 59 | 60 | public boolean isOnlineByDefault() { 61 | return !POLICY_OFFLINE.equalsIgnoreCase(this.getOrNull("*")); 62 | } 63 | 64 | public void setDefaultPolicy(boolean defaultIsOnline) { 65 | this.set("*", defaultIsOnline ? POLICY_ONLINE : POLICY_OFFLINE); 66 | } 67 | 68 | public Set getUsers() { 69 | Set users = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); 70 | 71 | for (Map.Entry entry : this.rootNode.entrySet()) { 72 | String key = entry.getKey(); 73 | if (!"*".equals(key)) 74 | users.add(key); 75 | } 76 | 77 | return users; 78 | } 79 | 80 | public static boolean isUUID(String policy) { 81 | try { 82 | UUID.fromString(policy); 83 | return true; 84 | } catch (Exception e) { 85 | return false; 86 | } 87 | } 88 | 89 | public static boolean isOnlinePolicy(String policy) { 90 | return POLICY_ONLINE.equalsIgnoreCase(policy); 91 | } 92 | 93 | public static boolean isOfflinePolicy(String policy) { 94 | return POLICY_OFFLINE.equalsIgnoreCase(policy); 95 | } 96 | 97 | public static boolean isValidPolicy(String policy) { 98 | if (isOnlinePolicy(policy)) 99 | return true; 100 | if (isOfflinePolicy(policy)) 101 | return true; 102 | 103 | return isUUID(policy); 104 | } 105 | 106 | public int count() { 107 | int count = 0; 108 | for (Map.Entry entry : this.rootNode.entrySet()) { 109 | try { 110 | String policy = entry.getValue().getAsString(); 111 | if (isValidPolicy(policy)) 112 | count++; 113 | } catch (Exception e) {} 114 | } 115 | return count; 116 | } 117 | 118 | public void set(String key, String value) { 119 | this.remove(key); 120 | this.rootNode.addProperty(key, value); 121 | } 122 | 123 | /** 124 | * @param parent the root Json node 125 | * @param key a case-insensitive key, can be * or the player name 126 | * @return policy string, uuid string, or null if not specified 127 | */ 128 | public String getOrNull(String key) { 129 | for (Map.Entry entry : this.rootNode.entrySet()) { 130 | if (entry.getKey().equalsIgnoreCase(key)) { 131 | try { 132 | return entry.getValue().getAsString(); 133 | } catch (Exception e) { 134 | return null; 135 | } 136 | } 137 | } 138 | 139 | return null; 140 | } 141 | 142 | public boolean remove(String playerName) { 143 | boolean removed = false; 144 | 145 | Iterator> iterator = this.rootNode.entrySet().iterator(); 146 | while (iterator.hasNext()) { 147 | Map.Entry entry = iterator.next(); 148 | if (entry.getKey().equalsIgnoreCase(playerName)) { 149 | iterator.remove(); 150 | removed = true; 151 | } 152 | } 153 | 154 | return removed; 155 | } 156 | 157 | @Nullable 158 | public UUID uuidOf(String playerName) { 159 | String policy = this.getOrNull(playerName); 160 | 161 | if (policy == null) { 162 | policy = this.isOnlineByDefault() ? POLICY_ONLINE : POLICY_OFFLINE; 163 | } 164 | 165 | LOGGER.info("Policy of " + playerName + " is: " + policy); 166 | 167 | if (POLICY_OFFLINE.equalsIgnoreCase(policy)) 168 | return null; // The policy specify a user as offline 169 | 170 | try { 171 | // Use the specified UUID as override 172 | return UUID.fromString(policy); 173 | } catch (IllegalArgumentException e) { 174 | return getOfficialUUID(playerName); 175 | } 176 | } 177 | 178 | public void save() { 179 | try { 180 | String json = GSON.toJson(this.rootNode); 181 | Files.write(this.location, json.getBytes("utf-8"), StandardOpenOption.TRUNCATE_EXISTING, 182 | StandardOpenOption.CREATE); 183 | } catch (IOException e) { 184 | LOGGER.warn("Unable to write config file!", e); 185 | } 186 | } 187 | } 188 | 189 | /** 190 | * Mixin/ Coremod callback 191 | * Return non-null to override, null to use vanilla offline UUID. 192 | */ 193 | public static UUID hookEntry(String playerName) { 194 | if (!enabled) 195 | return null; 196 | 197 | return new PolicyHolder().uuidOf(playerName); 198 | } 199 | 200 | @Nullable 201 | public static UUID getOfficialUUID(String playerName) { 202 | String url = "https://api.mojang.com/users/profiles/minecraft/" + playerName; 203 | try { 204 | String UUIDJson = IOUtils.toString(URI.create(url), Charset.defaultCharset()); 205 | if (!UUIDJson.isEmpty()) { 206 | JsonObject root = JsonParser.parseString(UUIDJson).getAsJsonObject(); 207 | String playerName2 = root.getAsJsonPrimitive("name").getAsString(); 208 | String uuidString = root.getAsJsonPrimitive("id").getAsString(); 209 | // com.mojang.util.UUIDTypeAdapter.fromString(String) 210 | long uuidMSB = Long.parseLong(uuidString.substring(0, 8), 16); 211 | uuidMSB <<= 32; 212 | uuidMSB |= Long.parseLong(uuidString.substring(8, 16), 16); 213 | long uuidLSB = Long.parseLong(uuidString.substring(16, 24), 16); 214 | uuidLSB <<= 32; 215 | uuidLSB |= Long.parseLong(uuidString.substring(24, 32), 16); 216 | UUID uuid = new UUID(uuidMSB, uuidLSB); 217 | 218 | if (playerName2.equalsIgnoreCase(playerName)) 219 | return uuid; 220 | } 221 | } catch (IOException | JsonSyntaxException e) { 222 | e.printStackTrace(); 223 | } 224 | 225 | return null; 226 | } 227 | } -------------------------------------------------------------------------------- /src/main/java/com/dosse/upnp/UPnP.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Federico Dossena (adolfintel.com). 3 | * 4 | * This library is free software; you can redistribute it and/or 5 | * modify it under the terms of the GNU Lesser General Public 6 | * License as published by the Free Software Foundation; either 7 | * version 2.1 of the License, or (at your option) any later version. 8 | * 9 | * This library is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | * Lesser General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU Lesser General Public 15 | * License along with this library; if not, write to the Free Software 16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 17 | * MA 02110-1301 USA 18 | */ 19 | package com.dosse.upnp; 20 | 21 | /** 22 | * This class contains static methods that allow quick access to UPnP Port Mapping.
23 | * Commands will be sent to the default gateway. 24 | * 25 | * @author Federico 26 | */ 27 | public class UPnP { 28 | 29 | private static Gateway defaultGW = null; 30 | private static final String DEFAULT_APP_NAME = "WaifUPnP"; 31 | private static final GatewayFinder finder = new GatewayFinder() { 32 | @Override 33 | public void gatewayFound(Gateway g) { 34 | synchronized (finder) { 35 | if (defaultGW == null) { 36 | defaultGW = g; 37 | } 38 | } 39 | } 40 | }; 41 | 42 | /** 43 | * Waits for UPnP to be initialized (takes ~3 seconds).
44 | * It is not necessary to call this method manually before using UPnP functions 45 | */ 46 | public static void waitInit() { 47 | while (finder.isSearching()) { 48 | try { 49 | Thread.sleep(1); 50 | } catch (InterruptedException ex) { 51 | } 52 | } 53 | } 54 | 55 | /** 56 | * Is there an UPnP gateway?
57 | * This method is blocking if UPnP is still initializing
58 | * All UPnP commands will fail if UPnP is not available 59 | * 60 | * @return true if available, false if not 61 | */ 62 | public static boolean isUPnPAvailable(){ 63 | waitInit(); 64 | return defaultGW!=null; 65 | } 66 | 67 | /** 68 | * Opens a TCP port on the gateway 69 | * 70 | * @param port TCP port (0-65535) 71 | * @return true if the operation was successful, false otherwise 72 | */ 73 | public static boolean openPortTCP(int port) { 74 | return openPortTCP(port, DEFAULT_APP_NAME); 75 | } 76 | 77 | /** 78 | * Opens a TCP port on the gateway 79 | * 80 | * @param port TCP port (0-65535) 81 | * @param appName custom app name to be used for the rule 82 | * @return true if the operation was successful, false otherwise 83 | */ 84 | public static boolean openPortTCP(int port, String appName) { 85 | return openPortTCP(port, null, appName); 86 | } 87 | 88 | /** 89 | * Opens a TCP port on the gateway 90 | * 91 | * @param port TCP port (0-65535) 92 | * @param remoteHost IP address of remote host 93 | * @param appName custom app name to be used for the rule 94 | * @return true if the operation was successful, false otherwise 95 | */ 96 | public static boolean openPortTCP(int port, String remoteHost, String appName) { 97 | if(!isUPnPAvailable()) return false; 98 | return defaultGW.openPort(port, remoteHost, false, appName); 99 | } 100 | 101 | /** 102 | * Opens a UDP port on the gateway 103 | * 104 | * @param port UDP port (0-65535) 105 | * @return true if the operation was successful, false otherwise 106 | */ 107 | public static boolean openPortUDP(int port) { 108 | return openPortUDP(port, null, DEFAULT_APP_NAME); 109 | } 110 | 111 | /** 112 | * Opens a UDP port on the gateway 113 | * 114 | * @param port UDP port (0-65535) 115 | * @param appName custom app name to be used for the rule 116 | * @return true if the operation was successful, false otherwise 117 | */ 118 | public static boolean openPortUDP(int port, String appName) { 119 | return openPortUDP(port, null, appName); 120 | } 121 | 122 | /** 123 | * Opens a UDP port on the gateway 124 | * 125 | * @param port UDP port (0-65535) 126 | * @param remoteHost IP address of remote host 127 | * @param appName custom app name to be used for the rule 128 | * @return true if the operation was successful, false otherwise 129 | */ 130 | public static boolean openPortUDP(int port, String remoteHost, String appName) { 131 | if(!isUPnPAvailable()) return false; 132 | return defaultGW.openPort(port, remoteHost, true, appName); 133 | } 134 | 135 | /** 136 | * Closes a TCP port on the gateway
137 | * Most gateways seem to refuse to do this 138 | * 139 | * @param port TCP port (0-65535) 140 | * @return true if the operation was successful, false otherwise 141 | */ 142 | public static boolean closePortTCP(int port) { 143 | return closePortTCP(port, null); 144 | } 145 | 146 | /** 147 | * Closes a TCP port on the gateway
148 | * Most gateways seem to refuse to do this 149 | * 150 | * @param port TCP port (0-65535) 151 | * @param remoteHost IP address of remote host 152 | * @return true if the operation was successful, false otherwise 153 | */ 154 | public static boolean closePortTCP(int port, String remoteHost) { 155 | if(!isUPnPAvailable()) return false; 156 | return defaultGW.closePort(port, remoteHost, false); 157 | } 158 | 159 | /** 160 | * Closes a UDP port on the gateway
161 | * Most gateways seem to refuse to do this 162 | * 163 | * @param port UDP port (0-65535) 164 | * @return true if the operation was successful, false otherwise 165 | */ 166 | public static boolean closePortUDP(int port) { 167 | return closePortUDP(port, null); 168 | } 169 | 170 | /** 171 | * Closes a UDP port on the gateway
172 | * Most gateways seem to refuse to do this 173 | * 174 | * @param port UDP port (0-65535) 175 | * @param remoteHost IP address of remote host 176 | * @return true if the operation was successful, false otherwise 177 | */ 178 | public static boolean closePortUDP(int port, String remoteHost) { 179 | if(!isUPnPAvailable()) return false; 180 | return defaultGW.closePort(port, remoteHost, true); 181 | } 182 | 183 | /** 184 | * Checks if a TCP port is mapped
185 | * 186 | * @param port TCP port (0-65535) 187 | * @return true if the port is mapped, false otherwise 188 | */ 189 | public static boolean isMappedTCP(int port) { 190 | return isMappedTCP(port, null); 191 | } 192 | 193 | /** 194 | * Checks if a TCP port is mapped
195 | * 196 | * @param port TCP port (0-65535) 197 | * @param remoteHost IP address of remote host 198 | * @return true if the port is mapped, false otherwise 199 | */ 200 | public static boolean isMappedTCP(int port, String remoteHost) { 201 | if(!isUPnPAvailable()) return false; 202 | return defaultGW.isMapped(port, remoteHost, false); 203 | } 204 | 205 | /** 206 | * Checks if a UDP port is mapped
207 | * 208 | * @param port UDP port (0-65535) 209 | * @return true if the port is mapped, false otherwise 210 | */ 211 | public static boolean isMappedUDP(int port) { 212 | return isMappedUDP(port, null); 213 | } 214 | 215 | /** 216 | * Checks if a UDP port is mapped
217 | * 218 | * @param port UDP port (0-65535) 219 | * @param remoteHost IP address of remote host 220 | * @return true if the port is mapped, false otherwise 221 | */ 222 | public static boolean isMappedUDP(int port, String remoteHost) { 223 | if(!isUPnPAvailable()) return false; 224 | return defaultGW.isMapped(port, remoteHost, true); 225 | } 226 | 227 | /** 228 | * Gets the external IP address of the default gateway 229 | * 230 | * @return external IP address as string, or null if not available 231 | */ 232 | public static String getExternalIP(){ 233 | if(!isUPnPAvailable()) return null; 234 | return defaultGW.getExternalIP(); 235 | } 236 | 237 | /** 238 | * Gets the internal IP address of this machine 239 | * 240 | * @return internal IP address as string, or null if not available 241 | */ 242 | public static String getLocalIP(){ 243 | if(!isUPnPAvailable()) return null; 244 | return defaultGW.getLocalIP(); 245 | } 246 | 247 | /** 248 | * Gets the IP address of the router 249 | * 250 | * @return internal IP address as string, or null if not available 251 | */ 252 | public static String getDefaultGatewayIP(){ 253 | if(!isUPnPAvailable()) return null; 254 | return defaultGW.getGatewayIP(); 255 | } 256 | 257 | } 258 | -------------------------------------------------------------------------------- /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 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /src/main/java/com/dosse/upnp/Gateway.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Federico Dossena (adolfintel.com). 3 | * 4 | * This library is free software; you can redistribute it and/or 5 | * modify it under the terms of the GNU Lesser General Public 6 | * License as published by the Free Software Foundation; either 7 | * version 2.1 of the License, or (at your option) any later version. 8 | * 9 | * This library is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | * Lesser General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU Lesser General Public 15 | * License along with this library; if not, write to the Free Software 16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 17 | * MA 02110-1301 USA 18 | */ 19 | package com.dosse.upnp; 20 | 21 | import static java.nio.charset.StandardCharsets.UTF_8; 22 | 23 | import java.io.BufferedInputStream; 24 | import java.io.ByteArrayOutputStream; 25 | import java.io.IOException; 26 | import java.io.InputStream; 27 | import java.io.StringReader; 28 | import java.net.HttpURLConnection; 29 | import java.net.Inet4Address; 30 | import java.net.InetAddress; 31 | import java.net.URI; 32 | import java.util.HashMap; 33 | import java.util.Map; 34 | import java.util.StringTokenizer; 35 | 36 | import javax.xml.parsers.DocumentBuilderFactory; 37 | 38 | import org.w3c.dom.Document; 39 | import org.w3c.dom.Node; 40 | import org.w3c.dom.NodeList; 41 | import org.w3c.dom.traversal.DocumentTraversal; 42 | import org.w3c.dom.traversal.NodeFilter; 43 | import org.w3c.dom.traversal.NodeIterator; 44 | import org.xml.sax.InputSource; 45 | 46 | /** 47 | * 48 | * @author Federico 49 | */ 50 | class Gateway { 51 | 52 | private final Inet4Address iface; 53 | private final InetAddress routerip; 54 | 55 | private String serviceType = null, controlURL = null; 56 | 57 | public Gateway(byte[] data, Inet4Address ip, InetAddress gatewayip) throws Exception { 58 | iface = ip; 59 | routerip = gatewayip; 60 | String location = null; 61 | StringTokenizer st = new StringTokenizer(new String(data, UTF_8), "\n"); 62 | while (st.hasMoreTokens()) { 63 | String s = st.nextToken().trim(); 64 | if (s.isEmpty() || s.startsWith("HTTP/1.") || s.startsWith("NOTIFY *")) { 65 | continue; 66 | } 67 | String name = s.substring(0, s.indexOf(':')), val = s.substring(name.length() + 1).trim(); 68 | if (name.equalsIgnoreCase("location")) { 69 | location = val; 70 | } 71 | } 72 | if (location == null) { 73 | throw new Exception("Unsupported Gateway"); 74 | } 75 | // receiving xml file manually to the buffer 76 | byte[] xmlBytes = null; 77 | InputStream inputStream = null; 78 | ByteArrayOutputStream outputStream = null; 79 | try { 80 | inputStream = new BufferedInputStream(new URI(location).toURL().openConnection().getInputStream()); 81 | outputStream = new ByteArrayOutputStream(); 82 | byte[] buffer = new byte[1024]; 83 | int bytesRead; 84 | while ((bytesRead = inputStream.read(buffer)) != -1) { 85 | outputStream.write(buffer, 0, bytesRead); 86 | } 87 | xmlBytes = outputStream.toByteArray(); 88 | } catch (IOException e) { 89 | } finally { 90 | try { 91 | if (inputStream != null) { 92 | inputStream.close(); 93 | } 94 | } catch (IOException e) { 95 | } 96 | try { 97 | if (outputStream != null) { 98 | outputStream.close(); 99 | } 100 | } catch (IOException e) { 101 | } 102 | } 103 | if (xmlBytes == null) { 104 | throw new Exception("Unable to retrieve XML file " + location); 105 | } 106 | // in some XML files there may be NUL byte at the end of the file that cannot be parse, remove them 107 | String xmlString = new String(xmlBytes).replaceAll("\0", ""); 108 | Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(xmlString))); 109 | NodeList services = d.getElementsByTagName("service"); 110 | for (int i = 0; i < services.getLength(); i++) { 111 | Node service = services.item(i); 112 | NodeList n = service.getChildNodes(); 113 | String serviceType = null, controlURL = null; 114 | for (int j = 0; j < n.getLength(); j++) { 115 | Node x = n.item(j); 116 | if (x.getNodeName().trim().equalsIgnoreCase("serviceType")) { 117 | serviceType = x.getFirstChild().getNodeValue(); 118 | } else if (x.getNodeName().trim().equalsIgnoreCase("controlURL")) { 119 | controlURL = x.getFirstChild().getNodeValue(); 120 | } 121 | } 122 | if (serviceType == null || controlURL == null) { 123 | continue; 124 | } 125 | if (serviceType.trim().toLowerCase().contains(":wanipconnection:") 126 | || serviceType.trim().toLowerCase().contains(":wanpppconnection:")) { 127 | this.serviceType = serviceType.trim(); 128 | this.controlURL = controlURL.trim(); 129 | } 130 | } 131 | if (controlURL == null) { 132 | throw new Exception("Unsupported Gateway"); 133 | } 134 | int slash = location.indexOf("/", 7); // finds first slash after http:// 135 | if (slash == -1) { 136 | throw new Exception("Unsupported Gateway"); 137 | } 138 | location = location.substring(0, slash); 139 | if (!controlURL.startsWith("/")) { 140 | controlURL = "/" + controlURL; 141 | } 142 | controlURL = location + controlURL; 143 | } 144 | 145 | private Map command(String action, Map params) throws Exception { 146 | Map ret = new HashMap<>(); 147 | final byte[] req = getReq(action, params); 148 | HttpURLConnection conn = (HttpURLConnection) new URI(controlURL).toURL().openConnection(); 149 | conn.setRequestMethod("POST"); 150 | conn.setDoOutput(true); 151 | conn.setRequestProperty("Content-Type", "text/xml"); 152 | conn.setRequestProperty("SOAPAction", "\"" + serviceType + "#" + action + "\""); 153 | conn.setRequestProperty("Connection", "Close"); 154 | conn.setRequestProperty("Content-Length", "" + req.length); 155 | conn.getOutputStream().write(req); 156 | Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(conn.getInputStream()); 157 | NodeIterator iter = ((DocumentTraversal) d).createNodeIterator(d.getDocumentElement(), NodeFilter.SHOW_ELEMENT, 158 | null, true); 159 | Node n; 160 | while ((n = iter.nextNode()) != null) { 161 | try { 162 | if (n.getFirstChild().getNodeType() == Node.TEXT_NODE) { 163 | ret.put(n.getNodeName(), n.getTextContent()); 164 | } 165 | } catch (Throwable t) { 166 | } 167 | } 168 | conn.disconnect(); 169 | return ret; 170 | } 171 | 172 | private byte[] getReq(String action, Map params) { 173 | StringBuilder soap = new StringBuilder("\r\n" 174 | + "" 175 | + "" 176 | + ""); 177 | if (params != null) { 178 | for (Map.Entry entry : params.entrySet()) { 179 | soap.append("<").append(entry.getKey()).append(">").append(entry.getValue()).append(""); 181 | } 182 | } 183 | soap.append(""); 184 | return soap.toString().getBytes(UTF_8); 185 | } 186 | 187 | public String getGatewayIP() { 188 | return routerip.getHostAddress(); 189 | } 190 | 191 | public String getLocalIP() { 192 | return iface.getHostAddress(); 193 | } 194 | 195 | public String getExternalIP() { 196 | try { 197 | Map r = command("GetExternalIPAddress", null); 198 | return r.get("NewExternalIPAddress"); 199 | } catch (Throwable t) { 200 | return null; 201 | } 202 | } 203 | 204 | public boolean openPort(int port, String remoteHost, boolean udp, String appName) { 205 | if (port < 0 || port > 65535) { 206 | throw new IllegalArgumentException("Invalid port"); 207 | } 208 | Map params = new HashMap<>(); 209 | params.put("NewRemoteHost", remoteHost == null ? "" : remoteHost); 210 | params.put("NewProtocol", udp ? "UDP" : "TCP"); 211 | params.put("NewInternalClient", iface.getHostAddress()); 212 | params.put("NewExternalPort", "" + port); 213 | params.put("NewInternalPort", "" + port); 214 | params.put("NewEnabled", "1"); 215 | params.put("NewPortMappingDescription", appName); 216 | params.put("NewLeaseDuration", "0"); 217 | try { 218 | Map r = command("AddPortMapping", params); 219 | return r.get("errorCode") == null; 220 | } catch (Exception ex) { 221 | return false; 222 | } 223 | } 224 | 225 | public boolean closePort(int port, String remoteHost, boolean udp) { 226 | if (port < 0 || port > 65535) { 227 | throw new IllegalArgumentException("Invalid port"); 228 | } 229 | Map params = new HashMap<>(); 230 | params.put("NewRemoteHost", remoteHost == null ? "" : remoteHost); 231 | params.put("NewProtocol", udp ? "UDP" : "TCP"); 232 | params.put("NewExternalPort", "" + port); 233 | try { 234 | command("DeletePortMapping", params); 235 | return true; 236 | } catch (Exception ex) { 237 | return false; 238 | } 239 | } 240 | 241 | public boolean isMapped(int port, String remoteHost, boolean udp) { 242 | if (port < 0 || port > 65535) { 243 | throw new IllegalArgumentException("Invalid port"); 244 | } 245 | Map params = new HashMap<>(); 246 | params.put("NewRemoteHost", remoteHost == null ? "" : remoteHost); 247 | params.put("NewProtocol", udp ? "UDP" : "TCP"); 248 | params.put("NewExternalPort", "" + port); 249 | try { 250 | Map r = command("GetSpecificPortMappingEntry", params); 251 | if (r.get("errorCode") != null) { 252 | throw new Exception(); 253 | } 254 | return r.get("NewInternalPort") != null; 255 | } catch (Exception ex) { 256 | return false; 257 | } 258 | 259 | } 260 | 261 | } 262 | -------------------------------------------------------------------------------- /src/main/java/io/github/satxm/mcwifipnp/commands/UUIDFixerCommand.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp.commands; 2 | 3 | import com.mojang.brigadier.CommandDispatcher; 4 | import com.mojang.brigadier.arguments.BoolArgumentType; 5 | import com.mojang.brigadier.arguments.StringArgumentType; 6 | import com.mojang.brigadier.exceptions.CommandSyntaxException; 7 | import net.minecraft.commands.SharedSuggestionProvider; 8 | import net.minecraft.server.MinecraftServer; 9 | 10 | import com.mojang.brigadier.builder.LiteralArgumentBuilder; 11 | import com.mojang.brigadier.builder.RequiredArgumentBuilder; 12 | import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; 13 | 14 | import io.github.satxm.mcwifipnp.Config; 15 | import io.github.satxm.mcwifipnp.UUIDFixer; 16 | 17 | import java.util.LinkedHashSet; 18 | import java.util.List; 19 | import java.util.Set; 20 | import java.util.function.Supplier; 21 | import java.util.stream.Collectors; 22 | 23 | import net.minecraft.commands.CommandSourceStack; 24 | import net.minecraft.commands.Commands; 25 | import net.minecraft.network.chat.CommonComponents; 26 | import net.minecraft.network.chat.Component; 27 | import net.minecraft.network.chat.MutableComponent; 28 | 29 | public class UUIDFixerCommand { 30 | private final static Component POLICY_ONLINE = Component.translatable("mcwifipnp.commands.uuidfixer.policy.online"); 31 | private final static Component POLICY_OFFLINE = Component.translatable("mcwifipnp.commands.uuidfixer.policy.offline"); 32 | private final static Component POLICY_INVALID = Component.translatable("mcwifipnp.commands.uuidfixer.policy.invalid"); 33 | 34 | private static Component policyToComponent(String policy) { 35 | if (UUIDFixer.PolicyHolder.isUUID(policy)) { 36 | return Component.literal(policy); 37 | } else if (UUIDFixer.PolicyHolder.isOfflinePolicy(policy)) { 38 | return POLICY_OFFLINE; 39 | } else if (UUIDFixer.PolicyHolder.isOnlinePolicy(policy)) { 40 | return POLICY_ONLINE; 41 | } else { 42 | return POLICY_INVALID; 43 | } 44 | } 45 | 46 | public static void register(CommandDispatcher commandDispatcher) { 47 | 48 | LiteralArgumentBuilder cmdBuilder = Commands.literal("uuidfixer") 49 | .requires((cmdStack) -> cmdStack.hasPermission(3)); 50 | 51 | cmdBuilder = cmdBuilder.then(Commands.literal("list").executes((commandContext) -> { 52 | return showList((CommandSourceStack) commandContext.getSource()); 53 | })); 54 | 55 | RequiredArgumentBuilder anyKnownPlayerNameArg = 56 | Commands.argument("playerName", StringArgumentType.string()) 57 | .suggests((commandContext, suggestionsBuilder) -> { 58 | MinecraftServer server = ((CommandSourceStack) commandContext.getSource()).getServer(); 59 | Set players = server.getPlayerList().getPlayers().stream() 60 | .map(player -> player.getGameProfile().name()).collect(Collectors.toSet()); 61 | 62 | Set hints = new LinkedHashSet<>(); 63 | 64 | UUIDFixer.PolicyHolder policyHolder = new UUIDFixer.PolicyHolder(); 65 | policyHolder.getUsers().stream().filter(playerName -> !players.contains(playerName)).forEach(hints::add); 66 | hints.addAll(players); 67 | 68 | return SharedSuggestionProvider.suggest(hints, suggestionsBuilder); 69 | }); 70 | 71 | RequiredArgumentBuilder modeArg = 72 | Commands.argument("mode", StringArgumentType.string()) 73 | .suggests((commandContext, suggestionsBuilder) -> { 74 | return SharedSuggestionProvider.suggest(List.of("online", "offline", ""), suggestionsBuilder); 75 | }); 76 | 77 | cmdBuilder = cmdBuilder.then(Commands.literal("force").then( 78 | modeArg.then(anyKnownPlayerNameArg.executes( 79 | (commandContext) -> { 80 | return setPolicy((CommandSourceStack) commandContext.getSource(), 81 | StringArgumentType.getString(commandContext, "playerName"), 82 | StringArgumentType.getString(commandContext, "mode")); 83 | } 84 | )) 85 | )); 86 | 87 | cmdBuilder = cmdBuilder.then(Commands.literal("default-online") 88 | .then(Commands.argument("mode", BoolArgumentType.bool()) 89 | .executes(commandContext -> { 90 | return setDefaultPolicy(commandContext.getSource(), BoolArgumentType.getBool(commandContext, "mode")); 91 | }) 92 | ) 93 | .executes(commandContext -> { 94 | return showDefaultPolicy(commandContext.getSource()); 95 | }) 96 | ); 97 | 98 | RequiredArgumentBuilder playerNameArg = 99 | Commands.argument("playerName", StringArgumentType.string()) 100 | .suggests((commandContext, suggestionsBuilder) -> { 101 | UUIDFixer.PolicyHolder policyHolder = new UUIDFixer.PolicyHolder(); 102 | return SharedSuggestionProvider.suggest(policyHolder.getUsers(), suggestionsBuilder); 103 | }); 104 | 105 | cmdBuilder = cmdBuilder.then(Commands.literal("remove").then(playerNameArg.executes( 106 | (commandContext) -> { 107 | return removePolicy((CommandSourceStack) commandContext.getSource(), 108 | StringArgumentType.getString(commandContext, "playerName")); 109 | } 110 | ))); 111 | 112 | 113 | cmdBuilder = cmdBuilder.then(Commands.literal("test").then(anyKnownPlayerNameArg.executes( 114 | (commandContext) -> { 115 | return testPolicy((CommandSourceStack) commandContext.getSource(), 116 | StringArgumentType.getString(commandContext, "playerName")); 117 | } 118 | ))); 119 | 120 | cmdBuilder = cmdBuilder.then(Commands.literal("enabled").then( 121 | Commands.argument("enabled", BoolArgumentType.bool()).executes(commandContext -> { 122 | return setEnabled(commandContext.getSource(), BoolArgumentType.getBool(commandContext, "enabled")); 123 | }) 124 | ).executes(commandContext -> { 125 | return showEnabled(commandContext.getSource()); 126 | })); 127 | 128 | commandDispatcher.register(cmdBuilder); 129 | } 130 | 131 | private static int setEnabled(CommandSourceStack commandSourceStack, boolean enabled) { 132 | MinecraftServer server = commandSourceStack.getServer(); 133 | Config cfg = Config.readFromPublishedServer(server); 134 | cfg.enableUUIDFixer = enabled; 135 | cfg.saveAndApply(server); 136 | 137 | return showEnabled(commandSourceStack); 138 | } 139 | 140 | private static int showEnabled(CommandSourceStack commandSourceStack) { 141 | MinecraftServer server = commandSourceStack.getServer(); 142 | Config cfg = Config.readFromPublishedServer(server); 143 | 144 | Component status = Component.translatable("mcwifipnp.commands.uuidfixer.name") 145 | .append(": ").append(cfg.enableUUIDFixer ? CommonComponents.OPTION_ON : CommonComponents.OPTION_OFF); 146 | commandSourceStack.sendSuccess(()->status, false); 147 | return 1; 148 | } 149 | 150 | private static int setPolicy(CommandSourceStack commandSourceStack, String playerName, 151 | String policy) throws CommandSyntaxException { 152 | 153 | UUIDFixer.PolicyHolder policyHolder = new UUIDFixer.PolicyHolder(); 154 | 155 | if (!UUIDFixer.PolicyHolder.isValidPolicy(policy)) { 156 | throw new SimpleCommandExceptionType( 157 | Component.translatable("mcwifipnp.commands.uuidfixer.set.bad-policy", policy)).create(); 158 | } 159 | policyHolder.set(playerName, policy); 160 | 161 | if (UUIDFixer.PolicyHolder.isUUID(policy)) { 162 | commandSourceStack.sendSuccess(() -> { 163 | return Component.translatable("mcwifipnp.commands.uuidfixer.set.override", 164 | playerName, policy); 165 | }, true); 166 | } else { 167 | commandSourceStack.sendSuccess(() -> { 168 | return Component.translatable("mcwifipnp.commands.uuidfixer.set.success", 169 | playerName, policyToComponent(policy)); 170 | }, true); 171 | } 172 | 173 | policyHolder.save(); 174 | return 1; 175 | } 176 | 177 | private static int removePolicy(CommandSourceStack commandSourceStack, String playerName) 178 | throws CommandSyntaxException { 179 | 180 | UUIDFixer.PolicyHolder policyHolder = new UUIDFixer.PolicyHolder(); 181 | 182 | if (policyHolder.getOrNull(playerName) == null) { 183 | throw new SimpleCommandExceptionType( 184 | Component.translatable("mcwifipnp.commands.uuidfixer.policy.not-exist", playerName)).create(); 185 | } else { 186 | policyHolder.remove(playerName); 187 | commandSourceStack.sendSuccess(() -> { 188 | return Component.translatable("mcwifipnp.commands.uuidfixer.remove.success", playerName); 189 | }, true); 190 | 191 | policyHolder.save(); 192 | commandSourceStack.getServer().kickUnlistedPlayers(); 193 | return 1; 194 | } 195 | } 196 | 197 | private static int setDefaultPolicy(CommandSourceStack commandSourceStack, final boolean defaultIsOnline) { 198 | UUIDFixer.PolicyHolder policyHolder = new UUIDFixer.PolicyHolder(); 199 | policyHolder.setDefaultPolicy(defaultIsOnline); 200 | policyHolder.save(); 201 | 202 | commandSourceStack.sendSuccess( 203 | () -> Component.translatable("mcwifipnp.commands.uuidfixer.default.set", 204 | defaultIsOnline ? POLICY_ONLINE : POLICY_OFFLINE), false); 205 | 206 | return 1; 207 | } 208 | 209 | private static Supplier showDefaultPolicy(UUIDFixer.PolicyHolder policyHolder) { 210 | final boolean defaultIsOnline = policyHolder.isOnlineByDefault(); 211 | return () -> Component.translatable("mcwifipnp.commands.uuidfixer.default.show", 212 | defaultIsOnline ? POLICY_ONLINE : POLICY_OFFLINE); 213 | } 214 | 215 | private static int showDefaultPolicy(CommandSourceStack commandSourceStack) { 216 | UUIDFixer.PolicyHolder policyHolder = new UUIDFixer.PolicyHolder(); 217 | commandSourceStack.sendSuccess(showDefaultPolicy(policyHolder), false); 218 | return 1; 219 | } 220 | 221 | private static Component showPolicy(UUIDFixer.PolicyHolder policyHolder, String playerName, boolean simulate) { 222 | MutableComponent policyStr = Component.empty(); 223 | 224 | policyStr.append(playerName + ": "); 225 | String policy = policyHolder.getOrNull(playerName); 226 | if (simulate && policy == null) { 227 | policyStr.append(policyHolder.isOnlineByDefault() ? POLICY_ONLINE : POLICY_OFFLINE); 228 | } else { 229 | policyStr.append(policyToComponent(policy)); 230 | } 231 | 232 | return policyStr; 233 | } 234 | 235 | private static int showList(CommandSourceStack commandSourceStack) { 236 | UUIDFixer.PolicyHolder policyHolder = new UUIDFixer.PolicyHolder(); 237 | int count = policyHolder.count(); 238 | 239 | final MutableComponent list = (MutableComponent) showDefaultPolicy(policyHolder).get(); 240 | if (count == 0) { 241 | list.append("\n"); 242 | list.append(Component.translatable("mcwifipnp.commands.uuidfixer.none")); 243 | } else { 244 | list.append("\n"); 245 | list.append(Component.translatable("mcwifipnp.commands.uuidfixer.list", policyHolder.count())); 246 | for (String playerName: policyHolder.getUsers()) { 247 | list.append("\n"); 248 | list.append(showPolicy(policyHolder, playerName, false)); 249 | } 250 | } 251 | 252 | commandSourceStack.sendSuccess(() -> list, false); 253 | 254 | return count; 255 | } 256 | 257 | private static int testPolicy(CommandSourceStack commandSourceStack, String playerName) { 258 | UUIDFixer.PolicyHolder policyHolder = new UUIDFixer.PolicyHolder(); 259 | final Component component = showPolicy(policyHolder, playerName, true); 260 | commandSourceStack.sendSuccess(() -> component, false); 261 | return 1; 262 | } 263 | } 264 | -------------------------------------------------------------------------------- /src/main/java/io/github/satxm/mcwifipnp/commands/IpCommand.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp.commands; 2 | 3 | import java.net.InetAddress; 4 | import java.net.NetworkInterface; 5 | import java.net.SocketException; 6 | import java.util.ArrayList; 7 | import java.util.Enumeration; 8 | import java.util.LinkedList; 9 | import java.util.List; 10 | import java.util.function.Consumer; 11 | 12 | import com.dosse.upnp.UPnP; 13 | import com.mojang.brigadier.Command; 14 | import com.mojang.brigadier.CommandDispatcher; 15 | import com.mojang.brigadier.builder.LiteralArgumentBuilder; 16 | import com.mojang.brigadier.context.CommandContext; 17 | 18 | import io.github.satxm.mcwifipnp.network.GlobalIPs; 19 | import io.github.satxm.mcwifipnp.network.UPnPModule; 20 | import io.netty.channel.socket.InternetProtocolFamily; 21 | import net.minecraft.ChatFormatting; 22 | import net.minecraft.commands.CommandSourceStack; 23 | import net.minecraft.commands.Commands; 24 | import net.minecraft.network.chat.ClickEvent; 25 | import net.minecraft.network.chat.Component; 26 | import net.minecraft.network.chat.ComponentUtils; 27 | import net.minecraft.network.chat.HoverEvent; 28 | import net.minecraft.network.chat.MutableComponent; 29 | import net.minecraft.server.MinecraftServer; 30 | 31 | public class IpCommand { 32 | public static String LOCAL_IP_KEY = "mcwifipnp.gui.localIP"; 33 | public static String GLOBAL_IP_KEY = "mcwifipnp.gui.globalIP"; 34 | public static Component CANNOT_GET_IP = Component.translatable("mcwifipnp.upnp.cantgetip"); 35 | 36 | public static void register(CommandDispatcher commandDispatcher) { 37 | LiteralArgumentBuilder cmdBuilder = Commands.literal("ip") 38 | .requires((cmdStack) -> cmdStack.hasPermission(4)); 39 | 40 | cmdBuilder = cmdBuilder.then(Commands.literal("get") 41 | .then(EnumArgument.IP_FAMILY.appendTo(Commands.literal("local").executes(IpCommand::showLocalIPsAll), 42 | (enumOption) -> enumOption.executes(IpCommand::showLocalIPs))) 43 | .then(EnumArgument.IP_FAMILY.appendTo(Commands.literal("global").executes(IpCommand::showGlobalIPAll), 44 | (enumOption) -> enumOption.executes(IpCommand::showGlobalIP))) 45 | .then(Commands.literal("upnp").executes(IpCommand::showUPnPIP)) 46 | .executes(IpCommand::showDetail)); 47 | 48 | // The default action 49 | cmdBuilder = cmdBuilder.executes(IpCommand::showBrief); 50 | 51 | commandDispatcher.register(cmdBuilder); 52 | } 53 | 54 | private static int showLocalIPs(CommandContext context) { 55 | InternetProtocolFamily family = EnumArgument.IP_FAMILY.valueOf(context, 0); 56 | 57 | return getAndReply(context, (components) -> getIPComponentLocal(components, family)); 58 | } 59 | 60 | private static void showLocalIPsAllImpl(List results) { 61 | int labelIndex = results.size(); 62 | 63 | int count = getIPComponentLocal(results, InternetProtocolFamily.IPv4); 64 | count += getIPComponentLocal(results, InternetProtocolFamily.IPv6); 65 | if (count > 0) { 66 | results.add(labelIndex, Component.translatable(LOCAL_IP_KEY, "IP:")); 67 | } 68 | } 69 | 70 | private static int showLocalIPsAll(CommandContext context) { 71 | return getAndReply(context, IpCommand::showLocalIPsAllImpl); 72 | } 73 | 74 | private static int showGlobalIP(CommandContext context) { 75 | InternetProtocolFamily family = EnumArgument.IP_FAMILY.valueOf(context, 0); 76 | 77 | return getAndReply(context, (components) -> { 78 | getIPComponentGlobal(components, family); 79 | }); 80 | } 81 | 82 | private static void showGlobalIPAllImpl(List results) { 83 | int labelIndex = results.size(); 84 | 85 | int count = getIPComponentGlobal(results, InternetProtocolFamily.IPv4); 86 | count += getIPComponentGlobal(results, InternetProtocolFamily.IPv6); 87 | if (count > 0) { 88 | results.add(labelIndex, Component.translatable(GLOBAL_IP_KEY, "IP:")); 89 | } 90 | } 91 | 92 | private static int showGlobalIPAll(CommandContext context) { 93 | return getAndReply(context, IpCommand::showGlobalIPAllImpl); 94 | } 95 | 96 | private static int showUPnPIP(CommandContext context) { 97 | return getAndReply(context, (components) -> { 98 | showUPnPIPAllImpl(components, context); 99 | }); 100 | } 101 | 102 | private static void showUPnPIPAllImpl(List results, CommandContext context) { 103 | int labelIndex = results.size(); 104 | 105 | if (getIPComponentUPnP(results, context) > 0) { 106 | results.add(labelIndex, Component.literal("UPnP IPv4:")); 107 | } 108 | } 109 | 110 | private static int showDetail(CommandContext context) { 111 | return getAndReply(context, (components) -> { 112 | showGlobalIPAllImpl(components); 113 | showLocalIPsAllImpl(components); 114 | showUPnPIPAllImpl(components, context); 115 | }); 116 | } 117 | 118 | private static int showBrief(CommandContext context) { 119 | Component result = getBrief(context.getSource().getServer()); 120 | if (result == CANNOT_GET_IP) { 121 | context.getSource().sendFailure(result); 122 | } else { 123 | context.getSource().sendSuccess(() -> result, false); 124 | } 125 | return result == CANNOT_GET_IP ? 0 : Command.SINGLE_SUCCESS; 126 | } 127 | 128 | private static int getAndReply(CommandContext context, Consumer> sources) { 129 | List components = new LinkedList<>(); 130 | sources.accept(components); 131 | 132 | if (components.isEmpty()) { 133 | context.getSource().sendFailure(CANNOT_GET_IP); 134 | return 0; 135 | } else { 136 | components.forEach(component -> context.getSource().sendSuccess(() -> component, false)); 137 | return components.size(); 138 | } 139 | } 140 | 141 | private static int getIPComponentLocal(List results, InternetProtocolFamily family) { 142 | List localIPs = getLocalIPs(); 143 | if (localIPs.isEmpty()) { 144 | return 0; 145 | } 146 | 147 | for (InetAddress addr : localIPs) { 148 | if (family == InternetProtocolFamily.of(addr)) { 149 | String addrString = addr.getHostAddress(); 150 | addrString = formatIPString(addrString, family); 151 | results.add(copyable(addrString)); 152 | } 153 | } 154 | return results.size(); 155 | } 156 | 157 | private static int getIPComponentGlobal(List results, InternetProtocolFamily family) { 158 | String ip = GlobalIPs.fetchGlobalIP(family); 159 | if (ip == null) { 160 | return 0; 161 | } 162 | 163 | ip = formatIPString(ip, family); 164 | results.add(copyable(ip)); 165 | return 1; 166 | } 167 | 168 | private static int getIPComponentUPnP(List results, CommandContext context) { 169 | String upnpIP = UPnP.getExternalIP(); 170 | if (!UPnPModule.has(context.getSource().getServer()) || upnpIP == null) { 171 | return 0; 172 | } 173 | 174 | final MutableComponent component = copyable(upnpIP); 175 | results.add(component); 176 | return 1; 177 | } 178 | 179 | public static Component getBrief(MinecraftServer server) { 180 | int port = server.getPort(); 181 | boolean useUPnP = UPnPModule.has(server); 182 | 183 | List IPComponentList = new LinkedList<>(); 184 | ArrayList IPList = new ArrayList(); 185 | 186 | List localIPs = getLocalIPs(); 187 | for (InetAddress addr : localIPs) { 188 | String addrString = addr.getHostAddress(); 189 | InternetProtocolFamily family = InternetProtocolFamily.of(addr); 190 | IPComponentList.add(copyable(LOCAL_IP_KEY, addrString, family, port)); 191 | IPList.add(addrString); 192 | } 193 | 194 | String ipv4 = GlobalIPs.fetchGlobalIP(InternetProtocolFamily.IPv4); 195 | if (ipv4 != null && !IPList.contains(ipv4)) { 196 | IPComponentList.add(copyable(GLOBAL_IP_KEY, ipv4, InternetProtocolFamily.IPv4, port)); 197 | IPList.add(ipv4); 198 | } 199 | 200 | String ipv6 = GlobalIPs.fetchGlobalIP(InternetProtocolFamily.IPv6); 201 | if (ipv6 != null && !IPList.contains(ipv6)) { 202 | IPComponentList.add(copyable(GLOBAL_IP_KEY, ipv6, InternetProtocolFamily.IPv6, port)); 203 | IPList.add(ipv6); 204 | } 205 | 206 | String upnpIP = UPnP.getExternalIP(); 207 | if (useUPnP && upnpIP != null && !IPList.contains(upnpIP)) { 208 | IPComponentList 209 | .add(ComponentUtils.wrapInSquareBrackets(copyable(Component.literal("UPnP IPv4"), upnpIP + ":" + port))); 210 | IPList.add(upnpIP); 211 | } 212 | 213 | if (IPComponentList.isEmpty()) { 214 | return IpCommand.CANNOT_GET_IP; 215 | } else { 216 | MutableComponent component = Component.empty(); 217 | IPComponentList.forEach(component::append); 218 | return Component.translatable("mcwifipnp.upnp.clipboard", component); 219 | } 220 | } 221 | 222 | public static MutableComponent copyable(String ipTypeKey, String ip, InternetProtocolFamily family, int port) { 223 | return copyable(ipTypeKey, ip, family, ":" + port); 224 | } 225 | 226 | public static String formatIPString(String ip, InternetProtocolFamily family) { 227 | if (family == InternetProtocolFamily.IPv6) { 228 | ip = "[" + ip + "]"; 229 | } 230 | return ip; 231 | } 232 | 233 | public static MutableComponent copyable(String ipTypeKey, String ip, InternetProtocolFamily family, String suffix) { 234 | return copyable(ComponentUtils.wrapInSquareBrackets(Component.translatable(ipTypeKey, family.toString())), 235 | formatIPString(ip, family) + suffix); 236 | } 237 | 238 | public static MutableComponent copyable(String content) { 239 | return copyable(Component.literal(content), content); 240 | } 241 | 242 | public static MutableComponent copyable(MutableComponent base, String content) { 243 | return base.withStyle(style -> style.withColor(ChatFormatting.GREEN) 244 | .withClickEvent(new ClickEvent.CopyToClipboard(content)) 245 | .withHoverEvent(new HoverEvent.ShowText( 246 | Component.translatable("chat.copy.click").append("\n").append(content))) 247 | .withInsertion(content)); 248 | } 249 | 250 | public static List getLocalIPs() { 251 | List results = new LinkedList<>(); 252 | 253 | Enumeration ifaces = null; 254 | try { 255 | ifaces = NetworkInterface.getNetworkInterfaces(); 256 | } catch (Throwable t) { 257 | return results; 258 | } 259 | 260 | while (ifaces.hasMoreElements()) { 261 | NetworkInterface iface = ifaces.nextElement(); 262 | try { 263 | if (!iface.isUp() || iface.isLoopback() || iface.isVirtual() || iface.isPointToPoint()) { 264 | continue; 265 | } 266 | } catch (SocketException e) { 267 | } 268 | if (iface.getDisplayName().contains("Virtual") || iface.getDisplayName().contains("VMware") 269 | || iface.getDisplayName().contains("VirtualBox") || iface.getDisplayName().contains("Bluetooth") 270 | || iface.getDisplayName().contains("Hyper-V")) { 271 | continue; 272 | } 273 | Enumeration addrs = iface.getInetAddresses(); 274 | if (addrs == null) { 275 | continue; 276 | } 277 | while (addrs.hasMoreElements()) { 278 | InetAddress addr = addrs.nextElement(); 279 | if (addr.isLinkLocalAddress()) { 280 | continue; 281 | } 282 | 283 | results.add(addr); 284 | } 285 | } 286 | 287 | return results; 288 | } 289 | } 290 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2021 Satxm 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/main/java/io/github/satxm/mcwifipnp/client/ShareToLanScreenNew.java: -------------------------------------------------------------------------------- 1 | package io.github.satxm.mcwifipnp.client; 2 | 3 | import javax.annotation.Nullable; 4 | 5 | import io.github.satxm.mcwifipnp.Config; 6 | import io.github.satxm.mcwifipnp.MCWiFiPnPUnit; 7 | import io.github.satxm.mcwifipnp.OnlineMode; 8 | import io.github.satxm.mcwifipnp.commands.IpCommand; 9 | import io.github.satxm.mcwifipnp.network.UPnPModule; 10 | import net.minecraft.client.Minecraft; 11 | import net.minecraft.client.gui.GuiGraphics; 12 | import net.minecraft.client.gui.components.Button; 13 | import net.minecraft.client.gui.components.Checkbox; 14 | import net.minecraft.client.gui.components.CycleButton; 15 | import net.minecraft.client.gui.components.EditBox; 16 | import net.minecraft.client.gui.components.StringWidget; 17 | import net.minecraft.client.gui.components.Tooltip; 18 | import net.minecraft.client.gui.components.tabs.GridLayoutTab; 19 | import net.minecraft.client.gui.components.tabs.TabManager; 20 | import net.minecraft.client.gui.components.tabs.TabNavigationBar; 21 | import net.minecraft.client.gui.layouts.CommonLayouts; 22 | import net.minecraft.client.gui.layouts.GridLayout; 23 | import net.minecraft.client.gui.layouts.HeaderAndFooterLayout; 24 | import net.minecraft.client.gui.layouts.LinearLayout; 25 | import net.minecraft.client.gui.navigation.ScreenRectangle; 26 | import net.minecraft.client.gui.screens.Screen; 27 | import net.minecraft.client.gui.screens.ShareToLanScreen; 28 | import net.minecraft.client.renderer.RenderPipelines; 29 | import net.minecraft.client.server.IntegratedServer; 30 | import net.minecraft.network.chat.CommonComponents; 31 | import net.minecraft.network.chat.Component; 32 | import net.minecraft.network.chat.MutableComponent; 33 | import net.minecraft.server.commands.PublishCommand; 34 | import net.minecraft.server.level.ServerPlayer; 35 | import net.minecraft.server.players.NameAndId; 36 | import net.minecraft.server.players.PlayerList; 37 | import net.minecraft.server.players.ServerOpListEntry; 38 | import net.minecraft.server.players.UserWhiteListEntry; 39 | import net.minecraft.util.HttpUtil; 40 | import net.minecraft.world.level.GameType; 41 | 42 | public class ShareToLanScreenNew extends Screen { 43 | private final Config cfg; 44 | private final Screen lastScreen; 45 | private final boolean serverPublished; 46 | 47 | private final TabManager tabManager = new TabManager(this::addRenderableWidget, this::removeWidget); 48 | 49 | @Nullable 50 | private TabNavigationBar tabNavigationBar; 51 | 52 | public final HeaderAndFooterLayout layout = new HeaderAndFooterLayout(this); 53 | 54 | protected Button confirmButton; 55 | 56 | protected Checkbox removePlayerReportingButtonBox; 57 | 58 | @Nullable 59 | protected Button backToVanillaScreenButton; 60 | 61 | private boolean oldUPnPEnabled; 62 | private boolean oldCopyIP; 63 | private String oldMotd; 64 | 65 | public ShareToLanScreenNew(Screen screen, boolean serverPublished) { 66 | super(Component.translatable("lanServer.title")); 67 | this.lastScreen = screen; 68 | this.serverPublished = serverPublished; 69 | 70 | IntegratedServer server = Minecraft.getInstance().getSingleplayerServer(); 71 | 72 | this.cfg = Config.read(server); 73 | 74 | if (serverPublished) { 75 | this.cfg.readFromRunningServer(server); 76 | } else if (this.cfg.usingDefaults) { 77 | this.cfg.readFromRunningServer(server); 78 | this.cfg.port = HttpUtil.getAvailablePort(); 79 | this.cfg.allowHostCheat = server.getWorldData().isAllowCommands(); 80 | } 81 | 82 | this.oldMotd = this.cfg.motd; 83 | this.oldUPnPEnabled = this.cfg.useUPnP; 84 | this.oldCopyIP = this.cfg.getPublicIP; 85 | } 86 | 87 | protected void onConfirmClicked() { 88 | IntegratedServer server = Minecraft.getInstance().getSingleplayerServer(); 89 | PlayerList playerList = server.getPlayerList(); 90 | NameAndId hostPlayer = new NameAndId(server.getSingleplayerProfile()); 91 | this.cfg.save(); 92 | 93 | if (this.serverPublished) { 94 | if (!this.oldMotd.equals(this.cfg.motd) || this.cfg.useUPnP ^ oldUPnPEnabled) { 95 | // Motd has changed, update UPnP display name 96 | UPnPModule.stop(server); 97 | UPnPModule.startIfEnabled(server, cfg); 98 | } 99 | if (this.cfg.getPublicIP && this.cfg.getPublicIP ^ oldCopyIP) { 100 | new Thread(() -> { 101 | server.getPlayerList().getPlayer(hostPlayer.id()).sendSystemMessage(IpCommand.getBrief(server)); 102 | }, "MCWiFiPnP").start(); 103 | } 104 | } else { 105 | // Publish server 106 | MutableComponent component = server.publishServer(this.cfg.gameType, this.cfg.allowEveryoneCheat, this.cfg.port) 107 | ? PublishCommand.getSuccessMessage(this.cfg.port) 108 | : Component.translatable("commands.publish.failed"); 109 | this.minecraft.gui.getChat().addMessage(component); 110 | 111 | UPnPModule.startIfEnabled(server, cfg); 112 | if (this.cfg.getPublicIP) { 113 | new Thread(() -> { 114 | server.getPlayerList().getPlayer(hostPlayer.id()).sendSystemMessage(IpCommand.getBrief(server)); 115 | }, "MCWiFiPnP").start(); 116 | } 117 | } 118 | this.cfg.applyTo(server); 119 | 120 | if (!this.cfg.allowEveryoneCheat) { 121 | playerList.getOps().clear(); 122 | } 123 | if (this.cfg.allowHostCheat) { 124 | playerList.getOps().add(new ServerOpListEntry(hostPlayer, 4, playerList.canBypassPlayerLimit(hostPlayer))); 125 | } 126 | for (ServerPlayer serverPlayer : server.getPlayerList().getPlayers()) { 127 | playerList.sendPlayerPermissionLevel(serverPlayer); 128 | } 129 | 130 | if (playerList.isUsingWhitelist()) { 131 | playerList.getWhiteList().add(new UserWhiteListEntry(hostPlayer)); 132 | playerList.reloadWhiteList(); 133 | } 134 | if (MCWiFiPnPUnit.convertOldUsers(this.minecraft.getSingleplayerServer())) 135 | this.minecraft.getSingleplayerServer().services().nameToIdCache().add(hostPlayer); 136 | 137 | this.minecraft.updateTitle(); 138 | this.minecraft.setScreen((Screen) null); 139 | } 140 | 141 | @Override 142 | protected void init() { 143 | this.tabNavigationBar = TabNavigationBar.builder(this.tabManager, this.width) 144 | .addTabs(new DefaultTab1(), new DefaultTab2(), new DefaultTab3()).build(); 145 | this.addRenderableWidget(this.tabNavigationBar); 146 | 147 | // Add footer widgets 148 | LinearLayout footer = this.layout.addToFooter(LinearLayout.horizontal().spacing(8)); 149 | this.confirmButton = Button.builder( 150 | this.serverPublished ? CommonComponents.GUI_DONE : Component.translatable("lanServer.start"), 151 | button -> this.onConfirmClicked()).width(150).build(); 152 | footer.addChild(this.confirmButton); 153 | footer.addChild(Button.builder(CommonComponents.GUI_CANCEL, button -> this.onClose()).build()); 154 | 155 | this.layout.visitWidgets(this::addRenderableWidget); 156 | this.tabNavigationBar.selectTab(0, false); 157 | this.repositionElements(); 158 | } 159 | 160 | private class DefaultTab1 extends GridLayoutTab { 161 | public DefaultTab1() { 162 | super(Component.translatable("mcwifipnp.gui.lanServerOptions")); 163 | GridLayout.RowHelper tabContents = this.layout.columnSpacing(8).rowSpacing(4).createRowHelper(4); 164 | 165 | // Row 1 166 | // Port field 167 | EditBox portField; 168 | if (ShareToLanScreenNew.this.serverPublished) { 169 | portField = new EditBox(ShareToLanScreenNew.this.font, 0, 0, 70, 20, Component.translatable("lanServer.port")); 170 | portField.setEditable(false); 171 | portField.setValue(Integer.toString(cfg.port)); 172 | } else { 173 | portField = EditBoxEx 174 | .numerical(ShareToLanScreenNew.this.font, 0, 0, 70, 20, Component.translatable("lanServer.port")) 175 | .defaults(cfg.port, EditBoxEx.TEXT_COLOR_HINT, 176 | Tooltip.create(Component.translatable("mcwifipnp.gui.port.info"))) 177 | .invalid(EditBoxEx.TEXT_COLOR_ERROR, 178 | Tooltip.create(Component.translatable("mcwifipnp.gui.port.invalid"))) 179 | .validator((port) -> { 180 | if (port < 1024 || port > 65535) { 181 | throw new NumberFormatException("Port out of range:" + port); 182 | } else if (!HttpUtil.isPortAvailable(port)) { 183 | return new EditBoxEx.ValidatorResult(EditBoxEx.TEXT_COLOR_WARN, 184 | Tooltip.create(Component.translatable("mcwifipnp.gui.port.unavailable")), false, 185 | true); 186 | } else { 187 | return null; 188 | } 189 | }).responder((newState, newPort) -> { 190 | confirmButton.active = newState.valid(); 191 | if (newState.updateBackendValue()) 192 | cfg.port = newPort; 193 | }); 194 | portField.setMaxLength(5); 195 | } 196 | tabContents.addChild(new StringWidget(portField.getMessage(), ShareToLanScreenNew.this.font), 197 | 1, this.layout.newCellSettings().alignHorizontallyLeft().paddingTop(6)); 198 | tabContents.addChild(portField, 199 | 1, this.layout.newCellSettings().alignHorizontallyRight()); 200 | 201 | // Number of players field 202 | EditBoxEx maxPlayersField = EditBoxEx 203 | .numerical(ShareToLanScreenNew.this.font, 0, 0, 70, 20, Component.translatable("mcwifipnp.gui.players")) 204 | .bistate(cfg.maxPlayers, Tooltip.create(Component.translatable("mcwifipnp.gui.players.info")), 205 | (maxPlayers) -> maxPlayers > 0) 206 | .responder((newState, maxPlayers) -> { 207 | confirmButton.active = newState.valid(); 208 | if (newState.updateBackendValue()) 209 | cfg.maxPlayers = maxPlayers; 210 | }); 211 | tabContents.addChild(new StringWidget(maxPlayersField.getMessage(), ShareToLanScreenNew.this.font), 212 | 1, this.layout.newCellSettings().alignHorizontallyLeft().paddingTop(6)); 213 | tabContents.addChild(maxPlayersField, 214 | 1, this.layout.newCellSettings().alignHorizontallyRight()); 215 | 216 | // Row2 217 | // Motd field 218 | tabContents.addChild(CommonLayouts.labeledElement(ShareToLanScreenNew.this.font, EditBoxEx 219 | .text(ShareToLanScreenNew.this.font, 0, 0, 308, 20, Component.translatable("mcwifipnp.gui.motd")) 220 | .bistate(cfg.motd, Tooltip.create(Component.translatable("mcwifipnp.gui.motd.info")), (newMotd) -> true) 221 | .responder((newState, newMotd) -> { 222 | confirmButton.active = newState.valid(); 223 | if (newState.updateBackendValue()) 224 | cfg.motd = newMotd; 225 | }).maxLength(32), Component.translatable("mcwifipnp.gui.motd")), 4); 226 | 227 | // Row3 228 | // Allow Cheat button (for other joined players) 229 | if (!ShareToLanScreenNew.this.serverPublished) { 230 | tabContents.addChild(CycleButton.onOffBuilder(cfg.allowHostCheat) 231 | .create(Component.translatable("selectWorld.allowCommands"), (cycleButton, allowHostCheat) -> { 232 | cfg.allowHostCheat = allowHostCheat; 233 | }), 2); 234 | } 235 | 236 | tabContents.addChild(CycleButton.onOffBuilder(cfg.enforceWhitelist) 237 | .withTooltip((state) -> Tooltip.create(Component.translatable("mcwifipnp.gui.Whitelist.info"))) 238 | .create(Component.translatable("mcwifipnp.gui.Whitelist"), (cycleButton, enforceWhitelist) -> { 239 | cfg.enforceWhitelist = enforceWhitelist; 240 | }), 2); 241 | 242 | // Row 4 243 | tabContents.addChild(CycleButton.builder(OnlineMode::getDisplayName) 244 | .withValues(OnlineMode.values()) 245 | .withInitialValue(OnlineMode.of(cfg.onlineMode, cfg.enableUUIDFixer)) 246 | .withTooltip((OnlineMode) -> Tooltip.create(OnlineMode.gettoolTip())) 247 | .create(Component.translatable("mcwifipnp.gui.OnlineMode"), (cycleButton, onlineMode) -> { 248 | cfg.onlineMode = onlineMode.onlineMode; 249 | cfg.enableUUIDFixer = onlineMode.fixUUID; 250 | }), 2); 251 | 252 | tabContents.addChild(CycleButton.onOffBuilder(cfg.enablePvP) 253 | .withTooltip((state) -> Tooltip.create(Component.translatable("mcwifipnp.gui.PvP.info"))) 254 | .create(Component.translatable("mcwifipnp.gui.PvP"), (cycleButton, PvP) -> { 255 | cfg.enablePvP = PvP; 256 | }), 2); 257 | } 258 | } 259 | 260 | private class DefaultTab2 extends GridLayoutTab { 261 | public DefaultTab2() { 262 | super(Component.translatable("lanServer.otherPlayers")); 263 | GridLayout.RowHelper tabContents = this.layout.columnSpacing(8).rowSpacing(4).createRowHelper(4); 264 | 265 | // Row 1 266 | // GameMode toggle button 267 | tabContents.addChild(CycleButton.builder(GameType::getShortDisplayName) 268 | .withValues(GameType.values()).withInitialValue(cfg.gameType) 269 | .create(Component.translatable("selectWorld.gameMode"), (cycleButton, gameType) -> { 270 | cfg.gameType = gameType; 271 | }), 2); 272 | 273 | // Allow Cheat button (for other joined players) 274 | tabContents.addChild(CycleButton.onOffBuilder(cfg.allowEveryoneCheat) 275 | .withTooltip((state) -> Tooltip.create(Component.translatable("mcwifipnp.gui.AllPlayersCheats.info"))) 276 | .create(Component.translatable("mcwifipnp.gui.AllPlayersCheats"), (cycleButton, allowEveryoneCheat) -> { 277 | cfg.allowEveryoneCheat = allowEveryoneCheat; 278 | }), 2); 279 | } 280 | } 281 | 282 | private class DefaultTab3 extends GridLayoutTab { 283 | public DefaultTab3() { 284 | super(Component.translatable("mcwifipnp.gui.otherOptions")); 285 | GridLayout.RowHelper tabContents = this.layout.columnSpacing(8).rowSpacing(4).createRowHelper(4); 286 | 287 | // Row 1 288 | tabContents.addChild(CycleButton.onOffBuilder(cfg.useUPnP) 289 | .withTooltip((state) -> Tooltip.create(Component.translatable("mcwifipnp.gui.UseUPnP.info"))) 290 | .create(Component.translatable("mcwifipnp.gui.UseUPnP"), (cycleButton, useUPnP) -> { 291 | cfg.useUPnP = useUPnP; 292 | }), 2); 293 | 294 | tabContents.addChild(CycleButton.onOffBuilder(cfg.getPublicIP) 295 | .withTooltip((state) -> Tooltip.create(Component.translatable("mcwifipnp.gui.CopyIP.info"))) 296 | .create(Component.translatable("mcwifipnp.gui.CopyIP"), (cycleButton, getPublicIP) -> { 297 | cfg.getPublicIP = getPublicIP; 298 | }), 2); 299 | 300 | // Row 2 301 | tabContents.addChild(CycleButton.onOffBuilder(cfg.removePlayerReportingButton) 302 | .create(Component.translatable("mcwifipnp.gui.removePlayerReportingButton"), 303 | (cycleButton, removePlayerReportingButton) -> { 304 | cfg.removePlayerReportingButton = removePlayerReportingButton; 305 | }), 306 | 2); 307 | 308 | if (!ShareToLanScreenNew.this.serverPublished) { 309 | tabContents 310 | .addChild(Button.builder(Component.translatable("mcwifipnp.gui.backToVanillaScreen"), button -> { 311 | ShareToLanScreenNew.this.minecraft.setScreen(new ShareToLanScreen(ShareToLanScreenNew.this.lastScreen)); 312 | }).build(), 2); 313 | } 314 | } 315 | } 316 | 317 | @Override 318 | public void onClose() { 319 | this.minecraft.setScreen(this.lastScreen); 320 | } 321 | 322 | @Override 323 | protected void repositionElements() { 324 | if (this.tabNavigationBar != null) { 325 | this.tabNavigationBar.setWidth(this.width); 326 | this.tabNavigationBar.arrangeElements(); 327 | int i = this.tabNavigationBar.getRectangle().bottom(); 328 | ScreenRectangle screenrectangle = new ScreenRectangle(0, i, this.width, 329 | this.height - this.layout.getFooterHeight() - i); 330 | this.tabManager.setTabArea(screenrectangle); 331 | this.layout.setHeaderHeight(i); 332 | this.layout.arrangeElements(); 333 | } 334 | } 335 | 336 | @Override 337 | public void render(GuiGraphics guiGraphics, int i, int j, float f) { 338 | super.render(guiGraphics, i, j, f); 339 | guiGraphics.blit(RenderPipelines.GUI_TEXTURED, Screen.FOOTER_SEPARATOR, 0, 340 | this.height - this.layout.getFooterHeight() - 2, 0.0F, 0.0F, this.width, 2, 32, 2); 341 | } 342 | } 343 | --------------------------------------------------------------------------------