forked from McModLauncher/securejarhandler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJarContentsImpl.java
More file actions
225 lines (205 loc) · 8.75 KB
/
JarContentsImpl.java
File metadata and controls
225 lines (205 loc) · 8.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package cpw.mods.jarhandling.impl;
import cpw.mods.jarhandling.JarContents;
import cpw.mods.jarhandling.SecureJar;
import cpw.mods.niofs.union.UnionFileSystem;
import cpw.mods.niofs.union.UnionFileSystemProvider;
import cpw.mods.niofs.union.UnionPathFilter;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.spi.FileSystemProvider;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
public class JarContentsImpl implements JarContents {
private static final UnionFileSystemProvider UFSP = (UnionFileSystemProvider) FileSystemProvider.installedProviders()
.stream()
.filter(fsp->fsp.getScheme().equals("union"))
.findFirst()
.orElseThrow(()->new IllegalStateException("Couldn't find UnionFileSystemProvider"));
private static final Set<String> NAUGHTY_SERVICE_FILES = Set.of("org.codehaus.groovy.runtime.ExtensionModule");
final UnionFileSystem filesystem;
// Code signing data
final JarSigningData signingData = new JarSigningData();
// Manifest of the jar
private final Manifest manifest;
// Name overrides, if the jar is a multi-release jar
private final Map<Path, Integer> nameOverrides;
// Cache for repeated getPackages calls
private Set<String> packages;
// Cache for repeated getMetaInfServices calls
private List<SecureJar.Provider> providers;
public JarContentsImpl(Path[] paths, Supplier<Manifest> defaultManifest, @Nullable UnionPathFilter pathFilter) {
var validPaths = Arrays.stream(paths).filter(Files::exists).toArray(Path[]::new);
if (validPaths.length == 0)
throw new UncheckedIOException(new IOException("Invalid paths argument, contained no existing paths: " + Arrays.toString(paths)));
this.filesystem = UFSP.newFileSystem(pathFilter, validPaths);
// Find the manifest, and read its signing data
this.manifest = readManifestAndSigningData(defaultManifest, validPaths);
// Read multi-release jar information
this.nameOverrides = readMultiReleaseInfo();
}
private Manifest readManifestAndSigningData(Supplier<Manifest> defaultManifest, Path[] validPaths) {
try {
for (int x = validPaths.length - 1; x >= 0; x--) { // Walk backwards because this is what cpw wanted?
var path = validPaths[x];
if (Files.isDirectory(path)) {
// Just a directory: read the manifest file, but don't do any signature verification
var manfile = path.resolve(JarFile.MANIFEST_NAME);
if (Files.exists(manfile)) {
try (var is = Files.newInputStream(manfile)) {
return new Manifest(is);
}
}
} else {
try (var jis = new JarInputStream(Files.newInputStream(path))) {
// Jar file: use the signature verification code
signingData.readJarSigningData(jis);
if (jis.getManifest() != null) {
return new Manifest(jis.getManifest());
}
}
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return defaultManifest.get();
}
/**
* Read multi-release information from the jar.
* Example of a multi-release jar layout:
*
* <pre>
* jar root
* - A.class
* - B.class
* - C.class
* - D.class
* - META-INF
* - versions
* - 9
* - A.class
* - B.class
* - 10
* - A.class
* </pre>
*/
private Map<Path, Integer> readMultiReleaseInfo() {
// Must have the manifest entry
boolean isMultiRelease = Boolean.parseBoolean(getManifest().getMainAttributes().getValue("Multi-Release"));
if (!isMultiRelease) {
return Map.of();
}
var vers = filesystem.getRoot().resolve("META-INF/versions");
if (!Files.isDirectory(vers)) return Map.of();
try (var walk = Files.walk(vers)) {
Map<Path, Integer> pathToJavaVersion = new HashMap<>();
walk
// Look for files, not directories
.filter(p -> !Files.isDirectory(p))
.forEach(p -> {
int javaVersion = Integer.parseInt(p.getName(2).toString());
Path remainder = p.subpath(3, p.getNameCount());
if (javaVersion <= Runtime.version().feature()) {
// Associate path with the highest supported java version
pathToJavaVersion.merge(remainder, javaVersion, Integer::max);
}
});
return pathToJavaVersion;
} catch (IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
@Override
public Path getPrimaryPath() {
return filesystem.getPrimaryPath();
}
@Override
public Optional<URI> findFile(String name) {
var rel = filesystem.getPath(name);
if (this.nameOverrides.containsKey(rel)) {
rel = this.filesystem.getPath("META-INF", "versions", this.nameOverrides.get(rel).toString()).resolve(rel);
}
return Optional.of(this.filesystem.getRoot().resolve(rel)).filter(Files::exists).map(Path::toUri);
}
@Override
public Manifest getManifest() {
return manifest;
}
@Override
public Set<String> getPackagesExcluding(String... excludedRootPackages) {
Set<String> ignoredRootPackages = new HashSet<>(excludedRootPackages.length+1);
ignoredRootPackages.add("META-INF"); // Always ignore META-INF
ignoredRootPackages.addAll(List.of(excludedRootPackages)); // And additional user-provided packages
Set<String> packages = new HashSet<>();
try {
Files.walkFileTree(this.filesystem.getRoot(), new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (file.getFileName().toString().endsWith(".class") && attrs.isRegularFile()) {
var pkg = JarContentsImpl.this.filesystem.getRoot().relativize(file.getParent()).toString().replace('/', '.');
if (!pkg.isEmpty()) {
packages.add(pkg);
}
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes attrs) {
if (path.getNameCount() > 0 && ignoredRootPackages.contains(path.getName(0).toString())) {
return FileVisitResult.SKIP_SUBTREE;
}
return FileVisitResult.CONTINUE;
}
});
return Set.copyOf(packages);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public Set<String> getPackages() {
if (this.packages == null) {
this.packages = getPackagesExcluding();
}
return this.packages;
}
@Override
public List<SecureJar.Provider> getMetaInfServices() {
if (this.providers == null) {
final var services = this.filesystem.getRoot().resolve("META-INF/services/");
if (Files.exists(services)) {
try (var walk = Files.walk(services, 1)) {
this.providers = walk.filter(path->!Files.isDirectory(path))
.filter(path -> !NAUGHTY_SERVICE_FILES.contains(path.getFileName().toString()))
.map((Path path1) -> SecureJar.Provider.fromPath(path1, filesystem.getFilesystemFilter()))
.toList();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
} else {
this.providers = List.of();
}
}
return this.providers;
}
@Override
public void close() throws IOException {
filesystem.close();
}
}