-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathExtensionClassLoader.java
More file actions
248 lines (215 loc) · 8.5 KB
/
Copy pathExtensionClassLoader.java
File metadata and controls
248 lines (215 loc) · 8.5 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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.javaagent.tooling;
import static java.util.Collections.emptyList;
import io.opentelemetry.context.Context;
import io.opentelemetry.javaagent.tooling.config.EarlyInitAgentConfig;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.security.AllPermission;
import java.security.CodeSource;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import javax.annotation.Nullable;
import net.bytebuddy.dynamic.loading.MultipleParentClassLoader;
/**
* This class creates a class loader which encapsulates arbitrary extensions for Otel Java
* instrumentation agent. Such extensions may include SDK components (exporters or propagators) and
* additional instrumentations. They have to be isolated and shaded to reduce interference with the
* user application and to make it compatible with shaded SDK used by the agent. Thus each extension
* jar gets a separate class loader and all of them are aggregated with the help of {@link
* MultipleParentClassLoader}.
*/
// TODO find a way to initialize logging before using this class
@SuppressWarnings("SystemOut")
public class ExtensionClassLoader extends URLClassLoader {
private final boolean isSecurityManagerSupportEnabled;
// NOTE it's important not to use logging in this class, because this class is used before logging
// is initialized
static {
ClassLoader.registerAsParallelCapable();
}
public static ClassLoader getInstance(
ClassLoader parent, File javaagentFile, boolean isSecurityManagerSupportEnabled) {
List<URL> extensions = new ArrayList<>();
includeEmbeddedExtensionsIfFound(extensions, javaagentFile);
extensions.addAll(parseLocation(EarlyInitAgentConfig.get().getExtensions(), javaagentFile));
// TODO when logging is configured add warning about deprecated property
if (extensions.isEmpty()) {
return parent;
}
List<ClassLoader> delegates = new ArrayList<>(extensions.size());
for (URL url : extensions) {
delegates.add(getDelegate(parent, url, isSecurityManagerSupportEnabled));
}
return new MultipleParentClassLoader(parent, delegates);
}
private static void includeEmbeddedExtensionsIfFound(List<URL> extensions, File javaagentFile) {
try (JarFile jarFile = new JarFile(javaagentFile, false)) {
Enumeration<JarEntry> entryEnumeration = jarFile.entries();
String prefix = "extensions/";
File tempDirectory = null;
while (entryEnumeration.hasMoreElements()) {
JarEntry jarEntry = entryEnumeration.nextElement();
String name = jarEntry.getName();
if (name.startsWith(prefix) && !jarEntry.isDirectory()) {
tempDirectory = ensureTempDirectoryExists(tempDirectory);
File tempFile = new File(tempDirectory, name.substring(prefix.length()));
// reject extensions that would be extracted outside of temp directory
// https://security.snyk.io/research/zip-slip-vulnerability
if (!tempFile
.getCanonicalFile()
.toPath()
.startsWith(tempDirectory.getCanonicalFile().toPath())) {
throw new IllegalStateException("Invalid extension " + name);
}
if (tempFile.createNewFile()) {
tempFile.deleteOnExit();
extractFile(jarFile, jarEntry, tempFile);
addFileUrl(extensions, tempFile);
} else {
System.err.println("Failed to create temp file " + tempFile);
}
}
}
} catch (IOException e) {
System.err.println("Failed to open embedded extensions " + e.getMessage());
}
}
private static File ensureTempDirectoryExists(@Nullable File tempDirectory) throws IOException {
if (tempDirectory == null) {
tempDirectory = Files.createTempDirectory("otel-extensions").toFile();
tempDirectory.deleteOnExit();
}
return tempDirectory;
}
private static URLClassLoader getDelegate(
ClassLoader parent, URL extensionUrl, boolean isSecurityManagerSupportEnabled) {
return new ExtensionClassLoader(extensionUrl, parent, isSecurityManagerSupportEnabled);
}
// visible for testing
static List<URL> parseLocation(@Nullable String locationName, File javaagentFile) {
if (locationName == null) {
return emptyList();
}
List<URL> result = new ArrayList<>();
for (String location : locationName.split(",")) {
parseLocation(location, javaagentFile, result);
}
return result;
}
private static void parseLocation(String locationName, File javaagentFile, List<URL> locations) {
if (locationName.isEmpty()) {
return;
}
File location = new File(locationName);
if (isJar(location)) {
addFileUrl(locations, location);
} else if (location.isDirectory()) {
File[] files = location.listFiles(ExtensionClassLoader::isJar);
if (files != null) {
for (File file : files) {
if (isJar(file) && !file.getAbsolutePath().equals(javaagentFile.getAbsolutePath())) {
addFileUrl(locations, file);
}
}
}
}
}
private static boolean isJar(File f) {
return f.isFile() && f.getName().endsWith(".jar");
}
private static void addFileUrl(List<URL> result, File file) {
try {
// skip shading extension classes if opentelemetry-api is not shaded (happens when using
// disableShadowRelocate=true)
if (Context.class.getName().contains(".shaded.")) {
URL wrappedUrl = new URL("otel", null, -1, "/", new RemappingUrlStreamHandler(file));
result.add(wrappedUrl);
} else {
result.add(file.toURI().toURL());
}
} catch (MalformedURLException ignored) {
System.err.println("Ignoring " + file);
}
}
private static void extractFile(JarFile jarFile, JarEntry jarEntry, File outputFile)
throws IOException {
try (InputStream in = jarFile.getInputStream(jarEntry);
ReadableByteChannel rbc = Channels.newChannel(in);
FileOutputStream fos = new FileOutputStream(outputFile)) {
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}
}
@Override
protected PermissionCollection getPermissions(CodeSource codesource) {
if (isSecurityManagerSupportEnabled) {
Permissions permissions = new Permissions();
permissions.add(new AllPermission());
return permissions;
}
return super.getPermissions(codesource);
}
private ExtensionClassLoader(
URL url, ClassLoader parent, boolean isSecurityManagerSupportEnabled) {
super(new URL[] {url}, parent);
this.isSecurityManagerSupportEnabled = isSecurityManagerSupportEnabled;
}
@Override
public Enumeration<URL> findResources(String name) throws IOException {
Enumeration<URL> result = super.findResources(name);
// Agent shades instrumentation-api-incubator, in extensions references to these classes are
// remapped at load time. Here we handle looking up the service files for the classes that
// were renamed using the original name.
if (name.startsWith(
"META-INF/services/io.opentelemetry.javaagent.shaded.instrumentation.api.incubator")) {
String originalName =
name.replace(
"opentelemetry.javaagent.shaded.instrumentation", "opentelemetry.instrumentation");
return new CompoundEnumeration<>(result, super.findResources(originalName));
}
return result;
}
private static class CompoundEnumeration<E> implements Enumeration<E> {
private final Enumeration<E>[] enumerations;
private int index = 0;
@SafeVarargs
@SuppressWarnings("varargs")
CompoundEnumeration(Enumeration<E>... enumerations) {
this.enumerations = enumerations;
}
@Override
public boolean hasMoreElements() {
while (index < enumerations.length) {
if (enumerations[index].hasMoreElements()) {
return true;
}
index++;
}
return false;
}
@Override
public E nextElement() {
if (!hasMoreElements()) {
throw new NoSuchElementException();
}
return enumerations[index].nextElement();
}
}
}