diff --git a/build.gradle b/build.gradle index 7dd37a3dd..09e8800c7 100644 --- a/build.gradle +++ b/build.gradle @@ -175,6 +175,19 @@ def generateNativeRuntime = tasks.register('generateNativeRuntime') { nativeRuntimeOutput.get().asFile, nativeRuntimeRules.get().asFile) } } +// The Bukkit jar leaves VolmLib's noise natives out and pins them instead; NoiseNatives downloads the +// platform's binary at startup and verifies it against this manifest. +def noiseNativesOutput = layout.buildDirectory.dir('generated/noise-natives') +def generateNoiseNatives = tasks.register('generateNoiseNatives') { + inputs.files(included) + outputs.dir(noiseNativesOutput) + doLast { + File manifest = new File(noiseNativesOutput.get().asFile, NoiseNativeArtifacts.MANIFEST) + NoiseNativeArtifacts.generate(included.resolve(), localVolmLibCheckout, manifest).each { String warning -> + logger.warn(warning) + } + } +} def jarJar = configurations.create('jarJar') dependencies { add('included', project(path: ':core', configuration: 'shadow')) @@ -184,8 +197,9 @@ dependencies { tasks.named('jar', Jar).configure { inputs.files(included) - dependsOn(generateNativeRuntime) + dependsOn(generateNativeRuntime, generateNoiseNatives) from(nativeRuntimeOutput) + from(noiseNativesOutput) from(tasks.named('generateVolmLibStamp')) { into('META-INF/volmit') } @@ -196,6 +210,8 @@ tasks.named('jar', Jar).configure { exclude('META-INF/INDEX.LIST') exclude('languages/**') exclude('com/fren_gor/**') + exclude(NoiseNativeArtifacts.RESOURCE_PREFIX + '**') + exclude('iris-language-guides/*.txt') } archiveFileName.set(bukkitArtifactName) @@ -510,6 +526,7 @@ List requiredBukkitArtifactEntries = [ 'slimjar.dat', 'slimjar-resolutions.dat', 'META-INF/iris/native-runtime.properties', + NoiseNativeArtifacts.MANIFEST, 'META-INF/volmit/volmlib.properties', 'iris-language-source.properties', 'agent.jar', @@ -547,6 +564,7 @@ tasks.register('verifyBukkitArtifact') { 16, runtimeDownloadedPrefixes) NativeRuntimeArtifacts.verify(archive, nativeRuntimeModules, embeddedNatives()) + NoiseNativeArtifacts.verify(archive) logger.lifecycle("Verified ${archive.name} packaging and class reference graph") } } diff --git a/buildSrc/src/main/java/NoiseNativeArtifacts.java b/buildSrc/src/main/java/NoiseNativeArtifacts.java new file mode 100644 index 000000000..f83f9c1d5 --- /dev/null +++ b/buildSrc/src/main/java/NoiseNativeArtifacts.java @@ -0,0 +1,170 @@ +import org.gradle.api.GradleException; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.Writer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Enumeration; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.TreeMap; +import java.util.concurrent.TimeUnit; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +/** + * Pins the VolmLib noise natives the Bukkit jar leaves out. The runtime downloads the binary for its platform and + * accepts it only when the size and SHA-256 recorded here match; the git blob id lets it fetch the exact bytes by + * content even when the build had no VolmLib checkout to name a commit. + */ +public final class NoiseNativeArtifacts { + public static final String MANIFEST = "META-INF/iris/noise-natives.properties"; + public static final String RESOURCE_PREFIX = "art/arcane/volmlib/native/"; + public static final String SOURCE_PATH = "shared/native/noise/prebuilt"; + + private NoiseNativeArtifacts() { + } + + public static List generate(Collection jars, File volmLibDirectory, File output) throws IOException { + Map natives = collect(jars); + if (natives.isEmpty()) { + throw new GradleException("No VolmLib noise natives under " + RESOURCE_PREFIX + " in " + jars); + } + List warnings = new ArrayList<>(); + String commit = volmLibDirectory == null ? "" : commit(volmLibDirectory, natives, warnings); + Properties manifest = new Properties(); + manifest.setProperty("commit", commit); + manifest.setProperty("source", SOURCE_PATH); + manifest.setProperty("platforms", String.join(",", natives.keySet())); + for (NativeFile file : natives.values()) { + manifest.setProperty(file.platform() + ".file", file.name()); + manifest.setProperty(file.platform() + ".size", String.valueOf(file.size())); + manifest.setProperty(file.platform() + ".sha256", file.sha256()); + manifest.setProperty(file.platform() + ".blob", file.blob()); + } + Files.createDirectories(output.toPath().getParent()); + try (Writer writer = Files.newBufferedWriter(output.toPath(), StandardCharsets.UTF_8)) { + manifest.store(writer, null); + } + return warnings; + } + + public static void verify(File artifact) throws IOException { + try (JarFile jar = new JarFile(artifact)) { + if (jar.getJarEntry(MANIFEST) == null) { + throw new GradleException(artifact.getName() + " is missing " + MANIFEST); + } + Enumeration entries = jar.entries(); + while (entries.hasMoreElements()) { + String name = entries.nextElement().getName(); + if (name.startsWith(RESOURCE_PREFIX) && !name.endsWith("/")) { + throw new GradleException(artifact.getName() + " bundles " + name + + "; the Bukkit jar downloads noise natives through " + MANIFEST); + } + } + } + } + + static String sha256(byte[] bytes) { + return HexFormat.of().formatHex(digest("SHA-256", bytes)); + } + + static String blob(byte[] bytes) { + byte[] header = ("blob " + bytes.length + "\0").getBytes(StandardCharsets.US_ASCII); + byte[] object = new byte[header.length + bytes.length]; + System.arraycopy(header, 0, object, 0, header.length); + System.arraycopy(bytes, 0, object, header.length, bytes.length); + return HexFormat.of().formatHex(digest("SHA-1", object)); + } + + private static Map collect(Collection jars) throws IOException { + Map natives = new TreeMap<>(); + for (File file : jars) { + if (!file.isFile()) { + continue; + } + try (JarFile jar = new JarFile(file)) { + Enumeration entries = jar.entries(); + while (entries.hasMoreElements()) { + JarEntry entry = entries.nextElement(); + String name = entry.getName(); + if (entry.isDirectory() || !name.startsWith(RESOURCE_PREFIX)) { + continue; + } + String[] parts = name.substring(RESOURCE_PREFIX.length()).split("/"); + if (parts.length != 2) { + continue; + } + byte[] bytes; + try (InputStream input = jar.getInputStream(entry)) { + bytes = input.readAllBytes(); + } + NativeFile resolved = new NativeFile(parts[0], parts[1], bytes.length, sha256(bytes), blob(bytes)); + NativeFile previous = natives.putIfAbsent(parts[0], resolved); + if (previous != null && !previous.equals(resolved)) { + throw new GradleException("Conflicting noise natives for " + parts[0] + " in " + jars); + } + } + } + } + return natives; + } + + private static String commit(File checkout, Map natives, List warnings) { + String commit = git(checkout, "log", "-1", "--format=%H", "--", SOURCE_PATH); + if (commit == null || commit.isEmpty()) { + warnings.add("Noise natives: no commit touches " + SOURCE_PATH + " in " + checkout + "; downloads fall back to the blob id"); + return ""; + } + for (NativeFile file : natives.values()) { + String path = commit + ":" + SOURCE_PATH + "/" + file.platform() + "/" + file.name(); + if (!file.blob().equals(git(checkout, "rev-parse", path))) { + warnings.add("Noise natives: " + file.platform() + " differs from " + commit.substring(0, 7) + + " (uncommitted rebuild?); downloads fall back to the blob id"); + return ""; + } + } + String remotes = git(checkout, "branch", "-r", "--contains", commit); + if (remotes == null || remotes.isEmpty()) { + warnings.add("Noise natives: " + commit.substring(0, 7) + " is not on any remote branch; downloads fail until it is pushed"); + } + return commit; + } + + private static String git(File directory, String... arguments) { + List command = new ArrayList<>(List.of("git", "-C", directory.getAbsolutePath())); + command.addAll(List.of(arguments)); + try { + Process process = new ProcessBuilder(command).redirectError(ProcessBuilder.Redirect.DISCARD).start(); + String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8).trim(); + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + return null; + } + return output; + } catch (IOException failure) { + return null; + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + return null; + } + } + + private static byte[] digest(String algorithm, byte[] bytes) { + try { + return MessageDigest.getInstance(algorithm).digest(bytes); + } catch (NoSuchAlgorithmException missing) { + throw new IllegalStateException(missing); + } + } + + private record NativeFile(String platform, String name, long size, String sha256, String blob) { + } +} diff --git a/buildSrc/src/test/java/NoiseNativeArtifactsTest.java b/buildSrc/src/test/java/NoiseNativeArtifactsTest.java new file mode 100644 index 000000000..121957fc0 --- /dev/null +++ b/buildSrc/src/test/java/NoiseNativeArtifactsTest.java @@ -0,0 +1,142 @@ +import org.gradle.api.GradleException; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.Reader; +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.Map; +import java.util.Properties; +import java.util.TreeMap; +import java.util.jar.JarEntry; +import java.util.jar.JarOutputStream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +public class NoiseNativeArtifactsTest { + private static final String LINUX = "art/arcane/volmlib/native/linux-x86_64/libvolmlib_noise.so"; + private static final String WINDOWS = "art/arcane/volmlib/native/windows-x86_64/volmlib_noise.dll"; + private static final byte[] LINUX_BYTES = "linux-native".getBytes(StandardCharsets.UTF_8); + private static final byte[] WINDOWS_BYTES = "windows-native".getBytes(StandardCharsets.UTF_8); + + @Rule + public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Test + public void blobMatchesGitHashObject() throws Exception { + File file = temporaryFolder.newFile("blob.bin"); + Files.write(file.toPath(), LINUX_BYTES); + assertEquals(git(temporaryFolder.getRoot(), "hash-object", file.getAbsolutePath()), NoiseNativeArtifacts.blob(LINUX_BYTES)); + } + + @Test + public void generateRecordsEveryPlatformWithoutCommitWhenNoCheckoutIsKnown() throws Exception { + File output = temporaryFolder.getRoot().toPath().resolve("out/noise-natives.properties").toFile(); + List warnings = NoiseNativeArtifacts.generate(List.of(volmLibJar()), null, output); + + Properties manifest = read(output); + assertEquals("", manifest.getProperty("commit")); + assertEquals("linux-x86_64,windows-x86_64", manifest.getProperty("platforms")); + assertEquals("libvolmlib_noise.so", manifest.getProperty("linux-x86_64.file")); + assertEquals(String.valueOf(LINUX_BYTES.length), manifest.getProperty("linux-x86_64.size")); + assertEquals(NoiseNativeArtifacts.sha256(LINUX_BYTES), manifest.getProperty("linux-x86_64.sha256")); + assertEquals(NoiseNativeArtifacts.blob(WINDOWS_BYTES), manifest.getProperty("windows-x86_64.blob")); + assertTrue(warnings.isEmpty()); + } + + @Test + public void generatePinsTheLastCommitThatHoldsTheSameBytes() throws Exception { + File checkout = checkout(LINUX_BYTES, WINDOWS_BYTES); + File output = temporaryFolder.newFile("pinned.properties"); + NoiseNativeArtifacts.generate(List.of(volmLibJar()), checkout, output); + + assertEquals(git(checkout, "rev-parse", "HEAD"), read(output).getProperty("commit")); + } + + @Test + public void generateDropsTheCommitWhenTheCheckoutBytesDiffer() throws Exception { + File checkout = checkout("stale".getBytes(StandardCharsets.UTF_8), WINDOWS_BYTES); + File output = temporaryFolder.newFile("stale.properties"); + List warnings = NoiseNativeArtifacts.generate(List.of(volmLibJar()), checkout, output); + + assertEquals("", read(output).getProperty("commit")); + assertFalse(warnings.isEmpty()); + } + + @Test + public void generateRejectsJarsWithoutNatives() throws Exception { + File empty = jar("empty.jar", Map.of("plugin.yml", new byte[]{1})); + File output = temporaryFolder.newFile("none.properties"); + assertThrows(GradleException.class, () -> NoiseNativeArtifacts.generate(List.of(empty), null, output)); + } + + @Test + public void verifyRejectsBundledNativesAndMissingManifest() throws Exception { + File manifest = temporaryFolder.newFile("manifest.properties"); + NoiseNativeArtifacts.generate(List.of(volmLibJar()), null, manifest); + byte[] manifestBytes = Files.readAllBytes(manifest.toPath()); + + NoiseNativeArtifacts.verify(jar("clean.jar", Map.of(NoiseNativeArtifacts.MANIFEST, manifestBytes))); + assertThrows(GradleException.class, () -> NoiseNativeArtifacts.verify( + jar("bundled.jar", Map.of(NoiseNativeArtifacts.MANIFEST, manifestBytes, LINUX, LINUX_BYTES)))); + assertThrows(GradleException.class, () -> NoiseNativeArtifacts.verify( + jar("unpinned.jar", Map.of("plugin.yml", new byte[]{1})))); + } + + private File volmLibJar() throws IOException { + return jar("volmlib-shared.jar", Map.of(LINUX, LINUX_BYTES, WINDOWS, WINDOWS_BYTES, + "art/arcane/volmlib/util/Noise.class", new byte[]{(byte) 0xCA, (byte) 0xFE})); + } + + private File checkout(byte[] linux, byte[] windows) throws Exception { + File root = temporaryFolder.newFolder(); + Path prebuilt = root.toPath().resolve(NoiseNativeArtifacts.SOURCE_PATH); + Files.createDirectories(prebuilt.resolve("linux-x86_64")); + Files.createDirectories(prebuilt.resolve("windows-x86_64")); + Files.write(prebuilt.resolve("linux-x86_64/libvolmlib_noise.so"), linux); + Files.write(prebuilt.resolve("windows-x86_64/volmlib_noise.dll"), windows); + git(root, "init", "-q"); + git(root, "add", "."); + git(root, "-c", "user.name=test", "-c", "user.email=test@example.com", "commit", "-q", "-m", "natives"); + return root; + } + + private File jar(String name, Map entries) throws IOException { + File file = new File(temporaryFolder.getRoot(), name); + try (JarOutputStream output = new JarOutputStream(new FileOutputStream(file))) { + for (Map.Entry entry : new TreeMap<>(entries).entrySet()) { + output.putNextEntry(new JarEntry(entry.getKey())); + output.write(entry.getValue()); + output.closeEntry(); + } + } + return file; + } + + private static Properties read(File file) throws IOException { + Properties properties = new Properties(); + try (Reader reader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) { + properties.load(reader); + } + return properties; + } + + private static String git(File directory, String... arguments) throws Exception { + List command = new ArrayList<>(List.of("git", "-C", directory.getAbsolutePath())); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8).trim(); + assertEquals(output, 0, process.waitFor()); + return output; + } +} diff --git a/core/build.gradle b/core/build.gradle index b0a82549e..38b601b81 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -62,13 +62,20 @@ def languageGuidesTask = tasks.register('generateLanguageGuides') { doLast { File output = guideDirectory.get().asFile output.mkdirs() + // index.properties lets jars that leave the guide text out accept an upstream guide only when it is + // byte-identical to the one this build would have bundled. + Properties index = new Properties() for (File source : languageSourceFiles) { List header = source.readLines('UTF-8').takeWhile { String line -> line.isBlank() || line.stripLeading().startsWith('#') } String locale = source.name.substring(0, source.name.length() - '.toml'.length()) - new File(output, locale + '.txt').setText(header.join('\n').stripTrailing() + '\n', 'UTF-8') + String guide = header.join('\n').stripTrailing() + '\n' + new File(output, locale + '.txt').setText(guide, 'UTF-8') + index.setProperty(locale, java.security.MessageDigest.getInstance('SHA-256') + .digest(guide.getBytes('UTF-8')).encodeHex().toString()) } + new File(output, 'index.properties').withWriter('UTF-8') { Writer writer -> index.store(writer, null) } } } tasks.named('processResources').configure { diff --git a/core/src/main/java/art/arcane/iris/localization/IrisLanguage.java b/core/src/main/java/art/arcane/iris/localization/IrisLanguage.java index f005fc552..5d28ee2c1 100644 --- a/core/src/main/java/art/arcane/iris/localization/IrisLanguage.java +++ b/core/src/main/java/art/arcane/iris/localization/IrisLanguage.java @@ -88,6 +88,7 @@ public final class IrisLanguage { new CopyOnWriteArrayList<>(); private static volatile File dataFolder; private static volatile String activeLocale = CATALOG.englishLocale(); + private static final Set GUIDE_FETCHES = ConcurrentHashMap.newKeySet(); private static volatile RemoteLanguageCatalog remote; private static volatile Path remoteRoot; private static volatile PluginLanguageService selections; @@ -668,13 +669,51 @@ public final class IrisLanguage { private static void refreshLanguageGuide(File file, String locale) { try { - IrisLanguageGuide.refresh(file, locale); + ClassLoader resources = IrisLanguage.class.getClassLoader(); + if (!IrisLanguageGuide.refresh(file, locale, resources) && IrisLanguageGuide.fetchable(locale, resources)) { + fetchLanguageGuide(file, locale, resources); + } } catch (IOException failure) { IrisLogging.error("Could not update the language guide in " + file.getPath() + "."); IrisLogging.reportError(failure); } } + // Jars that leave the guides out (the size-capped Bukkit jar) take this build's guide from the upstream + // locale file, once per locale per run; it is cached only when its digest matches the build's guide index. + private static void fetchLanguageGuide(File file, String locale, ClassLoader resources) { + File root = dataFolder; + if (root == null || !GUIDE_FETCHES.add(locale)) { + return; + } + Path cache = IrisLanguageGuide.guideCache(file); + Path source = cache.resolve(locale + ".source.toml"); + try { + Files.deleteIfExists(source); + } catch (IOException failure) { + IrisLogging.debug("Language guide source " + source + " could not be cleared: " + failure.getMessage()); + return; + } + remote(root).requestInstallIfMissing(locale, source, IrisLanguage::validateDownload, result -> { + try { + if (result.successful() + && IrisLanguageGuide.cacheUpstream(cache, locale, Files.readString(source, StandardCharsets.UTF_8), resources)) { + IrisLanguageGuide.refresh(file, locale, resources); + } else { + IrisLogging.debug("Language guide for " + locale + " is not available upstream for this build"); + } + } catch (IOException failure) { + IrisLogging.debug("Language guide for " + locale + " could not be cached: " + failure.getMessage()); + } finally { + try { + Files.deleteIfExists(source); + } catch (IOException ignored) { + IrisLogging.debug("Language guide source " + source + " could not be removed"); + } + } + }); + } + private static void createEnglishLanguageIfMissing(File root) throws IOException { Path target = overrideFile(Objects.requireNonNull(root, "Language data folder"), CATALOG.englishLocale()).toPath(); if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) { diff --git a/core/src/main/java/art/arcane/iris/localization/IrisLanguageGuide.java b/core/src/main/java/art/arcane/iris/localization/IrisLanguageGuide.java index 4052d1ca1..8529b0d7d 100644 --- a/core/src/main/java/art/arcane/iris/localization/IrisLanguageGuide.java +++ b/core/src/main/java/art/arcane/iris/localization/IrisLanguageGuide.java @@ -7,20 +7,28 @@ import art.arcane.volmlib.util.localization.TomlLanguageWriter; import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; 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.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HexFormat; import java.util.List; import java.util.Map; +import java.util.Properties; import java.util.regex.Pattern; final class IrisLanguageGuide { private static final String START = "# === Iris language guide ==="; private static final String END = "# === End Iris language guide ==="; + private static final String ENGLISH_LOCALE = "en_US"; + private static final String GUIDE_DIRECTORY = "iris-language-guides/"; + private static final String GUIDE_INDEX = "index.properties"; + private static final String GUIDE_CACHE = ".guides"; private static final Pattern UNDESCRIBED_VARIABLES = Pattern.compile("#\\s+(?:\\{[A-Za-z][A-Za-z0-9_]*}\\s*)+"); private static final Map UNMARKED_GUIDE_FINGERPRINTS = Map.ofEntries( Map.entry("de_DE", "c32159c55e437c3e0e638a48618d2c4ea3bcefebacd3883e94095c986fb9a7e6"), @@ -318,12 +326,91 @@ final class IrisLanguageGuide { } static String header(String locale) throws IOException { - try (InputStream input = IrisLanguageGuide.class.getResourceAsStream("/iris-language-guides/" + locale + ".txt")) { + return header(locale, null, IrisLanguageGuide.class.getClassLoader()); + } + + /** + * The guide this build ships for {@code locale}: the bundled copy, the English template, or a copy cached from + * the upstream locale file whose digest matches the build's guide index. Null when none is available yet, so + * a translated guide is never replaced with English or with a different revision's text. + */ + static String header(String locale, Path guideCache, ClassLoader resources) throws IOException { + try (InputStream input = resources.getResourceAsStream(GUIDE_DIRECTORY + locale + ".txt")) { if (input != null) { return new String(input.readAllBytes(), StandardCharsets.UTF_8).stripTrailing() + "\n"; } } - return englishHeader(locale); + if (ENGLISH_LOCALE.equals(locale)) { + return englishHeader(locale); + } + String expected = expectedDigest(locale, resources); + if (expected == null || guideCache == null) { + return null; + } + Path cached = guideCache.resolve(expected + ".txt"); + if (!Files.isRegularFile(cached, LinkOption.NOFOLLOW_LINKS)) { + return null; + } + String text = Files.readString(cached, StandardCharsets.UTF_8); + return expected.equals(sha256(text)) ? text : null; + } + + static Path guideCache(File languageFile) { + return languageFile.toPath().toAbsolutePath().resolveSibling(GUIDE_CACHE); + } + + static boolean fetchable(String locale, ClassLoader resources) throws IOException { + return !ENGLISH_LOCALE.equals(locale) && expectedDigest(locale, resources) != null; + } + + /** Stores the guide from an upstream locale file when it is exactly the guide this build expects. */ + static boolean cacheUpstream(Path guideCache, String locale, String upstream, ClassLoader resources) throws IOException { + String expected = expectedDigest(locale, resources); + String guide = extractHeader(upstream); + if (expected == null || !expected.equals(sha256(guide))) { + return false; + } + Files.createDirectories(guideCache); + Path temporary = Files.createTempFile(guideCache, locale + "-", ".tmp"); + try { + Files.writeString(temporary, guide, StandardCharsets.UTF_8); + Files.move(temporary, guideCache.resolve(expected + ".txt"), StandardCopyOption.REPLACE_EXISTING, + StandardCopyOption.ATOMIC_MOVE); + } finally { + Files.deleteIfExists(temporary); + } + return true; + } + + /** Same rule as core/build.gradle generateLanguageGuides: the leading blank and comment lines. */ + static String extractHeader(String toml) { + List lines = new ArrayList<>(); + for (String line : toml.split("\\R", -1)) { + if (!line.isBlank() && !line.stripLeading().startsWith("#")) { + break; + } + lines.add(line); + } + return String.join("\n", lines).stripTrailing() + "\n"; + } + + private static String expectedDigest(String locale, ClassLoader resources) throws IOException { + try (InputStream input = resources.getResourceAsStream(GUIDE_DIRECTORY + GUIDE_INDEX)) { + if (input == null) { + return null; + } + Properties index = new Properties(); + index.load(new InputStreamReader(input, StandardCharsets.UTF_8)); + return index.getProperty(locale); + } + } + + private static String sha256(String text) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException missing) { + throw new IllegalStateException(missing); + } } static String englishHeader(String locale) { @@ -339,14 +426,23 @@ final class IrisLanguageGuide { } static void refresh(File file, String locale) throws IOException { + refresh(file, locale, IrisLanguageGuide.class.getClassLoader()); + } + + /** Returns false when this build's guide for the locale is not available yet. */ + static boolean refresh(File file, String locale, ClassLoader resources) throws IOException { if (!Files.isRegularFile(file.toPath(), LinkOption.NOFOLLOW_LINKS) || Files.size(file.toPath()) > 2L * 1024L * 1024L) { - return; + return true; + } + String guide = header(locale, guideCache(file), resources); + if (guide == null) { + return false; } String original = Files.readString(file.toPath(), StandardCharsets.UTF_8); - String updated = replaceHeader(original, header(locale), locale); + String updated = replaceHeader(original, guide, locale); if (original.equals(updated)) { - return; + return true; } LanguageFileEditor.update(file.toPath(), current -> { if (!current.equals(original)) { @@ -354,6 +450,7 @@ final class IrisLanguageGuide { } return new LanguageFileEditor.Prepared<>(updated, null); }); + return true; } static String replaceHeader(String content, String header, String locale) { diff --git a/core/src/main/java/art/arcane/iris/platform/bootstrap/NoiseNatives.java b/core/src/main/java/art/arcane/iris/platform/bootstrap/NoiseNatives.java new file mode 100644 index 000000000..766078bcd --- /dev/null +++ b/core/src/main/java/art/arcane/iris/platform/bootstrap/NoiseNatives.java @@ -0,0 +1,196 @@ +package art.arcane.iris.platform.bootstrap; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Locale; +import java.util.Properties; + +/** + * Provides VolmLib's native noise kernels to jars that leave them out (the size-capped Bukkit jar). The build pins + * each platform's binary in {@link #MANIFEST}; the matching file is downloaded once into a cache folder named by its + * SHA-256 and handed to VolmLib through {@code volmlib.native.library}. Jars that bundle the kernels never download. + * Any failure leaves VolmLib on its Java kernels, which produce identical output. + */ +public final class NoiseNatives { + static final String MANIFEST = "META-INF/iris/noise-natives.properties"; + static final String LIBRARY_PROPERTY = "volmlib.native.library"; + static final String POLICY_PROPERTY = "volmlib.native"; + private static final String RESOURCE_PREFIX = "art/arcane/volmlib/native/"; + private static final String RAW_ROOT = "https://raw.githubusercontent.com/VolmitSoftware/VolmLib/"; + private static final String BLOB_ROOT = "https://api.github.com/repos/VolmitSoftware/VolmLib/git/blobs/"; + private static final int CONNECT_TIMEOUT_MILLIS = 5_000; + private static final int READ_TIMEOUT_MILLIS = 15_000; + + private NoiseNatives() { + } + + public static void provision(Path cacheRoot, SlimJar.BootstrapLogger logger) { + if (System.getProperty(LIBRARY_PROPERTY) != null + || "off".equalsIgnoreCase(System.getProperty(POLICY_PROPERTY, "").trim())) { + return; + } + String platform = platform(System.getProperty("os.name", ""), System.getProperty("os.arch", "")); + Path library = install(cacheRoot, platform, NoiseNatives.class.getClassLoader(), NoiseNatives::download, logger); + if (library != null) { + System.setProperty(LIBRARY_PROPERTY, library.toAbsolutePath().toString()); + } + } + + static String platform(String operatingSystem, String architecture) { + String os = operatingSystem.toLowerCase(Locale.ROOT); + String family = os.contains("mac") ? "macos" : os.contains("linux") ? "linux" : os.contains("win") ? "windows" : null; + String arch = switch (architecture) { + case "aarch64", "arm64" -> "aarch64"; + case "amd64", "x86_64" -> "x86_64"; + default -> null; + }; + return family == null || arch == null ? null : family + "-" + arch; + } + + static Path install(Path cacheRoot, String platform, ClassLoader resources, Fetcher fetcher, + SlimJar.BootstrapLogger logger) { + if (platform == null) { + return null; + } + Pin pin = pin(resources, platform); + if (pin == null || resources.getResource(RESOURCE_PREFIX + platform + "/" + pin.file()) != null) { + return null; + } + Path target = cacheRoot.resolve(pin.sha256()).resolve(pin.file()); + try { + if (Files.isRegularFile(target)) { + if (pin.matches(Files.readAllBytes(target))) { + return target; + } + Files.delete(target); + } + } catch (IOException failure) { + logger.error("Native noise cache " + target + " is unreadable (" + failure.getMessage() + ")"); + } + List failures = new ArrayList<>(); + for (URI source : pin.sources(platform)) { + long started = System.nanoTime(); + try { + byte[] bytes = fetcher.fetch(source, pin.size()); + if (!pin.matches(bytes)) { + failures.add(source.getHost() + ": checksum mismatch"); + continue; + } + write(target, bytes); + logger.info("Native noise kernels for " + platform + ": " + (bytes.length / 1024) + " KiB in " + + ((System.nanoTime() - started) / 1_000_000L) + " ms from " + source.getHost()); + return target; + } catch (IOException failure) { + failures.add(source.getHost() + ": " + failure.getMessage()); + } + } + logger.error("Native noise kernels unavailable for " + platform + " (" + String.join("; ", failures) + + "); generation uses the Java kernels with identical output. To install manually, save " + + pin.sources(platform).get(0) + " (sha256 " + pin.sha256() + ") as " + target); + return null; + } + + private static Pin pin(ClassLoader resources, String platform) { + Properties manifest = new Properties(); + try (InputStream input = resources.getResourceAsStream(MANIFEST)) { + if (input == null) { + return null; + } + try (Reader reader = new InputStreamReader(input, StandardCharsets.UTF_8)) { + manifest.load(reader); + } + } catch (IOException failure) { + return null; + } + String file = manifest.getProperty(platform + ".file"); + String sha256 = manifest.getProperty(platform + ".sha256"); + String blob = manifest.getProperty(platform + ".blob"); + String size = manifest.getProperty(platform + ".size"); + if (file == null || sha256 == null || blob == null || size == null) { + return null; + } + return new Pin(file, Long.parseLong(size), sha256, blob, manifest.getProperty("commit", ""), + manifest.getProperty("source", "")); + } + + private static void write(Path target, byte[] bytes) throws IOException { + Files.createDirectories(target.getParent()); + Path temporary = Files.createTempFile(target.getParent(), target.getFileName().toString(), ".part"); + try { + Files.write(temporary, bytes); + try { + Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } catch (AtomicMoveNotSupportedException unsupported) { + Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING); + } + } finally { + Files.deleteIfExists(temporary); + } + } + + private static byte[] download(URI source, long size) throws IOException { + URL url = source.toURL(); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setConnectTimeout(CONNECT_TIMEOUT_MILLIS); + connection.setReadTimeout(READ_TIMEOUT_MILLIS); + connection.setRequestProperty("User-Agent", "Iris"); + connection.setRequestProperty("Accept", "application/vnd.github.raw+json"); + try { + int status = connection.getResponseCode(); + if (status != HttpURLConnection.HTTP_OK) { + throw new IOException("HTTP " + status); + } + try (InputStream input = connection.getInputStream()) { + byte[] bytes = input.readNBytes((int) Math.min(Integer.MAX_VALUE - 8L, size + 1L)); + if (bytes.length != size) { + throw new IOException("expected " + size + " bytes, got " + bytes.length); + } + return bytes; + } + } finally { + connection.disconnect(); + } + } + + @FunctionalInterface + interface Fetcher { + byte[] fetch(URI source, long size) throws IOException; + } + + private record Pin(String file, long size, String sha256, String blob, String commit, String source) { + boolean matches(byte[] bytes) { + if (bytes.length != size) { + return false; + } + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)).equals(sha256); + } catch (NoSuchAlgorithmException missing) { + throw new IllegalStateException(missing); + } + } + + List sources(String platform) { + List sources = new ArrayList<>(2); + if (!commit.isEmpty() && !source.isEmpty()) { + sources.add(URI.create(RAW_ROOT + commit + "/" + source + "/" + platform + "/" + file)); + } + sources.add(URI.create(BLOB_ROOT + blob)); + return sources; + } + } +} diff --git a/core/src/main/java/art/arcane/iris/platform/bootstrap/SlimJar.java b/core/src/main/java/art/arcane/iris/platform/bootstrap/SlimJar.java index 046c4a15b..6cba7b236 100644 --- a/core/src/main/java/art/arcane/iris/platform/bootstrap/SlimJar.java +++ b/core/src/main/java/art/arcane/iris/platform/bootstrap/SlimJar.java @@ -58,6 +58,7 @@ public class SlimJar { }) .build(); nativeProviders = libraries.openProviderLoader(downloadPath); + NoiseNatives.provision(downloadPath.resolveSibling("natives"), logger); loaded.set(true); } finally { lock.unlock(); @@ -100,6 +101,22 @@ public class SlimJar { }) .build(); nativeProviders = libraries.openProviderLoader(downloadPath); + NoiseNatives.provision(downloadPath.resolveSibling("natives"), new BootstrapLogger() { + @Override + public void info(String message) { + plugin.getLogger().info(message); + } + + @Override + public void error(String message) { + plugin.getLogger().warning(message); + } + + @Override + public void debug(String message) { + SlimJar.debug(plugin, message); + } + }); loaded.set(true); debug(plugin, "Libraries loaded successfully!"); } finally { diff --git a/core/src/test/java/art/arcane/iris/localization/IrisLanguageGuideCacheTest.java b/core/src/test/java/art/arcane/iris/localization/IrisLanguageGuideCacheTest.java new file mode 100644 index 000000000..88caa71a2 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/localization/IrisLanguageGuideCacheTest.java @@ -0,0 +1,89 @@ +package art.arcane.iris.localization; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.util.HexFormat; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +public class IrisLanguageGuideCacheTest { + private static final String LOCALE = "de_DE"; + private static final String GUIDE = "# === Iris language guide ===\n# Deutsche Anleitung\n# === End Iris language guide ===\n"; + private static final String BODY = "\n[iris.command]\nunknown = 'Unbekannt'\n"; + + @Rule + public final TemporaryFolder temporary = new TemporaryFolder(); + + @Test + public void unbundledGuideComesFromAnUpstreamCopyOnlyWhenItMatchesTheBuildIndex() throws Exception { + Path cache = temporary.newFolder(".guides").toPath(); + try (URLClassLoader resources = indexOnly(GUIDE)) { + assertNull(IrisLanguageGuide.header(LOCALE, cache, resources)); + assertFalse(IrisLanguageGuide.cacheUpstream(cache, LOCALE, GUIDE.replace("Deutsche", "Alte") + BODY, resources)); + assertNull(IrisLanguageGuide.header(LOCALE, cache, resources)); + assertTrue(IrisLanguageGuide.cacheUpstream(cache, LOCALE, GUIDE.replace("\n", "\r\n") + BODY, resources)); + assertEquals(GUIDE, IrisLanguageGuide.header(LOCALE, cache, resources)); + } + } + + @Test + public void refreshLeavesATranslatedGuideAloneWhenThisBuildsGuideIsUnavailable() throws Exception { + File languages = temporary.newFolder("languages"); + File file = new File(languages, LOCALE + ".toml"); + String original = "# === Iris language guide ===\n# Eigene Anleitung\n# === End Iris language guide ===\n" + BODY; + Files.writeString(file.toPath(), original, StandardCharsets.UTF_8); + try (URLClassLoader resources = indexOnly(GUIDE)) { + assertFalse(IrisLanguageGuide.refresh(file, LOCALE, resources)); + assertTrue(IrisLanguageGuide.fetchable(LOCALE, resources)); + assertEquals(original, Files.readString(file.toPath(), StandardCharsets.UTF_8)); + + assertTrue(IrisLanguageGuide.cacheUpstream(IrisLanguageGuide.guideCache(file), LOCALE, GUIDE + BODY, resources)); + assertTrue(IrisLanguageGuide.refresh(file, LOCALE, resources)); + assertEquals(GUIDE + BODY, Files.readString(file.toPath(), StandardCharsets.UTF_8)); + } + } + + @Test + public void englishNeverNeedsADownload() throws Exception { + try (URLClassLoader resources = new URLClassLoader(new URL[0], null)) { + assertEquals(IrisLanguageGuide.englishHeader("en_US"), IrisLanguageGuide.header("en_US", null, resources)); + assertFalse(IrisLanguageGuide.fetchable("en_US", resources)); + assertFalse(IrisLanguageGuide.fetchable(LOCALE, resources)); + } + } + + @Test + public void extractedHeaderFollowsTheBuildRule() { + assertEquals(GUIDE, IrisLanguageGuide.extractHeader("\n" + GUIDE + " \n[iris]\nkey = 'value'\n# trailing\n").stripLeading()); + assertEquals("\n", IrisLanguageGuide.extractHeader("[iris]\nkey = 'value'\n")); + } + + private URLClassLoader indexOnly(String guide) throws IOException { + Path root = temporary.newFolder().toPath(); + Path index = root.resolve("iris-language-guides/index.properties"); + Files.createDirectories(index.getParent()); + Files.writeString(index, LOCALE + "=" + sha256(guide) + "\n", StandardCharsets.UTF_8); + return new URLClassLoader(new URL[]{root.toUri().toURL()}, null); + } + + private static String sha256(String text) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8))); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + } +} diff --git a/core/src/test/java/art/arcane/iris/platform/bootstrap/NoiseNativesTest.java b/core/src/test/java/art/arcane/iris/platform/bootstrap/NoiseNativesTest.java new file mode 100644 index 000000000..a4ac0ba86 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/platform/bootstrap/NoiseNativesTest.java @@ -0,0 +1,169 @@ +package art.arcane.iris.platform.bootstrap; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.IOException; +import java.net.URI; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +public class NoiseNativesTest { + private static final String PLATFORM = "linux-x86_64"; + private static final String FILE = "libvolmlib_noise.so"; + private static final byte[] NATIVE = "native-kernels".getBytes(StandardCharsets.UTF_8); + private static final String COMMIT = "0123456789abcdef0123456789abcdef01234567"; + + @Rule + public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + + private final List errors = new ArrayList<>(); + private final SlimJar.BootstrapLogger logger = new SlimJar.BootstrapLogger() { + @Override + public void info(String message) { + } + + @Override + public void error(String message) { + errors.add(message); + } + + @Override + public void debug(String message) { + } + }; + + @Test + public void platformMatchesVolmLibNaming() { + assertEquals("macos-aarch64", NoiseNatives.platform("Mac OS X", "aarch64")); + assertEquals("windows-x86_64", NoiseNatives.platform("Windows 11", "amd64")); + assertEquals("linux-aarch64", NoiseNatives.platform("Linux", "arm64")); + assertNull(NoiseNatives.platform("FreeBSD", "amd64")); + assertNull(NoiseNatives.platform("Linux", "riscv64")); + } + + @Test + public void installsAVerifiedDownloadIntoAHashedCacheAndReusesIt() throws Exception { + List requested = new ArrayList<>(); + Path cache = temporaryFolder.newFolder("cache").toPath(); + try (URLClassLoader resources = resources(manifest(""), Map.of())) { + Path installed = NoiseNatives.install(cache, PLATFORM, resources, serving(requested, Map.of()), logger); + assertEquals(cache.resolve(sha256(NATIVE)).resolve(FILE), installed); + assertArrayEquals(NATIVE, Files.readAllBytes(installed)); + assertEquals(List.of(URI.create("https://api.github.com/repos/VolmitSoftware/VolmLib/git/blobs/" + blob(NATIVE))), requested); + + Path reused = NoiseNatives.install(cache, PLATFORM, resources, (uri, limit) -> { + throw new IOException("must not fetch"); + }, logger); + assertEquals(installed, reused); + } + assertTrue(errors.isEmpty()); + } + + @Test + public void rejectsBytesThatDoNotMatchThePinAndTriesTheNextSource() throws Exception { + Path cache = temporaryFolder.newFolder("cache").toPath(); + URI raw = URI.create("https://raw.githubusercontent.com/VolmitSoftware/VolmLib/" + COMMIT + + "/shared/native/noise/prebuilt/" + PLATFORM + "/" + FILE); + List requested = new ArrayList<>(); + try (URLClassLoader resources = resources(manifest(COMMIT), Map.of())) { + Path installed = NoiseNatives.install(cache, PLATFORM, resources, + serving(requested, Map.of(raw, "tampered!!!!!!".getBytes(StandardCharsets.UTF_8))), logger); + assertArrayEquals(NATIVE, Files.readAllBytes(installed)); + assertEquals(raw, requested.get(0)); + assertEquals(2, requested.size()); + } + } + + @Test + public void fallsBackToJavaWithOneErrorWhenEverySourceFails() throws Exception { + Path cache = temporaryFolder.newFolder("cache").toPath(); + try (URLClassLoader resources = resources(manifest(COMMIT), Map.of())) { + assertNull(NoiseNatives.install(cache, PLATFORM, resources, (uri, limit) -> { + throw new IOException("offline"); + }, logger)); + } + assertEquals(1, errors.size()); + assertTrue(errors.get(0).contains(sha256(NATIVE))); + try (Stream files = Files.walk(cache)) { + assertFalse(files.anyMatch(Files::isRegularFile)); + } + } + + @Test + public void bundledNativesAndMissingManifestsNeverDownload() throws Exception { + Path cache = temporaryFolder.newFolder("cache").toPath(); + NoiseNatives.Fetcher refuse = (uri, limit) -> { + throw new AssertionError("must not fetch " + uri); + }; + try (URLClassLoader bundled = resources(manifest(""), Map.of("art/arcane/volmlib/native/" + PLATFORM + "/" + FILE, NATIVE)); + URLClassLoader unpinned = resources(null, Map.of())) { + assertNull(NoiseNatives.install(cache, PLATFORM, bundled, refuse, logger)); + assertNull(NoiseNatives.install(cache, PLATFORM, unpinned, refuse, logger)); + assertNull(NoiseNatives.install(cache, "macos-x86_64", bundled, refuse, logger)); + } + assertTrue(errors.isEmpty()); + } + + private NoiseNatives.Fetcher serving(List requested, Map overrides) { + return (uri, limit) -> { + requested.add(uri); + return overrides.getOrDefault(uri, NATIVE); + }; + } + + private String manifest(String commit) { + return "commit=" + commit + "\nsource=shared/native/noise/prebuilt\nplatforms=" + PLATFORM + "\n" + + PLATFORM + ".file=" + FILE + "\n" + PLATFORM + ".size=" + NATIVE.length + "\n" + + PLATFORM + ".sha256=" + sha256(NATIVE) + "\n" + PLATFORM + ".blob=" + blob(NATIVE) + "\n"; + } + + private URLClassLoader resources(String manifest, Map extra) throws IOException { + Path root = temporaryFolder.newFolder().toPath(); + if (manifest != null) { + Path file = root.resolve(NoiseNatives.MANIFEST); + Files.createDirectories(file.getParent()); + Files.writeString(file, manifest, StandardCharsets.UTF_8); + } + for (Map.Entry entry : extra.entrySet()) { + Path file = root.resolve(entry.getKey()); + Files.createDirectories(file.getParent()); + Files.write(file, entry.getValue()); + } + return new URLClassLoader(new URL[]{root.toUri().toURL()}, null); + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + } + + private static String blob(byte[] bytes) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-1"); + digest.update(("blob " + bytes.length + "\0").getBytes(StandardCharsets.US_ASCII)); + return HexFormat.of().formatHex(digest.digest(bytes)); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + } +}