Skip to content

Misc. cleanup #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion settings.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ dependencyResolutionManagement {
plugin('eclipse-apt', 'com.diffplug.eclipse.apt' ).version('3.43.0')
plugin('signer', 'net.minecraftforge.gradlejarsigner').version('1.0.5')

version('asm', '9.7')
version('asm', '9.7.1')
library('asm', 'org.ow2.asm', 'asm' ).versionRef('asm')
library('asm-tree', 'org.ow2.asm', 'asm-tree' ).versionRef('asm')
library('asm-commons', 'org.ow2.asm', 'asm-commons').versionRef('asm')
Expand Down
29 changes: 13 additions & 16 deletions src/main/java/cpw/mods/jarhandling/impl/Jar.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ public class Jar implements SecureJar {
private final Manifest manifest;
private final Hashtable<String, CodeSigner[]> pendingSigners = new Hashtable<>();
private final Hashtable<String, CodeSigner[]> verifiedSigners = new Hashtable<>();
private final ManifestVerifier verifier = new ManifestVerifier();
private final Map<String, StatusData> statusData = new HashMap<>();
private final JarMetadata metadata;
private final Path filesystemRoot;
Expand Down Expand Up @@ -205,15 +204,13 @@ private Path newFileSystem(BiPredicate<String, String> filter, Path[] paths) {
fs = UFSP.newFileSystem(paths[0], Map.of("filter", (BiPredicate<String, String>)(a, b) -> true));
}
} else {
var map = new HashMap<String, Object>();
if (filter != null)
map.put("filter", filter);

var lst = new ArrayList<>(Arrays.asList(paths));
var base = lst.remove(0);
map.put("additional", lst);

fs = UFSP.newFileSystem(base, map);
if (filter == null)
fs = UFSP.newFileSystem(base, Map.of("additional", lst));
else
fs = UFSP.newFileSystem(base, Map.of("filter", filter, "additional", lst));
}
} catch (IOException | URISyntaxException e) {
return sneak(e);
Expand All @@ -234,7 +231,7 @@ public synchronized CodeSigner[] verifyAndGetSigners(String name, byte[] bytes)
if (data != null)
return data.signers();

var signers = verifier.verify(this.manifest, pendingSigners, verifiedSigners, name, bytes);
var signers = ManifestVerifier.verify(this.manifest, pendingSigners, verifiedSigners, name, bytes);
if (signers == null) {
this.statusData.put(name, new StatusData(Status.INVALID, null));
return null;
Expand Down Expand Up @@ -281,8 +278,8 @@ private List<Provider> gatherProviders(BiPredicate<String, String> filter) {
if (!Files.exists(services))
return List.of();

try {
return Files.list(services)
try (var servicesDirStream = Files.list(services)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought this had issues with Zip file systems, calling close anywhere on them caused the entire thing to shut down.

return servicesDirStream
.filter(Files::isRegularFile)
.map(path -> getProvider(path, filter))
.toList();
Expand Down Expand Up @@ -324,9 +321,9 @@ private Map<String, String> gatherVersionedFiles() {
return Map.of();

var ret = new HashMap<String, String>();
var versions = new HashMap<String, Integer>();
try {
Files.walk(versionsDir)
var versions = new HashMap<String, Integer>(8);
try (var versionsDirStream = Files.walk(versionsDir)) {
versionsDirStream
.filter(Files::isRegularFile)
.map(filesystemRoot::relativize)
.forEach(path -> {
Expand All @@ -340,13 +337,13 @@ private Map<String, String> gatherVersionedFiles() {
} catch (IOException e) {
sneak(e);
}
return ret;
return Map.copyOf(ret);
}

private Set<String> gatherPackages() {
var files = new HashSet<String>(this.nameOverrides.keySet());
try {
Files.walk(this.filesystemRoot)
try (var filesStream = Files.walk(this.filesystemRoot)) {
filesStream
.filter(p -> Files.isRegularFile(p) && !"META-INF".equals(p.getName(0).toString()))
.map(p -> this.filesystemRoot.relativize(p).toString().replace('\\', '/'))
.forEach(files::add);
Expand Down
12 changes: 7 additions & 5 deletions src/main/java/cpw/mods/jarhandling/impl/ManifestVerifier.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@
import java.util.jar.Attributes;
import java.util.jar.Manifest;

class ManifestVerifier {
final class ManifestVerifier {
private ManifestVerifier() {}

private static final boolean DEBUG = Boolean.parseBoolean(System.getProperty("securejarhandler.debugVerifier", "false"));

private static final Base64.Decoder BASE64D = Base64.getDecoder();
private final Map<String, MessageDigest> HASHERS = new HashMap<>();
private MessageDigest getHasher(String name) {
private static final Map<String, MessageDigest> HASHERS = new HashMap<>();
private static MessageDigest getHasher(String name) {
return HASHERS.computeIfAbsent(name.toLowerCase(Locale.ENGLISH), k -> {
try {
return MessageDigest.getInstance(k);
Expand All @@ -27,7 +29,7 @@ private MessageDigest getHasher(String name) {
});
}

private void log(String line) {
private static void log(String line) {
System.out.println(line);
}

Expand All @@ -38,7 +40,7 @@ private void log(String line) {
* Optional.empty() - No signatures to verify, missing *-Digest entry in manifest, or nobody signed that particular entry
* Optional.isPresent() - code signers!
*/
Optional<CodeSigner[]> verify(final Manifest manifest, final Map<String, CodeSigner[]> pending,
static Optional<CodeSigner[]> verify(final Manifest manifest, final Map<String, CodeSigner[]> pending,
final Map<String, CodeSigner[]> verified, final String name, final byte[] data) {
if (DEBUG)
log("[SJH] Verifying: " + name);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public ModuleJarMetadata(final URI uri, final Set<String> packages) {
}
}

private class ModuleClassVisitor extends ClassVisitor {
private static final class ModuleClassVisitor extends ClassVisitor {
private ModFileVisitor mfv;

ModuleClassVisitor() {
Expand All @@ -55,7 +55,8 @@ public ModFileVisitor mfv() {
return mfv;
}
}
private class ModFileVisitor extends ModuleVisitor {

private static final class ModFileVisitor extends ModuleVisitor {
private final ModuleDescriptor.Builder builder;
private final Set<String> packages = new HashSet<>();

Expand Down Expand Up @@ -129,6 +130,7 @@ public Set<String> packages() {
return packages;
}
}

@Override
public String name() {
return descriptor.name();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
public class SecureJarVerifier {
private static final char[] LOOKUP = "0123456789abcdef".toCharArray();
public static String toHexString(final byte[] bytes) {
final var buffer = new StringBuffer(2*bytes.length);
final var buffer = new StringBuilder(2*bytes.length);
for (int i = 0, bytesLength = bytes.length; i < bytesLength; i++) {
final int aByte = bytes[i] &0xff;
buffer.append(LOOKUP[(aByte&0xf0)>>4]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,14 @@ public record SimpleJarMetadata(String name, String version, Set<String> pkgs, L
@Override
public ModuleDescriptor descriptor() {
var bld = ModuleDescriptor.newAutomaticModule(name());
if (version()!=null)
if (version() != null)
bld.version(version());
bld.packages(pkgs());
providers.stream().filter(p->!p.providers().isEmpty()).forEach(p->bld.provides(p.serviceName(), p.providers()));
for (SecureJar.Provider p : providers) {
if (!p.providers().isEmpty()) {
bld.provides(p.serviceName(), p.providers());
}
}
return bld.build();
}
}
4 changes: 2 additions & 2 deletions src/main/java/cpw/mods/niofs/union/UnionFileSystem.java
Original file line number Diff line number Diff line change
Expand Up @@ -324,14 +324,14 @@ private Path toRealPath(final Path basePath, final UnionPath path) {
public SeekableByteChannel newReadByteChannel(final UnionPath path) throws IOException {
try {
return findFirstFiltered(path)
.map(this::byteChannel)
.map(UnionFileSystem::byteChannel)
.orElseThrow(FileNotFoundException::new);
} catch (UncheckedIOException ioe) {
throw ioe.getCause();
}
}

private SeekableByteChannel byteChannel(final Path path) {
private static SeekableByteChannel byteChannel(final Path path) {
try {
return Files.newByteChannel(path, StandardOpenOption.READ);
} catch (IOException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ void removeFileSystem(UnionFileSystem fs) {
}
}

private class UnionBasicFileAttributeView implements BasicFileAttributeView {
private final class UnionBasicFileAttributeView implements BasicFileAttributeView {

private final Path path;
private final LinkOption[] options;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ private static void setupModularURLHandler() {
// TODO: [SM][Deprecation] Make private once cpw.mods.cl.ModuleClassLoader is deleted
protected final Configuration configuration;
private final ClassLoader parent;
private final Set<ModuleLayer> parents;
private final List<ClassLoader> allParentLoaders;
private final Map<String, ModuleReference> ourModules = new HashMap<>();
private final Map<String, SecureModuleReference> ourModulesSecure = new HashMap<>();
Expand Down Expand Up @@ -107,15 +106,15 @@ public SecureModuleClassLoader(String name, ClassLoader parent, Configuration co

this.configuration = config;
this.useCachedSignersForUnsignedCode = useCachedSignersForUnsignedCode;
this.parents = findAllParentLayers(parentLayers);
Set<ModuleLayer> parents = findAllParentLayers(parentLayers);

// If we only have one parent, then use it as the main parent so we don't duplicate resources
if (parent == null && parentLoaders.size() == 1) {
this.parent = parentLoaders.iterator().next();
this.allParentLoaders = Collections.emptyList();
} else {
this.parent = parent;
this.allParentLoaders = !parentLoaders.isEmpty() ? parentLoaders : findAllParentLoaders(this.parents);
this.allParentLoaders = !parentLoaders.isEmpty() ? parentLoaders : findAllParentLoaders(parents);
}

// Find all modules for this config, if the reference is our special Secure reference, we can define packages with security info.
Expand Down Expand Up @@ -145,15 +144,15 @@ public SecureModuleClassLoader(String name, ClassLoader parent, Configuration co
if (other.configuration() == this.configuration)
continue;

var layer = this.parents.stream()
var layer = parents.stream()
.filter(p -> p.configuration() == other.configuration())
.findFirst()
.orElse(null);

if (layer == null)
throw new IllegalStateException("Could not find parent layer for module `" + other.name() + "` read by `" + module.name() + "`");

var cl = layer == null ? null : layer.findLoader(other.name());
var cl = layer.findLoader(other.name());
if (cl == null)
cl = ClassLoader.getPlatformClassLoader();

Expand All @@ -175,7 +174,7 @@ else if (config == other.configuration() && !export.targets().contains(module.na

protected byte[] getClassBytes(ModuleReader reader, ModuleReference ref, String name) throws IOException {
var read = reader.open(classToResource(name));
if (!read.isPresent())
if (read.isEmpty())
return new byte[0];

try (var is = read.get()) {
Expand Down Expand Up @@ -732,6 +731,9 @@ private static Set<ModuleLayer> findAllParentLayers(Collection<ModuleLayer> pare
}
}

if (ret.size() == 1)
return Collections.singleton(ret.iterator().next());

return ret;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public static SecureModuleFinder of(Iterable<SecureJar> jars) {
return new SecureModuleFinder(jars);
}

private static class Reference extends SecureModuleReference {
private static final class Reference extends SecureModuleReference {
private final SecureJar.ModuleDataProvider jar;
private final Manifest manifest;

Expand Down