| 1 | package net.minecraft.server.dedicated;
|
| 2 |
|
| 3 | import com.google.common.base.Splitter;
|
| 4 | import com.google.common.base.Strings;
|
| 5 | import com.google.gson.JsonElement;
|
| 6 | import com.google.gson.JsonObject;
|
| 7 | import com.mojang.logging.LogUtils;
|
| 8 | import com.mojang.serialization.Dynamic;
|
| 9 | import com.mojang.serialization.JsonOps;
|
| 10 | import java.nio.charset.StandardCharsets;
|
| 11 | import java.nio.file.Path;
|
| 12 | import java.util.List;
|
| 13 | import java.util.Locale;
|
| 14 | import java.util.Map;
|
| 15 | import java.util.Optional;
|
| 16 | import java.util.Properties;
|
| 17 | import java.util.UUID;
|
| 18 | import java.util.concurrent.TimeUnit;
|
| 19 | import java.util.regex.Pattern;
|
| 20 | import net.minecraft.core.Holder;
|
| 21 | import net.minecraft.core.HolderLookup;
|
| 22 | import net.minecraft.core.RegistryAccess;
|
| 23 | import net.minecraft.core.registries.Registries;
|
| 24 | import net.minecraft.network.chat.Component;
|
| 25 | import net.minecraft.network.chat.ComponentSerialization;
|
| 26 | import net.minecraft.resources.Identifier;
|
| 27 | import net.minecraft.resources.RegistryOps;
|
| 28 | import net.minecraft.resources.ResourceKey;
|
| 29 | import net.minecraft.server.MinecraftServer;
|
| 30 | import net.minecraft.server.jsonrpc.security.SecurityConfig;
|
| 31 | import net.minecraft.server.permissions.LevelBasedPermissionSet;
|
| 32 | import net.minecraft.server.permissions.PermissionLevel;
|
| 33 | import net.minecraft.util.GsonHelper;
|
| 34 | import net.minecraft.util.Mth;
|
| 35 | import net.minecraft.util.StrictJsonParser;
|
| 36 | import net.minecraft.world.Difficulty;
|
| 37 | import net.minecraft.world.level.DataPackConfig;
|
| 38 | import net.minecraft.world.level.GameType;
|
| 39 | import net.minecraft.world.level.WorldDataConfiguration;
|
| 40 | import net.minecraft.world.level.levelgen.FlatLevelSource;
|
| 41 | import net.minecraft.world.level.levelgen.WorldDimensions;
|
| 42 | import net.minecraft.world.level.levelgen.WorldOptions;
|
| 43 | import net.minecraft.world.level.levelgen.flat.FlatLevelGeneratorSettings;
|
| 44 | import net.minecraft.world.level.levelgen.presets.WorldPreset;
|
| 45 | import net.minecraft.world.level.levelgen.presets.WorldPresets;
|
| 46 | import org.jspecify.annotations.Nullable;
|
| 47 | import org.slf4j.Logger;
|
| 48 |
|
| 49 | public class DedicatedServerProperties extends Settings<DedicatedServerProperties> {
|
| 50 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 51 | private static final Pattern SHA1 = Pattern.compile("^[a-fA-F0-9]{40}$");
|
| 52 | private static final Splitter COMMA_SPLITTER = Splitter.on(',').trimResults();
|
| 53 | public static final String MANAGEMENT_SERVER_TLS_ENABLED_KEY = "management-server-tls-enabled";
|
| 54 | public static final String MANAGEMENT_SERVER_TLS_KEYSTORE_KEY = "management-server-tls-keystore";
|
| 55 | public static final String MANAGEMENT_SERVER_TLS_KEYSTORE_PASSWORD_KEY = "management-server-tls-keystore-password";
|
| 56 | public final boolean onlineMode = this.get("online-mode", true);
|
| 57 | public final boolean preventProxyConnections = this.get("prevent-proxy-connections", false);
|
| 58 | public final String serverIp = this.get("server-ip", "");
|
| 59 | public final Settings<DedicatedServerProperties>.MutableValue<Boolean> allowFlight = this.getMutable("allow-flight", false);
|
| 60 | public final Settings<DedicatedServerProperties>.MutableValue<String> motd = this.getMutable("motd", "A Minecraft Server");
|
| 61 | public final boolean codeOfConduct = this.get("enable-code-of-conduct", false);
|
| 62 | public final String bugReportLink = this.get("bug-report-link", "");
|
| 63 | public final Settings<DedicatedServerProperties>.MutableValue<Boolean> forceGameMode = this.getMutable("force-gamemode", false);
|
| 64 | public final Settings<DedicatedServerProperties>.MutableValue<Boolean> enforceWhitelist = this.getMutable("enforce-whitelist", false);
|
| 65 | public final Settings<DedicatedServerProperties>.MutableValue<Difficulty> difficulty = this.getMutable(
|
| 66 | "difficulty", dispatchNumberOrString(Difficulty::byId, Difficulty::byName), Difficulty::getSerializedName, Difficulty.EASY
|
| 67 | );
|
| 68 | public final Settings<DedicatedServerProperties>.MutableValue<GameType> gameMode = this.getMutable(
|
| 69 | "gamemode", dispatchNumberOrString(GameType::byId, GameType::byName), GameType::getName, GameType.SURVIVAL
|
| 70 | );
|
| 71 | public final String levelName = this.get("level-name", "world");
|
| 72 | public final int serverPort = this.get("server-port", 25565);
|
| 73 | public final boolean managementServerEnabled = this.get("management-server-enabled", false);
|
| 74 | public final String managementServerHost = this.get("management-server-host", "localhost");
|
| 75 | public final int managementServerPort = this.get("management-server-port", 0);
|
| 76 | public final String managementServerSecret = this.get("management-server-secret", SecurityConfig.generateSecretKey());
|
| 77 | public final boolean managementServerTlsEnabled = this.get("management-server-tls-enabled", true);
|
| 78 | public final String managementServerTlsKeystore = this.get("management-server-tls-keystore", "");
|
| 79 | public final String managementServerTlsKeystorePassword = this.get("management-server-tls-keystore-password", "");
|
| 80 | public final String managementServerAllowedOrigins = this.get("management-server-allowed-origins", "");
|
| 81 | public final @Nullable Boolean announcePlayerAchievements = this.getLegacyBoolean("announce-player-achievements");
|
| 82 | public final boolean enableQuery = this.get("enable-query", false);
|
| 83 | public final int queryPort = this.get("query.port", 25565);
|
| 84 | public final boolean enableRcon = this.get("enable-rcon", false);
|
| 85 | public final int rconPort = this.get("rcon.port", 25575);
|
| 86 | public final String rconPassword = this.get("rcon.password", "");
|
| 87 | public final boolean hardcore = this.get("hardcore", false);
|
| 88 | public final boolean useNativeTransport = this.get("use-native-transport", true);
|
| 89 | public final Settings<DedicatedServerProperties>.MutableValue<Integer> spawnProtection = this.getMutable("spawn-protection", 16);
|
| 90 | public final Settings<DedicatedServerProperties>.MutableValue<LevelBasedPermissionSet> opPermissions = this.getMutable(
|
| 91 | "op-permission-level", DedicatedServerProperties::deserializePermission, DedicatedServerProperties::serializePermission, LevelBasedPermissionSet.OWNER
|
| 92 | );
|
| 93 | public final LevelBasedPermissionSet functionPermissions = this.get(
|
| 94 | "function-permission-level",
|
| 95 | DedicatedServerProperties::deserializePermission,
|
| 96 | DedicatedServerProperties::serializePermission,
|
| 97 | LevelBasedPermissionSet.GAMEMASTER
|
| 98 | );
|
| 99 | public final long maxTickTime = this.get("max-tick-time", (long)TimeUnit.MINUTES.toMillis(1L));
|
| 100 | public final int maxChainedNeighborUpdates = this.get("max-chained-neighbor-updates", 1000000);
|
| 101 | public final int rateLimitPacketsPerSecond = this.get("rate-limit", 0);
|
| 102 | public final int commandSpamThresholdSeconds = this.get("command-spam-threshold-seconds", 10);
|
| 103 | public final int chatSpamThresholdSeconds = this.get("chat-spam-threshold-seconds", 10);
|
| 104 | public final Settings<DedicatedServerProperties>.MutableValue<Integer> viewDistance = this.getMutable("view-distance", 10);
|
| 105 | public final Settings<DedicatedServerProperties>.MutableValue<Integer> simulationDistance = this.getMutable("simulation-distance", 10);
|
| 106 | public final Settings<DedicatedServerProperties>.MutableValue<Integer> maxPlayers = this.getMutable("max-players", 20);
|
| 107 | public final int networkCompressionThreshold = this.get("network-compression-threshold", 256);
|
| 108 | public final boolean broadcastRconToOps = this.get("broadcast-rcon-to-ops", true);
|
| 109 | public final boolean broadcastConsoleToOps = this.get("broadcast-console-to-ops", true);
|
| 110 | public final int maxWorldSize = this.get("max-world-size", v -> Mth.clamp(v, 1, 29999984), 29999984);
|
| 111 | public final boolean syncChunkWrites = this.get("sync-chunk-writes", true);
|
| 112 | public final String regionFileComression = this.get("region-file-compression", "deflate");
|
| 113 | public final boolean enableJmxMonitoring = this.get("enable-jmx-monitoring", false);
|
| 114 | public final Settings<DedicatedServerProperties>.MutableValue<Boolean> enableStatus = this.getMutable("enable-status", true);
|
| 115 | public final Settings<DedicatedServerProperties>.MutableValue<Boolean> hideOnlinePlayers = this.getMutable("hide-online-players", false);
|
| 116 | public final Settings<DedicatedServerProperties>.MutableValue<Integer> entityBroadcastRangePercentage = this.getMutable(
|
| 117 | "entity-broadcast-range-percentage", v -> Mth.clamp(Integer.parseInt(v), 10, 1000), 100
|
| 118 | );
|
| 119 | public final String textFilteringConfig = this.get("text-filtering-config", "");
|
| 120 | public final int textFilteringVersion = this.get("text-filtering-version", 0);
|
| 121 | public final Optional<MinecraftServer.ServerResourcePackInfo> serverResourcePackInfo;
|
| 122 | public final DataPackConfig initialDataPackConfiguration;
|
| 123 | public final Settings<DedicatedServerProperties>.MutableValue<Integer> playerIdleTimeout = this.getMutable("player-idle-timeout", 0);
|
| 124 | public final Settings<DedicatedServerProperties>.MutableValue<Integer> statusHeartbeatInterval = this.getMutable("status-heartbeat-interval", 0);
|
| 125 | public final Settings<DedicatedServerProperties>.MutableValue<Boolean> whiteList = this.getMutable("white-list", true);
|
| 126 | public final boolean enforceSecureProfile = this.get("enforce-secure-profile", true);
|
| 127 | public final boolean logIPs = this.get("log-ips", true);
|
| 128 | public final Settings<DedicatedServerProperties>.MutableValue<Integer> pauseWhenEmptySeconds = this.getMutable("pause-when-empty-seconds", 60);
|
| 129 | private final DedicatedServerProperties.WorldDimensionData worldDimensionData;
|
| 130 | public final WorldOptions worldOptions;
|
| 131 | public final Settings<DedicatedServerProperties>.MutableValue<Boolean> acceptsTransfers = this.getMutable("accepts-transfers", false);
|
| 132 |
|
| 133 | public DedicatedServerProperties(final Properties settings) {
|
| 134 | super(settings);
|
| 135 | String levelSeed = this.get("level-seed", "");
|
| 136 | boolean generateStructures = this.get("generate-structures", true);
|
| 137 | long seed = WorldOptions.parseSeed(levelSeed).orElse(WorldOptions.randomSeed());
|
| 138 | this.worldOptions = new WorldOptions(seed, generateStructures, false);
|
| 139 | this.worldDimensionData = new DedicatedServerProperties.WorldDimensionData(
|
| 140 | this.get("generator-settings", s -> GsonHelper.parse(!s.isEmpty() ? s : "{}"), new JsonObject()),
|
| 141 | this.get("level-type", v -> v.toLowerCase(Locale.ROOT), WorldPresets.NORMAL.identifier().toString())
|
| 142 | );
|
| 143 | this.serverResourcePackInfo = getServerPackInfo(
|
| 144 | this.get("resource-pack-id", ""),
|
| 145 | this.get("resource-pack", ""),
|
| 146 | this.get("resource-pack-sha1", ""),
|
| 147 | this.getLegacyString("resource-pack-hash"),
|
| 148 | this.get("require-resource-pack", false),
|
| 149 | this.get("resource-pack-prompt", "")
|
| 150 | );
|
| 151 | this.initialDataPackConfiguration = getDatapackConfig(
|
| 152 | this.get("initial-enabled-packs", String.join(",", WorldDataConfiguration.DEFAULT.dataPacks().getEnabled())),
|
| 153 | this.get("initial-disabled-packs", String.join(",", WorldDataConfiguration.DEFAULT.dataPacks().getDisabled()))
|
| 154 | );
|
| 155 | }
|
| 156 |
|
| 157 | public static DedicatedServerProperties fromFile(final Path file) {
|
| 158 | return new DedicatedServerProperties(loadFromFile(file));
|
| 159 | }
|
| 160 |
|
| 161 | protected DedicatedServerProperties reload(final RegistryAccess registryAccess, final Properties properties) {
|
| 162 | return new DedicatedServerProperties(properties);
|
| 163 | }
|
| 164 |
|
| 165 | private static @Nullable Component parseResourcePackPrompt(final String prompt) {
|
| 166 | if (!Strings.isNullOrEmpty(prompt)) {
|
| 167 | try {
|
| 168 | JsonElement element = StrictJsonParser.parse(prompt);
|
| 169 | return ComponentSerialization.CODEC
|
| 170 | .parse(RegistryAccess.EMPTY.createSerializationContext(JsonOps.INSTANCE), element)
|
| 171 | .resultOrPartial(msg -> LOGGER.warn("Failed to parse resource pack prompt '{}': {}", prompt, msg))
|
| 172 | .orElse(null);
|
| 173 | } catch (Exception e) {
|
| 174 | LOGGER.warn("Failed to parse resource pack prompt '{}'", prompt, e);
|
| 175 | }
|
| 176 | }
|
| 177 |
|
| 178 | return null;
|
| 179 | }
|
| 180 |
|
| 181 | private static Optional<MinecraftServer.ServerResourcePackInfo> getServerPackInfo(
|
| 182 | final String id,
|
| 183 | final String url,
|
| 184 | final String resourcePackSha1,
|
| 185 | final @Nullable String resourcePackHash,
|
| 186 | final boolean requireResourcePack,
|
| 187 | final String resourcePackPrompt
|
| 188 | ) {
|
| 189 | if (url.isEmpty()) {
|
| 190 | return Optional.empty();
|
| 191 | }
|
| 192 |
|
| 193 | String hash;
|
| 194 | if (!resourcePackSha1.isEmpty()) {
|
| 195 | hash = resourcePackSha1;
|
| 196 | if (!Strings.isNullOrEmpty(resourcePackHash)) {
|
| 197 | LOGGER.warn("resource-pack-hash is deprecated and found along side resource-pack-sha1. resource-pack-hash will be ignored.");
|
| 198 | }
|
| 199 | } else if (!Strings.isNullOrEmpty(resourcePackHash)) {
|
| 200 | LOGGER.warn("resource-pack-hash is deprecated. Please use resource-pack-sha1 instead.");
|
| 201 | hash = resourcePackHash;
|
| 202 | } else {
|
| 203 | hash = "";
|
| 204 | }
|
| 205 |
|
| 206 | if (hash.isEmpty()) {
|
| 207 | LOGGER.warn("You specified a resource pack without providing a sha1 hash. Pack will be updated on the client only if you change the name of the pack.");
|
| 208 | } else if (!SHA1.matcher(hash).matches()) {
|
| 209 | LOGGER.warn("Invalid sha1 for resource-pack-sha1");
|
| 210 | }
|
| 211 |
|
| 212 | Component prompt = parseResourcePackPrompt(resourcePackPrompt);
|
| 213 | UUID parsedId;
|
| 214 | if (id.isEmpty()) {
|
| 215 | parsedId = UUID.nameUUIDFromBytes(url.getBytes(StandardCharsets.UTF_8));
|
| 216 | LOGGER.warn("resource-pack-id missing, using default of {}", parsedId);
|
| 217 | } else {
|
| 218 | try {
|
| 219 | parsedId = UUID.fromString(id);
|
| 220 | } catch (IllegalArgumentException e) {
|
| 221 | LOGGER.warn("Failed to parse '{}' into UUID", id);
|
| 222 | return Optional.empty();
|
| 223 | }
|
| 224 | }
|
| 225 |
|
| 226 | return Optional.of(new MinecraftServer.ServerResourcePackInfo(parsedId, url, hash, requireResourcePack, prompt));
|
| 227 | }
|
| 228 |
|
| 229 | private static DataPackConfig getDatapackConfig(final String enabledPacks, final String disabledPacks) {
|
| 230 | List<String> enabledPacksIds = COMMA_SPLITTER.splitToList(enabledPacks);
|
| 231 | List<String> disabledPacksIds = COMMA_SPLITTER.splitToList(disabledPacks);
|
| 232 | return new DataPackConfig(enabledPacksIds, disabledPacksIds);
|
| 233 | }
|
| 234 |
|
| 235 | public static @Nullable LevelBasedPermissionSet deserializePermission(final String value) {
|
| 236 | try {
|
| 237 | PermissionLevel permissionLevel = PermissionLevel.byId(Integer.parseInt(value));
|
| 238 | return LevelBasedPermissionSet.forLevel(permissionLevel);
|
| 239 | } catch (NumberFormatException e) {
|
| 240 | return null;
|
| 241 | }
|
| 242 | }
|
| 243 |
|
| 244 | public static String serializePermission(final LevelBasedPermissionSet permission) {
|
| 245 | return Integer.toString(permission.level().id());
|
| 246 | }
|
| 247 |
|
| 248 | public WorldDimensions createDimensions(final HolderLookup.Provider registries) {
|
| 249 | return this.worldDimensionData.create(registries);
|
| 250 | }
|
| 251 |
|
| 252 | private record WorldDimensionData(JsonObject generatorSettings, String levelType) {
|
| 253 | private static final Map<String, ResourceKey<WorldPreset>> LEGACY_PRESET_NAMES = Map.of(
|
| 254 | "default", WorldPresets.NORMAL, "largebiomes", WorldPresets.LARGE_BIOMES
|
| 255 | );
|
| 256 |
|
| 257 | public WorldDimensions create(final HolderLookup.Provider registries) {
|
| 258 | HolderLookup<WorldPreset> worldPresets = registries.lookupOrThrow(Registries.WORLD_PRESET);
|
| 259 | Holder.Reference<WorldPreset> defaultHolder = worldPresets.get(WorldPresets.NORMAL)
|
| 260 | .or(() -> worldPresets.listElements().findAny())
|
| 261 | .orElseThrow(() -> new IllegalStateException("Invalid datapack contents: can't find default preset"));
|
| 262 | Holder<WorldPreset> worldPreset = Optional.ofNullable(Identifier.tryParse(this.levelType))
|
| 263 | .map(id -> ResourceKey.create(Registries.WORLD_PRESET, id))
|
| 264 | .or(() -> Optional.ofNullable(LEGACY_PRESET_NAMES.get(this.levelType)))
|
| 265 | .flatMap(worldPresets::get)
|
| 266 | .orElseGet(() -> {
|
| 267 | DedicatedServerProperties.LOGGER.warn("Failed to parse level-type {}, defaulting to {}", this.levelType, defaultHolder.key().identifier());
|
| 268 | return defaultHolder;
|
| 269 | });
|
| 270 | WorldDimensions worldDimensions = worldPreset.value().createWorldDimensions();
|
| 271 | if (worldPreset.is(WorldPresets.FLAT)) {
|
| 272 | RegistryOps<JsonElement> ops = registries.createSerializationContext(JsonOps.INSTANCE);
|
| 273 | Optional<FlatLevelGeneratorSettings> parsedSettings = FlatLevelGeneratorSettings.CODEC
|
| 274 | .parse(new Dynamic<>(ops, this.generatorSettings()))
|
| 275 | .resultOrPartial(DedicatedServerProperties.LOGGER::error);
|
| 276 | if (parsedSettings.isPresent()) {
|
| 277 | return worldDimensions.replaceOverworldGenerator(registries, new FlatLevelSource(parsedSettings.get()));
|
| 278 | }
|
| 279 | }
|
| 280 |
|
| 281 | return worldDimensions;
|
| 282 | }
|
| 283 | }
|
| 284 | }
|
| 285 |
|