From 51f12741c923767c98e050db28eb690f296f73db Mon Sep 17 00:00:00 2001 From: "Lukas Rieger (Blue)" Date: Tue, 10 Dec 2024 23:52:53 +0100 Subject: [PATCH] Improve minecraft-client.jar download to use a temporary file before verification --- .../core/resources/MinecraftVersion.java | 39 ++++++++++++------- 1 file changed, 24 insertions(+), 15 deletions(-) diff --git a/core/src/main/java/de/bluecolored/bluemap/core/resources/MinecraftVersion.java b/core/src/main/java/de/bluecolored/bluemap/core/resources/MinecraftVersion.java index b39c8ef1..dbc58e11 100644 --- a/core/src/main/java/de/bluecolored/bluemap/core/resources/MinecraftVersion.java +++ b/core/src/main/java/de/bluecolored/bluemap/core/resources/MinecraftVersion.java @@ -134,32 +134,41 @@ public static MinecraftVersion load(@Nullable String id, Path dataRoot, boolean } private static void download(VersionManifest.Version version, Path file) throws IOException { - boolean downloadCompletedAndVerified = false; VersionManifest.Download download = version.fetchDetail().getDownloads().getClient(); Logger.global.logInfo("Downloading '" + download.getUrl() + "' to '" + file + "'..."); FileHelper.createDirectories(file.toAbsolutePath().normalize().getParent()); + Path unverifiedFile = file.getParent().resolve(file.getFileName().toString() + ".unverified"); - try ( - DigestInputStream in = new DigestInputStream(new URI(download.getUrl()).toURL().openStream(), MessageDigest.getInstance("SHA-1")); - OutputStream out = Files.newOutputStream(file, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING) - ) { - in.transferTo(out); + try { + try ( + DigestInputStream in = new DigestInputStream( + new URI(download.getUrl()).toURL().openStream(), + MessageDigest.getInstance("SHA-1") + ); + OutputStream out = Files.newOutputStream(unverifiedFile) + ) { + + // download + in.transferTo(out); + + // verify sha-1 + if (!Arrays.equals( + in.getMessageDigest().digest(), + hexStringToByteArray(download.getSha1()) + )) { + throw new IOException("SHA-1 of the downloaded file does not match!"); + } - // verify sha-1 - if (!Arrays.equals( - in.getMessageDigest().digest(), - hexStringToByteArray(download.getSha1()) - )) { - throw new IOException("SHA-1 of the downloaded file does not match!"); } - downloadCompletedAndVerified = true; + // rename once verified + FileHelper.atomicMove(unverifiedFile, file); + } catch (NoSuchAlgorithmException | IOException | URISyntaxException ex) { Logger.global.logWarning("Failed to download '" + download.getUrl() + "': " + ex); } finally { - if (!downloadCompletedAndVerified) - Files.deleteIfExists(file); + Files.deleteIfExists(unverifiedFile); } }