From 1d116305745b559fa000375073e5cfc91b316873 Mon Sep 17 00:00:00 2001 From: LexManos Date: Fri, 3 Nov 2023 10:44:51 -0700 Subject: [PATCH] Fix issue when opening the same jar file multiple times. --- .../securemodules/test/TestSecureJarLoading.java | 9 +++++++++ src/main/java/cpw/mods/jarhandling/impl/Jar.java | 11 +++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/sm-test/src/test/java/net/minecraftforge/securemodules/test/TestSecureJarLoading.java b/sm-test/src/test/java/net/minecraftforge/securemodules/test/TestSecureJarLoading.java index 24a63ff..da6139b 100644 --- a/sm-test/src/test/java/net/minecraftforge/securemodules/test/TestSecureJarLoading.java +++ b/sm-test/src/test/java/net/minecraftforge/securemodules/test/TestSecureJarLoading.java @@ -122,4 +122,13 @@ void testEmptyJar() throws Exception { } } } + + @Test // Test opening the same file multiple times. + void testSameJar() throws Exception { + var path = Paths.get("src", "test", "resources", "empty.zip"); + var jar1 = SecureJar.from(path); + assertNotNull(jar1); + var jar2 = SecureJar.from(path); + assertNotNull(jar2); + } } diff --git a/src/main/java/cpw/mods/jarhandling/impl/Jar.java b/src/main/java/cpw/mods/jarhandling/impl/Jar.java index 5e9ad82..9d6e88e 100644 --- a/src/main/java/cpw/mods/jarhandling/impl/Jar.java +++ b/src/main/java/cpw/mods/jarhandling/impl/Jar.java @@ -16,6 +16,8 @@ import java.net.URI; import java.net.URISyntaxException; import java.nio.file.FileSystem; +import java.nio.file.FileSystemAlreadyExistsException; +import java.nio.file.FileSystemNotFoundException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; @@ -185,9 +187,14 @@ private Path newFileSystem(BiPredicate filter, Path[] paths) { return paths[0]; // We have to manually open the jar files up via a URI instead of a Path // because the ZipFileSystem implementation only caches the FileSystems - // when accessed that way. + // when accessed that way. But we can only open it once or else it throws + // a FileSystemAlreadyExistsException. So, exceptions as codeflow, yay! var uri = new URI("jar:" + paths[0].toUri()); - fs = FileSystems.newFileSystem(uri, Map.of(), null); + try { + fs = FileSystems.newFileSystem(uri, Map.of(), null); + } catch (FileSystemAlreadyExistsException e) { + fs = FileSystems.getFileSystem(uri); + } } else { var map = new HashMap(); if (filter != null)