| 1 | package net.minecraft.world.level.storage;
|
| 2 |
|
| 3 | import com.google.common.collect.Maps;
|
| 4 | import com.mojang.datafixers.DataFixer;
|
| 5 | import com.mojang.logging.LogUtils;
|
| 6 | import com.mojang.serialization.Codec;
|
| 7 | import com.mojang.serialization.DataResult;
|
| 8 | import com.mojang.serialization.Dynamic;
|
| 9 | import com.mojang.serialization.DynamicOps;
|
| 10 | import com.mojang.serialization.Lifecycle;
|
| 11 | import java.io.BufferedOutputStream;
|
| 12 | import java.io.BufferedReader;
|
| 13 | import java.io.IOException;
|
| 14 | import java.io.UncheckedIOException;
|
| 15 | import java.nio.file.FileVisitResult;
|
| 16 | import java.nio.file.Files;
|
| 17 | import java.nio.file.InvalidPathException;
|
| 18 | import java.nio.file.Path;
|
| 19 | import java.nio.file.PathMatcher;
|
| 20 | import java.nio.file.Paths;
|
| 21 | import java.nio.file.SimpleFileVisitor;
|
| 22 | import java.nio.file.attribute.BasicFileAttributes;
|
| 23 | import java.time.Instant;
|
| 24 | import java.time.ZonedDateTime;
|
| 25 | import java.util.ArrayList;
|
| 26 | import java.util.Iterator;
|
| 27 | import java.util.List;
|
| 28 | import java.util.Map;
|
| 29 | import java.util.Objects;
|
| 30 | import java.util.Optional;
|
| 31 | import java.util.Set;
|
| 32 | import java.util.UUID;
|
| 33 | import java.util.concurrent.CompletableFuture;
|
| 34 | import java.util.function.Consumer;
|
| 35 | import java.util.function.Function;
|
| 36 | import java.util.stream.Collectors;
|
| 37 | import java.util.stream.Stream;
|
| 38 | import java.util.zip.ZipEntry;
|
| 39 | import java.util.zip.ZipOutputStream;
|
| 40 | import net.minecraft.CrashReport;
|
| 41 | import net.minecraft.CrashReportCategory;
|
| 42 | import net.minecraft.ReportedException;
|
| 43 | import net.minecraft.core.HolderLookup;
|
| 44 | import net.minecraft.core.Registry;
|
| 45 | import net.minecraft.core.RegistryAccess;
|
| 46 | import net.minecraft.nbt.CompoundTag;
|
| 47 | import net.minecraft.nbt.NbtAccounter;
|
| 48 | import net.minecraft.nbt.NbtException;
|
| 49 | import net.minecraft.nbt.NbtFormatException;
|
| 50 | import net.minecraft.nbt.NbtIo;
|
| 51 | import net.minecraft.nbt.NbtOps;
|
| 52 | import net.minecraft.nbt.NbtUtils;
|
| 53 | import net.minecraft.nbt.ReportedNbtException;
|
| 54 | import net.minecraft.nbt.Tag;
|
| 55 | import net.minecraft.nbt.visitors.FieldSelector;
|
| 56 | import net.minecraft.nbt.visitors.SkipFields;
|
| 57 | import net.minecraft.network.chat.Component;
|
| 58 | import net.minecraft.resources.Identifier;
|
| 59 | import net.minecraft.resources.RegistryOps;
|
| 60 | import net.minecraft.resources.ResourceKey;
|
| 61 | import net.minecraft.server.WorldLoader;
|
| 62 | import net.minecraft.server.packs.repository.PackRepository;
|
| 63 | import net.minecraft.util.DirectoryLock;
|
| 64 | import net.minecraft.util.FileUtil;
|
| 65 | import net.minecraft.util.MemoryReserve;
|
| 66 | import net.minecraft.util.Util;
|
| 67 | import net.minecraft.util.datafix.DataFixTypes;
|
| 68 | import net.minecraft.util.datafix.DataFixers;
|
| 69 | import net.minecraft.world.flag.FeatureFlagSet;
|
| 70 | import net.minecraft.world.flag.FeatureFlags;
|
| 71 | import net.minecraft.world.level.Level;
|
| 72 | import net.minecraft.world.level.LevelSettings;
|
| 73 | import net.minecraft.world.level.WorldDataConfiguration;
|
| 74 | import net.minecraft.world.level.dimension.DimensionType;
|
| 75 | import net.minecraft.world.level.dimension.LevelStem;
|
| 76 | import net.minecraft.world.level.gamerules.GameRuleMap;
|
| 77 | import net.minecraft.world.level.gamerules.GameRules;
|
| 78 | import net.minecraft.world.level.levelgen.WorldDimensions;
|
| 79 | import net.minecraft.world.level.levelgen.WorldGenSettings;
|
| 80 | import net.minecraft.world.level.levelgen.WorldOptions;
|
| 81 | import net.minecraft.world.level.saveddata.SavedData;
|
| 82 | import net.minecraft.world.level.saveddata.SavedDataType;
|
| 83 | import net.minecraft.world.level.validation.ContentValidationException;
|
| 84 | import net.minecraft.world.level.validation.DirectoryValidator;
|
| 85 | import net.minecraft.world.level.validation.ForbiddenSymlinkInfo;
|
| 86 | import net.minecraft.world.level.validation.PathAllowList;
|
| 87 | import org.apache.commons.io.function.IORunnable;
|
| 88 | import org.jspecify.annotations.Nullable;
|
| 89 | import org.slf4j.Logger;
|
| 90 |
|
| 91 | public class LevelStorageSource {
|
| 92 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 93 | public static final String TAG_DATA = "Data";
|
| 94 | private static final PathMatcher NO_SYMLINKS_ALLOWED = path -> false;
|
| 95 | public static final String ALLOWED_SYMLINKS_CONFIG_NAME = "allowed_symlinks.txt";
|
| 96 | private static final int DISK_SPACE_WARNING_THRESHOLD = 67108864;
|
| 97 | private static final Component LOAD_FOLDER_ACCESS_MESSAGE = Component.translatable("selectWorld.load_folder_access");
|
| 98 | private final Path baseDir;
|
| 99 | private final Path backupDir;
|
| 100 | private final DataFixer fixerUpper;
|
| 101 | private final DirectoryValidator worldDirValidator;
|
| 102 |
|
| 103 | public LevelStorageSource(final Path baseDir, final Path backupDir, final DirectoryValidator worldDirValidator, final DataFixer fixerUpper) {
|
| 104 | this.fixerUpper = fixerUpper;
|
| 105 |
|
| 106 | try {
|
| 107 | FileUtil.createDirectoriesSafe(baseDir);
|
| 108 | } catch (IOException e) {
|
| 109 | throw new UncheckedIOException(e);
|
| 110 | }
|
| 111 |
|
| 112 | this.baseDir = baseDir;
|
| 113 | this.backupDir = backupDir;
|
| 114 | this.worldDirValidator = worldDirValidator;
|
| 115 | }
|
| 116 |
|
| 117 | public static DirectoryValidator parseValidator(final Path configPath) {
|
| 118 | if (Files.exists(configPath)) {
|
| 119 | try (BufferedReader reader = Files.newBufferedReader(configPath)) {
|
| 120 | return new DirectoryValidator(PathAllowList.readPlain(reader));
|
| 121 | } catch (Exception e) {
|
| 122 | LOGGER.error("Failed to parse {}, disallowing all symbolic links", "allowed_symlinks.txt", e);
|
| 123 | }
|
| 124 | }
|
| 125 |
|
| 126 | return new DirectoryValidator(NO_SYMLINKS_ALLOWED);
|
| 127 | }
|
| 128 |
|
| 129 | public static LevelStorageSource createDefault(final Path path) {
|
| 130 | DirectoryValidator validator = parseValidator(path.resolve("allowed_symlinks.txt"));
|
| 131 | return new LevelStorageSource(path, path.resolve("../backups"), validator, DataFixers.getDataFixer());
|
| 132 | }
|
| 133 |
|
| 134 | public static WorldDataConfiguration readDataConfig(final Dynamic<?> levelData) {
|
| 135 | return WorldDataConfiguration.CODEC.parse(levelData).resultOrPartial(LOGGER::error).orElse(WorldDataConfiguration.DEFAULT);
|
| 136 | }
|
| 137 |
|
| 138 | public static WorldLoader.PackConfig getPackConfig(final Dynamic<?> levelDataTag, final PackRepository packRepository, final boolean safeMode) {
|
| 139 | return new WorldLoader.PackConfig(packRepository, readDataConfig(levelDataTag), safeMode, false);
|
| 140 | }
|
| 141 |
|
| 142 | public static LevelDataAndDimensions getLevelDataAndDimensions(
|
| 143 | final LevelStorageSource.LevelStorageAccess worldAccess,
|
| 144 | final Dynamic<?> levelDataTag,
|
| 145 | final WorldDataConfiguration dataConfiguration,
|
| 146 | final Registry<LevelStem> datapackDimensions,
|
| 147 | final HolderLookup.Provider registryAccess
|
| 148 | ) {
|
| 149 | if (DataFixers.getFileFixer().requiresFileFixing(NbtUtils.getDataVersion(levelDataTag))) {
|
| 150 | throw new IllegalStateException("Cannot get level data without file fixing first");
|
| 151 | }
|
| 152 |
|
| 153 | Dynamic<?> dataTag = RegistryOps.injectRegistryContext(levelDataTag, registryAccess);
|
| 154 | WorldGenSettings worldGenSettings = readExistingSavedData(worldAccess, registryAccess, WorldGenSettings.TYPE).mapOrElse(Function.identity(), error -> {
|
| 155 | LOGGER.error("Unable to read or access the world gen settings file! Falling back to the default settings with a random world seed. {}", error.message());
|
| 156 | return new WorldGenSettings(WorldOptions.defaultWithRandomSeed(), new WorldDimensions(datapackDimensions));
|
| 157 | });
|
| 158 | LevelSettings settings = LevelSettings.parse(dataTag, dataConfiguration);
|
| 159 | WorldDimensions.Complete dimensions = worldGenSettings.dimensions().bake(datapackDimensions);
|
| 160 | Lifecycle lifecycle = dimensions.lifecycle().add(registryAccess.allRegistriesLifecycle());
|
| 161 | PrimaryLevelData worldData = PrimaryLevelData.parse(dataTag, settings, dimensions.specialWorldProperty(), lifecycle);
|
| 162 | return LevelDataAndDimensions.create(worldData, worldGenSettings, dimensions);
|
| 163 | }
|
| 164 |
|
| 165 | public static <T extends SavedData> DataResult<T> readExistingSavedData(
|
| 166 | final LevelStorageSource.LevelStorageAccess access, final HolderLookup.Provider registryAccess, final SavedDataType<T> savedDataType
|
| 167 | ) {
|
| 168 | Path dataLocation = savedDataType.id().withSuffix(".dat").resolveAgainst(access.getLevelPath(LevelResource.DATA));
|
| 169 |
|
| 170 | CompoundTag fileContents;
|
| 171 | try {
|
| 172 | fileContents = NbtIo.readCompressed(dataLocation, NbtAccounter.unlimitedHeap());
|
| 173 | } catch (IOException e) {
|
| 174 | return DataResult.error(e::getMessage);
|
| 175 | }
|
| 176 |
|
| 177 | return savedDataType.codec().parse(RegistryOps.create(NbtOps.INSTANCE, registryAccess), fileContents.getCompoundOrEmpty("data"));
|
| 178 | }
|
| 179 |
|
| 180 | public static void writeGameRules(final WorldData worldData, final Path worldFolder, final GameRules gameRules) throws IOException {
|
| 181 | Codec<GameRules> codec = GameRules.codec(worldData.enabledFeatures());
|
| 182 | writeSavedData(worldFolder, NbtOps.INSTANCE, GameRuleMap.TYPE, codec, gameRules);
|
| 183 | }
|
| 184 |
|
| 185 | public static void writeWorldGenSettings(final RegistryAccess registryAccess, final Path worldFolder, final WorldGenSettings worldGenSettings) throws IOException {
|
| 186 | RegistryOps<Tag> ops = RegistryOps.create(NbtOps.INSTANCE, registryAccess);
|
| 187 | writeSavedData(worldFolder, ops, WorldGenSettings.TYPE, WorldGenSettings.CODEC, worldGenSettings);
|
| 188 | }
|
| 189 |
|
| 190 | private static <T> void writeSavedData(final Path worldFolder, final DynamicOps<Tag> ops, final SavedDataType<?> type, final Codec<T> codec, final T data) throws IOException {
|
| 191 | Tag encoded = codec.encodeStart(ops, data).getOrThrow();
|
| 192 | CompoundTag fullTag = new CompoundTag();
|
| 193 | fullTag.put("data", encoded);
|
| 194 | NbtUtils.addCurrentDataVersion(fullTag);
|
| 195 | Path path = type.id().withSuffix(".dat").resolveAgainst(worldFolder.resolve("data"));
|
| 196 | FileUtil.createDirectoriesSafe(path.getParent());
|
| 197 | NbtIo.writeCompressed(fullTag, path);
|
| 198 | }
|
| 199 |
|
| 200 | public String getName() {
|
| 201 | return "Anvil";
|
| 202 | }
|
| 203 |
|
| 204 | public LevelStorageSource.LevelCandidates findLevelCandidates() throws LevelStorageException {
|
| 205 | if (!Files.exists(this.baseDir)) {
|
| 206 | try {
|
| 207 | Files.createDirectory(this.baseDir);
|
| 208 | } catch (IOException e) {
|
| 209 | throw new LevelStorageException(LOAD_FOLDER_ACCESS_MESSAGE, e);
|
| 210 | }
|
| 211 | } else if (!Files.isDirectory(this.baseDir)) {
|
| 212 | throw new LevelStorageException(LOAD_FOLDER_ACCESS_MESSAGE);
|
| 213 | }
|
| 214 |
|
| 215 | try (Stream<Path> paths = Files.list(this.baseDir)) {
|
| 216 | List<LevelStorageSource.LevelDirectory> candidates = paths.filter(x$0 -> Files.isDirectory(x$0))
|
| 217 | .map(LevelStorageSource.LevelDirectory::new)
|
| 218 | .filter(directory -> Files.isRegularFile(directory.dataFile()) || Files.isRegularFile(directory.oldDataFile()))
|
| 219 | .toList();
|
| 220 | return new LevelStorageSource.LevelCandidates(candidates);
|
| 221 | } catch (IOException e) {
|
| 222 | throw new LevelStorageException(LOAD_FOLDER_ACCESS_MESSAGE);
|
| 223 | }
|
| 224 | }
|
| 225 |
|
| 226 | public CompletableFuture<List<LevelSummary>> loadLevelSummaries(final LevelStorageSource.LevelCandidates candidates) {
|
| 227 | List<CompletableFuture<LevelSummary>> futures = new ArrayList<>(candidates.levels.size());
|
| 228 |
|
| 229 | for (LevelStorageSource.LevelDirectory level : candidates.levels) {
|
| 230 | futures.add(CompletableFuture.supplyAsync(() -> {
|
| 231 | boolean locked;
|
| 232 | try {
|
| 233 | locked = DirectoryLock.isLocked(level.path());
|
| 234 | } catch (Exception e) {
|
| 235 | LOGGER.warn("Failed to read {} lock", level.path(), e);
|
| 236 | return null;
|
| 237 | }
|
| 238 |
|
| 239 | try {
|
| 240 | return this.readLevelSummary(level, locked);
|
| 241 | } catch (OutOfMemoryError e) {
|
| 242 | MemoryReserve.release();
|
| 243 | String detailedMessage = "Ran out of memory trying to read summary of world folder \"" + level.directoryName() + "\"";
|
| 244 | LOGGER.error(LogUtils.FATAL_MARKER, "{}", detailedMessage);
|
| 245 | OutOfMemoryError detailedException = new OutOfMemoryError("Ran out of memory reading level data");
|
| 246 | detailedException.initCause(e);
|
| 247 | CrashReport crashReport = CrashReport.forThrowable(detailedException, detailedMessage);
|
| 248 | CrashReportCategory worldDetails = crashReport.addCategory("World details");
|
| 249 | worldDetails.setDetail("Folder Name", level.directoryName());
|
| 250 |
|
| 251 | try {
|
| 252 | long size = Files.size(level.dataFile());
|
| 253 | worldDetails.setDetail("level.dat size", size);
|
| 254 | } catch (IOException ex) {
|
| 255 | worldDetails.setDetailError("level.dat size", ex);
|
| 256 | }
|
| 257 |
|
| 258 | throw new ReportedException(crashReport);
|
| 259 | }
|
| 260 | }, Util.backgroundExecutor().forName("loadLevelSummaries")));
|
| 261 | }
|
| 262 |
|
| 263 | return Util.sequenceFailFastAndCancel(futures).thenApply(levels -> levels.stream().filter(Objects::nonNull).sorted().toList());
|
| 264 | }
|
| 265 |
|
| 266 | private int getStorageVersion() {
|
| 267 | return 19133;
|
| 268 | }
|
| 269 |
|
| 270 | private static CompoundTag readLevelDataTagRaw(final Path dataFile) throws IOException {
|
| 271 | return NbtIo.readCompressed(dataFile, NbtAccounter.uncompressedQuota());
|
| 272 | }
|
| 273 |
|
| 274 | private LevelSummary readLevelSummary(final LevelStorageSource.LevelDirectory level, final boolean locked) {
|
| 275 | Path dataFile = level.dataFile();
|
| 276 | if (Files.exists(dataFile)) {
|
| 277 | try {
|
| 278 | if (Files.isSymbolicLink(dataFile)) {
|
| 279 | List<ForbiddenSymlinkInfo> issues = this.worldDirValidator.validateSymlink(dataFile);
|
| 280 | if (!issues.isEmpty()) {
|
| 281 | LOGGER.warn("{}", ContentValidationException.getMessage(dataFile, issues));
|
| 282 | return new LevelSummary.SymlinkLevelSummary(level.directoryName(), level.iconFile());
|
| 283 | }
|
| 284 | }
|
| 285 |
|
| 286 | if (readLightweightData(dataFile) instanceof CompoundTag root) {
|
| 287 | CompoundTag tag = root.getCompoundOrEmpty("Data");
|
| 288 | int dataVersion = NbtUtils.getDataVersion(tag);
|
| 289 | Dynamic<?> updated = DataFixTypes.LEVEL_SUMMARY.updateToCurrentVersion(this.fixerUpper, new Dynamic<>(NbtOps.INSTANCE, tag), dataVersion);
|
| 290 | return this.makeLevelSummary(updated, level, locked, dataVersion);
|
| 291 | }
|
| 292 |
|
| 293 | LOGGER.warn("Invalid root tag in {}", dataFile);
|
| 294 | } catch (Exception e) {
|
| 295 | LOGGER.error("Exception reading {}", dataFile, e);
|
| 296 | }
|
| 297 | }
|
| 298 |
|
| 299 | return new LevelSummary.CorruptedLevelSummary(level.directoryName(), level.iconFile(), getFileModificationTime(level));
|
| 300 | }
|
| 301 |
|
| 302 | private static long getFileModificationTime(final LevelStorageSource.LevelDirectory level) {
|
| 303 | Instant timeStamp = getFileModificationTime(level.dataFile());
|
| 304 | if (timeStamp == null) {
|
| 305 | timeStamp = getFileModificationTime(level.oldDataFile());
|
| 306 | }
|
| 307 |
|
| 308 | return timeStamp == null ? -1L : timeStamp.toEpochMilli();
|
| 309 | }
|
| 310 |
|
| 311 | private static @Nullable Instant getFileModificationTime(final Path path) {
|
| 312 | try {
|
| 313 | return Files.getLastModifiedTime(path).toInstant();
|
| 314 | } catch (IOException var2) {
|
| 315 | return null;
|
| 316 | }
|
| 317 | }
|
| 318 |
|
| 319 | private LevelSummary makeLevelSummary(
|
| 320 | final Dynamic<?> dataTag, final LevelStorageSource.LevelDirectory levelDirectory, final boolean locked, final int dataVersion
|
| 321 | ) {
|
| 322 | LevelVersion levelVersion = LevelVersion.parse(dataTag);
|
| 323 | int levelDataVersion = levelVersion.levelDataVersion();
|
| 324 | if (levelDataVersion != 19132 && levelDataVersion != 19133) {
|
| 325 | throw new NbtFormatException("Unknown data version: " + Integer.toHexString(levelDataVersion));
|
| 326 | }
|
| 327 |
|
| 328 | boolean requiresManualConversion = levelDataVersion != this.getStorageVersion();
|
| 329 | boolean requiresFileFixing = DataFixers.getFileFixer().requiresFileFixing(dataVersion);
|
| 330 | Path icon = levelDirectory.iconFile();
|
| 331 | WorldDataConfiguration dataConfiguration = readDataConfig(dataTag);
|
| 332 | LevelSettings settings = LevelSettings.parse(dataTag, dataConfiguration);
|
| 333 | FeatureFlagSet enabledFeatureFlags = parseFeatureFlagsFromSummary(dataTag);
|
| 334 | boolean experimental = FeatureFlags.isExperimental(enabledFeatureFlags);
|
| 335 | return new LevelSummary(settings, levelVersion, levelDirectory.directoryName(), requiresManualConversion, requiresFileFixing, locked, experimental, icon);
|
| 336 | }
|
| 337 |
|
| 338 | private static FeatureFlagSet parseFeatureFlagsFromSummary(final Dynamic<?> tag) {
|
| 339 | Set<Identifier> enabledFlags = tag.get("enabled_features")
|
| 340 | .asStream()
|
| 341 | .flatMap(entry -> entry.asString().result().map(Identifier::tryParse).stream())
|
| 342 | .collect(Collectors.toSet());
|
| 343 | return FeatureFlags.REGISTRY.fromNames(enabledFlags, unknownId -> {});
|
| 344 | }
|
| 345 |
|
| 346 | private static @Nullable Tag readLightweightData(final Path dataFile) throws IOException {
|
| 347 | SkipFields parser = new SkipFields(new FieldSelector("Data", CompoundTag.TYPE, "Player"), new FieldSelector("Data", CompoundTag.TYPE, "WorldGenSettings"));
|
| 348 | NbtIo.parseCompressed(dataFile, parser, NbtAccounter.uncompressedQuota());
|
| 349 | return parser.getResult();
|
| 350 | }
|
| 351 |
|
| 352 | public boolean isNewLevelIdAcceptable(final String levelId) {
|
| 353 | try {
|
| 354 | Path fullPath = this.getLevelPath(levelId);
|
| 355 | Files.createDirectory(fullPath);
|
| 356 | Files.deleteIfExists(fullPath);
|
| 357 | return true;
|
| 358 | } catch (IOException e) {
|
| 359 | return false;
|
| 360 | }
|
| 361 | }
|
| 362 |
|
| 363 | public boolean levelExists(final String levelId) {
|
| 364 | try {
|
| 365 | return Files.isDirectory(this.getLevelPath(levelId));
|
| 366 | } catch (InvalidPathException e) {
|
| 367 | return false;
|
| 368 | }
|
| 369 | }
|
| 370 |
|
| 371 | public Path getLevelPath(final String levelId) {
|
| 372 | return this.baseDir.resolve(levelId);
|
| 373 | }
|
| 374 |
|
| 375 | public Path getBaseDir() {
|
| 376 | return this.baseDir;
|
| 377 | }
|
| 378 |
|
| 379 | public Path getBackupPath() {
|
| 380 | return this.backupDir;
|
| 381 | }
|
| 382 |
|
| 383 | public LevelStorageSource.LevelStorageAccess validateAndCreateAccess(final String levelId) throws IOException, ContentValidationException {
|
| 384 | Path levelPath = this.getLevelPath(levelId);
|
| 385 | List<ForbiddenSymlinkInfo> validationResults = this.worldDirValidator.validateDirectory(levelPath, true);
|
| 386 | if (!validationResults.isEmpty()) {
|
| 387 | throw new ContentValidationException(levelPath, validationResults);
|
| 388 | } else {
|
| 389 | return new LevelStorageSource.LevelStorageAccess(levelId, levelPath);
|
| 390 | }
|
| 391 | }
|
| 392 |
|
| 393 | public LevelStorageSource.LevelStorageAccess createAccess(final String levelId) throws IOException {
|
| 394 | Path levelPath = this.getLevelPath(levelId);
|
| 395 | return new LevelStorageSource.LevelStorageAccess(levelId, levelPath);
|
| 396 | }
|
| 397 |
|
| 398 | public DirectoryValidator getWorldDirValidator() {
|
| 399 | return this.worldDirValidator;
|
| 400 | }
|
| 401 |
|
| 402 | public record LevelCandidates(List<LevelStorageSource.LevelDirectory> levels) implements Iterable<LevelStorageSource.LevelDirectory> {
|
| 403 | public boolean isEmpty() {
|
| 404 | return this.levels.isEmpty();
|
| 405 | }
|
| 406 |
|
| 407 | @Override
|
| 408 | public Iterator<LevelStorageSource.LevelDirectory> iterator() {
|
| 409 | return this.levels.iterator();
|
| 410 | }
|
| 411 | }
|
| 412 |
|
| 413 | public record LevelDirectory(Path path) {
|
| 414 | public String directoryName() {
|
| 415 | return this.path.getFileName().toString();
|
| 416 | }
|
| 417 |
|
| 418 | public Path dataFile() {
|
| 419 | return this.resourcePath(LevelResource.LEVEL_DATA_FILE);
|
| 420 | }
|
| 421 |
|
| 422 | public Path oldDataFile() {
|
| 423 | return this.resourcePath(LevelResource.OLD_LEVEL_DATA_FILE);
|
| 424 | }
|
| 425 |
|
| 426 | public Path corruptedDataFile(final ZonedDateTime time) {
|
| 427 | return this.path.resolve(LevelResource.LEVEL_DATA_FILE.id() + "_corrupted_" + time.format(FileNameDateFormatter.FORMATTER));
|
| 428 | }
|
| 429 |
|
| 430 | public Path rawDataFile(final ZonedDateTime time) {
|
| 431 | return this.path.resolve(LevelResource.LEVEL_DATA_FILE.id() + "_raw_" + time.format(FileNameDateFormatter.FORMATTER));
|
| 432 | }
|
| 433 |
|
| 434 | public Path iconFile() {
|
| 435 | return this.resourcePath(LevelResource.ICON_FILE);
|
| 436 | }
|
| 437 |
|
| 438 | public Path lockFile() {
|
| 439 | return this.resourcePath(LevelResource.LOCK_FILE);
|
| 440 | }
|
| 441 |
|
| 442 | public Path resourcePath(final LevelResource resource) {
|
| 443 | return this.path.resolve(resource.id());
|
| 444 | }
|
| 445 | }
|
| 446 |
|
| 447 | public class LevelStorageAccess implements AutoCloseable {
|
| 448 | private DirectoryLock lock;
|
| 449 | private final LevelStorageSource.LevelDirectory levelDirectory;
|
| 450 | private final String levelId;
|
| 451 | private final Map<LevelResource, Path> resources = Maps.newHashMap();
|
| 452 |
|
| 453 | private LevelStorageAccess(final String levelId, final Path path) throws IOException {
|
| 454 | this.levelId = levelId;
|
| 455 | this.levelDirectory = new LevelStorageSource.LevelDirectory(path);
|
| 456 | this.createLock();
|
| 457 | }
|
| 458 |
|
| 459 | private void createLock() throws IOException {
|
| 460 | this.lock = DirectoryLock.create(this.levelDirectory.path);
|
| 461 | }
|
| 462 |
|
| 463 | public void releaseTemporarilyAndRun(final IORunnable runnable) throws IOException {
|
| 464 | this.close();
|
| 465 |
|
| 466 | try {
|
| 467 | runnable.run();
|
| 468 | } finally {
|
| 469 | this.createLock();
|
| 470 | }
|
| 471 | }
|
| 472 |
|
| 473 | public long estimateDiskSpace() {
|
| 474 | try {
|
| 475 | return Files.getFileStore(this.levelDirectory.path).getUsableSpace();
|
| 476 | } catch (Exception ignored) {
|
| 477 | return Long.MAX_VALUE;
|
| 478 | }
|
| 479 | }
|
| 480 |
|
| 481 | public boolean checkForLowDiskSpace() {
|
| 482 | return this.estimateDiskSpace() < 67108864L;
|
| 483 | }
|
| 484 |
|
| 485 | public void safeClose() {
|
| 486 | try {
|
| 487 | this.close();
|
| 488 | } catch (IOException e) {
|
| 489 | LevelStorageSource.LOGGER.warn("Failed to unlock access to level {}", this.getLevelId(), e);
|
| 490 | }
|
| 491 | }
|
| 492 |
|
| 493 | public LevelStorageSource parent() {
|
| 494 | return LevelStorageSource.this;
|
| 495 | }
|
| 496 |
|
| 497 | public LevelStorageSource.LevelDirectory getLevelDirectory() {
|
| 498 | return this.levelDirectory;
|
| 499 | }
|
| 500 |
|
| 501 | public String getLevelId() {
|
| 502 | return this.levelId;
|
| 503 | }
|
| 504 |
|
| 505 | public Path getLevelPath(final LevelResource resource) {
|
| 506 | return this.resources.computeIfAbsent(resource, this.levelDirectory::resourcePath);
|
| 507 | }
|
| 508 |
|
| 509 | public Path getDimensionPath(final ResourceKey<Level> name) {
|
| 510 | return DimensionType.getStorageFolder(name, this.levelDirectory.path());
|
| 511 | }
|
| 512 |
|
| 513 | private void checkLock() {
|
| 514 | if (!this.lock.isValid()) {
|
| 515 | throw new IllegalStateException("Lock is no longer valid");
|
| 516 | }
|
| 517 | }
|
| 518 |
|
| 519 | public PlayerDataStorage createPlayerStorage() {
|
| 520 | this.checkLock();
|
| 521 | return new PlayerDataStorage(this, LevelStorageSource.this.fixerUpper);
|
| 522 | }
|
| 523 |
|
| 524 | public void collectIssues(final boolean useFallback) throws IOException {
|
| 525 | this.checkLock();
|
| 526 | Dynamic<?> unfixedDataTag = this.getUnfixedDataTag(useFallback);
|
| 527 | int dataVersion = NbtUtils.getDataVersion(unfixedDataTag);
|
| 528 | Dynamic<?> fixedDataTag = DataFixTypes.LEVEL.updateToCurrentVersion(LevelStorageSource.this.fixerUpper, unfixedDataTag, dataVersion);
|
| 529 | LevelStorageSource.this.makeLevelSummary(fixedDataTag, this.levelDirectory, false, dataVersion);
|
| 530 | }
|
| 531 |
|
| 532 | public LevelSummary fixAndGetSummary() throws IOException {
|
| 533 | this.checkLock();
|
| 534 | return this.fixAndGetSummaryFromTag(this.getUnfixedDataTag(false));
|
| 535 | }
|
| 536 |
|
| 537 | public LevelSummary fixAndGetSummaryFromTag(final Dynamic<?> dataTag) {
|
| 538 | this.checkLock();
|
| 539 | int dataVersion = NbtUtils.getDataVersion(dataTag);
|
| 540 | Dynamic<?> dataTagFixed = DataFixTypes.LEVEL_SUMMARY.updateToCurrentVersion(LevelStorageSource.this.fixerUpper, dataTag, dataVersion);
|
| 541 | return LevelStorageSource.this.makeLevelSummary(dataTagFixed, this.levelDirectory, false, dataVersion);
|
| 542 | }
|
| 543 |
|
| 544 | public Dynamic<?> getUnfixedDataTagWithFallback() throws IOException {
|
| 545 | Dynamic<?> unfixedDataTag;
|
| 546 | try {
|
| 547 | unfixedDataTag = this.getUnfixedDataTag(false);
|
| 548 | } catch (IOException | NbtException | ReportedNbtException e) {
|
| 549 | LevelStorageSource.LOGGER.warn("Failed to load world data from {}", this.levelDirectory.dataFile(), e);
|
| 550 | LevelStorageSource.LOGGER.info("Attempting to use fallback {}", this.levelDirectory.oldDataFile());
|
| 551 | unfixedDataTag = this.getUnfixedDataTag(true);
|
| 552 | this.restoreLevelDataFromOld();
|
| 553 | }
|
| 554 |
|
| 555 | return unfixedDataTag;
|
| 556 | }
|
| 557 |
|
| 558 | public Dynamic<?> getUnfixedDataTag(final boolean useFallback) throws IOException {
|
| 559 | this.checkLock();
|
| 560 | Path dataFile = this.getDataFile(useFallback);
|
| 561 | CompoundTag root = LevelStorageSource.readLevelDataTagRaw(dataFile);
|
| 562 | return new Dynamic<>(NbtOps.INSTANCE, root.getCompoundOrEmpty("Data"));
|
| 563 | }
|
| 564 |
|
| 565 | private Path getDataFile(final boolean useFallback) {
|
| 566 | return useFallback ? this.levelDirectory.oldDataFile() : this.levelDirectory.dataFile();
|
| 567 | }
|
| 568 |
|
| 569 | public void saveDataTag(final WorldData levelData) {
|
| 570 | this.saveDataTag(levelData, null);
|
| 571 | }
|
| 572 |
|
| 573 | public void saveDataTag(final WorldData levelData, final @Nullable UUID singleplayerUUID) {
|
| 574 | CompoundTag dataTag = levelData.createTag(singleplayerUUID);
|
| 575 | CompoundTag root = new CompoundTag();
|
| 576 | root.put("Data", dataTag);
|
| 577 | this.saveLevelData(root);
|
| 578 | }
|
| 579 |
|
| 580 | public void saveLevelData(final Dynamic<?> tag) {
|
| 581 | Tag genericTag = tag.convert(NbtOps.INSTANCE).getValue();
|
| 582 | CompoundTag root = new CompoundTag();
|
| 583 | root.put("Data", genericTag);
|
| 584 | this.saveLevelData(root);
|
| 585 | }
|
| 586 |
|
| 587 | private void saveLevelData(final CompoundTag root) {
|
| 588 | Path worldDir = this.levelDirectory.path();
|
| 589 |
|
| 590 | try {
|
| 591 | Path dataFile = Files.createTempFile(worldDir, "level", ".dat");
|
| 592 | NbtIo.writeCompressed(root, dataFile);
|
| 593 | Path oldDataFile = this.levelDirectory.oldDataFile();
|
| 594 | Path currentFile = this.levelDirectory.dataFile();
|
| 595 | Util.safeReplaceFile(currentFile, dataFile, oldDataFile);
|
| 596 | } catch (Exception e) {
|
| 597 | LevelStorageSource.LOGGER.error("Failed to save level {}", worldDir, e);
|
| 598 | }
|
| 599 | }
|
| 600 |
|
| 601 | public Optional<Path> getIconFile() {
|
| 602 | return !this.lock.isValid() ? Optional.empty() : Optional.of(this.levelDirectory.iconFile());
|
| 603 | }
|
| 604 |
|
| 605 | public void deleteLevel() throws IOException {
|
| 606 | this.checkLock();
|
| 607 | final Path lockPath = this.levelDirectory.lockFile();
|
| 608 | LevelStorageSource.LOGGER.info("Deleting level {}", this.levelId);
|
| 609 |
|
| 610 | for (int attempt = 1; attempt <= 5; attempt++) {
|
| 611 | LevelStorageSource.LOGGER.info("Attempt {}...", attempt);
|
| 612 |
|
| 613 | try {
|
| 614 | Files.walkFileTree(this.levelDirectory.path(), new SimpleFileVisitor<Path>() {
|
| 615 | public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
|
| 616 | if (!file.equals(lockPath)) {
|
| 617 | LevelStorageSource.LOGGER.debug("Deleting {}", file);
|
| 618 | Files.deleteIfExists(file);
|
| 619 | }
|
| 620 |
|
| 621 | return FileVisitResult.CONTINUE;
|
| 622 | }
|
| 623 |
|
| 624 | public FileVisitResult postVisitDirectory(final Path dir, final @Nullable IOException exc) throws IOException {
|
| 625 | if (exc != null) {
|
| 626 | throw exc;
|
| 627 | }
|
| 628 |
|
| 629 | if (dir.equals(LevelStorageAccess.this.levelDirectory.path())) {
|
| 630 | LevelStorageAccess.this.lock.close();
|
| 631 | Files.deleteIfExists(lockPath);
|
| 632 | }
|
| 633 |
|
| 634 | Files.deleteIfExists(dir);
|
| 635 | return FileVisitResult.CONTINUE;
|
| 636 | }
|
| 637 | });
|
| 638 | break;
|
| 639 | } catch (IOException e) {
|
| 640 | if (attempt >= 5) {
|
| 641 | throw e;
|
| 642 | }
|
| 643 |
|
| 644 | LevelStorageSource.LOGGER.warn("Failed to delete {}", this.levelDirectory.path(), e);
|
| 645 |
|
| 646 | try {
|
| 647 | Thread.sleep(500L);
|
| 648 | } catch (InterruptedException var5) {
|
| 649 | }
|
| 650 | }
|
| 651 | }
|
| 652 | }
|
| 653 |
|
| 654 | public void renameLevel(final String newName) throws IOException {
|
| 655 | this.modifyLevelDataWithoutDatafix(tag -> tag.putString("LevelName", newName.trim()));
|
| 656 | }
|
| 657 |
|
| 658 | public void renameAndDropPlayer(final String newName) throws IOException {
|
| 659 | this.modifyLevelDataWithoutDatafix(tag -> {
|
| 660 | tag.putString("LevelName", newName.trim());
|
| 661 | tag.remove("singleplayer_uuid");
|
| 662 | });
|
| 663 | }
|
| 664 |
|
| 665 | private void modifyLevelDataWithoutDatafix(final Consumer<CompoundTag> updater) throws IOException {
|
| 666 | this.checkLock();
|
| 667 | CompoundTag root = LevelStorageSource.readLevelDataTagRaw(this.levelDirectory.dataFile());
|
| 668 | updater.accept(root.getCompoundOrEmpty("Data"));
|
| 669 | this.saveLevelData(root);
|
| 670 | }
|
| 671 |
|
| 672 | public long makeWorldBackup() throws IOException {
|
| 673 | this.checkLock();
|
| 674 | String zipFilePrefix = FileNameDateFormatter.FORMATTER.format(ZonedDateTime.now()) + "_" + this.levelId;
|
| 675 | Path root = LevelStorageSource.this.getBackupPath();
|
| 676 |
|
| 677 | try {
|
| 678 | FileUtil.createDirectoriesSafe(root);
|
| 679 | } catch (IOException e) {
|
| 680 | throw new RuntimeException(e);
|
| 681 | }
|
| 682 |
|
| 683 | Path zipFilePath = root.resolve(FileUtil.findAvailableName(root, zipFilePrefix, ".zip"));
|
| 684 |
|
| 685 | try (final ZipOutputStream stream = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(zipFilePath)))) {
|
| 686 | final Path rootPath = Paths.get(this.levelId);
|
| 687 | Files.walkFileTree(this.levelDirectory.path(), new SimpleFileVisitor<Path>() {
|
| 688 | public FileVisitResult visitFile(final Path path, final BasicFileAttributes attrs) throws IOException {
|
| 689 | if (path.endsWith("session.lock")) {
|
| 690 | return FileVisitResult.CONTINUE;
|
| 691 | }
|
| 692 |
|
| 693 | String entryPath = rootPath.resolve(LevelStorageAccess.this.levelDirectory.path().relativize(path)).toString().replace('\\', '/');
|
| 694 | ZipEntry entry = new ZipEntry(entryPath);
|
| 695 | stream.putNextEntry(entry);
|
| 696 | com.google.common.io.Files.asByteSource(path.toFile()).copyTo(stream);
|
| 697 | stream.closeEntry();
|
| 698 | return FileVisitResult.CONTINUE;
|
| 699 | }
|
| 700 | });
|
| 701 | }
|
| 702 |
|
| 703 | return Files.size(zipFilePath);
|
| 704 | }
|
| 705 |
|
| 706 | public boolean hasWorldData() {
|
| 707 | return Files.exists(this.levelDirectory.dataFile()) || Files.exists(this.levelDirectory.oldDataFile());
|
| 708 | }
|
| 709 |
|
| 710 | @Override
|
| 711 | public void close() throws IOException {
|
| 712 | this.lock.close();
|
| 713 | }
|
| 714 |
|
| 715 | public boolean restoreLevelDataFromOld() {
|
| 716 | return Util.safeReplaceOrMoveFile(
|
| 717 | this.levelDirectory.dataFile(), this.levelDirectory.oldDataFile(), this.levelDirectory.corruptedDataFile(ZonedDateTime.now()), true
|
| 718 | );
|
| 719 | }
|
| 720 |
|
| 721 | public @Nullable Instant getFileModificationTime(final boolean fallback) {
|
| 722 | return LevelStorageSource.getFileModificationTime(this.getDataFile(fallback));
|
| 723 | }
|
| 724 | }
|
| 725 | }
|
| 726 |
|