Clarify resource build stages, command registration and download flow
This commit is contained in:
@@ -1,8 +1,11 @@
|
|||||||
package online.astradev.packs;
|
package online.astradev.packs;
|
||||||
|
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Collection;
|
||||||
|
|
||||||
|
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
||||||
import com.mojang.brigadier.context.CommandContext;
|
import com.mojang.brigadier.context.CommandContext;
|
||||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||||
|
|
||||||
import net.minecraft.commands.CommandSourceStack;
|
import net.minecraft.commands.CommandSourceStack;
|
||||||
import net.minecraft.commands.Commands;
|
import net.minecraft.commands.Commands;
|
||||||
import net.minecraft.commands.arguments.EntityArgument;
|
import net.minecraft.commands.arguments.EntityArgument;
|
||||||
@@ -20,112 +23,119 @@ import net.neoforged.neoforge.event.server.ServerAboutToStartEvent;
|
|||||||
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
|
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
|
||||||
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
||||||
import net.neoforged.neoforge.network.event.RegisterConfigurationTasksEvent;
|
import net.neoforged.neoforge.network.event.RegisterConfigurationTasksEvent;
|
||||||
|
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.util.Collection;
|
|
||||||
|
|
||||||
@Mod(value = "astrapacks", dist = Dist.DEDICATED_SERVER)
|
@Mod(value = "astrapacks", dist = Dist.DEDICATED_SERVER)
|
||||||
public final class AstraPacks {
|
public final class AstraPacks {
|
||||||
public static final Logger LOG = LoggerFactory.getLogger("AstraPacks");
|
public static final Logger LOG = LoggerFactory.getLogger("AstraPacks");
|
||||||
|
|
||||||
public AstraPacks(IEventBus modBus) {
|
public AstraPacks(IEventBus modBus) {
|
||||||
modBus.addListener(this::configuration);
|
modBus.addListener(this::registerConfigurationTask);
|
||||||
NeoForge.EVENT_BUS.addListener(this::start);
|
NeoForge.EVENT_BUS.addListener(this::start);
|
||||||
NeoForge.EVENT_BUS.addListener(this::stop);
|
NeoForge.EVENT_BUS.addListener(this::stop);
|
||||||
NeoForge.EVENT_BUS.addListener(this::commands);
|
NeoForge.EVENT_BUS.addListener(this::registerCommands);
|
||||||
NeoForge.EVENT_BUS.addListener(this::tick);
|
NeoForge.EVENT_BUS.addListener(this::tick);
|
||||||
NeoForge.EVENT_BUS.addListener(this::login);
|
NeoForge.EVENT_BUS.addListener(this::login);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void start(ServerAboutToStartEvent event) {
|
private void start(ServerAboutToStartEvent event) {
|
||||||
Path root = FMLPaths.GAMEDIR.get().toAbsolutePath();
|
Path root = FMLPaths.GAMEDIR.get().toAbsolutePath();
|
||||||
Path path = FMLPaths.CONFIGDIR.get().resolve("astrapacks.json");
|
Path configPath = FMLPaths.CONFIGDIR.get().resolve("astrapacks.json");
|
||||||
try {
|
try {
|
||||||
PackRuntime runtime =
|
PackConfig config = PackConfig.load(configPath);
|
||||||
new PackRuntime(event.getServer(), root, path, PackConfig.load(path));
|
PackRuntime runtime = new PackRuntime(event.getServer(), root, configPath, config);
|
||||||
PackRuntime.INSTANCE = runtime;
|
PackRuntime.INSTANCE = runtime;
|
||||||
runtime.start();
|
runtime.start();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
if (PackRuntime.INSTANCE != null) PackRuntime.INSTANCE.close();
|
if (PackRuntime.INSTANCE != null) {
|
||||||
PackRuntime.INSTANCE = null;
|
PackRuntime.INSTANCE.close();
|
||||||
|
PackRuntime.INSTANCE = null;
|
||||||
|
}
|
||||||
throw new IllegalStateException("Cannot initialize AstraPacks", e);
|
throw new IllegalStateException("Cannot initialize AstraPacks", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void configuration(RegisterConfigurationTasksEvent event) {
|
private void stop(ServerStoppedEvent event) {
|
||||||
PackRuntime runtime = PackRuntime.INSTANCE;
|
PackRuntime runtime = PackRuntime.INSTANCE;
|
||||||
if (runtime != null && runtime.config().enabled && runtime.config().delivery.sendOnJoin)
|
PackRuntime.INSTANCE = null;
|
||||||
event.register(runtime.session((ServerCommonPacketListenerImpl) event.getListener()));
|
if (runtime != null) {
|
||||||
|
runtime.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void registerConfigurationTask(RegisterConfigurationTasksEvent event) {
|
||||||
|
PackRuntime runtime = PackRuntime.INSTANCE;
|
||||||
|
if (runtime == null || !runtime.config().enabled || !runtime.config().delivery.sendOnJoin) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var listener = (ServerCommonPacketListenerImpl) event.getListener();
|
||||||
|
event.register(runtime.session(listener));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void tick(ServerTickEvent.Post event) {
|
private void tick(ServerTickEvent.Post event) {
|
||||||
if (PackRuntime.INSTANCE != null) PackRuntime.INSTANCE.tick();
|
PackRuntime runtime = PackRuntime.INSTANCE;
|
||||||
|
if (runtime != null) {
|
||||||
|
runtime.tick();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void login(PlayerEvent.PlayerLoggedInEvent event) {
|
private void login(PlayerEvent.PlayerLoggedInEvent event) {
|
||||||
if (PackRuntime.INSTANCE != null && event.getEntity() instanceof ServerPlayer player)
|
PackRuntime runtime = PackRuntime.INSTANCE;
|
||||||
PackRuntime.INSTANCE.welcome(player);
|
if (runtime != null && event.getEntity() instanceof ServerPlayer player) {
|
||||||
|
runtime.welcome(player);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void stop(ServerStoppedEvent event) {
|
private void registerCommands(RegisterCommandsEvent event) {
|
||||||
if (PackRuntime.INSTANCE != null) PackRuntime.INSTANCE.close();
|
LiteralArgumentBuilder<CommandSourceStack> command = Commands.literal("astrapacks")
|
||||||
PackRuntime.INSTANCE = null;
|
.requires(Commands.hasPermission(Commands.LEVEL_ADMINS))
|
||||||
}
|
.executes(this::status);
|
||||||
|
|
||||||
private void commands(RegisterCommandsEvent event) {
|
command.then(Commands.literal("status").executes(this::status));
|
||||||
event.getDispatcher()
|
command.then(Commands.literal("build").executes(this::build));
|
||||||
.register(
|
command.then(Commands.literal("reload").executes(this::reload));
|
||||||
Commands.literal("astrapacks")
|
command.then(Commands.literal("publish").executes(this::publish));
|
||||||
.requires(Commands.hasPermission(Commands.LEVEL_ADMINS))
|
command.then(Commands.literal("send")
|
||||||
.executes(this::status)
|
.then(Commands.argument("players", EntityArgument.players()).executes(this::send)));
|
||||||
.then(Commands.literal("status").executes(this::status))
|
|
||||||
.then(
|
event.getDispatcher().register(command);
|
||||||
Commands.literal("build")
|
|
||||||
.executes(ctx -> rebuild(ctx, false, false)))
|
|
||||||
.then(
|
|
||||||
Commands.literal("reload")
|
|
||||||
.executes(ctx -> rebuild(ctx, true, false)))
|
|
||||||
.then(
|
|
||||||
Commands.literal("publish")
|
|
||||||
.executes(ctx -> rebuild(ctx, false, true)))
|
|
||||||
.then(
|
|
||||||
Commands.literal("send")
|
|
||||||
.then(
|
|
||||||
Commands.argument(
|
|
||||||
"players",
|
|
||||||
EntityArgument.players())
|
|
||||||
.executes(this::send))));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private int status(CommandContext<CommandSourceStack> context) {
|
private int status(CommandContext<CommandSourceStack> context) {
|
||||||
context.getSource()
|
String status = PackRuntime.INSTANCE.status();
|
||||||
.sendSuccess(() -> Component.literal(PackRuntime.INSTANCE.status()), false);
|
context.getSource().sendSuccess(() -> Component.literal(status), false);
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
private int rebuild(
|
private int build(CommandContext<CommandSourceStack> context) {
|
||||||
CommandContext<CommandSourceStack> context, boolean reload, boolean publishOnly) {
|
PackRuntime.INSTANCE.build(context.getSource());
|
||||||
PackRuntime.INSTANCE.rebuild(context.getSource(), reload, publishOnly);
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int reload(CommandContext<CommandSourceStack> context) {
|
||||||
|
PackRuntime.INSTANCE.reload(context.getSource());
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int publish(CommandContext<CommandSourceStack> context) {
|
||||||
|
PackRuntime.INSTANCE.publish(context.getSource());
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
private int send(CommandContext<CommandSourceStack> context) throws CommandSyntaxException {
|
private int send(CommandContext<CommandSourceStack> context) throws CommandSyntaxException {
|
||||||
PackRuntime runtime = PackRuntime.INSTANCE;
|
PackRuntime runtime = PackRuntime.INSTANCE;
|
||||||
|
CommandSourceStack source = context.getSource();
|
||||||
if (!runtime.config().enabled) {
|
if (!runtime.config().enabled) {
|
||||||
context.getSource()
|
source.sendFailure(Component.literal("AstraPacks отключён в конфигурации."));
|
||||||
.sendFailure(Component.literal("AstraPacks отключён в конфигурации."));
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
Collection<ServerPlayer> players = EntityArgument.getPlayers(context, "players");
|
Collection<ServerPlayer> players = EntityArgument.getPlayers(context, "players");
|
||||||
for (ServerPlayer player : players) {
|
for (ServerPlayer player : players) {
|
||||||
runtime.session(player.connection).start(player.connection::send);
|
runtime.session(player.connection).start(player.connection::send);
|
||||||
}
|
}
|
||||||
context.getSource()
|
source.sendSuccess(() -> Component.literal("Ресурспак отправлен: " + players.size()), false);
|
||||||
.sendSuccess(
|
|
||||||
() -> Component.literal("Ресурспак отправлен: " + players.size()), false);
|
|
||||||
return players.size();
|
return players.size();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,5 @@
|
|||||||
package online.astradev.packs;
|
package online.astradev.packs;
|
||||||
|
|
||||||
import com.google.gson.JsonElement;
|
|
||||||
import com.google.gson.JsonObject;
|
|
||||||
import com.google.gson.JsonParser;
|
|
||||||
|
|
||||||
import java.io.BufferedOutputStream;
|
import java.io.BufferedOutputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
@@ -29,15 +25,19 @@ import java.util.zip.ZipEntry;
|
|||||||
import java.util.zip.ZipFile;
|
import java.util.zip.ZipFile;
|
||||||
import java.util.zip.ZipOutputStream;
|
import java.util.zip.ZipOutputStream;
|
||||||
|
|
||||||
/** Deterministic, bounded build. Immutable published ZIPs remain valid during later builds. */
|
import com.google.gson.JsonElement;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import com.google.gson.JsonParser;
|
||||||
|
|
||||||
|
/** Builds reproducible ZIPs and keeps old artifacts available to clients still downloading them. */
|
||||||
public final class PackBuilder {
|
public final class PackBuilder {
|
||||||
public record Pack(Path path, String sha1, int files, long bytes) {}
|
public record Pack(Path path, String sha1, int files, long bytes) {}
|
||||||
|
|
||||||
private record Asset(byte[] data, String owner) {}
|
private record Asset(byte[] data, String source) {}
|
||||||
|
|
||||||
private final PackConfig config;
|
private final PackConfig config;
|
||||||
private final SortedMap<String, Asset> assets = new TreeMap<>();
|
private final SortedMap<String, Asset> assets = new TreeMap<>();
|
||||||
private long total;
|
private long sourceBytes;
|
||||||
|
|
||||||
public PackBuilder(PackConfig config) {
|
public PackBuilder(PackConfig config) {
|
||||||
this.config = config;
|
this.config = config;
|
||||||
@@ -45,126 +45,107 @@ public final class PackBuilder {
|
|||||||
|
|
||||||
public Pack build(Path root, String resourceVersion) throws IOException {
|
public Pack build(Path root, String resourceVersion) throws IOException {
|
||||||
assets.clear();
|
assets.clear();
|
||||||
total = 0;
|
sourceBytes = 0;
|
||||||
|
|
||||||
|
readSources(root);
|
||||||
|
if (config.build.scanModJars) {
|
||||||
|
readModBundles(root.resolve("mods"));
|
||||||
|
}
|
||||||
|
addMetadata(resourceVersion);
|
||||||
|
return writePack(config.storage(root).resolve("output"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void readSources(Path root) throws IOException {
|
||||||
for (String source : config.build.sources) {
|
for (String source : config.build.sources) {
|
||||||
Path path = root.resolve(source).toAbsolutePath().normalize();
|
Path path = root.resolve(source).toAbsolutePath().normalize();
|
||||||
if (!Files.exists(path)) throw new IOException("Source does not exist: " + path);
|
if (!Files.exists(path)) {
|
||||||
if (Files.isDirectory(path)) directory(path);
|
throw new IOException("Source does not exist: " + path);
|
||||||
else archive(path, false);
|
}
|
||||||
}
|
if (Files.isDirectory(path)) {
|
||||||
if (config.build.scanModJars && Files.isDirectory(root.resolve("mods"))) {
|
readDirectory(path);
|
||||||
try (var files = Files.list(root.resolve("mods"))) {
|
} else {
|
||||||
for (Path jar : files.filter(p -> p.toString().endsWith(".jar")).sorted().toList())
|
readArchive(path);
|
||||||
archive(jar, true);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
JsonObject pack = new JsonObject();
|
}
|
||||||
// 26.2 uses major/minor resource-pack versions.
|
|
||||||
JsonElement version = JsonParser.parseString(resourceVersion);
|
private void readDirectory(Path root) throws IOException {
|
||||||
pack.add("min_format", version);
|
if (Files.isSymbolicLink(root)) {
|
||||||
pack.add("max_format", version.deepCopy());
|
throw new IOException("Symlink source: " + root);
|
||||||
pack.addProperty("description", config.build.description);
|
}
|
||||||
JsonObject meta = new JsonObject();
|
try (var paths = Files.walk(root)) {
|
||||||
meta.add("pack", pack);
|
for (Path file : paths.sorted().toList()) {
|
||||||
assets.put(
|
if (Files.isSymbolicLink(file)) {
|
||||||
"pack.mcmeta",
|
throw new IOException("Symlink resource: " + file);
|
||||||
new Asset(
|
}
|
||||||
PackConfig.JSON.toJson(meta).getBytes(StandardCharsets.UTF_8),
|
if (!Files.isRegularFile(file)) {
|
||||||
"AstraPacks"));
|
continue;
|
||||||
Path output = config.storage(root).resolve("output");
|
|
||||||
Files.createDirectories(output);
|
|
||||||
Path temp = Files.createTempFile(output, "build-", ".tmp");
|
|
||||||
try {
|
|
||||||
try (var zip =
|
|
||||||
new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(temp)))) {
|
|
||||||
for (var item : assets.entrySet()) {
|
|
||||||
ZipEntry entry = new ZipEntry(item.getKey());
|
|
||||||
entry.setTime(0);
|
|
||||||
zip.putNextEntry(entry);
|
|
||||||
zip.write(item.getValue().data());
|
|
||||||
zip.closeEntry();
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
String hash = hash(temp, "SHA-1");
|
|
||||||
Path destination = output.resolve(hash + ".zip");
|
|
||||||
if (!Files.exists(destination))
|
|
||||||
Files.move(temp, destination, StandardCopyOption.ATOMIC_MOVE);
|
|
||||||
else if (!hash(destination, "SHA-1").equals(hash))
|
|
||||||
throw new IOException("Published ZIP was modified: " + destination);
|
|
||||||
PackFiles.atomicWrite(
|
|
||||||
output.resolve("current.json"),
|
|
||||||
PackConfig.JSON
|
|
||||||
.toJson(Map.of("sha1", hash, "files", assets.size()))
|
|
||||||
.getBytes(StandardCharsets.UTF_8));
|
|
||||||
return new Pack(destination, hash, assets.size(), Files.size(destination));
|
|
||||||
} finally {
|
|
||||||
Files.deleteIfExists(temp);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static Pack previous(Path root, PackConfig config) throws IOException {
|
String name = root.relativize(file).toString().replace('\\', '/');
|
||||||
Path output = config.storage(root).resolve("output");
|
// Accept a pack root or a directory containing named pack roots.
|
||||||
try {
|
|
||||||
JsonObject info =
|
|
||||||
JsonParser.parseString(Files.readString(output.resolve("current.json")))
|
|
||||||
.getAsJsonObject();
|
|
||||||
String sha1 = info.get("sha1").getAsString();
|
|
||||||
if (!sha1.matches("[a-f0-9]{40}")) throw new IOException("Invalid pack hash");
|
|
||||||
Path path = output.resolve(sha1 + ".zip");
|
|
||||||
if (!hash(path, "SHA-1").equals(sha1))
|
|
||||||
throw new IOException("Stored resource pack hash mismatch");
|
|
||||||
return new Pack(path, sha1, info.get("files").getAsInt(), Files.size(path));
|
|
||||||
} catch (RuntimeException e) {
|
|
||||||
throw new IOException("Invalid previous build", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void directory(Path root) throws IOException {
|
|
||||||
if (Files.isSymbolicLink(root)) throw new IOException("Symlink source: " + root);
|
|
||||||
try (var walk = Files.walk(root)) {
|
|
||||||
for (Path p : walk.sorted().toList()) {
|
|
||||||
if (Files.isSymbolicLink(p)) throw new IOException("Symlink resource: " + p);
|
|
||||||
if (!Files.isRegularFile(p)) continue;
|
|
||||||
String name = root.relativize(p).toString().replace('\\', '/');
|
|
||||||
// A source is a pack root, or a directory of named pack roots.
|
|
||||||
if (!isResource(name)) {
|
if (!isResource(name)) {
|
||||||
int slash = name.indexOf('/');
|
int separator = name.indexOf('/');
|
||||||
if (slash >= 0 && isResource(name.substring(slash + 1)))
|
String nestedName = name.substring(separator + 1);
|
||||||
name = name.substring(slash + 1);
|
if (separator >= 0 && isResource(nestedName)) {
|
||||||
else if (name.endsWith(".zip")) {
|
name = nestedName;
|
||||||
archive(p, false);
|
} else if (name.endsWith(".zip")) {
|
||||||
|
readArchive(file);
|
||||||
continue;
|
continue;
|
||||||
} else continue;
|
} else {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
try (var in = Files.newInputStream(p)) {
|
try (InputStream input = Files.newInputStream(file)) {
|
||||||
add(name, in, p.toString());
|
addAsset(name, input, file.toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void archive(Path path, boolean mod) throws IOException {
|
private void readArchive(Path path) throws IOException {
|
||||||
try (var zip = new ZipFile(path.toFile())) {
|
try (ZipFile zip = new ZipFile(path.toFile())) {
|
||||||
String prefix = "";
|
readEntries(zip, "");
|
||||||
if (mod) {
|
}
|
||||||
var descriptor = zip.getEntry("astra-pack.properties");
|
}
|
||||||
if (descriptor == null) return;
|
|
||||||
Properties props = new Properties();
|
private void readModBundles(Path mods) throws IOException {
|
||||||
try (var in = zip.getInputStream(descriptor)) {
|
if (!Files.isDirectory(mods)) {
|
||||||
props.load(in);
|
return;
|
||||||
|
}
|
||||||
|
try (var paths = Files.list(mods)) {
|
||||||
|
for (Path jar : paths.filter(path -> path.toString().endsWith(".jar")).sorted().toList()) {
|
||||||
|
try (ZipFile zip = new ZipFile(jar.toFile())) {
|
||||||
|
ZipEntry descriptor = zip.getEntry("astra-pack.properties");
|
||||||
|
if (descriptor == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Properties properties = new Properties();
|
||||||
|
try (InputStream input = zip.getInputStream(descriptor)) {
|
||||||
|
properties.load(input);
|
||||||
|
}
|
||||||
|
if (!"2".equals(properties.getProperty("schema"))) {
|
||||||
|
throw new IOException("Invalid AstraPacks bundle descriptor: " + jar);
|
||||||
|
}
|
||||||
|
readEntries(zip, "astra-resourcepack/");
|
||||||
}
|
}
|
||||||
String schema = props.getProperty("schema", "");
|
|
||||||
if (schema.equals("2")) prefix = "astra-resourcepack/";
|
|
||||||
else throw new IOException("Invalid AstraPacks bundle descriptor: " + path);
|
|
||||||
}
|
}
|
||||||
for (var entries = zip.entries(); entries.hasMoreElements(); ) {
|
}
|
||||||
ZipEntry entry = entries.nextElement();
|
}
|
||||||
if (entry.isDirectory() || !entry.getName().startsWith(prefix)) continue;
|
|
||||||
String name = entry.getName().substring(prefix.length());
|
private void readEntries(ZipFile zip, String prefix) throws IOException {
|
||||||
if (!isResource(name)) continue;
|
var entries = zip.entries();
|
||||||
try (var in = zip.getInputStream(entry)) {
|
while (entries.hasMoreElements()) {
|
||||||
add(name, in, path + "!/" + entry.getName());
|
ZipEntry entry = entries.nextElement();
|
||||||
}
|
if (entry.isDirectory() || !entry.getName().startsWith(prefix)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String name = entry.getName().substring(prefix.length());
|
||||||
|
if (!isResource(name)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
try (InputStream input = zip.getInputStream(entry)) {
|
||||||
|
addAsset(name, input, zip.getName() + "!/" + entry.getName());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -173,29 +154,95 @@ public final class PackBuilder {
|
|||||||
return name.startsWith("assets/") || name.equals("pack.png");
|
return name.startsWith("assets/") || name.equals("pack.png");
|
||||||
}
|
}
|
||||||
|
|
||||||
private void add(String name, InputStream in, String owner) throws IOException {
|
private void addAsset(String name, InputStream input, String source) throws IOException {
|
||||||
PackFiles.safe(Path.of("."), name);
|
PackFiles.safe(Path.of("."), name);
|
||||||
int limit = config.build.maxFileMiB * 1024 * 1024;
|
int limit = config.build.maxFileMiB * 1024 * 1024;
|
||||||
byte[] bytes = in.readNBytes(limit + 1);
|
byte[] bytes = input.readNBytes(limit + 1);
|
||||||
if (bytes.length > limit) throw new IOException("Resource exceeds maxFileMiB: " + owner);
|
if (bytes.length > limit) {
|
||||||
total += bytes.length;
|
throw new IOException("Resource exceeds maxFileMiB: " + source);
|
||||||
if (total > config.build.maxTotalMiB * 1024L * 1024L)
|
}
|
||||||
|
sourceBytes += bytes.length;
|
||||||
|
if (sourceBytes > config.build.maxTotalMiB * 1024L * 1024L) {
|
||||||
throw new IOException("Sources exceed maxTotalMiB");
|
throw new IOException("Sources exceed maxTotalMiB");
|
||||||
Asset old = assets.get(name);
|
}
|
||||||
if (old != null
|
|
||||||
&& !Arrays.equals(bytes, old.data())
|
Asset previous = assets.get(name);
|
||||||
&& config.build.conflictPolicy.equals("error"))
|
if (previous != null && config.build.conflictPolicy.equals("error")
|
||||||
throw new IOException(
|
&& !Arrays.equals(bytes, previous.data())) {
|
||||||
"Conflicting resource " + name + " from " + old.owner() + " and " + owner);
|
throw new IOException("Conflicting resource " + name + " from " + previous.source() + " and " + source);
|
||||||
assets.put(name, new Asset(bytes, owner));
|
}
|
||||||
if (assets.size() > config.build.maxFiles) throw new IOException("Too many resources");
|
assets.put(name, new Asset(bytes, source));
|
||||||
|
if (assets.size() > config.build.maxFiles) {
|
||||||
|
throw new IOException("Too many resources");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addMetadata(String resourceVersion) {
|
||||||
|
JsonElement version = JsonParser.parseString(resourceVersion);
|
||||||
|
JsonObject pack = new JsonObject();
|
||||||
|
pack.add("min_format", version);
|
||||||
|
pack.add("max_format", version.deepCopy());
|
||||||
|
pack.addProperty("description", config.build.description);
|
||||||
|
|
||||||
|
JsonObject metadata = new JsonObject();
|
||||||
|
metadata.add("pack", pack);
|
||||||
|
byte[] bytes = PackConfig.JSON.toJson(metadata).getBytes(StandardCharsets.UTF_8);
|
||||||
|
assets.put("pack.mcmeta", new Asset(bytes, "AstraPacks"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Pack writePack(Path output) throws IOException {
|
||||||
|
Files.createDirectories(output);
|
||||||
|
Path temporary = Files.createTempFile(output, "build-", ".tmp");
|
||||||
|
try {
|
||||||
|
try (var zip = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(temporary)))) {
|
||||||
|
for (var asset : assets.entrySet()) {
|
||||||
|
ZipEntry entry = new ZipEntry(asset.getKey());
|
||||||
|
entry.setTime(0);
|
||||||
|
zip.putNextEntry(entry);
|
||||||
|
zip.write(asset.getValue().data());
|
||||||
|
zip.closeEntry();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String sha1 = hash(temporary, "SHA-1");
|
||||||
|
Path destination = output.resolve(sha1 + ".zip");
|
||||||
|
if (!Files.exists(destination)) {
|
||||||
|
Files.move(temporary, destination, StandardCopyOption.ATOMIC_MOVE);
|
||||||
|
} else if (!hash(destination, "SHA-1").equals(sha1)) {
|
||||||
|
throw new IOException("Published ZIP was modified: " + destination);
|
||||||
|
}
|
||||||
|
String manifest = PackConfig.JSON.toJson(Map.of("sha1", sha1, "files", assets.size()));
|
||||||
|
PackFiles.atomicWrite(output.resolve("current.json"), manifest.getBytes(StandardCharsets.UTF_8));
|
||||||
|
return new Pack(destination, sha1, assets.size(), Files.size(destination));
|
||||||
|
} finally {
|
||||||
|
Files.deleteIfExists(temporary);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Pack previous(Path root, PackConfig config) throws IOException {
|
||||||
|
Path output = config.storage(root).resolve("output");
|
||||||
|
try {
|
||||||
|
String manifest = Files.readString(output.resolve("current.json"));
|
||||||
|
JsonObject info = JsonParser.parseString(manifest).getAsJsonObject();
|
||||||
|
String sha1 = info.get("sha1").getAsString();
|
||||||
|
if (!sha1.matches("[a-f0-9]{40}")) {
|
||||||
|
throw new IOException("Invalid pack hash");
|
||||||
|
}
|
||||||
|
Path path = output.resolve(sha1 + ".zip");
|
||||||
|
if (!hash(path, "SHA-1").equals(sha1)) {
|
||||||
|
throw new IOException("Stored resource pack hash mismatch");
|
||||||
|
}
|
||||||
|
return new Pack(path, sha1, info.get("files").getAsInt(), Files.size(path));
|
||||||
|
} catch (RuntimeException e) {
|
||||||
|
throw new IOException("Invalid previous build", e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String hash(Path file, String algorithm) throws IOException {
|
public static String hash(Path file, String algorithm) throws IOException {
|
||||||
try {
|
try {
|
||||||
MessageDigest digest = MessageDigest.getInstance(algorithm);
|
MessageDigest digest = MessageDigest.getInstance(algorithm);
|
||||||
try (var in = new DigestInputStream(Files.newInputStream(file), digest)) {
|
try (var input = new DigestInputStream(Files.newInputStream(file), digest)) {
|
||||||
in.transferTo(OutputStream.nullOutputStream());
|
input.transferTo(OutputStream.nullOutputStream());
|
||||||
}
|
}
|
||||||
return HexFormat.of().formatHex(digest.digest());
|
return HexFormat.of().formatHex(digest.digest());
|
||||||
} catch (NoSuchAlgorithmException e) {
|
} catch (NoSuchAlgorithmException e) {
|
||||||
@@ -203,34 +250,29 @@ public final class PackBuilder {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static void verifyExternal(PackConfig config, PackBuilder.Pack pack) throws IOException {
|
static void verifyExternal(PackConfig config, Pack pack) throws IOException {
|
||||||
if (!config.hosting.mode.equals("no_host") || !config.delivery.sendOnJoin) return;
|
if (!config.hosting.mode.equals("no_host") || !config.delivery.sendOnJoin) {
|
||||||
try (HttpClient client =
|
return;
|
||||||
HttpClient.newBuilder()
|
}
|
||||||
.connectTimeout(Duration.ofSeconds(10))
|
try (HttpClient client = HttpClient.newBuilder()
|
||||||
.followRedirects(HttpClient.Redirect.NORMAL)
|
.connectTimeout(Duration.ofSeconds(10))
|
||||||
.build()) {
|
.followRedirects(HttpClient.Redirect.NORMAL)
|
||||||
HttpRequest request =
|
.build()) {
|
||||||
HttpRequest.newBuilder(PackConfig.validateUrl(config.hosting.externalUrl))
|
HttpRequest request = HttpRequest.newBuilder(PackConfig.validateUrl(config.hosting.externalUrl))
|
||||||
.timeout(Duration.ofSeconds(30))
|
.timeout(Duration.ofSeconds(30))
|
||||||
.GET()
|
.GET()
|
||||||
.build();
|
.build();
|
||||||
// A bounded subscriber prevents an external host from consuming arbitrary memory/disk.
|
var bodyHandler = HttpResponse.BodyHandlers.limiting(HttpResponse.BodyHandlers.ofByteArray(), pack.bytes());
|
||||||
HttpResponse<byte[]> response =
|
HttpResponse<byte[]> response = client.send(request, bodyHandler);
|
||||||
client.send(
|
if (response.statusCode() != 200) {
|
||||||
request,
|
|
||||||
HttpResponse.BodyHandlers.limiting(
|
|
||||||
HttpResponse.BodyHandlers.ofByteArray(), pack.bytes()));
|
|
||||||
if (response.statusCode() != 200)
|
|
||||||
throw new IOException("External pack HTTP " + response.statusCode());
|
throw new IOException("External pack HTTP " + response.statusCode());
|
||||||
String hash =
|
}
|
||||||
HexFormat.of()
|
|
||||||
.formatHex(MessageDigest.getInstance("SHA-1").digest(response.body()));
|
byte[] digest = MessageDigest.getInstance("SHA-1").digest(response.body());
|
||||||
if (!hash.equals(pack.sha1()))
|
if (!HexFormat.of().formatHex(digest).equals(pack.sha1())) {
|
||||||
throw new IOException(
|
throw new IOException("External ZIP differs from built ZIP. Upload " + pack.path()
|
||||||
"External ZIP differs from built ZIP. Upload "
|
+ ", then /astrapacks publish");
|
||||||
+ pack.path()
|
}
|
||||||
+ ", then /astrapacks publish");
|
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
Thread.currentThread().interrupt();
|
Thread.currentThread().interrupt();
|
||||||
throw new IOException(e);
|
throw new IOException(e);
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
package online.astradev.packs;
|
package online.astradev.packs;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
|
||||||
import com.google.gson.GsonBuilder;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
@@ -13,10 +10,13 @@ import java.util.List;
|
|||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
|
import com.google.gson.Gson;
|
||||||
|
import com.google.gson.GsonBuilder;
|
||||||
|
|
||||||
/** Server-local configuration, deliberately never synchronized to clients. */
|
/** Server-local configuration, deliberately never synchronized to clients. */
|
||||||
public final class PackConfig {
|
public final class PackConfig {
|
||||||
public static final Gson JSON =
|
public static final Gson JSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
|
||||||
new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
|
|
||||||
public boolean enabled = true;
|
public boolean enabled = true;
|
||||||
public Build build = new Build();
|
public Build build = new Build();
|
||||||
public Hosting hosting = new Hosting();
|
public Hosting hosting = new Hosting();
|
||||||
@@ -72,18 +72,13 @@ public final class PackConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static final class Messages {
|
public static final class Messages {
|
||||||
public String prompt =
|
public String prompt = "&6Привет, {player}!\\n"
|
||||||
"&6Привет, {player}!\\n"
|
+ "&fДля игры на сервере необходим ресурспак AstraDev.\\n"
|
||||||
+ "&fДля игры на сервере необходим ресурспак AstraDev.\\n"
|
+ "&aНажми «Продолжить», чтобы загрузить его.";
|
||||||
+ "&aНажми «Продолжить», чтобы загрузить его.";
|
public String declined = "&cДля входа необходимо принять ресурспак сервера.\\n"
|
||||||
public String declined =
|
+ "&fВ настройках этого сервера включи «Наборы ресурсов сервера» и подключись снова.";
|
||||||
"&cДля входа необходимо принять ресурспак сервера.\\n"
|
public String failed = "&cНе удалось загрузить ресурспак сервера.\\n"
|
||||||
+ "&fВ настройках этого сервера включи «Наборы ресурсов сервера» и подключись"
|
+ "&fПопробуй подключиться ещё раз. Если ошибка повторится, сообщи администрации.";
|
||||||
+ " снова.";
|
|
||||||
public String failed =
|
|
||||||
"&cНе удалось загрузить ресурспак сервера.\\n"
|
|
||||||
+ "&fПопробуй подключиться ещё раз. Если ошибка повторится, сообщи"
|
|
||||||
+ " администрации.";
|
|
||||||
public String timeout = "&cВремя ожидания ресурспака истекло. Попробуй подключиться снова.";
|
public String timeout = "&cВремя ожидания ресурспака истекло. Попробуй подключиться снова.";
|
||||||
public String unavailable = "&cРесурспак сервера пока недоступен. Попробуй зайти позже.";
|
public String unavailable = "&cРесурспак сервера пока недоступен. Попробуй зайти позже.";
|
||||||
public String loaded = "&aРесурспак AstraDev загружен.";
|
public String loaded = "&aРесурспак AstraDev загружен.";
|
||||||
@@ -91,12 +86,14 @@ public final class PackConfig {
|
|||||||
|
|
||||||
public static PackConfig load(Path path) throws IOException {
|
public static PackConfig load(Path path) throws IOException {
|
||||||
if (!Files.exists(path)) {
|
if (!Files.exists(path)) {
|
||||||
PackFiles.atomicWrite(
|
byte[] defaults = (JSON.toJson(new PackConfig()) + "\n").getBytes(StandardCharsets.UTF_8);
|
||||||
path, (JSON.toJson(new PackConfig()) + "\n").getBytes(StandardCharsets.UTF_8));
|
PackFiles.atomicWrite(path, defaults);
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
PackConfig config = JSON.fromJson(Files.readString(path), PackConfig.class);
|
PackConfig config = JSON.fromJson(Files.readString(path), PackConfig.class);
|
||||||
if (config == null) throw new IllegalArgumentException("Empty config");
|
if (config == null) {
|
||||||
|
throw new IllegalArgumentException("Empty config");
|
||||||
|
}
|
||||||
config.validate();
|
config.validate();
|
||||||
return config;
|
return config;
|
||||||
} catch (RuntimeException e) {
|
} catch (RuntimeException e) {
|
||||||
@@ -105,68 +102,85 @@ public final class PackConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void validate() {
|
public void validate() {
|
||||||
Objects.requireNonNull(build);
|
Objects.requireNonNull(build, "build");
|
||||||
Objects.requireNonNull(hosting);
|
Objects.requireNonNull(hosting, "hosting");
|
||||||
Objects.requireNonNull(delivery);
|
Objects.requireNonNull(delivery, "delivery");
|
||||||
Objects.requireNonNull(messages);
|
Objects.requireNonNull(messages, "messages");
|
||||||
Objects.requireNonNull(hosting.bindAddress, "hosting.bindAddress");
|
validateBuild();
|
||||||
Objects.requireNonNull(hosting.externalUrl, "hosting.externalUrl");
|
validateHosting();
|
||||||
if (!Set.of("simple_self_host", "self_host", "no_host").contains(hosting.mode))
|
|
||||||
throw new IllegalArgumentException(
|
range(delivery.timeoutSeconds, 10, 3600, "timeoutSeconds");
|
||||||
"hosting.mode: simple_self_host, self_host or no_host");
|
range(delivery.retries, 0, 5, "retries");
|
||||||
if (!Set.of("error", "last_wins").contains(build.conflictPolicy))
|
if (enabled && delivery.required && !delivery.sendOnJoin) {
|
||||||
|
throw new IllegalArgumentException("required needs sendOnJoin=true");
|
||||||
|
}
|
||||||
|
if (hosting.mode.equals("no_host")) {
|
||||||
|
if (enabled && delivery.sendOnJoin) {
|
||||||
|
validateUrl(hosting.externalUrl);
|
||||||
|
}
|
||||||
|
} else if (hosting.tokenLifetimeSeconds < delivery.timeoutSeconds) {
|
||||||
|
throw new IllegalArgumentException("tokenLifetimeSeconds must be >= timeoutSeconds");
|
||||||
|
}
|
||||||
|
|
||||||
|
var texts = List.of(messages.prompt, messages.declined, messages.failed,
|
||||||
|
messages.timeout, messages.unavailable, messages.loaded);
|
||||||
|
for (String message : texts) {
|
||||||
|
if (message.length() > 8192) {
|
||||||
|
throw new IllegalArgumentException("Message exceeds 8192 characters");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateBuild() {
|
||||||
|
if (!Set.of("error", "last_wins").contains(build.conflictPolicy)) {
|
||||||
throw new IllegalArgumentException("build.conflictPolicy: error or last_wins");
|
throw new IllegalArgumentException("build.conflictPolicy: error or last_wins");
|
||||||
if (build.storageDirectory.isBlank()
|
}
|
||||||
|| build.sources == null
|
Objects.requireNonNull(build.storageDirectory, "build.storageDirectory");
|
||||||
|| build.sources.stream().anyMatch(s -> s == null || s.isBlank()))
|
Objects.requireNonNull(build.sources, "build.sources");
|
||||||
|
Objects.requireNonNull(build.description, "build.description");
|
||||||
|
if (build.storageDirectory.isBlank()) {
|
||||||
throw new IllegalArgumentException("Invalid build paths");
|
throw new IllegalArgumentException("Invalid build paths");
|
||||||
Objects.requireNonNull(build.description);
|
}
|
||||||
|
for (String source : build.sources) {
|
||||||
|
if (source == null || source.isBlank()) {
|
||||||
|
throw new IllegalArgumentException("Invalid build paths");
|
||||||
|
}
|
||||||
|
}
|
||||||
range(build.maxFileMiB, 1, 128, "maxFileMiB");
|
range(build.maxFileMiB, 1, 128, "maxFileMiB");
|
||||||
range(build.maxTotalMiB, build.maxFileMiB, 1024, "maxTotalMiB");
|
range(build.maxTotalMiB, build.maxFileMiB, 1024, "maxTotalMiB");
|
||||||
range(build.maxFiles, 1, 200000, "maxFiles");
|
range(build.maxFiles, 1, 200000, "maxFiles");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateHosting() {
|
||||||
|
if (!Set.of("simple_self_host", "self_host", "no_host").contains(hosting.mode)) {
|
||||||
|
throw new IllegalArgumentException("hosting.mode: simple_self_host, self_host or no_host");
|
||||||
|
}
|
||||||
|
Objects.requireNonNull(hosting.bindAddress, "hosting.bindAddress");
|
||||||
|
Objects.requireNonNull(hosting.externalUrl, "hosting.externalUrl");
|
||||||
|
Objects.requireNonNull(hosting.publicAddress, "hosting.publicAddress");
|
||||||
|
if (!hosting.publicAddress.equals("auto") && validateUrl(hosting.publicAddress).getQuery() != null) {
|
||||||
|
throw new IllegalArgumentException("hosting.publicAddress must not contain query parameters");
|
||||||
|
}
|
||||||
range(hosting.port, 1, 65535, "port");
|
range(hosting.port, 1, 65535, "port");
|
||||||
range(hosting.maxDownloadsPerIp, 1, 100, "maxDownloadsPerIp");
|
range(hosting.maxDownloadsPerIp, 1, 100, "maxDownloadsPerIp");
|
||||||
range(hosting.maxConcurrentDownloads, 1, 256, "maxConcurrentDownloads");
|
range(hosting.maxConcurrentDownloads, 1, 256, "maxConcurrentDownloads");
|
||||||
range(hosting.maxSpeedMiBPerSecond, 1, 1024, "maxSpeedMiBPerSecond");
|
range(hosting.maxSpeedMiBPerSecond, 1, 1024, "maxSpeedMiBPerSecond");
|
||||||
range(hosting.tokenLifetimeSeconds, 30, 86400, "tokenLifetimeSeconds");
|
range(hosting.tokenLifetimeSeconds, 30, 86400, "tokenLifetimeSeconds");
|
||||||
range(delivery.timeoutSeconds, 10, 3600, "timeoutSeconds");
|
|
||||||
range(delivery.retries, 0, 5, "retries");
|
|
||||||
if (enabled && delivery.required && !delivery.sendOnJoin)
|
|
||||||
throw new IllegalArgumentException("required needs sendOnJoin=true");
|
|
||||||
if (!hosting.publicAddress.equals("auto")
|
|
||||||
&& validateUrl(hosting.publicAddress).getQuery() != null)
|
|
||||||
throw new IllegalArgumentException(
|
|
||||||
"hosting.publicAddress must not contain query parameters");
|
|
||||||
if (!hosting.mode.equals("no_host")
|
|
||||||
&& hosting.tokenLifetimeSeconds < delivery.timeoutSeconds)
|
|
||||||
throw new IllegalArgumentException("tokenLifetimeSeconds must be >= timeoutSeconds");
|
|
||||||
if (hosting.mode.equals("no_host") && enabled && delivery.sendOnJoin)
|
|
||||||
validateUrl(hosting.externalUrl);
|
|
||||||
for (String s :
|
|
||||||
List.of(
|
|
||||||
messages.prompt,
|
|
||||||
messages.declined,
|
|
||||||
messages.failed,
|
|
||||||
messages.timeout,
|
|
||||||
messages.unavailable,
|
|
||||||
messages.loaded))
|
|
||||||
if (s.length() > 8192)
|
|
||||||
throw new IllegalArgumentException("Message exceeds 8192 characters");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static URI validateUrl(String value) {
|
public static URI validateUrl(String value) {
|
||||||
URI uri = URI.create(value);
|
URI uri = URI.create(value);
|
||||||
if (!("http".equals(uri.getScheme()) || "https".equals(uri.getScheme()))
|
boolean http = "http".equals(uri.getScheme()) || "https".equals(uri.getScheme());
|
||||||
|| uri.getHost() == null
|
if (!http || uri.getHost() == null || uri.getUserInfo() != null || uri.getFragment() != null) {
|
||||||
|| uri.getUserInfo() != null
|
|
||||||
|| uri.getFragment() != null)
|
|
||||||
throw new IllegalArgumentException("Expected a direct http(s) URL: " + value);
|
throw new IllegalArgumentException("Expected a direct http(s) URL: " + value);
|
||||||
|
}
|
||||||
return uri;
|
return uri;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void range(int n, int min, int max, String key) {
|
private static void range(int value, int min, int max, String key) {
|
||||||
if (n < min || n > max)
|
if (value < min || value > max) {
|
||||||
throw new IllegalArgumentException(key + " must be " + min + ".." + max);
|
throw new IllegalArgumentException(key + " must be " + min + ".." + max);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public Path storage(Path root) {
|
public Path storage(Path root) {
|
||||||
|
|||||||
@@ -5,45 +5,47 @@ import java.nio.file.AtomicMoveNotSupportedException;
|
|||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.StandardCopyOption;
|
import java.nio.file.StandardCopyOption;
|
||||||
import java.util.Arrays;
|
|
||||||
|
|
||||||
|
|
||||||
final class PackFiles {
|
final class PackFiles {
|
||||||
private PackFiles() {}
|
private PackFiles() {}
|
||||||
|
|
||||||
static Path safe(Path root, String name) throws IOException {
|
static Path safe(Path root, String name) throws IOException {
|
||||||
if (name.isBlank()
|
if (name.isBlank() || name.contains("\\") || name.contains(":") || name.startsWith("/")) {
|
||||||
|| name.contains("\\")
|
|
||||||
|| name.contains(":")
|
|
||||||
|| name.startsWith("/")
|
|
||||||
|| Arrays.stream(name.split("/", -1))
|
|
||||||
.anyMatch(p -> p.isEmpty() || p.equals(".") || p.equals("..")))
|
|
||||||
throw new IOException("Unsafe resource path: " + name);
|
throw new IOException("Unsafe resource path: " + name);
|
||||||
|
}
|
||||||
|
for (String part : name.split("/", -1)) {
|
||||||
|
if (part.isEmpty() || part.equals(".") || part.equals("..")) {
|
||||||
|
throw new IOException("Unsafe resource path: " + name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
root = root.toAbsolutePath().normalize();
|
root = root.toAbsolutePath().normalize();
|
||||||
Path target = root.resolve(name).normalize();
|
Path target = root.resolve(name).normalize();
|
||||||
if (!target.startsWith(root))
|
if (!target.startsWith(root)) {
|
||||||
throw new IOException("Resource escapes content root: " + name);
|
throw new IOException("Resource escapes content root: " + name);
|
||||||
for (Path part = target; part != null; part = part.getParent())
|
}
|
||||||
if (Files.isSymbolicLink(part))
|
for (Path part = target; part != null; part = part.getParent()) {
|
||||||
|
if (Files.isSymbolicLink(part)) {
|
||||||
throw new IOException("Symbolic links are not supported: " + part);
|
throw new IOException("Symbolic links are not supported: " + part);
|
||||||
|
}
|
||||||
|
}
|
||||||
return target;
|
return target;
|
||||||
}
|
}
|
||||||
|
|
||||||
static void atomicWrite(Path target, byte[] bytes) throws IOException {
|
static void atomicWrite(Path target, byte[] bytes) throws IOException {
|
||||||
Files.createDirectories(target.getParent());
|
Files.createDirectories(target.getParent());
|
||||||
Path temp = Files.createTempFile(target.getParent(), ".astra-", ".tmp");
|
Path temporary = Files.createTempFile(target.getParent(), ".astra-", ".tmp");
|
||||||
try {
|
try {
|
||||||
Files.write(temp, bytes);
|
Files.write(temporary, bytes);
|
||||||
try {
|
try {
|
||||||
Files.move(
|
Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||||
temp,
|
|
||||||
target,
|
|
||||||
StandardCopyOption.ATOMIC_MOVE,
|
|
||||||
StandardCopyOption.REPLACE_EXISTING);
|
|
||||||
} catch (AtomicMoveNotSupportedException e) {
|
} catch (AtomicMoveNotSupportedException e) {
|
||||||
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING);
|
Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING);
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
Files.deleteIfExists(temp);
|
Files.deleteIfExists(temporary);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,22 @@
|
|||||||
package online.astradev.packs;
|
package online.astradev.packs;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.ConcurrentMap;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
import io.netty.bootstrap.ServerBootstrap;
|
import io.netty.bootstrap.ServerBootstrap;
|
||||||
import io.netty.buffer.ByteBuf;
|
import io.netty.buffer.ByteBuf;
|
||||||
|
import io.netty.buffer.Unpooled;
|
||||||
import io.netty.channel.Channel;
|
import io.netty.channel.Channel;
|
||||||
import io.netty.channel.ChannelFutureListener;
|
import io.netty.channel.ChannelFutureListener;
|
||||||
import io.netty.channel.ChannelHandlerContext;
|
import io.netty.channel.ChannelHandlerContext;
|
||||||
@@ -34,226 +49,231 @@ import io.netty.handler.stream.ChunkedWriteHandler;
|
|||||||
import io.netty.handler.timeout.ReadTimeoutHandler;
|
import io.netty.handler.timeout.ReadTimeoutHandler;
|
||||||
import io.netty.handler.traffic.ChannelTrafficShapingHandler;
|
import io.netty.handler.traffic.ChannelTrafficShapingHandler;
|
||||||
|
|
||||||
import java.io.IOException;
|
/** Serves published ZIPs only; request paths never map to arbitrary files on disk. */
|
||||||
import java.net.InetSocketAddress;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
import java.util.concurrent.ConcurrentMap;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
|
|
||||||
/** Only immutable pack artifacts are exposed; no directory or arbitrary file routes. */
|
|
||||||
public final class PackHost implements AutoCloseable {
|
public final class PackHost implements AutoCloseable {
|
||||||
private record Grant(String hash, long expires) {}
|
private record Grant(String hash, long expires) {}
|
||||||
|
|
||||||
private final PackConfig.Hosting config;
|
private final PackConfig.Hosting config;
|
||||||
private final ConcurrentMap<String, Grant> grants = new ConcurrentHashMap<>();
|
private final ConcurrentMap<String, Grant> grants = new ConcurrentHashMap<>();
|
||||||
private final ConcurrentMap<String, Path> published = new ConcurrentHashMap<>();
|
private final ConcurrentMap<String, Path> published = new ConcurrentHashMap<>();
|
||||||
private final Map<String, Integer> downloads = new HashMap<>();
|
private final Map<String, Integer> downloadsByIp = new HashMap<>();
|
||||||
private int active;
|
private int activeDownloads;
|
||||||
private EventLoopGroup group;
|
private EventLoopGroup eventLoops;
|
||||||
private Channel listening;
|
private Channel listeningChannel;
|
||||||
|
|
||||||
public PackHost(PackConfig.Hosting config) {
|
public PackHost(PackConfig.Hosting config) {
|
||||||
this.config = config;
|
this.config = config;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void start() throws InterruptedException {
|
||||||
|
if (!config.mode.equals("self_host")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
eventLoops = new MultiThreadIoEventLoopGroup(2, NioIoHandler.newFactory());
|
||||||
|
ServerBootstrap bootstrap = new ServerBootstrap()
|
||||||
|
.group(eventLoops)
|
||||||
|
.channel(NioServerSocketChannel.class)
|
||||||
|
.childHandler(new ChannelInitializer<SocketChannel>() {
|
||||||
|
@Override
|
||||||
|
protected void initChannel(SocketChannel channel) {
|
||||||
|
installHttp(channel.pipeline());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
listeningChannel = bootstrap.bind(config.bindAddress, config.port).sync().channel();
|
||||||
|
} catch (InterruptedException | RuntimeException e) {
|
||||||
|
close();
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public void publish(PackBuilder.Pack pack) {
|
public void publish(PackBuilder.Pack pack) {
|
||||||
published.put(pack.sha1(), pack.path());
|
published.put(pack.sha1(), pack.path());
|
||||||
}
|
}
|
||||||
|
|
||||||
public String issuePath(PackBuilder.Pack pack) {
|
public String issuePath(PackBuilder.Pack pack) {
|
||||||
String path = "/astrapacks/" + pack.sha1() + ".zip";
|
String path = "/astrapacks/" + pack.sha1() + ".zip";
|
||||||
if (!config.blockNonGameRequests) return path;
|
if (!config.blockNonGameRequests) {
|
||||||
|
return path;
|
||||||
|
}
|
||||||
long now = System.currentTimeMillis();
|
long now = System.currentTimeMillis();
|
||||||
grants.entrySet().removeIf(e -> e.getValue().expires() < now);
|
grants.entrySet().removeIf(entry -> entry.getValue().expires() < now);
|
||||||
if (grants.size() >= 10000)
|
if (grants.size() >= 10000) {
|
||||||
throw new IllegalStateException("Too many resource-pack download grants");
|
throw new IllegalStateException("Too many resource-pack download grants");
|
||||||
|
}
|
||||||
|
|
||||||
String token = UUID.randomUUID().toString();
|
String token = UUID.randomUUID().toString();
|
||||||
grants.put(token, new Grant(pack.sha1(), now + config.tokenLifetimeSeconds * 1000L));
|
long expires = now + config.tokenLifetimeSeconds * 1000L;
|
||||||
|
grants.put(token, new Grant(pack.sha1(), expires));
|
||||||
return path + "?token=" + token;
|
return path + "?token=" + token;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void start() throws InterruptedException {
|
private boolean authorized(QueryStringDecoder uri, String hash) {
|
||||||
if (!config.mode.equals("self_host")) return;
|
if (!config.blockNonGameRequests) {
|
||||||
group = new MultiThreadIoEventLoopGroup(2, NioIoHandler.newFactory());
|
return true;
|
||||||
try {
|
|
||||||
listening =
|
|
||||||
new ServerBootstrap()
|
|
||||||
.group(group)
|
|
||||||
.channel(NioServerSocketChannel.class)
|
|
||||||
.childHandler(
|
|
||||||
new ChannelInitializer<SocketChannel>() {
|
|
||||||
@Override
|
|
||||||
protected void initChannel(SocketChannel ch) {
|
|
||||||
installHttp(ch.pipeline());
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.bind(config.bindAddress, config.port)
|
|
||||||
.sync()
|
|
||||||
.channel();
|
|
||||||
} catch (InterruptedException | RuntimeException e) {
|
|
||||||
close();
|
|
||||||
throw e;
|
|
||||||
}
|
}
|
||||||
|
String token = uri.parameters().getOrDefault("token", List.of("")).getFirst();
|
||||||
|
Grant grant = grants.get(token);
|
||||||
|
return grant != null && grant.expires() >= System.currentTimeMillis() && grant.hash().equals(hash);
|
||||||
|
}
|
||||||
|
|
||||||
|
private synchronized boolean acquireDownload(String ip) {
|
||||||
|
int count = downloadsByIp.getOrDefault(ip, 0);
|
||||||
|
if (count >= config.maxDownloadsPerIp || activeDownloads >= config.maxConcurrentDownloads) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
downloadsByIp.put(ip, count + 1);
|
||||||
|
activeDownloads++;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private synchronized void releaseDownload(String ip) {
|
||||||
|
int remaining = downloadsByIp.get(ip) - 1;
|
||||||
|
if (remaining == 0) {
|
||||||
|
downloadsByIp.remove(ip);
|
||||||
|
} else {
|
||||||
|
downloadsByIp.put(ip, remaining);
|
||||||
|
}
|
||||||
|
activeDownloads--;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void installSniffer(ChannelPipeline pipeline) {
|
public void installSniffer(ChannelPipeline pipeline) {
|
||||||
pipeline.addFirst("astrapacks_detect", new Sniffer());
|
pipeline.addFirst("astrapacks_detect", new Sniffer());
|
||||||
}
|
}
|
||||||
|
|
||||||
private void installHttp(ChannelPipeline p) {
|
private void installHttp(ChannelPipeline pipeline) {
|
||||||
p.addLast("astrapacks_timeout", new ReadTimeoutHandler(30));
|
long bytesPerSecond = config.maxSpeedMiBPerSecond * 1024L * 1024L;
|
||||||
p.addLast("astrapacks_http", new HttpServerCodec(4096, 8192, 8192));
|
pipeline.addLast("astrapacks_timeout", new ReadTimeoutHandler(30));
|
||||||
p.addLast("astrapacks_aggregate", new HttpObjectAggregator(4096));
|
pipeline.addLast("astrapacks_http", new HttpServerCodec(4096, 8192, 8192));
|
||||||
p.addLast(
|
pipeline.addLast("astrapacks_aggregate", new HttpObjectAggregator(4096));
|
||||||
"astrapacks_speed",
|
pipeline.addLast("astrapacks_speed", new ChannelTrafficShapingHandler(bytesPerSecond, 0));
|
||||||
new ChannelTrafficShapingHandler(config.maxSpeedMiBPerSecond * 1024L * 1024L, 0));
|
pipeline.addLast("astrapacks_chunks", new ChunkedWriteHandler());
|
||||||
p.addLast("astrapacks_chunks", new ChunkedWriteHandler());
|
pipeline.addLast("astrapacks_download", new Download());
|
||||||
p.addLast("astrapacks_download", new Download());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private final class Sniffer extends ByteToMessageDecoder {
|
private final class Sniffer extends ByteToMessageDecoder {
|
||||||
@Override
|
@Override
|
||||||
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
|
protected void decode(ChannelHandlerContext context, ByteBuf input, List<Object> output) {
|
||||||
if (in.readableBytes() < 4) return;
|
if (input.readableBytes() < 4) {
|
||||||
int start = in.readerIndex();
|
return;
|
||||||
boolean http =
|
|
||||||
(in.getByte(start) == 'G'
|
|
||||||
&& in.getByte(start + 1) == 'E'
|
|
||||||
&& in.getByte(start + 2) == 'T'
|
|
||||||
&& in.getByte(start + 3) == ' ')
|
|
||||||
|| (in.getByte(start) == 'H'
|
|
||||||
&& in.getByte(start + 1) == 'E'
|
|
||||||
&& in.getByte(start + 2) == 'A'
|
|
||||||
&& in.getByte(start + 3) == 'D');
|
|
||||||
if (http) {
|
|
||||||
ChannelPipeline p = ctx.pipeline();
|
|
||||||
for (String name : new ArrayList<>(p.names()))
|
|
||||||
if (p.get(name) != null && p.get(name) != this) p.remove(name);
|
|
||||||
installHttp(p);
|
|
||||||
}
|
}
|
||||||
// Removal forwards all accumulated bytes to the selected protocol decoder.
|
String prefix = input.toString(input.readerIndex(), 4, StandardCharsets.US_ASCII);
|
||||||
ctx.pipeline().remove(this);
|
ChannelPipeline pipeline = context.pipeline();
|
||||||
|
if (prefix.equals("GET ") || prefix.equals("HEAD")) {
|
||||||
|
for (String name : new ArrayList<>(pipeline.names())) {
|
||||||
|
if (pipeline.get(name) != null && pipeline.get(name) != this) {
|
||||||
|
pipeline.remove(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
installHttp(pipeline);
|
||||||
|
}
|
||||||
|
// Removing the decoder forwards the buffered bytes to HTTP or Minecraft unchanged.
|
||||||
|
pipeline.remove(this);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private synchronized boolean acquire(String ip) {
|
|
||||||
int count = downloads.getOrDefault(ip, 0);
|
|
||||||
if (count >= config.maxDownloadsPerIp || active >= config.maxConcurrentDownloads)
|
|
||||||
return false;
|
|
||||||
downloads.put(ip, count + 1);
|
|
||||||
active++;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
private synchronized void release(String ip) {
|
|
||||||
downloads.computeIfPresent(ip, (key, count) -> count <= 1 ? null : count - 1);
|
|
||||||
active--;
|
|
||||||
}
|
|
||||||
|
|
||||||
private final class Download extends SimpleChannelInboundHandler<FullHttpRequest> {
|
private final class Download extends SimpleChannelInboundHandler<FullHttpRequest> {
|
||||||
private boolean handled;
|
private boolean handled;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request)
|
protected void channelRead0(ChannelHandlerContext context, FullHttpRequest request) throws IOException {
|
||||||
throws IOException {
|
if (handled) {
|
||||||
if (handled) return;
|
return;
|
||||||
|
}
|
||||||
handled = true;
|
handled = true;
|
||||||
if (!request.decoderResult().isSuccess()) {
|
if (!request.decoderResult().isSuccess()) {
|
||||||
error(ctx, HttpResponseStatus.BAD_REQUEST);
|
sendError(context, HttpResponseStatus.BAD_REQUEST);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!request.method().equals(HttpMethod.GET)
|
if (!request.method().equals(HttpMethod.GET) && !request.method().equals(HttpMethod.HEAD)) {
|
||||||
&& !request.method().equals(HttpMethod.HEAD)) {
|
sendError(context, HttpResponseStatus.METHOD_NOT_ALLOWED);
|
||||||
error(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
QueryStringDecoder uri = new QueryStringDecoder(request.uri());
|
QueryStringDecoder uri = new QueryStringDecoder(request.uri());
|
||||||
String path = uri.path();
|
String path = uri.path();
|
||||||
if (!path.matches("/astrapacks/[a-f0-9]{40}\\.zip")) {
|
if (!path.matches("/astrapacks/[a-f0-9]{40}\\.zip")) {
|
||||||
error(ctx, HttpResponseStatus.NOT_FOUND);
|
sendError(context, HttpResponseStatus.NOT_FOUND);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
String hash = path.substring("/astrapacks/".length(), path.length() - ".zip".length());
|
String hash = path.substring("/astrapacks/".length(), path.length() - ".zip".length());
|
||||||
Path file = published.get(hash);
|
Path file = published.get(hash);
|
||||||
if (file == null || !Files.isRegularFile(file)) {
|
if (file == null || !Files.isRegularFile(file)) {
|
||||||
error(ctx, HttpResponseStatus.NOT_FOUND);
|
sendError(context, HttpResponseStatus.NOT_FOUND);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (config.blockNonGameRequests) {
|
if (!authorized(uri, hash)) {
|
||||||
String token = uri.parameters().getOrDefault("token", List.of("")).getFirst();
|
sendError(context, HttpResponseStatus.FORBIDDEN);
|
||||||
Grant grant = grants.get(token);
|
|
||||||
if (grant == null
|
|
||||||
|| grant.expires() < System.currentTimeMillis()
|
|
||||||
|| !grant.hash().equals(hash)) {
|
|
||||||
error(ctx, HttpResponseStatus.FORBIDDEN);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
String ip =
|
|
||||||
((InetSocketAddress) ctx.channel().remoteAddress())
|
|
||||||
.getAddress()
|
|
||||||
.getHostAddress();
|
|
||||||
if (!acquire(ip)) {
|
|
||||||
error(ctx, HttpResponseStatus.TOO_MANY_REQUESTS);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Every response closes its connection; release the slot exactly once there.
|
|
||||||
ctx.channel().closeFuture().addListener(f -> release(ip));
|
InetSocketAddress remote = (InetSocketAddress) context.channel().remoteAddress();
|
||||||
ChunkedNioFile stream = null;
|
String ip = remote.getAddress().getHostAddress();
|
||||||
try {
|
if (!acquireDownload(ip)) {
|
||||||
long size = Files.size(file);
|
sendError(context, HttpResponseStatus.TOO_MANY_REQUESTS);
|
||||||
if (request.method().equals(HttpMethod.GET))
|
return;
|
||||||
stream = new ChunkedNioFile(file.toFile(), 65536);
|
|
||||||
HttpResponse response =
|
|
||||||
new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
|
|
||||||
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/zip");
|
|
||||||
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, size);
|
|
||||||
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
|
|
||||||
response.headers()
|
|
||||||
.set(HttpHeaderNames.CACHE_CONTROL, "private, max-age=31536000, immutable");
|
|
||||||
response.headers().set(HttpHeaderNames.ETAG, '"' + hash + '"');
|
|
||||||
ctx.write(response);
|
|
||||||
if (stream != null) ctx.write(new HttpChunkedInput(stream));
|
|
||||||
else ctx.write(LastHttpContent.EMPTY_LAST_CONTENT);
|
|
||||||
ctx.writeAndFlush(io.netty.buffer.Unpooled.EMPTY_BUFFER)
|
|
||||||
.addListener(ChannelFutureListener.CLOSE);
|
|
||||||
} catch (Exception e) {
|
|
||||||
if (stream != null) {
|
|
||||||
try {
|
|
||||||
stream.close();
|
|
||||||
} catch (Exception closeError) {
|
|
||||||
e.addSuppressed(closeError);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ctx.close();
|
|
||||||
throw e;
|
|
||||||
}
|
}
|
||||||
|
// Every response closes its connection, so this releases the slot exactly once.
|
||||||
|
context.channel().closeFuture().addListener(future -> releaseDownload(ip));
|
||||||
|
sendFile(context, file, hash, request.method().equals(HttpMethod.HEAD));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
|
public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
|
||||||
ctx.close();
|
context.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void error(ChannelHandlerContext ctx, HttpResponseStatus status) {
|
private static void sendFile(ChannelHandlerContext context, Path file, String hash, boolean headOnly)
|
||||||
|
throws IOException {
|
||||||
|
ChunkedNioFile stream = null;
|
||||||
|
try {
|
||||||
|
long size = Files.size(file);
|
||||||
|
if (!headOnly) {
|
||||||
|
stream = new ChunkedNioFile(file.toFile(), 65536);
|
||||||
|
}
|
||||||
|
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
|
||||||
|
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/zip");
|
||||||
|
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, size);
|
||||||
|
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
|
||||||
|
response.headers().set(HttpHeaderNames.CACHE_CONTROL, "private, max-age=31536000, immutable");
|
||||||
|
response.headers().set(HttpHeaderNames.ETAG, '"' + hash + '"');
|
||||||
|
context.write(response);
|
||||||
|
|
||||||
|
if (stream != null) {
|
||||||
|
context.write(new HttpChunkedInput(stream));
|
||||||
|
} else {
|
||||||
|
context.write(LastHttpContent.EMPTY_LAST_CONTENT);
|
||||||
|
}
|
||||||
|
context.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
|
||||||
|
} catch (Exception e) {
|
||||||
|
if (stream != null) {
|
||||||
|
try {
|
||||||
|
stream.close();
|
||||||
|
} catch (Exception closeError) {
|
||||||
|
e.addSuppressed(closeError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
context.close();
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void sendError(ChannelHandlerContext context, HttpResponseStatus status) {
|
||||||
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
|
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
|
||||||
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
|
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
|
||||||
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
|
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
|
||||||
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
|
context.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void close() {
|
public void close() {
|
||||||
if (listening != null) listening.close().awaitUninterruptibly();
|
if (listeningChannel != null) {
|
||||||
if (group != null) group.shutdownGracefully(0, 2, TimeUnit.SECONDS).awaitUninterruptibly();
|
listeningChannel.close().awaitUninterruptibly();
|
||||||
|
}
|
||||||
|
if (eventLoops != null) {
|
||||||
|
eventLoops.shutdownGracefully(0, 2, TimeUnit.SECONDS).awaitUninterruptibly();
|
||||||
|
}
|
||||||
grants.clear();
|
grants.clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,5 @@
|
|||||||
package online.astradev.packs;
|
package online.astradev.packs;
|
||||||
|
|
||||||
import net.minecraft.commands.CommandSourceStack;
|
|
||||||
import net.minecraft.network.Connection;
|
|
||||||
import net.minecraft.network.chat.Component;
|
|
||||||
import net.minecraft.network.protocol.common.ServerboundResourcePackPacket;
|
|
||||||
import net.minecraft.server.MinecraftServer;
|
|
||||||
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
|
|
||||||
|
|
||||||
import online.astradev.packs.mixin.CommonAccessor;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
import java.net.URISyntaxException;
|
import java.net.URISyntaxException;
|
||||||
@@ -20,23 +11,35 @@ import java.util.concurrent.ConcurrentHashMap;
|
|||||||
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.ExecutorService;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
|
|
||||||
|
import net.minecraft.commands.CommandSourceStack;
|
||||||
|
import net.minecraft.network.Connection;
|
||||||
|
import net.minecraft.network.chat.Component;
|
||||||
|
import net.minecraft.network.protocol.common.ServerboundResourcePackPacket;
|
||||||
|
import net.minecraft.server.MinecraftServer;
|
||||||
|
import net.minecraft.server.level.ServerPlayer;
|
||||||
|
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
|
||||||
|
import net.minecraft.server.network.ServerGamePacketListenerImpl;
|
||||||
|
import online.astradev.packs.mixin.CommonAccessor;
|
||||||
|
|
||||||
public final class PackRuntime implements AutoCloseable {
|
public final class PackRuntime implements AutoCloseable {
|
||||||
public static volatile PackRuntime INSTANCE;
|
public static volatile PackRuntime INSTANCE;
|
||||||
|
|
||||||
|
private static final String RESOURCE_VERSION = "[88,0]";
|
||||||
|
|
||||||
private final MinecraftServer server;
|
private final MinecraftServer server;
|
||||||
private final Path root;
|
private final Path root;
|
||||||
private final Path configPath;
|
private final Path configPath;
|
||||||
|
private final PackHost host;
|
||||||
|
private final Map<ServerCommonPacketListenerImpl, PackSession> sessions = new ConcurrentHashMap<>();
|
||||||
|
private final Map<UUID, String> pendingWelcome = new ConcurrentHashMap<>();
|
||||||
|
private final ExecutorService worker = Executors.newSingleThreadExecutor(
|
||||||
|
Thread.ofPlatform().daemon().name("AstraPacks-build").factory());
|
||||||
|
|
||||||
private volatile PackConfig config;
|
private volatile PackConfig config;
|
||||||
private volatile PackBuilder.Pack current;
|
private volatile PackBuilder.Pack current;
|
||||||
private final PackHost host;
|
|
||||||
private final Map<ServerCommonPacketListenerImpl, PackSession> sessions =
|
|
||||||
new ConcurrentHashMap<>();
|
|
||||||
private final Map<UUID, String> welcome = new ConcurrentHashMap<>();
|
|
||||||
private final ExecutorService worker =
|
|
||||||
Executors.newSingleThreadExecutor(
|
|
||||||
Thread.ofPlatform().daemon().name("AstraPacks-build").factory());
|
|
||||||
// Read and written on the server thread, including build completion callbacks.
|
|
||||||
private boolean busy;
|
|
||||||
private volatile boolean closed;
|
private volatile boolean closed;
|
||||||
|
// Only the server thread changes this flag, including publication and failure callbacks.
|
||||||
|
private boolean building;
|
||||||
|
|
||||||
public PackRuntime(MinecraftServer server, Path root, Path configPath, PackConfig config) {
|
public PackRuntime(MinecraftServer server, Path root, Path configPath, PackConfig config) {
|
||||||
this.server = server;
|
this.server = server;
|
||||||
@@ -46,46 +49,46 @@ public final class PackRuntime implements AutoCloseable {
|
|||||||
this.host = new PackHost(config.hosting);
|
this.host = new PackHost(config.hosting);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void start() throws Exception {
|
public void start() throws IOException, InterruptedException {
|
||||||
if (!config.enabled) return;
|
if (!config.enabled) {
|
||||||
if (server.getServerResourcePack().isPresent())
|
return;
|
||||||
throw new IOException(
|
}
|
||||||
"AstraPacks must be the only pack sender: clear resource-pack in"
|
if (server.getServerResourcePack().isPresent()) {
|
||||||
+ " server.properties");
|
throw new IOException("AstraPacks must be the only pack sender: clear resource-pack in server.properties");
|
||||||
// Only create the default source automatically. A typo in a custom path must fail visibly.
|
}
|
||||||
|
|
||||||
|
// Custom source paths are not created: a typo in the configuration must be visible.
|
||||||
Files.createDirectories(root.resolve("astrapacks/contents"));
|
Files.createDirectories(root.resolve("astrapacks/contents"));
|
||||||
PackBuilder.Pack candidate;
|
PackBuilder.Pack pack = loadStartupPack();
|
||||||
try {
|
if (pack != null) {
|
||||||
candidate =
|
|
||||||
config.build.onStartup
|
|
||||||
? new PackBuilder(config).build(root, "[88,0]")
|
|
||||||
: PackBuilder.previous(root, config);
|
|
||||||
} catch (IOException e) {
|
|
||||||
AstraPacks.LOG.error("Resource-pack build failed; trying the last successful build", e);
|
|
||||||
try {
|
try {
|
||||||
candidate = PackBuilder.previous(root, config);
|
PackBuilder.verifyExternal(config, pack);
|
||||||
} catch (IOException absent) {
|
host.publish(pack);
|
||||||
AstraPacks.LOG.error(
|
current = pack;
|
||||||
"No usable pack. Required-pack logins will be refused.", absent);
|
|
||||||
candidate = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (candidate != null) {
|
|
||||||
try {
|
|
||||||
PackBuilder.verifyExternal(config, candidate);
|
|
||||||
current = candidate;
|
|
||||||
host.publish(candidate);
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
AstraPacks.LOG.error(
|
AstraPacks.LOG.error("External ZIP is not ready. Required-pack logins will be refused.", e);
|
||||||
"External ZIP is not ready. Required-pack logins will be refused.", e);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
host.start();
|
host.start();
|
||||||
AstraPacks.LOG.info(
|
AstraPacks.LOG.info("AstraPacks: mode={}, required={}, pack={}",
|
||||||
"AstraPacks: mode={}, required={}, pack={}",
|
config.hosting.mode, config.delivery.required, current == null ? "UNAVAILABLE" : current.path());
|
||||||
config.hosting.mode,
|
}
|
||||||
config.delivery.required,
|
|
||||||
current == null ? "UNAVAILABLE" : current.path());
|
private PackBuilder.Pack loadStartupPack() {
|
||||||
|
if (config.build.onStartup) {
|
||||||
|
try {
|
||||||
|
return new PackBuilder(config).build(root, RESOURCE_VERSION);
|
||||||
|
} catch (IOException e) {
|
||||||
|
AstraPacks.LOG.error("Resource-pack build failed; trying the last successful build", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return PackBuilder.previous(root, config);
|
||||||
|
} catch (IOException e) {
|
||||||
|
AstraPacks.LOG.error("No usable pack. Required-pack logins will be refused.", e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public PackConfig config() {
|
public PackConfig config() {
|
||||||
@@ -102,86 +105,108 @@ public final class PackRuntime implements AutoCloseable {
|
|||||||
|
|
||||||
public PackSession session(ServerCommonPacketListenerImpl listener) {
|
public PackSession session(ServerCommonPacketListenerImpl listener) {
|
||||||
PackSession session = new PackSession(this, listener);
|
PackSession session = new PackSession(this, listener);
|
||||||
PackSession old = sessions.put(listener, session);
|
PackSession previous = sessions.put(listener, session);
|
||||||
if (old != null) old.replace();
|
if (previous != null) {
|
||||||
|
previous.removeFromClient();
|
||||||
|
}
|
||||||
return session;
|
return session;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean intercept(
|
public boolean intercept(ServerCommonPacketListenerImpl listener, ServerboundResourcePackPacket packet) {
|
||||||
ServerCommonPacketListenerImpl listener, ServerboundResourcePackPacket packet) {
|
if (!config.enabled) {
|
||||||
if (!config.enabled) return false;
|
return false;
|
||||||
// Vanilla configuration handling finishes its own task for ANY terminal UUID.
|
}
|
||||||
// Consume unrelated/stale replies too, so they cannot finish our gate or another task.
|
// Consume stale replies too: vanilla treats any terminal UUID as completion of its task.
|
||||||
server.execute(
|
server.execute(() -> {
|
||||||
() -> {
|
PackSession session = sessions.get(listener);
|
||||||
PackSession session = sessions.get(listener);
|
if (session != null) {
|
||||||
if (session != null) session.response(packet);
|
session.response(packet);
|
||||||
});
|
}
|
||||||
|
});
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void tick() {
|
public void tick() {
|
||||||
sessions.entrySet()
|
var iterator = sessions.entrySet().iterator();
|
||||||
.removeIf(
|
while (iterator.hasNext()) {
|
||||||
entry -> {
|
var entry = iterator.next();
|
||||||
if (!((CommonAccessor) entry.getKey())
|
ServerCommonPacketListenerImpl listener = entry.getKey();
|
||||||
.astrapacks$connection()
|
Connection connection = ((CommonAccessor) listener).astrapacks$connection();
|
||||||
.isConnected()) {
|
if (connection.isConnected()) {
|
||||||
welcome.remove(entry.getKey().getOwner().id());
|
entry.getValue().tick();
|
||||||
return true;
|
} else {
|
||||||
}
|
pendingWelcome.remove(listener.getOwner().id());
|
||||||
entry.getValue().tick();
|
iterator.remove();
|
||||||
return false;
|
}
|
||||||
});
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void loaded(ServerCommonPacketListenerImpl listener, String message) {
|
public void loaded(ServerCommonPacketListenerImpl listener, String message) {
|
||||||
if (listener instanceof net.minecraft.server.network.ServerGamePacketListenerImpl game) {
|
if (listener instanceof ServerGamePacketListenerImpl game) {
|
||||||
if (!message.isBlank())
|
if (!message.isBlank()) {
|
||||||
game.player.sendSystemMessage(PackText.of(message, listener.getOwner().name()));
|
game.player.sendSystemMessage(PackText.of(message, listener.getOwner().name()));
|
||||||
} else welcome.put(listener.getOwner().id(), message);
|
}
|
||||||
|
} else {
|
||||||
|
pendingWelcome.put(listener.getOwner().id(), message);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void welcome(net.minecraft.server.level.ServerPlayer player) {
|
public void welcome(ServerPlayer player) {
|
||||||
String text = welcome.remove(player.getUUID());
|
String message = pendingWelcome.remove(player.getUUID());
|
||||||
if (text != null && !text.isBlank())
|
if (message != null && !message.isBlank()) {
|
||||||
player.sendSystemMessage(PackText.of(text, player.getGameProfile().name()));
|
player.sendSystemMessage(PackText.of(message, player.getGameProfile().name()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public String url(ServerCommonPacketListenerImpl listener, PackBuilder.Pack pack) {
|
public String url(ServerCommonPacketListenerImpl listener, PackBuilder.Pack pack) {
|
||||||
if (config.hosting.mode.equals("no_host")) return config.hosting.externalUrl;
|
if (config.hosting.mode.equals("no_host")) {
|
||||||
Connection connection = ((CommonAccessor) listener).astrapacks$connection();
|
return config.hosting.externalUrl;
|
||||||
|
}
|
||||||
String base = config.hosting.publicAddress;
|
String base = config.hosting.publicAddress;
|
||||||
if (base.equals("auto")) {
|
if (base.equals("auto")) {
|
||||||
String address = ((ConnectionData) connection).astrapacks$host();
|
base = automaticAddress(listener);
|
||||||
if (address == null || address.isBlank())
|
|
||||||
throw new IllegalArgumentException(
|
|
||||||
"Cannot determine server address; set hosting.publicAddress");
|
|
||||||
int port =
|
|
||||||
config.hosting.mode.equals("self_host")
|
|
||||||
? config.hosting.port
|
|
||||||
: server.getPort();
|
|
||||||
try {
|
|
||||||
base = new URI("http", null, address, port, null, null, null).toASCIIString();
|
|
||||||
} catch (URISyntaxException e) {
|
|
||||||
throw new IllegalArgumentException("Invalid server address", e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return base.replaceAll("/+$", "") + host.issuePath(pack);
|
return base.replaceAll("/+$", "") + host.issuePath(pack);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void rebuild(CommandSourceStack source, boolean reload, boolean publishOnly) {
|
private String automaticAddress(ServerCommonPacketListenerImpl listener) {
|
||||||
|
Connection connection = ((CommonAccessor) listener).astrapacks$connection();
|
||||||
|
String address = ((ConnectionData) connection).astrapacks$host();
|
||||||
|
if (address == null || address.isBlank()) {
|
||||||
|
throw new IllegalArgumentException("Cannot determine server address; set hosting.publicAddress");
|
||||||
|
}
|
||||||
|
int port = config.hosting.mode.equals("self_host") ? config.hosting.port : server.getPort();
|
||||||
|
try {
|
||||||
|
return new URI("http", null, address, port, null, null, null).toASCIIString();
|
||||||
|
} catch (URISyntaxException e) {
|
||||||
|
throw new IllegalArgumentException("Invalid server address", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void build(CommandSourceStack source) {
|
||||||
|
requestBuild(source, false, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void reload(CommandSourceStack source) {
|
||||||
|
requestBuild(source, true, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void publish(CommandSourceStack source) {
|
||||||
|
requestBuild(source, false, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requestBuild(CommandSourceStack source, boolean reload, boolean publishOnly) {
|
||||||
if (closed) {
|
if (closed) {
|
||||||
source.sendFailure(Component.literal("AstraPacks остановлен."));
|
source.sendFailure(Component.literal("AstraPacks остановлен."));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (busy) {
|
if (building) {
|
||||||
source.sendFailure(Component.literal("Сборка AstraPacks уже выполняется."));
|
source.sendFailure(Component.literal("Сборка AstraPacks уже выполняется."));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
busy = true;
|
|
||||||
source.sendSuccess(
|
building = true;
|
||||||
() -> Component.literal("AstraPacks: проверка и подготовка ресурспака…"), false);
|
source.sendSuccess(() -> Component.literal("AstraPacks: проверка и подготовка ресурспака…"), false);
|
||||||
worker.execute(() -> preparePack(source, reload, publishOnly));
|
worker.execute(() -> preparePack(source, reload, publishOnly));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -191,65 +216,45 @@ public final class PackRuntime implements AutoCloseable {
|
|||||||
if (next.enabled != config.enabled || !next.hosting.sameSettings(config.hosting)) {
|
if (next.enabled != config.enabled || !next.hosting.sameSettings(config.hosting)) {
|
||||||
throw new IOException("Изменение enabled или hosting требует перезапуска сервера.");
|
throw new IOException("Изменение enabled или hosting требует перезапуска сервера.");
|
||||||
}
|
}
|
||||||
PackBuilder.Pack pack =
|
PackBuilder.Pack pack = publishOnly
|
||||||
publishOnly
|
? PackBuilder.previous(root, next)
|
||||||
? PackBuilder.previous(root, next)
|
: new PackBuilder(next).build(root, RESOURCE_VERSION);
|
||||||
: new PackBuilder(next).build(root, "[88,0]");
|
|
||||||
PackBuilder.verifyExternal(next, pack);
|
PackBuilder.verifyExternal(next, pack);
|
||||||
server.execute(() -> publishPack(source, next, pack));
|
server.execute(() -> publishPack(source, next, pack));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
AstraPacks.LOG.error("Pack build/publication failed; active pack retained", e);
|
AstraPacks.LOG.error("Pack build/publication failed; active pack retained", e);
|
||||||
server.execute(
|
server.execute(() -> {
|
||||||
() -> {
|
building = false;
|
||||||
busy = false;
|
if (!closed) {
|
||||||
if (!closed) {
|
source.sendFailure(Component.literal("AstraPacks: " + e.getMessage() + " Рабочий пак сохранён."));
|
||||||
source.sendFailure(
|
}
|
||||||
Component.literal(
|
});
|
||||||
"AstraPacks: "
|
|
||||||
+ e.getMessage()
|
|
||||||
+ " Рабочий пак сохранён."));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void publishPack(CommandSourceStack source, PackConfig next, PackBuilder.Pack pack) {
|
private void publishPack(CommandSourceStack source, PackConfig next, PackBuilder.Pack pack) {
|
||||||
busy = false;
|
building = false;
|
||||||
if (closed) {
|
if (closed) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
config = next;
|
config = next;
|
||||||
current = pack;
|
|
||||||
host.publish(pack);
|
host.publish(pack);
|
||||||
String message =
|
current = pack;
|
||||||
"AstraPacks: готово, "
|
|
||||||
+ pack.files()
|
String message = "AstraPacks: готово, " + pack.files() + " файлов, "
|
||||||
+ " файлов, "
|
+ pack.bytes() + " байт. SHA-1: " + pack.sha1();
|
||||||
+ pack.bytes()
|
|
||||||
+ " байт. SHA-1: "
|
|
||||||
+ pack.sha1();
|
|
||||||
source.sendSuccess(() -> Component.literal(message), true);
|
source.sendSuccess(() -> Component.literal(message), true);
|
||||||
if (config.enabled && config.build.resendAfterBuild) {
|
if (config.enabled && config.build.resendAfterBuild) {
|
||||||
resendAll();
|
for (ServerPlayer player : server.getPlayerList().getPlayers()) {
|
||||||
|
session(player.connection).start(player.connection::send);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void resendAll() {
|
|
||||||
for (var player : server.getPlayerList().getPlayers())
|
|
||||||
session(player.connection).start(player.connection::send);
|
|
||||||
}
|
|
||||||
|
|
||||||
public String status() {
|
public String status() {
|
||||||
return "AstraPacks "
|
String pack = current == null ? "UNAVAILABLE" : current.path() + " (" + current.files() + " files)";
|
||||||
+ config.hosting.mode
|
return "AstraPacks " + config.hosting.mode + ", required=" + config.delivery.required
|
||||||
+ ", required="
|
+ ", build=" + building + ", pack=" + pack;
|
||||||
+ config.delivery.required
|
|
||||||
+ ", build="
|
|
||||||
+ busy
|
|
||||||
+ ", pack="
|
|
||||||
+ (current == null
|
|
||||||
? "UNAVAILABLE"
|
|
||||||
: current.path() + " (" + current.files() + " files)");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -258,6 +263,6 @@ public final class PackRuntime implements AutoCloseable {
|
|||||||
worker.shutdownNow();
|
worker.shutdownNow();
|
||||||
host.close();
|
host.close();
|
||||||
sessions.clear();
|
sessions.clear();
|
||||||
welcome.clear();
|
pendingWelcome.clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
package online.astradev.packs;
|
package online.astradev.packs;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
import net.minecraft.network.chat.Component;
|
||||||
import net.minecraft.network.protocol.Packet;
|
import net.minecraft.network.protocol.Packet;
|
||||||
import net.minecraft.network.protocol.common.ClientboundResourcePackPopPacket;
|
import net.minecraft.network.protocol.common.ClientboundResourcePackPopPacket;
|
||||||
import net.minecraft.network.protocol.common.ClientboundResourcePackPushPacket;
|
import net.minecraft.network.protocol.common.ClientboundResourcePackPushPacket;
|
||||||
@@ -7,23 +12,20 @@ import net.minecraft.network.protocol.common.ServerboundResourcePackPacket;
|
|||||||
import net.minecraft.server.network.ConfigurationTask;
|
import net.minecraft.server.network.ConfigurationTask;
|
||||||
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
|
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
|
||||||
|
|
||||||
import java.util.Optional;
|
/** Keeps the configuration task open until the client reports a loaded pack or an allowed failure. */
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.function.Consumer;
|
|
||||||
|
|
||||||
/** Configuration only completes on SUCCESSFULLY_LOADED, never merely ACCEPTED or DOWNLOADED. */
|
|
||||||
public final class PackSession implements ConfigurationTask {
|
public final class PackSession implements ConfigurationTask {
|
||||||
public static final Type TYPE = new Type("astrapacks:resource_pack");
|
public static final Type TYPE = new Type("astrapacks:resource_pack");
|
||||||
|
|
||||||
private final PackRuntime runtime;
|
private final PackRuntime runtime;
|
||||||
private final ServerCommonPacketListenerImpl listener;
|
private final ServerCommonPacketListenerImpl listener;
|
||||||
private final PackConfig config;
|
private final PackConfig config;
|
||||||
private final PackBuilder.Pack pack;
|
private final PackBuilder.Pack pack;
|
||||||
private UUID id;
|
|
||||||
private long deadline;
|
private UUID requestId;
|
||||||
private int retries;
|
private long deadlineNanos;
|
||||||
private boolean done;
|
private int retriesUsed;
|
||||||
private boolean failed;
|
private boolean complete;
|
||||||
private boolean started;
|
private boolean disconnected;
|
||||||
|
|
||||||
public PackSession(PackRuntime runtime, ServerCommonPacketListenerImpl listener) {
|
public PackSession(PackRuntime runtime, ServerCommonPacketListenerImpl listener) {
|
||||||
this.runtime = runtime;
|
this.runtime = runtime;
|
||||||
@@ -39,90 +41,98 @@ public final class PackSession implements ConfigurationTask {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void start(Consumer<Packet<?>> sender) {
|
public void start(Consumer<Packet<?>> sender) {
|
||||||
started = true;
|
if (pack != null) {
|
||||||
if (pack == null) {
|
sendAttempt();
|
||||||
if (config.delivery.required) disconnect(config.messages.unavailable);
|
} else if (config.delivery.required) {
|
||||||
else done = true;
|
disconnect(config.messages.unavailable);
|
||||||
return;
|
} else {
|
||||||
|
complete = true;
|
||||||
}
|
}
|
||||||
send();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void send() {
|
private void sendAttempt() {
|
||||||
if (id != null) listener.send(new ClientboundResourcePackPopPacket(Optional.of(id)));
|
removeFromClient();
|
||||||
id = UUID.randomUUID();
|
requestId = UUID.randomUUID();
|
||||||
deadline = System.nanoTime() + config.delivery.timeoutSeconds * 1_000_000_000L;
|
deadlineNanos = System.nanoTime() + config.delivery.timeoutSeconds * 1_000_000_000L;
|
||||||
try {
|
try {
|
||||||
listener.send(
|
Optional<Component> prompt = Optional.empty();
|
||||||
new ClientboundResourcePackPushPacket(
|
if (!config.messages.prompt.isBlank()) {
|
||||||
id,
|
prompt = Optional.of(PackText.of(config.messages.prompt, playerName()));
|
||||||
runtime.url(listener, pack),
|
}
|
||||||
pack.sha1(),
|
String url = runtime.url(listener, pack);
|
||||||
config.delivery.required,
|
listener.send(new ClientboundResourcePackPushPacket(
|
||||||
config.messages.prompt.isBlank()
|
requestId, url, pack.sha1(), config.delivery.required, prompt));
|
||||||
? Optional.empty()
|
|
||||||
: Optional.of(PackText.of(config.messages.prompt, player()))));
|
|
||||||
} catch (RuntimeException e) {
|
} catch (RuntimeException e) {
|
||||||
AstraPacks.LOG.error("Cannot send resource pack to {}", player(), e);
|
AstraPacks.LOG.error("Cannot send resource pack to {}", playerName(), e);
|
||||||
fail(config.messages.unavailable);
|
fail(config.messages.unavailable);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void response(ServerboundResourcePackPacket packet) {
|
public void response(ServerboundResourcePackPacket packet) {
|
||||||
if (!started || failed || !packet.id().equals(id)) return;
|
if (requestId == null || disconnected || !requestId.equals(packet.id())) {
|
||||||
if (config.delivery.logStatus)
|
return;
|
||||||
AstraPacks.LOG.info(
|
}
|
||||||
"Resource pack {}: {} ({})", player(), packet.action(), pack.sha1());
|
if (config.delivery.logStatus) {
|
||||||
if (done) return;
|
AstraPacks.LOG.info("Resource pack {}: {} ({})", playerName(), packet.action(), pack.sha1());
|
||||||
|
}
|
||||||
|
if (complete) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
switch (packet.action()) {
|
switch (packet.action()) {
|
||||||
case SUCCESSFULLY_LOADED -> {
|
case SUCCESSFULLY_LOADED -> {
|
||||||
done = true;
|
complete = true;
|
||||||
runtime.loaded(listener, config.messages.loaded);
|
runtime.loaded(listener, config.messages.loaded);
|
||||||
}
|
}
|
||||||
case DECLINED -> {
|
case DECLINED -> {
|
||||||
if (config.delivery.required) disconnect(config.messages.declined);
|
if (config.delivery.required) {
|
||||||
else done = true;
|
disconnect(config.messages.declined);
|
||||||
|
} else {
|
||||||
|
complete = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
case FAILED_DOWNLOAD, FAILED_RELOAD, INVALID_URL, DISCARDED -> {
|
case FAILED_DOWNLOAD, FAILED_RELOAD, INVALID_URL, DISCARDED -> {
|
||||||
if (retries < config.delivery.retries) {
|
if (retriesUsed < config.delivery.retries) {
|
||||||
retries++;
|
retriesUsed++;
|
||||||
send();
|
sendAttempt();
|
||||||
} else {
|
} else {
|
||||||
fail(config.messages.failed);
|
fail(config.messages.failed);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
default -> {
|
default -> {
|
||||||
/* Accept/download progress does not extend the bounded deadline. */
|
// ACCEPTED and DOWNLOADED neither finish the task nor extend its deadline.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean tick() {
|
public boolean tick() {
|
||||||
if (started && !done && !failed && System.nanoTime() >= deadline) {
|
if (requestId != null && !complete && !disconnected && System.nanoTime() >= deadlineNanos) {
|
||||||
fail(config.messages.timeout);
|
fail(config.messages.timeout);
|
||||||
}
|
}
|
||||||
return done;
|
return complete;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void replace() {
|
public void removeFromClient() {
|
||||||
if (id != null) listener.send(new ClientboundResourcePackPopPacket(Optional.of(id)));
|
if (requestId != null) {
|
||||||
}
|
listener.send(new ClientboundResourcePackPopPacket(Optional.of(requestId)));
|
||||||
|
}
|
||||||
private String player() {
|
|
||||||
return listener.getOwner().name();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void fail(String message) {
|
private void fail(String message) {
|
||||||
if (config.delivery.required || config.delivery.kickOnFailure) {
|
if (config.delivery.required || config.delivery.kickOnFailure) {
|
||||||
disconnect(message);
|
disconnect(message);
|
||||||
} else {
|
} else {
|
||||||
done = true;
|
complete = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void disconnect(String message) {
|
private void disconnect(String message) {
|
||||||
failed = true;
|
disconnected = true;
|
||||||
listener.disconnect(PackText.of(message, player()));
|
listener.disconnect(PackText.of(message, playerName()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private String playerName() {
|
||||||
|
return listener.getOwner().name();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,29 +11,33 @@ public final class PackText {
|
|||||||
public static Component of(String text, String player) {
|
public static Component of(String text, String player) {
|
||||||
text = text.replace("{player}", player).replace("\\n", "\n");
|
text = text.replace("{player}", player).replace("\\n", "\n");
|
||||||
MutableComponent result = Component.empty();
|
MutableComponent result = Component.empty();
|
||||||
|
StringBuilder segment = new StringBuilder();
|
||||||
Style style = Style.EMPTY;
|
Style style = Style.EMPTY;
|
||||||
StringBuilder part = new StringBuilder();
|
|
||||||
for (int i = 0; i < text.length(); i++) {
|
for (int index = 0; index < text.length(); index++) {
|
||||||
char ch = text.charAt(i);
|
char character = text.charAt(index);
|
||||||
if ((ch == '&' || ch == '§') && i + 1 < text.length()) {
|
if ((character != '&' && character != '§') || index + 1 == text.length()) {
|
||||||
ChatFormatting code = ChatFormatting.getByCode(text.charAt(i + 1));
|
segment.append(character);
|
||||||
if (code != null) {
|
continue;
|
||||||
result.append(Component.literal(part.toString()).setStyle(style));
|
|
||||||
part.setLength(0);
|
|
||||||
if (code == ChatFormatting.RESET) {
|
|
||||||
style = Style.EMPTY;
|
|
||||||
} else if ("0123456789abcdef".indexOf(Character.toLowerCase(text.charAt(i + 1)))
|
|
||||||
>= 0) {
|
|
||||||
style = Style.EMPTY.applyFormat(code);
|
|
||||||
} else {
|
|
||||||
style = style.applyFormat(code);
|
|
||||||
}
|
|
||||||
i++;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
part.append(ch);
|
char code = text.charAt(index + 1);
|
||||||
|
ChatFormatting formatting = ChatFormatting.getByCode(code);
|
||||||
|
if (formatting == null) {
|
||||||
|
segment.append(character);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
result.append(Component.literal(segment.toString()).setStyle(style));
|
||||||
|
segment.setLength(0);
|
||||||
|
if (formatting == ChatFormatting.RESET) {
|
||||||
|
style = Style.EMPTY;
|
||||||
|
} else if ("0123456789abcdef".indexOf(Character.toLowerCase(code)) >= 0) {
|
||||||
|
style = Style.EMPTY.applyFormat(formatting);
|
||||||
|
} else {
|
||||||
|
style = style.applyFormat(formatting);
|
||||||
|
}
|
||||||
|
index++;
|
||||||
}
|
}
|
||||||
return result.append(Component.literal(part.toString()).setStyle(style));
|
return result.append(Component.literal(segment.toString()).setStyle(style));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user