Skip to content

Commit 51f1274

Browse files
committed
Improve minecraft-client.jar download to use a temporary file before verification
1 parent 7200e94 commit 51f1274

File tree

1 file changed

+25
-16
lines changed

1 file changed

+25
-16
lines changed

core/src/main/java/de/bluecolored/bluemap/core/resources/MinecraftVersion.java

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -134,32 +134,41 @@ public static MinecraftVersion load(@Nullable String id, Path dataRoot, boolean
134134
}
135135

136136
private static void download(VersionManifest.Version version, Path file) throws IOException {
137-
boolean downloadCompletedAndVerified = false;
138137
VersionManifest.Download download = version.fetchDetail().getDownloads().getClient();
139138
Logger.global.logInfo("Downloading '" + download.getUrl() + "' to '" + file + "'...");
140139

141140
FileHelper.createDirectories(file.toAbsolutePath().normalize().getParent());
141+
Path unverifiedFile = file.getParent().resolve(file.getFileName().toString() + ".unverified");
142+
143+
try {
144+
try (
145+
DigestInputStream in = new DigestInputStream(
146+
new URI(download.getUrl()).toURL().openStream(),
147+
MessageDigest.getInstance("SHA-1")
148+
);
149+
OutputStream out = Files.newOutputStream(unverifiedFile)
150+
) {
151+
152+
// download
153+
in.transferTo(out);
154+
155+
// verify sha-1
156+
if (!Arrays.equals(
157+
in.getMessageDigest().digest(),
158+
hexStringToByteArray(download.getSha1())
159+
)) {
160+
throw new IOException("SHA-1 of the downloaded file does not match!");
161+
}
142162

143-
try (
144-
DigestInputStream in = new DigestInputStream(new URI(download.getUrl()).toURL().openStream(), MessageDigest.getInstance("SHA-1"));
145-
OutputStream out = Files.newOutputStream(file, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING)
146-
) {
147-
in.transferTo(out);
148-
149-
// verify sha-1
150-
if (!Arrays.equals(
151-
in.getMessageDigest().digest(),
152-
hexStringToByteArray(download.getSha1())
153-
)) {
154-
throw new IOException("SHA-1 of the downloaded file does not match!");
155163
}
156164

157-
downloadCompletedAndVerified = true;
165+
// rename once verified
166+
FileHelper.atomicMove(unverifiedFile, file);
167+
158168
} catch (NoSuchAlgorithmException | IOException | URISyntaxException ex) {
159169
Logger.global.logWarning("Failed to download '" + download.getUrl() + "': " + ex);
160170
} finally {
161-
if (!downloadCompletedAndVerified)
162-
Files.deleteIfExists(file);
171+
Files.deleteIfExists(unverifiedFile);
163172
}
164173

165174
}

0 commit comments

Comments
 (0)