Build shared resource folder with two-version retention and dedicated HTTP hosting

This commit is contained in:
2026-09-06 19:20:55 +03:00
parent 5b51cba772
commit f701699db8
12 changed files with 426 additions and 505 deletions
@@ -1,5 +1,6 @@
package online.astradev.packs;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
@@ -29,6 +30,7 @@ import org.slf4j.LoggerFactory;
@Mod(value = "astrapacks", dist = Dist.DEDICATED_SERVER)
public final class AstraPacks {
public static final Logger LOG = LoggerFactory.getLogger("AstraPacks");
private boolean startupPending;
public AstraPacks(IEventBus modBus) {
modBus.addListener(this::registerConfigurationTask);
@@ -46,7 +48,8 @@ public final class AstraPacks {
PackConfig config = PackConfig.load(configPath);
PackRuntime runtime = new PackRuntime(event.getServer(), root, configPath, config);
PackRuntime.INSTANCE = runtime;
runtime.start();
Files.createDirectories(config.contents(root));
startupPending = true;
} catch (Exception e) {
if (PackRuntime.INSTANCE != null) {
PackRuntime.INSTANCE.close();
@@ -59,6 +62,7 @@ public final class AstraPacks {
private void stop(ServerStoppedEvent event) {
PackRuntime runtime = PackRuntime.INSTANCE;
PackRuntime.INSTANCE = null;
startupPending = false;
if (runtime != null) {
runtime.close();
}
@@ -76,6 +80,17 @@ public final class AstraPacks {
private void tick(ServerTickEvent.Post event) {
PackRuntime runtime = PackRuntime.INSTANCE;
if (runtime != null) {
// All server startup events have finished: other mods can export resources there.
if (startupPending) {
startupPending = false;
try {
runtime.start();
} catch (Exception e) {
runtime.close();
PackRuntime.INSTANCE = null;
throw new IllegalStateException("Cannot start AstraPacks", e);
}
}
runtime.tick();
}
}
@@ -95,7 +110,6 @@ public final class AstraPacks {
command.then(Commands.literal("status").executes(this::status));
command.then(Commands.literal("build").executes(this::build));
command.then(Commands.literal("reload").executes(this::reload));
command.then(Commands.literal("publish").executes(this::publish));
command.then(Commands.literal("send")
.then(Commands.argument("players", EntityArgument.players()).executes(this::send)));
@@ -118,11 +132,6 @@ public final class AstraPacks {
return 1;
}
private int publish(CommandContext<CommandSourceStack> context) {
PackRuntime.INSTANCE.publish(context.getSource());
return 1;
}
private int send(CommandContext<CommandSourceStack> context) throws CommandSyntaxException {
PackRuntime runtime = PackRuntime.INSTANCE;
CommandSourceStack source = context.getSource();
@@ -1,6 +0,0 @@
package online.astradev.packs;
public interface ConnectionData {
String astrapacks$host();
void astrapacks$host(String host);
}
@@ -2,239 +2,185 @@ package online.astradev.packs;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.Map;
import java.util.Properties;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
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. */
/** Archives the shared content directory, keeping the current and one previous ZIP. */
public final class PackBuilder {
public record Pack(Path path, String sha1, int files, long bytes) {}
private record Asset(byte[] data, String source) {}
private final PackConfig config;
private final SortedMap<String, Asset> assets = new TreeMap<>();
private long sourceBytes;
public PackBuilder(PackConfig config) {
this.config = config;
}
public Pack build(Path root, String resourceVersion) throws IOException {
assets.clear();
sourceBytes = 0;
readSources(root);
if (config.build.scanModJars) {
readModBundles(root.resolve("mods"));
Path contents = config.contents(root);
if (!Files.isDirectory(contents) || Files.isSymbolicLink(contents)) {
throw new IOException("Resource directory is missing or is a symbolic link: " + contents);
}
addMetadata(resourceVersion);
return writePack(config.storage(root).resolve("output"));
}
private void readSources(Path root) throws IOException {
for (String source : config.build.sources) {
Path path = root.resolve(source).toAbsolutePath().normalize();
if (!Files.exists(path)) {
throw new IOException("Source does not exist: " + path);
}
if (Files.isDirectory(path)) {
readDirectory(path);
} else {
readArchive(path);
}
}
}
private void readDirectory(Path root) throws IOException {
if (Files.isSymbolicLink(root)) {
throw new IOException("Symlink source: " + root);
}
try (var paths = Files.walk(root)) {
for (Path file : paths.sorted().toList()) {
if (Files.isSymbolicLink(file)) {
throw new IOException("Symlink resource: " + file);
}
if (!Files.isRegularFile(file)) {
continue;
}
String name = root.relativize(file).toString().replace('\\', '/');
// Accept a pack root or a directory containing named pack roots.
if (!isResource(name)) {
int separator = name.indexOf('/');
String nestedName = name.substring(separator + 1);
if (separator >= 0 && isResource(nestedName)) {
name = nestedName;
} else if (name.endsWith(".zip")) {
readArchive(file);
continue;
} else {
continue;
}
}
try (InputStream input = Files.newInputStream(file)) {
addAsset(name, input, file.toString());
}
}
}
}
private void readArchive(Path path) throws IOException {
try (ZipFile zip = new ZipFile(path.toFile())) {
readEntries(zip, "");
}
}
private void readModBundles(Path mods) throws IOException {
if (!Files.isDirectory(mods)) {
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/");
}
}
}
}
private void readEntries(ZipFile zip, String prefix) throws IOException {
var entries = zip.entries();
while (entries.hasMoreElements()) {
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());
}
}
}
private static boolean isResource(String name) {
return name.startsWith("assets/") || name.equals("pack.png");
}
private void addAsset(String name, InputStream input, String source) throws IOException {
PackFiles.safe(Path.of("."), name);
int limit = config.build.maxFileMiB * 1024 * 1024;
byte[] bytes = input.readNBytes(limit + 1);
if (bytes.length > limit) {
throw new IOException("Resource exceeds maxFileMiB: " + source);
}
sourceBytes += bytes.length;
if (sourceBytes > config.build.maxTotalMiB * 1024L * 1024L) {
throw new IOException("Sources exceed maxTotalMiB");
}
Asset previous = assets.get(name);
if (previous != null && config.build.conflictPolicy.equals("error")
&& !Arrays.equals(bytes, previous.data())) {
throw new IOException("Conflicting resource " + name + " from " + previous.source() + " and " + source);
}
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 {
Path output = config.storage(root).resolve("output");
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();
}
}
int files = writeArchive(contents, temporary, resourceVersion);
String sha1 = hash(temporary, "SHA-1");
Path destination = output.resolve(sha1 + ".zip");
if (!Files.exists(destination)) {
boolean created = !Files.exists(destination);
if (created) {
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));
Pack pack = new Pack(destination, sha1, files, Files.size(destination));
try {
saveCurrent(output, pack);
} catch (IOException e) {
if (created) {
try {
Files.deleteIfExists(destination);
} catch (IOException cleanupError) {
e.addSuppressed(cleanupError);
}
}
throw e;
}
return pack;
} 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");
private int writeArchive(Path contents, Path target, String resourceVersion) throws IOException {
int files = 0;
long totalBytes = 0;
byte[] buffer = new byte[8192];
try (var paths = Files.walk(contents);
var zip = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(target)))) {
for (Path file : paths.sorted().toList()) {
if (Files.isSymbolicLink(file)) {
throw new IOException("Symbolic links are not supported: " + file);
}
if (!Files.isRegularFile(file)) {
continue;
}
String name = contents.relativize(file).toString().replace('\\', '/');
if (!name.startsWith("assets/") && !name.equals("pack.png")) {
continue;
}
PackFiles.safe(contents, name);
if (++files > config.build.maxFiles) {
throw new IOException("Too many resources");
}
ZipEntry entry = new ZipEntry(name);
entry.setTime(0);
zip.putNextEntry(entry);
long fileBytes = 0;
try (var input = Files.newInputStream(file)) {
int read;
while ((read = input.read(buffer)) != -1) {
fileBytes += read;
totalBytes += read;
if (fileBytes > config.build.maxFileMiB * 1024L * 1024L) {
throw new IOException("Resource exceeds maxFileMiB: " + file);
}
if (totalBytes > config.build.maxTotalMiB * 1024L * 1024L) {
throw new IOException("Resources exceed maxTotalMiB");
}
zip.write(buffer, 0, read);
}
}
zip.closeEntry();
}
ZipEntry metadata = new ZipEntry("pack.mcmeta");
metadata.setTime(0);
zip.putNextEntry(metadata);
zip.write(metadata(resourceVersion));
zip.closeEntry();
}
return files + 1;
}
private byte[] metadata(String resourceVersion) {
var 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);
return PackConfig.JSON.toJson(metadata).getBytes(StandardCharsets.UTF_8);
}
private static void saveCurrent(Path output, Pack pack) throws IOException {
Path manifest = output.resolve("current.json");
String previous = null;
if (Files.exists(manifest)) {
JsonObject old = readManifest(manifest);
String current = old.get("sha1").getAsString();
if (!current.equals(pack.sha1())) {
previous = current;
} else if (old.has("previousSha1")) {
previous = old.get("previousSha1").getAsString();
}
}
JsonObject info = new JsonObject();
info.addProperty("sha1", pack.sha1());
info.addProperty("files", pack.files());
if (previous != null) {
info.addProperty("previousSha1", previous);
}
// Only remove generated hash-named ZIPs, never user content or unrelated files.
try (var paths = Files.list(output)) {
for (Path path : paths.toList()) {
String name = path.getFileName().toString();
if (name.matches("[a-f0-9]{40}\\.zip") && !name.equals(pack.sha1() + ".zip")
&& (previous == null || !name.equals(previous + ".zip"))
&& Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) {
Files.delete(path);
}
}
}
PackFiles.atomicWrite(manifest, PackConfig.JSON.toJson(info).getBytes(StandardCharsets.UTF_8));
}
public static Pack latest(Path root, PackConfig config) throws IOException {
Path output = config.storage(root).resolve("output");
JsonObject info = readManifest(output.resolve("current.json"));
String sha1 = info.get("sha1").getAsString();
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));
}
private static JsonObject readManifest(Path path) throws IOException {
try {
JsonObject info = JsonParser.parseString(Files.readString(path)).getAsJsonObject();
if (!info.get("sha1").getAsString().matches("[a-f0-9]{40}")
|| (info.has("previousSha1") && !info.get("previousSha1").getAsString().matches("[a-f0-9]{40}"))
|| info.get("files").getAsInt() < 1) {
throw new IOException("Invalid resource pack manifest: " + path);
}
return info;
} catch (RuntimeException e) {
throw new IOException("Invalid previous build", e);
throw new IOException("Invalid resource pack manifest: " + path, e);
}
}
@@ -249,35 +195,4 @@ public final class PackBuilder {
throw new AssertionError(e);
}
}
static void verifyExternal(PackConfig config, Pack pack) throws IOException {
if (!config.hosting.mode.equals("no_host") || !config.delivery.sendOnJoin) {
return;
}
try (HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.followRedirects(HttpClient.Redirect.NORMAL)
.build()) {
HttpRequest request = HttpRequest.newBuilder(PackConfig.validateUrl(config.hosting.externalUrl))
.timeout(Duration.ofSeconds(30))
.GET()
.build();
var bodyHandler = HttpResponse.BodyHandlers.limiting(HttpResponse.BodyHandlers.ofByteArray(), pack.bytes());
HttpResponse<byte[]> response = client.send(request, bodyHandler);
if (response.statusCode() != 200) {
throw new IOException("External pack HTTP " + response.statusCode());
}
byte[] digest = MessageDigest.getInstance("SHA-1").digest(response.body());
if (!HexFormat.of().formatHex(digest).equals(pack.sha1())) {
throw new IOException("External ZIP differs from built ZIP. Upload " + pack.path()
+ ", then /astrapacks publish");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException(e);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
}
@@ -5,10 +5,8 @@ import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@@ -25,23 +23,18 @@ public final class PackConfig {
public static final class Build {
public String storageDirectory = "astrapacks";
public List<String> sources = new ArrayList<>(List.of("astrapacks/contents"));
public boolean scanModJars = true;
public boolean onStartup = true;
public boolean resendAfterBuild = true;
public String description = "AstraDev — общий серверный ресурспак";
public String conflictPolicy = "error";
public int maxFileMiB = 32;
public int maxTotalMiB = 256;
public int maxFiles = 50000;
}
public static final class Hosting {
public String mode = "simple_self_host";
public String publicAddress = "auto";
public String publicAddress = "";
public String bindAddress = "0.0.0.0";
public int port = 8163;
public String externalUrl = "";
public boolean blockNonGameRequests = true;
public int maxDownloadsPerIp = 5;
public int maxConcurrentDownloads = 32;
@@ -49,11 +42,8 @@ public final class PackConfig {
public int tokenLifetimeSeconds = 600;
public boolean sameSettings(Hosting other) {
return mode.equals(other.mode)
&& publicAddress.equals(other.publicAddress)
&& bindAddress.equals(other.bindAddress)
return bindAddress.equals(other.bindAddress)
&& port == other.port
&& externalUrl.equals(other.externalUrl)
&& blockNonGameRequests == other.blockNonGameRequests
&& maxDownloadsPerIp == other.maxDownloadsPerIp
&& maxConcurrentDownloads == other.maxConcurrentDownloads
@@ -94,6 +84,10 @@ public final class PackConfig {
if (config == null) {
throw new IllegalArgumentException("Empty config");
}
// Old automatic addressing is no longer supported; leave it for the owner to set.
if (config.hosting != null && "auto".equals(config.hosting.publicAddress)) {
config.hosting.publicAddress = "";
}
config.validate();
return config;
} catch (RuntimeException e) {
@@ -114,11 +108,7 @@ public final class PackConfig {
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) {
if (hosting.tokenLifetimeSeconds < delivery.timeoutSeconds) {
throw new IllegalArgumentException("tokenLifetimeSeconds must be >= timeoutSeconds");
}
@@ -132,19 +122,10 @@ public final class PackConfig {
}
private void validateBuild() {
if (!Set.of("error", "last_wins").contains(build.conflictPolicy)) {
throw new IllegalArgumentException("build.conflictPolicy: error or last_wins");
}
Objects.requireNonNull(build.storageDirectory, "build.storageDirectory");
Objects.requireNonNull(build.sources, "build.sources");
Objects.requireNonNull(build.description, "build.description");
if (build.storageDirectory.isBlank()) {
throw new IllegalArgumentException("Invalid build paths");
}
for (String source : build.sources) {
if (source == null || source.isBlank()) {
throw new IllegalArgumentException("Invalid build paths");
}
throw new IllegalArgumentException("Invalid build.storageDirectory");
}
range(build.maxFileMiB, 1, 128, "maxFileMiB");
range(build.maxTotalMiB, build.maxFileMiB, 1024, "maxTotalMiB");
@@ -152,13 +133,9 @@ public final class PackConfig {
}
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) {
if (!hosting.publicAddress.isBlank() && validateUrl(hosting.publicAddress).getQuery() != null) {
throw new IllegalArgumentException("hosting.publicAddress must not contain query parameters");
}
range(hosting.port, 1, 65535, "port");
@@ -183,6 +160,10 @@ public final class PackConfig {
}
}
public Path contents(Path root) {
return storage(root).resolve("contents");
}
public Path storage(Path root) {
return root.resolve(build.storageDirectory).toAbsolutePath().normalize();
}
@@ -2,10 +2,8 @@ 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;
@@ -15,7 +13,6 @@ import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
@@ -28,7 +25,6 @@ import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioIoHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
@@ -66,9 +62,6 @@ public final class PackHost implements AutoCloseable {
}
public void start() throws InterruptedException {
if (!config.mode.equals("self_host")) {
return;
}
eventLoops = new MultiThreadIoEventLoopGroup(2, NioIoHandler.newFactory());
ServerBootstrap bootstrap = new ServerBootstrap()
.group(eventLoops)
@@ -89,6 +82,8 @@ public final class PackHost implements AutoCloseable {
public void publish(PackBuilder.Pack pack) {
published.put(pack.sha1(), pack.path());
published.entrySet().removeIf(entry -> !Files.isRegularFile(entry.getValue()));
grants.entrySet().removeIf(entry -> !published.containsKey(entry.getValue().hash()));
}
public String issuePath(PackBuilder.Pack pack) {
@@ -137,10 +132,6 @@ public final class PackHost implements AutoCloseable {
activeDownloads--;
}
public void installSniffer(ChannelPipeline pipeline) {
pipeline.addFirst("astrapacks_detect", new Sniffer());
}
private void installHttp(ChannelPipeline pipeline) {
long bytesPerSecond = config.maxSpeedMiBPerSecond * 1024L * 1024L;
pipeline.addLast("astrapacks_timeout", new ReadTimeoutHandler(30));
@@ -151,27 +142,6 @@ public final class PackHost implements AutoCloseable {
pipeline.addLast("astrapacks_download", new Download());
}
private final class Sniffer extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext context, ByteBuf input, List<Object> output) {
if (input.readableBytes() < 4) {
return;
}
String prefix = input.toString(input.readerIndex(), 4, StandardCharsets.US_ASCII);
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 final class Download extends SimpleChannelInboundHandler<FullHttpRequest> {
private boolean handled;
@@ -1,8 +1,6 @@
package online.astradev.packs;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
@@ -19,7 +17,6 @@ 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 static volatile PackRuntime INSTANCE;
@@ -57,22 +54,18 @@ public final class PackRuntime implements AutoCloseable {
throw new IOException("AstraPacks must be the only pack sender: clear resource-pack in server.properties");
}
// Custom source paths are not created: a typo in the configuration must be visible.
Files.createDirectories(root.resolve("astrapacks/contents"));
Files.createDirectories(config.contents(root));
PackBuilder.Pack pack = loadStartupPack();
if (pack != null) {
try {
PackBuilder.verifyExternal(config, pack);
host.publish(pack);
current = pack;
} catch (IOException e) {
AstraPacks.LOG.error("External ZIP is not ready. Required-pack logins will be refused.", e);
}
}
host.start();
AstraPacks.LOG.info("AstraPacks: mode={}, required={}, pack={}",
config.hosting.mode, config.delivery.required, current == null ? "UNAVAILABLE" : current.path());
if (config.hosting.publicAddress.isBlank()) {
AstraPacks.LOG.error("Set hosting.publicAddress to the public HTTP address (port {}). Pack delivery is unavailable until configured.", config.hosting.port);
}
AstraPacks.LOG.info("AstraPacks: HTTP port={}, required={}, pack={}",
config.hosting.port, config.delivery.required, current == null ? "UNAVAILABLE" : current.path());
}
private PackBuilder.Pack loadStartupPack() {
@@ -84,7 +77,7 @@ public final class PackRuntime implements AutoCloseable {
}
}
try {
return PackBuilder.previous(root, config);
return PackBuilder.latest(root, config);
} catch (IOException e) {
AstraPacks.LOG.error("No usable pack. Required-pack logins will be refused.", e);
return null;
@@ -99,10 +92,6 @@ public final class PackRuntime implements AutoCloseable {
return current;
}
public PackHost host() {
return host;
}
public PackSession session(ServerCommonPacketListenerImpl listener) {
PackSession session = new PackSession(this, listener);
PackSession previous = sessions.put(listener, session);
@@ -131,7 +120,7 @@ public final class PackRuntime implements AutoCloseable {
while (iterator.hasNext()) {
var entry = iterator.next();
ServerCommonPacketListenerImpl listener = entry.getKey();
Connection connection = ((CommonAccessor) listener).astrapacks$connection();
Connection connection = listener.getConnection();
if (connection.isConnected()) {
entry.getValue().tick();
} else {
@@ -158,44 +147,23 @@ public final class PackRuntime implements AutoCloseable {
}
}
public String url(ServerCommonPacketListenerImpl listener, PackBuilder.Pack pack) {
if (config.hosting.mode.equals("no_host")) {
return config.hosting.externalUrl;
}
String base = config.hosting.publicAddress;
if (base.equals("auto")) {
base = automaticAddress(listener);
}
return base.replaceAll("/+$", "") + host.issuePath(pack);
}
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 String url(PackBuilder.Pack pack) {
String address = config.hosting.publicAddress;
if (address.isBlank()) {
throw new IllegalStateException("Set hosting.publicAddress before sending resource packs");
}
return address.replaceAll("/+$", "") + host.issuePath(pack);
}
public void build(CommandSourceStack source) {
requestBuild(source, false, false);
requestBuild(source, false);
}
public void reload(CommandSourceStack source) {
requestBuild(source, true, false);
requestBuild(source, true);
}
public void publish(CommandSourceStack source) {
requestBuild(source, false, true);
}
private void requestBuild(CommandSourceStack source, boolean reload, boolean publishOnly) {
private void requestBuild(CommandSourceStack source, boolean reload) {
if (closed) {
source.sendFailure(Component.literal("AstraPacks остановлен."));
return;
@@ -207,19 +175,17 @@ public final class PackRuntime implements AutoCloseable {
building = true;
source.sendSuccess(() -> Component.literal("AstraPacks: проверка и подготовка ресурспака…"), false);
worker.execute(() -> preparePack(source, reload, publishOnly));
worker.execute(() -> preparePack(source, reload));
}
private void preparePack(CommandSourceStack source, boolean reload, boolean publishOnly) {
private void preparePack(CommandSourceStack source, boolean reload) {
try {
PackConfig next = reload ? PackConfig.load(configPath) : config;
if (next.enabled != config.enabled || !next.hosting.sameSettings(config.hosting)) {
throw new IOException("Изменение enabled или hosting требует перезапуска сервера.");
if (next.enabled != config.enabled || !next.hosting.sameSettings(config.hosting)
|| !next.build.storageDirectory.equals(config.build.storageDirectory)) {
throw new IOException("Изменение enabled, каталога хранения или настроек HTTP-сервера требует перезапуска.");
}
PackBuilder.Pack pack = publishOnly
? PackBuilder.previous(root, next)
: new PackBuilder(next).build(root, RESOURCE_VERSION);
PackBuilder.verifyExternal(next, pack);
PackBuilder.Pack pack = new PackBuilder(next).build(root, RESOURCE_VERSION);
server.execute(() -> publishPack(source, next, pack));
} catch (Exception e) {
AstraPacks.LOG.error("Pack build/publication failed; active pack retained", e);
@@ -253,7 +219,8 @@ public final class PackRuntime implements AutoCloseable {
public String status() {
String pack = current == null ? "UNAVAILABLE" : current.path() + " (" + current.files() + " files)";
return "AstraPacks " + config.hosting.mode + ", required=" + config.delivery.required
String address = config.hosting.publicAddress.isBlank() ? "NOT SET" : config.hosting.publicAddress;
return "AstraPacks HTTP:" + config.hosting.port + ", address=" + address + ", required=" + config.delivery.required
+ ", build=" + building + ", pack=" + pack;
}
@@ -41,7 +41,7 @@ public final class PackSession implements ConfigurationTask {
@Override
public void start(Consumer<Packet<?>> sender) {
if (pack != null) {
if (pack != null && !config.hosting.publicAddress.isBlank()) {
sendAttempt();
} else if (config.delivery.required) {
disconnect(config.messages.unavailable);
@@ -59,7 +59,7 @@ public final class PackSession implements ConfigurationTask {
if (!config.messages.prompt.isBlank()) {
prompt = Optional.of(PackText.of(config.messages.prompt, playerName()));
}
String url = runtime.url(listener, pack);
String url = runtime.url(pack);
listener.send(new ClientboundResourcePackPushPacket(
requestId, url, pack.sha1(), config.delivery.required, prompt));
} catch (RuntimeException e) {
@@ -1,11 +0,0 @@
package online.astradev.packs.mixin;
import net.minecraft.network.Connection;
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(ServerCommonPacketListenerImpl.class)
public interface CommonAccessor {
@Accessor("connection") Connection astrapacks$connection();
}
@@ -1,24 +0,0 @@
package online.astradev.packs.mixin;
import io.netty.channel.ChannelPipeline;
import net.minecraft.network.BandwidthDebugMonitor;
import net.minecraft.network.Connection;
import net.minecraft.network.protocol.PacketFlow;
import online.astradev.packs.PackRuntime;
import online.astradev.packs.ConnectionData;
import org.spongepowered.asm.mixin.*;
import org.spongepowered.asm.mixin.injection.*;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(Connection.class)
public abstract class ConnectionMixin implements ConnectionData {
@Unique private String astrapacks$serverHost;
public String astrapacks$host() { return astrapacks$serverHost; }
public void astrapacks$host(String host) { astrapacks$serverHost = host; }
@Inject(method = "configureSerialization", at = @At("RETURN"))
private static void astrapacks$detectHttp(ChannelPipeline pipeline, PacketFlow flow, boolean local, BandwidthDebugMonitor monitor, CallbackInfo ci) {
PackRuntime runtime = PackRuntime.INSTANCE;
if (runtime != null && runtime.config().enabled && !local && flow == PacketFlow.SERVERBOUND
&& runtime.config().hosting.mode.equals("simple_self_host")) runtime.host().installSniffer(pipeline);
}
}
@@ -1,19 +0,0 @@
package online.astradev.packs.mixin;
import net.minecraft.network.Connection;
import online.astradev.packs.ConnectionData;
import net.minecraft.network.protocol.handshake.ClientIntentionPacket;
import net.minecraft.server.network.ServerHandshakePacketListenerImpl;
import org.spongepowered.asm.mixin.*;
import org.spongepowered.asm.mixin.injection.*;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ServerHandshakePacketListenerImpl.class)
public abstract class HandshakeMixin {
@Shadow @Final private Connection connection;
@Inject(method = "handleIntention", at = @At("HEAD"))
private void astrapacks$rememberHost(ClientIntentionPacket packet, CallbackInfo ci) {
String host = packet.hostName().split("\u0000", 2)[0];
if (host.matches("[a-zA-Z0-9._:\\[\\]-]+")) ((ConnectionData)connection).astrapacks$host(host);
}
}
+1 -1
View File
@@ -2,6 +2,6 @@
"required": true,
"package": "online.astradev.packs.mixin",
"compatibilityLevel": "JAVA_25",
"mixins": ["ConnectionMixin", "HandshakeMixin", "CommonAccessor", "CommonResponseMixin", "ConfigurationResponseMixin"],
"mixins": ["CommonResponseMixin", "ConfigurationResponseMixin"],
"injectors": { "defaultRequire": 1 }
}
@@ -1,124 +1,263 @@
package online.astradev.packs;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import com.google.gson.JsonParser;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.*;
import java.net.*;
import java.net.http.*;
import java.nio.file.*;
import java.util.*;
import java.util.zip.*;
import static org.junit.jupiter.api.Assertions.*;
class PackCoreTest {
@TempDir Path root;
private PackConfig config() throws IOException {
PackConfig c = new PackConfig();
Files.createDirectories(root.resolve("astrapacks/contents"));
return c;
PackConfig config = new PackConfig();
Files.createDirectories(config.contents(root));
return config;
}
private void asset(String name, String text) throws IOException {
Path p = root.resolve("astrapacks/contents/" + name);
Files.createDirectories(p.getParent()); Files.writeString(p, text);
Path file = root.resolve("astrapacks/contents").resolve(name);
Files.createDirectories(file.getParent());
Files.writeString(file, text);
}
private PackBuilder.Pack build(PackConfig config) throws IOException {
return new PackBuilder(config).build(root, "[88,0]");
}
private Set<String> archives() throws IOException {
try (var files = Files.list(root.resolve("astrapacks/output"))) {
return files.filter(path -> path.toString().endsWith(".zip"))
.map(path -> path.getFileName().toString()).collect(Collectors.toSet());
}
}
private static void zip(Path path, Map<String, String> files) throws IOException {
Files.createDirectories(path.getParent());
try (var z = new ZipOutputStream(Files.newOutputStream(path))) {
for (var e : files.entrySet()) { z.putNextEntry(new ZipEntry(e.getKey())); z.write(e.getValue().getBytes(java.nio.charset.StandardCharsets.UTF_8)); z.closeEntry(); }
try (var zip = new ZipOutputStream(Files.newOutputStream(path))) {
for (var entry : files.entrySet()) {
zip.putNextEntry(new ZipEntry(entry.getKey()));
zip.write(entry.getValue().getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
}
@Test void deterministicAndDeletedResourcesDisappear() throws Exception {
PackConfig c = config(); asset("assets/demo/lang/en_us.json", "{\"hello\":\"world\"}");
var builder = new PackBuilder(c);
var a = builder.build(root, "[88,0]");
var b = builder.build(root, "[88,0]");
assertEquals(a.sha1(), b.sha1());
Files.delete(root.resolve("astrapacks/contents/assets/demo/lang/en_us.json"));
var changed = builder.build(root, "[88,0]");
assertNotEquals(a.sha1(), changed.sha1());
assertTrue(Files.exists(a.path()), "in-flight clients must still be able to fetch the old ZIP");
try (var z = new ZipFile(changed.path().toFile())) { assertNull(z.getEntry("assets/demo/lang/en_us.json")); assertNotNull(z.getEntry("pack.mcmeta")); }
}
@Test void conflictingSourcesPreservePreviousBuild() throws Exception {
PackConfig c = config(); asset("one/assets/demo/test.txt", "a");
var good = new PackBuilder(c).build(root, "[88,0]");
asset("two/assets/demo/test.txt", "b");
assertThrows(IOException.class, () -> new PackBuilder(c).build(root, "[88,0]"));
assertEquals(good.sha1(), PackBuilder.previous(root, c).sha1());
c.build.conflictPolicy = "last_wins";
var newer = new PackBuilder(c).build(root, "[88,0]");
try (var z = new ZipFile(newer.path().toFile())) { assertEquals("b", new String(z.getInputStream(z.getEntry("assets/demo/test.txt")).readAllBytes())); }
@Test
void commonDirectoryPreservesNamespacesAndGeneratesMetadata() throws Exception {
PackConfig config = config();
asset("assets/astrahorses/lang/ru_ru.json", "horses");
asset("assets/astrasoups/lang/ru_ru.json", "soups");
asset("pack.mcmeta", "ignored source metadata");
asset("pack.png", "icon");
asset("notes.txt", "not a resource");
var pack = build(config);
try (var zip = new ZipFile(pack.path().toFile())) {
assertNotNull(zip.getEntry("assets/astrahorses/lang/ru_ru.json"));
assertNotNull(zip.getEntry("assets/astrasoups/lang/ru_ru.json"));
assertNotNull(zip.getEntry("pack.png"));
assertNull(zip.getEntry("notes.txt"));
String metadata = new String(zip.getInputStream(zip.getEntry("pack.mcmeta")).readAllBytes(), StandardCharsets.UTF_8);
var settings = JsonParser.parseString(metadata).getAsJsonObject().getAsJsonObject("pack");
assertEquals(config.build.description, settings.get("description").getAsString());
assertEquals(JsonParser.parseString("[88,0]"), settings.get("min_format"));
}
@Test void matchingDuplicatesAreAllowed() throws Exception {
PackConfig c = config(); asset("one/assets/demo/test.txt", "a"); asset("two/assets/demo/test.txt", "a");
assertEquals(2, new PackBuilder(c).build(root, "[88,0]").files());
assertEquals(4, pack.files());
}
@Test void unsafeZipEntryRejected() throws Exception {
PackConfig c = config();
zip(root.resolve("astrapacks/contents/bad.zip"), Map.of("assets/../../escape.txt", "bad"));
assertThrows(IOException.class, () -> new PackBuilder(c).build(root, "[88,0]"));
assertFalse(Files.exists(root.resolve("escape.txt")));
@Test
void deterministicAndDeletedResourcesDisappear() throws Exception {
PackConfig config = config();
asset("assets/demo/test.txt", "same content");
var first = build(config);
assertEquals(first.sha1(), build(config).sha1());
Files.delete(config.contents(root).resolve("assets/demo/test.txt"));
var changed = build(config);
assertNotEquals(first.sha1(), changed.sha1());
assertTrue(Files.exists(first.path()));
try (var zip = new ZipFile(changed.path().toFile())) {
assertNull(zip.getEntry("assets/demo/test.txt"));
assertNotNull(zip.getEntry("pack.mcmeta"));
}
@Test void fileAndTotalLimits() throws Exception {
PackConfig c = config(); c.build.maxFileMiB = 1;
}
@Test
void keepsExactlyCurrentAndOnePreviousDistinctArchive() throws Exception {
PackConfig config = config();
asset("assets/demo/test.txt", "first");
var first = build(config);
asset("assets/demo/test.txt", "second");
var second = build(config);
asset("assets/demo/test.txt", "third");
var third = build(config);
assertFalse(Files.exists(first.path()));
assertEquals(Set.of(second.sha1() + ".zip", third.sha1() + ".zip"), archives());
assertEquals(third.sha1(), PackBuilder.latest(root, config).sha1());
assertEquals(third.sha1(), build(config).sha1());
assertTrue(Files.exists(second.path()), "An unchanged build must not evict the previous version");
asset("assets/demo/test.txt", "second");
assertEquals(second.sha1(), build(config).sha1());
assertEquals(Set.of(second.sha1() + ".zip", third.sha1() + ".zip"), archives());
}
@Test
void failurePreservesBothArchivesAndRemovesTemporaryZip() throws Exception {
PackConfig config = config();
var first = build(config);
asset("assets/demo/test.txt", "second");
var second = build(config);
config.build.maxFileMiB = 1;
asset("assets/demo/large.txt", "x".repeat(1024 * 1024 + 1));
assertThrows(IOException.class, () -> new PackBuilder(c).build(root, "[88,0]"));
c.build.maxFileMiB = 2; c.build.maxTotalMiB = 1;
assertThrows(IOException.class, () -> new PackBuilder(c).build(root, "[88,0]"));
assertThrows(IOException.class, () -> build(config));
assertEquals(second.sha1(), PackBuilder.latest(root, config).sha1());
assertEquals(Set.of(first.sha1() + ".zip", second.sha1() + ".zip"), archives());
try (var paths = Files.list(config.storage(root).resolve("output"))) {
assertFalse(paths.anyMatch(path -> path.toString().endsWith(".tmp")));
}
@Test void modJarBundleOnlyExposesPackAssets() throws Exception {
PackConfig c = config();
zip(root.resolve("mods/example.jar"), Map.of("astra-pack.properties", "schema=2\n", "astra-resourcepack/assets/demo/test.txt", "hello", "secret.txt", "secret"));
var pack = new PackBuilder(c).build(root, "[88,0]");
try (var z = new ZipFile(pack.path().toFile())) { assertNotNull(z.getEntry("assets/demo/test.txt")); assertNull(z.getEntry("secret.txt")); }
}
@Test void invalidConfigIsNotSilentlyReplaced() throws Exception {
@Test
void ignoresJarBundlesNestedZipsAndNamedPackRoots() throws Exception {
PackConfig config = config();
zip(root.resolve("mods/example.jar"), Map.of("astra-pack.properties", "schema=2",
"astra-resourcepack/assets/demo/jar.txt", "ignored"));
zip(config.contents(root).resolve("other.zip"), Map.of("assets/demo/zip.txt", "ignored"));
asset("other/assets/demo/nested.txt", "ignored");
assertEquals(1, build(config).files());
}
@Test
void fileTotalAndCountLimits() throws Exception {
PackConfig config = config();
config.build.maxFileMiB = 1;
asset("assets/demo/a.txt", "x".repeat(1024 * 1024 + 1));
assertThrows(IOException.class, () -> build(config));
config.build.maxFileMiB = 2;
config.build.maxTotalMiB = 1;
assertThrows(IOException.class, () -> build(config));
config.build.maxTotalMiB = 3;
config.build.maxFiles = 1;
asset("assets/demo/b.txt", "second");
assertThrows(IOException.class, () -> build(config));
}
@Test
void cleanupRemovesLegacyGeneratedZipsOnly() throws Exception {
PackConfig config = config();
var current = build(config);
Path output = current.path().getParent();
Path legacy = output.resolve("a".repeat(40) + ".zip");
Files.writeString(legacy, "old generated archive");
Files.writeString(output.resolve("manual-backup.zip"), "unrelated file");
build(config);
assertFalse(Files.exists(legacy));
assertTrue(Files.exists(output.resolve("manual-backup.zip")));
}
@Test
void corruptManifestDoesNotLeaveAnExtraBuildArchive() throws Exception {
PackConfig config = config();
var first = build(config);
Files.writeString(config.storage(root).resolve("output/current.json"), "invalid json");
asset("assets/demo/new.txt", "new content");
assertThrows(IOException.class, () -> build(config));
assertEquals(Set.of(first.sha1() + ".zip"), archives());
}
@Test
void invalidConfigIsNotSilentlyReplaced() throws Exception {
Path path = root.resolve("config/astrapacks.json");
PackConfig c = PackConfig.load(path); assertTrue(c.delivery.required);
c.delivery.sendOnJoin = false; Files.writeString(path, PackConfig.JSON.toJson(c));
PackConfig config = PackConfig.load(path);
assertTrue(config.delivery.required);
config.delivery.sendOnJoin = false;
String invalid = PackConfig.JSON.toJson(config);
Files.writeString(path, invalid);
assertThrows(IOException.class, () -> PackConfig.load(path));
assertFalse(Files.readString(path).isEmpty());
assertEquals(invalid, Files.readString(path));
}
@Test void noHostRequiresValidUrlWhenSending() throws Exception {
PackConfig c = config(); c.hosting.mode = "no_host";
assertThrows(IllegalArgumentException.class, c::validate);
c.hosting.externalUrl = "https://example.com/pack.zip"; assertDoesNotThrow(c::validate);
c.hosting.externalUrl = "file:///secret"; assertThrows(IllegalArgumentException.class, c::validate);
@Test
void addressCanBeConfiguredLaterButMustBeAnExplicitHttpUrl() throws Exception {
PackConfig config = config();
assertDoesNotThrow(config::validate);
config.hosting.publicAddress = "http://packs.example.com:8163";
assertDoesNotThrow(config::validate);
config.hosting.publicAddress = "auto";
assertThrows(IllegalArgumentException.class, config::validate);
config.hosting.publicAddress = "file:///secret";
assertThrows(IllegalArgumentException.class, config::validate);
config.hosting.publicAddress = "https://packs.example.com/?token=x";
assertThrows(IllegalArgumentException.class, config::validate);
}
@Test void corruptedPreviousZipRejected() throws Exception {
PackConfig c = config(); var pack = new PackBuilder(c).build(root, "[88,0]");
@Test
void legacyAutomaticAddressIsUnsetWithoutRewritingUserConfig() throws Exception {
Path path = root.resolve("astrapacks.json");
String legacy = "{\"hosting\":{\"mode\":\"simple_self_host\",\"publicAddress\":\"auto\"}}";
Files.writeString(path, legacy);
assertEquals("", PackConfig.load(path).hosting.publicAddress);
assertEquals(legacy, Files.readString(path));
}
@Test
void corruptedLatestZipRejected() throws Exception {
PackConfig config = config();
var pack = build(config);
Files.writeString(pack.path(), "corrupted");
assertThrows(IOException.class, () -> PackBuilder.previous(root, c));
assertThrows(IOException.class, () -> PackBuilder.latest(root, config));
}
@Test void hostRequiresGrantAndServesExactZip() throws Exception {
PackConfig c = config(); var pack = new PackBuilder(c).build(root, "[88,0]");
c.hosting.mode = "self_host"; c.hosting.bindAddress = "127.0.0.1";
try (var reservation = new ServerSocket(0)) { c.hosting.port = reservation.getLocalPort(); }
try (PackHost host = new PackHost(c.hosting); HttpClient client = HttpClient.newHttpClient()) {
host.publish(pack); host.start(); String base = "http://127.0.0.1:" + c.hosting.port;
String path = host.issuePath(pack);
var response = client.send(HttpRequest.newBuilder(URI.create(base + path)).build(), HttpResponse.BodyHandlers.ofByteArray());
assertEquals(200, response.statusCode()); assertArrayEquals(Files.readAllBytes(pack.path()), response.body());
var denied = client.send(HttpRequest.newBuilder(URI.create(base + path.split("\\?")[0])).build(), HttpResponse.BodyHandlers.discarding());
assertEquals(403, denied.statusCode());
var head = client.send(HttpRequest.newBuilder(URI.create(base + path)).method("HEAD", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.discarding());
assertEquals(200, head.statusCode()); assertEquals(pack.bytes(), head.headers().firstValueAsLong("Content-Length").orElseThrow());
var secret = client.send(HttpRequest.newBuilder(URI.create(base + "/server.properties")).build(), HttpResponse.BodyHandlers.discarding());
assertEquals(404, secret.statusCode());
@Test
void hostServesCurrentAndPreviousButNotEvictedArchives() throws Exception {
PackConfig config = config();
config.hosting.bindAddress = "127.0.0.1";
try (var reservation = new ServerSocket(0)) {
config.hosting.port = reservation.getLocalPort();
}
try (PackHost host = new PackHost(config.hosting); HttpClient client = HttpClient.newHttpClient()) {
var first = build(config);
host.publish(first);
host.start();
String base = "http://127.0.0.1:" + config.hosting.port;
String firstUrl = base + host.issuePath(first);
asset("assets/demo/test.txt", "second");
var second = build(config);
host.publish(second);
String secondUrl = base + host.issuePath(second);
var response = client.send(HttpRequest.newBuilder(URI.create(firstUrl)).build(), HttpResponse.BodyHandlers.ofByteArray());
assertArrayEquals(Files.readAllBytes(first.path()), response.body());
asset("assets/demo/test.txt", "third");
var third = build(config);
host.publish(third);
assertEquals(404, get(client, firstUrl).statusCode());
assertEquals(200, get(client, secondUrl).statusCode());
String currentUrl = base + host.issuePath(third);
var head = client.send(HttpRequest.newBuilder(URI.create(currentUrl))
.method("HEAD", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.discarding());
assertEquals(200, head.statusCode());
assertEquals(third.bytes(), head.headers().firstValueAsLong("Content-Length").orElseThrow());
assertEquals(403, get(client, currentUrl.split("\\?")[0]).statusCode());
assertEquals(404, get(client, base + "/server.properties").statusCode());
}
}
@Test void externalPublicationChecksActualZip() throws Exception {
PackConfig c = config(); var pack = new PackBuilder(c).build(root, "[88,0]");
c.hosting.mode = "self_host"; c.hosting.bindAddress = "127.0.0.1"; c.hosting.blockNonGameRequests = false;
try (var reservation = new ServerSocket(0)) { c.hosting.port = reservation.getLocalPort(); }
try (PackHost host = new PackHost(c.hosting)) {
host.publish(pack); host.start();
PackConfig external = config(); external.hosting.mode = "no_host";
external.hosting.externalUrl = "http://127.0.0.1:" + c.hosting.port + host.issuePath(pack);
assertDoesNotThrow(() -> PackBuilder.verifyExternal(external, pack));
asset("assets/demo/new.txt", "new");
var newer = new PackBuilder(c).build(root, "[88,0]");
assertThrows(IOException.class, () -> PackBuilder.verifyExternal(external, newer));
}
private static HttpResponse<Void> get(HttpClient client, String url) throws Exception {
return client.send(HttpRequest.newBuilder(URI.create(url)).build(), HttpResponse.BodyHandlers.discarding());
}
}