Build shared resource folder with two-version retention and dedicated HTTP hosting
This commit is contained in:
@@ -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 {
|
||||
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 {
|
||||
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");
|
||||
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);
|
||||
}
|
||||
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));
|
||||
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.publish(pack);
|
||||
current = pack;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user