Files
AstraPacks/src/main/java/online/astradev/packs/PackBuilder.java
T

284 lines
11 KiB
Java
Raw Normal View History

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.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. */
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"));
}
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 {
Files.createDirectories(output);
Path temporary = Files.createTempFile(output, "build-", ".tmp");
try {
try (var zip = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(temporary)))) {
for (var asset : assets.entrySet()) {
ZipEntry entry = new ZipEntry(asset.getKey());
entry.setTime(0);
zip.putNextEntry(entry);
zip.write(asset.getValue().data());
zip.closeEntry();
}
}
String sha1 = hash(temporary, "SHA-1");
Path destination = output.resolve(sha1 + ".zip");
if (!Files.exists(destination)) {
Files.move(temporary, destination, StandardCopyOption.ATOMIC_MOVE);
} else if (!hash(destination, "SHA-1").equals(sha1)) {
throw new IOException("Published ZIP was modified: " + destination);
}
String manifest = PackConfig.JSON.toJson(Map.of("sha1", sha1, "files", assets.size()));
PackFiles.atomicWrite(output.resolve("current.json"), manifest.getBytes(StandardCharsets.UTF_8));
return new Pack(destination, sha1, assets.size(), Files.size(destination));
} finally {
Files.deleteIfExists(temporary);
}
}
public static Pack previous(Path root, PackConfig config) throws IOException {
Path output = config.storage(root).resolve("output");
try {
String manifest = Files.readString(output.resolve("current.json"));
JsonObject info = JsonParser.parseString(manifest).getAsJsonObject();
String sha1 = info.get("sha1").getAsString();
if (!sha1.matches("[a-f0-9]{40}")) {
throw new IOException("Invalid pack hash");
}
Path path = output.resolve(sha1 + ".zip");
if (!hash(path, "SHA-1").equals(sha1)) {
throw new IOException("Stored resource pack hash mismatch");
}
return new Pack(path, sha1, info.get("files").getAsInt(), Files.size(path));
} catch (RuntimeException e) {
throw new IOException("Invalid previous build", e);
}
}
public static String hash(Path file, String algorithm) throws IOException {
try {
MessageDigest digest = MessageDigest.getInstance(algorithm);
try (var input = new DigestInputStream(Files.newInputStream(file), digest)) {
input.transferTo(OutputStream.nullOutputStream());
}
return HexFormat.of().formatHex(digest.digest());
} catch (NoSuchAlgorithmException e) {
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);
}
}
}