Simplify pack delivery, build lifecycle and HTTP handling; remove project clutter
This commit is contained in:
@@ -1,72 +1,124 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.io.*;
|
||||
import java.net.http.*;
|
||||
import java.time.Duration;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
|
||||
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.*;
|
||||
import java.security.*;
|
||||
import java.util.*;
|
||||
import java.util.zip.*;
|
||||
import java.nio.file.Files;
|
||||
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;
|
||||
|
||||
/** Deterministic, bounded build. Immutable published ZIPs remain valid during later builds. */
|
||||
public final class PackBuilder {
|
||||
public record Pack(Path path, String sha1, int files, long bytes) {}
|
||||
|
||||
private record Asset(byte[] data, String owner) {}
|
||||
|
||||
private final PackConfig config;
|
||||
private final SortedMap<String, Asset> assets = new TreeMap<>();
|
||||
private long total;
|
||||
public PackBuilder(PackConfig config) { this.config = config; }
|
||||
|
||||
public PackBuilder(PackConfig config) {
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
public Pack build(Path root, String resourceVersion) throws IOException {
|
||||
assets.clear();
|
||||
total = 0;
|
||||
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)) directory(path); else archive(path, false);
|
||||
if (Files.isDirectory(path)) directory(path);
|
||||
else archive(path, false);
|
||||
}
|
||||
if (config.build.scanModJars && Files.isDirectory(root.resolve("mods"))) {
|
||||
try (var files = Files.list(root.resolve("mods"))) {
|
||||
for (Path jar : files.filter(p -> p.toString().endsWith(".jar")).sorted().toList()) archive(jar, true);
|
||||
for (Path jar : files.filter(p -> p.toString().endsWith(".jar")).sorted().toList())
|
||||
archive(jar, true);
|
||||
}
|
||||
}
|
||||
JsonObject pack = new JsonObject();
|
||||
// 26.2 uses major/minor resource-pack versions.
|
||||
JsonElement version = JsonParser.parseString(resourceVersion);
|
||||
pack.add("min_format", version); pack.add("max_format", version.deepCopy());
|
||||
pack.add("min_format", version);
|
||||
pack.add("max_format", version.deepCopy());
|
||||
pack.addProperty("description", config.build.description);
|
||||
JsonObject meta = new JsonObject(); meta.add("pack", pack);
|
||||
assets.put("pack.mcmeta", new Asset(PackConfig.JSON.toJson(meta).getBytes(StandardCharsets.UTF_8), "AstraPacks"));
|
||||
JsonObject meta = new JsonObject();
|
||||
meta.add("pack", pack);
|
||||
assets.put(
|
||||
"pack.mcmeta",
|
||||
new Asset(
|
||||
PackConfig.JSON.toJson(meta).getBytes(StandardCharsets.UTF_8),
|
||||
"AstraPacks"));
|
||||
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)))) {
|
||||
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();
|
||||
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);
|
||||
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));
|
||||
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); }
|
||||
} finally {
|
||||
Files.deleteIfExists(temp);
|
||||
}
|
||||
}
|
||||
|
||||
public static Pack previous(Path root, PackConfig config) throws IOException {
|
||||
Path output = config.storage(root).resolve("output");
|
||||
try {
|
||||
JsonObject info = JsonParser.parseString(Files.readString(output.resolve("current.json"))).getAsJsonObject();
|
||||
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");
|
||||
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); }
|
||||
} 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)) {
|
||||
@@ -77,14 +129,20 @@ public final class PackBuilder {
|
||||
// A source is a pack root, or a directory of named pack roots.
|
||||
if (!isResource(name)) {
|
||||
int slash = name.indexOf('/');
|
||||
if (slash >= 0 && isResource(name.substring(slash + 1))) name = name.substring(slash + 1);
|
||||
else if (name.endsWith(".zip")) { archive(p, false); continue; }
|
||||
else continue;
|
||||
if (slash >= 0 && isResource(name.substring(slash + 1)))
|
||||
name = name.substring(slash + 1);
|
||||
else if (name.endsWith(".zip")) {
|
||||
archive(p, false);
|
||||
continue;
|
||||
} else continue;
|
||||
}
|
||||
try (var in = Files.newInputStream(p)) {
|
||||
add(name, in, p.toString());
|
||||
}
|
||||
try (var in = Files.newInputStream(p)) { add(name, in, p.toString()); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void archive(Path path, boolean mod) throws IOException {
|
||||
try (var zip = new ZipFile(path.toFile())) {
|
||||
String prefix = "";
|
||||
@@ -92,52 +150,92 @@ public final class PackBuilder {
|
||||
var descriptor = zip.getEntry("astra-pack.properties");
|
||||
if (descriptor == null) return;
|
||||
Properties props = new Properties();
|
||||
try (var in = zip.getInputStream(descriptor)) { props.load(in); }
|
||||
try (var in = zip.getInputStream(descriptor)) {
|
||||
props.load(in);
|
||||
}
|
||||
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();) {
|
||||
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());
|
||||
if (!isResource(name)) continue;
|
||||
try (var in = zip.getInputStream(entry)) { add(name, in, path + "!/" + entry.getName()); }
|
||||
try (var in = zip.getInputStream(entry)) {
|
||||
add(name, in, path + "!/" + entry.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private static boolean isResource(String name) { return name.startsWith("assets/") || name.equals("pack.png"); }
|
||||
|
||||
private static boolean isResource(String name) {
|
||||
return name.startsWith("assets/") || name.equals("pack.png");
|
||||
}
|
||||
|
||||
private void add(String name, InputStream in, String owner) throws IOException {
|
||||
PackFiles.safe(Path.of("."), name);
|
||||
int limit = config.build.maxFileMiB * 1024 * 1024;
|
||||
byte[] bytes = in.readNBytes(limit + 1);
|
||||
if (bytes.length > limit) throw new IOException("Resource exceeds maxFileMiB: " + owner);
|
||||
total += bytes.length;
|
||||
if (total > config.build.maxTotalMiB * 1024L * 1024L) throw new IOException("Sources exceed maxTotalMiB");
|
||||
if (total > config.build.maxTotalMiB * 1024L * 1024L)
|
||||
throw new IOException("Sources exceed maxTotalMiB");
|
||||
Asset old = assets.get(name);
|
||||
if (old != null && !Arrays.equals(bytes, old.data()) && config.build.conflictPolicy.equals("error"))
|
||||
throw new IOException("Conflicting resource " + name + " from " + old.owner() + " and " + owner);
|
||||
if (old != null
|
||||
&& !Arrays.equals(bytes, old.data())
|
||||
&& config.build.conflictPolicy.equals("error"))
|
||||
throw new IOException(
|
||||
"Conflicting resource " + name + " from " + old.owner() + " and " + owner);
|
||||
assets.put(name, new Asset(bytes, owner));
|
||||
if (assets.size() > config.build.maxFiles) throw new IOException("Too many resources");
|
||||
}
|
||||
|
||||
public static String hash(Path file, String algorithm) throws IOException {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance(algorithm);
|
||||
try (var in = new DigestInputStream(Files.newInputStream(file), digest)) { in.transferTo(OutputStream.nullOutputStream()); }
|
||||
try (var in = new DigestInputStream(Files.newInputStream(file), digest)) {
|
||||
in.transferTo(OutputStream.nullOutputStream());
|
||||
}
|
||||
return HexFormat.of().formatHex(digest.digest());
|
||||
} catch (NoSuchAlgorithmException e) { throw new AssertionError(e); }
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
static void verifyExternal(PackConfig config, PackBuilder.Pack pack) throws IOException {
|
||||
if (!config.hosting.mode.equals("no_host") || !config.delivery.sendOnJoin) return;
|
||||
Path tmp = Files.createTempFile(pack.path().getParent(), "external-", ".tmp");
|
||||
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();
|
||||
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();
|
||||
// A bounded subscriber prevents an external host from consuming arbitrary memory/disk.
|
||||
HttpResponse<byte[]> response = client.send(request, info -> HttpResponse.BodySubscribers.limiting(HttpResponse.BodySubscribers.ofByteArray(), pack.bytes() + 1));
|
||||
if (response.statusCode() != 200) throw new IOException("External pack HTTP " + response.statusCode());
|
||||
Files.write(tmp, response.body());
|
||||
if (!PackBuilder.hash(tmp, "SHA-1").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); }
|
||||
finally { Files.deleteIfExists(tmp); }
|
||||
HttpResponse<byte[]> response =
|
||||
client.send(
|
||||
request,
|
||||
HttpResponse.BodyHandlers.limiting(
|
||||
HttpResponse.BodyHandlers.ofByteArray(), pack.bytes()));
|
||||
if (response.statusCode() != 200)
|
||||
throw new IOException("External pack HTTP " + response.statusCode());
|
||||
String hash =
|
||||
HexFormat.of()
|
||||
.formatHex(MessageDigest.getInstance("SHA-1").digest(response.body()));
|
||||
if (!hash.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user