1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.internal.aether;
20
21 import java.nio.file.Path;
22 import java.nio.file.Paths;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.LinkedHashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.function.Predicate;
31 import java.util.stream.Collectors;
32
33 import org.apache.maven.api.Constants;
34 import org.apache.maven.api.di.Inject;
35 import org.apache.maven.api.di.Named;
36 import org.apache.maven.api.di.Singleton;
37 import org.apache.maven.api.services.TypeRegistry;
38 import org.apache.maven.api.xml.XmlNode;
39 import org.apache.maven.eventspy.internal.EventSpyDispatcher;
40 import org.apache.maven.execution.MavenExecutionRequest;
41 import org.apache.maven.internal.impl.resolver.MavenSessionBuilderSupplier;
42 import org.apache.maven.internal.xml.XmlNodeImpl;
43 import org.apache.maven.internal.xml.XmlPlexusConfiguration;
44 import org.apache.maven.model.ModelBase;
45 import org.apache.maven.resolver.RepositorySystemSessionFactory;
46 import org.apache.maven.rtinfo.RuntimeInformation;
47 import org.apache.maven.settings.Mirror;
48 import org.apache.maven.settings.Proxy;
49 import org.apache.maven.settings.Server;
50 import org.apache.maven.settings.building.SettingsProblem;
51 import org.apache.maven.settings.crypto.DefaultSettingsDecryptionRequest;
52 import org.apache.maven.settings.crypto.SettingsDecrypter;
53 import org.apache.maven.settings.crypto.SettingsDecryptionResult;
54 import org.codehaus.plexus.configuration.PlexusConfiguration;
55 import org.eclipse.aether.ConfigurationProperties;
56 import org.eclipse.aether.RepositoryListener;
57 import org.eclipse.aether.RepositorySystem;
58 import org.eclipse.aether.RepositorySystemSession;
59 import org.eclipse.aether.RepositorySystemSession.SessionBuilder;
60 import org.eclipse.aether.artifact.Artifact;
61 import org.eclipse.aether.artifact.DefaultArtifact;
62 import org.eclipse.aether.collection.VersionFilter;
63 import org.eclipse.aether.repository.RepositoryPolicy;
64 import org.eclipse.aether.resolution.ResolutionErrorPolicy;
65 import org.eclipse.aether.util.graph.version.ChainedVersionFilter;
66 import org.eclipse.aether.util.graph.version.ContextualSnapshotVersionFilter;
67 import org.eclipse.aether.util.graph.version.HighestVersionFilter;
68 import org.eclipse.aether.util.graph.version.LowestVersionFilter;
69 import org.eclipse.aether.util.graph.version.PredicateVersionFilter;
70 import org.eclipse.aether.util.listener.ChainedRepositoryListener;
71 import org.eclipse.aether.util.repository.AuthenticationBuilder;
72 import org.eclipse.aether.util.repository.DefaultAuthenticationSelector;
73 import org.eclipse.aether.util.repository.DefaultMirrorSelector;
74 import org.eclipse.aether.util.repository.DefaultProxySelector;
75 import org.eclipse.aether.util.repository.SimpleArtifactDescriptorPolicy;
76 import org.eclipse.aether.util.repository.SimpleResolutionErrorPolicy;
77 import org.eclipse.aether.version.InvalidVersionSpecificationException;
78 import org.eclipse.aether.version.Version;
79 import org.eclipse.aether.version.VersionRange;
80 import org.eclipse.aether.version.VersionScheme;
81 import org.slf4j.Logger;
82 import org.slf4j.LoggerFactory;
83
84 import static java.util.Objects.requireNonNull;
85
86
87
88
89 @Named
90 @Singleton
91 public class DefaultRepositorySystemSessionFactory implements RepositorySystemSessionFactory {
92
93 public static final String MAVEN_RESOLVER_TRANSPORT_DEFAULT = "default";
94
95 public static final String MAVEN_RESOLVER_TRANSPORT_WAGON = "wagon";
96
97 public static final String MAVEN_RESOLVER_TRANSPORT_APACHE = "apache";
98
99 public static final String MAVEN_RESOLVER_TRANSPORT_JDK = "jdk";
100
101
102
103
104
105
106 @Deprecated
107 private static final String MAVEN_RESOLVER_TRANSPORT_NATIVE = "native";
108
109 public static final String MAVEN_RESOLVER_TRANSPORT_AUTO = "auto";
110
111 private static final String WAGON_TRANSPORTER_PRIORITY_KEY = "aether.priority.WagonTransporterFactory";
112
113 private static final String APACHE_HTTP_TRANSPORTER_PRIORITY_KEY = "aether.priority.ApacheTransporterFactory";
114
115 private static final String JDK_HTTP_TRANSPORTER_PRIORITY_KEY = "aether.priority.JdkTransporterFactory";
116
117 private static final String FILE_TRANSPORTER_PRIORITY_KEY = "aether.priority.FileTransporterFactory";
118
119 private static final String RESOLVER_MAX_PRIORITY = String.valueOf(Float.MAX_VALUE);
120
121 private final Logger logger = LoggerFactory.getLogger(getClass());
122
123 private final RepositorySystem repoSystem;
124
125 private final SettingsDecrypter settingsDecrypter;
126
127 private final EventSpyDispatcher eventSpyDispatcher;
128
129 private final RuntimeInformation runtimeInformation;
130
131 private final TypeRegistry typeRegistry;
132
133 private final VersionScheme versionScheme;
134
135 private final Map<String, MavenExecutionRequestExtender> requestExtenders;
136
137 private final Map<String, RepositorySystemSessionExtender> sessionExtenders;
138
139 @SuppressWarnings("checkstyle:ParameterNumber")
140 @Inject
141 DefaultRepositorySystemSessionFactory(
142 RepositorySystem repoSystem,
143 SettingsDecrypter settingsDecrypter,
144 EventSpyDispatcher eventSpyDispatcher,
145 RuntimeInformation runtimeInformation,
146 TypeRegistry typeRegistry,
147 VersionScheme versionScheme,
148 Map<String, MavenExecutionRequestExtender> requestExtenders,
149 Map<String, RepositorySystemSessionExtender> sessionExtenders) {
150 this.repoSystem = repoSystem;
151 this.settingsDecrypter = settingsDecrypter;
152 this.eventSpyDispatcher = eventSpyDispatcher;
153 this.runtimeInformation = runtimeInformation;
154 this.typeRegistry = typeRegistry;
155 this.versionScheme = versionScheme;
156 this.requestExtenders = requestExtenders;
157 this.sessionExtenders = sessionExtenders;
158 }
159
160 @Deprecated
161 public RepositorySystemSession newRepositorySession(MavenExecutionRequest request) {
162 return newRepositorySessionBuilder(request).build();
163 }
164
165 @SuppressWarnings({"checkstyle:methodLength"})
166 public SessionBuilder newRepositorySessionBuilder(MavenExecutionRequest request) {
167 requireNonNull(request, "request");
168
169
170 for (MavenExecutionRequestExtender requestExtender : requestExtenders.values()) {
171 requestExtender.extend(request);
172 }
173
174 MavenSessionBuilderSupplier supplier = new MavenSessionBuilderSupplier(repoSystem);
175 SessionBuilder sessionBuilder = supplier.get();
176 sessionBuilder.setArtifactTypeRegistry(new TypeRegistryAdapter(typeRegistry));
177 sessionBuilder.setCache(request.getRepositoryCache());
178
179
180 Map<String, String> mergedProps = createMergedProperties(request);
181
182
183 Map<String, Object> configProps = new LinkedHashMap<>();
184 configProps.put(ConfigurationProperties.USER_AGENT, getUserAgent());
185 configProps.put(ConfigurationProperties.INTERACTIVE, request.isInteractiveMode());
186 configProps.put("maven.startTime", request.getStartTime());
187
188 sessionBuilder.setOffline(request.isOffline());
189 sessionBuilder.setChecksumPolicy(request.getGlobalChecksumPolicy());
190 sessionBuilder.setUpdatePolicy(
191 request.isNoSnapshotUpdates()
192 ? RepositoryPolicy.UPDATE_POLICY_NEVER
193 : request.isUpdateSnapshots() ? RepositoryPolicy.UPDATE_POLICY_ALWAYS : null);
194
195 int errorPolicy = 0;
196 errorPolicy |= request.isCacheNotFound()
197 ? ResolutionErrorPolicy.CACHE_NOT_FOUND
198 : ResolutionErrorPolicy.CACHE_DISABLED;
199 errorPolicy |= request.isCacheTransferError()
200 ? ResolutionErrorPolicy.CACHE_TRANSFER_ERROR
201 : ResolutionErrorPolicy.CACHE_DISABLED;
202 sessionBuilder.setResolutionErrorPolicy(
203 new SimpleResolutionErrorPolicy(errorPolicy, errorPolicy | ResolutionErrorPolicy.CACHE_NOT_FOUND));
204
205 sessionBuilder.setArtifactDescriptorPolicy(new SimpleArtifactDescriptorPolicy(
206 request.isIgnoreMissingArtifactDescriptor(), request.isIgnoreInvalidArtifactDescriptor()));
207
208 VersionFilter versionFilter = buildVersionFilter(mergedProps.get(Constants.MAVEN_VERSION_FILTERS));
209 if (versionFilter != null) {
210 sessionBuilder.setVersionFilter(versionFilter);
211 }
212
213 DefaultSettingsDecryptionRequest decrypt = new DefaultSettingsDecryptionRequest();
214 decrypt.setProxies(request.getProxies());
215 decrypt.setServers(request.getServers());
216 SettingsDecryptionResult decrypted = settingsDecrypter.decrypt(decrypt);
217
218 if (logger.isDebugEnabled()) {
219 for (SettingsProblem problem : decrypted.getProblems()) {
220 logger.debug(problem.getMessage(), problem.getException());
221 }
222 }
223
224 DefaultMirrorSelector mirrorSelector = new DefaultMirrorSelector();
225 for (Mirror mirror : request.getMirrors()) {
226 mirrorSelector.add(
227 mirror.getId(),
228 mirror.getUrl(),
229 mirror.getLayout(),
230 false,
231 mirror.isBlocked(),
232 mirror.getMirrorOf(),
233 mirror.getMirrorOfLayouts());
234 }
235 sessionBuilder.setMirrorSelector(mirrorSelector);
236
237 DefaultProxySelector proxySelector = new DefaultProxySelector();
238 for (Proxy proxy : decrypted.getProxies()) {
239 AuthenticationBuilder authBuilder = new AuthenticationBuilder();
240 authBuilder.addUsername(proxy.getUsername()).addPassword(proxy.getPassword());
241 proxySelector.add(
242 new org.eclipse.aether.repository.Proxy(
243 proxy.getProtocol(), proxy.getHost(), proxy.getPort(), authBuilder.build()),
244 proxy.getNonProxyHosts());
245 }
246 sessionBuilder.setProxySelector(proxySelector);
247
248
249
250 DefaultAuthenticationSelector authSelector = new DefaultAuthenticationSelector();
251 for (Server server : decrypted.getServers()) {
252 AuthenticationBuilder authBuilder = new AuthenticationBuilder();
253 authBuilder.addUsername(server.getUsername()).addPassword(server.getPassword());
254 authBuilder.addPrivateKey(server.getPrivateKey(), server.getPassphrase());
255 authSelector.add(server.getId(), authBuilder.build());
256
257 if (server.getConfiguration() != null) {
258 XmlNode dom = server.getDelegate().getConfiguration();
259 List<XmlNode> children = dom.getChildren().stream()
260 .filter(c -> !"wagonProvider".equals(c.getName()))
261 .collect(Collectors.toList());
262 dom = new XmlNodeImpl(dom.getName(), null, null, children, null);
263 PlexusConfiguration config = XmlPlexusConfiguration.toPlexusConfiguration(dom);
264 configProps.put("aether.transport.wagon.config." + server.getId(), config);
265
266
267
268
269 Map<String, String> headers = null;
270 Integer connectTimeout = null;
271 Integer requestTimeout = null;
272
273 PlexusConfiguration httpHeaders = config.getChild("httpHeaders", false);
274 if (httpHeaders != null) {
275 PlexusConfiguration[] properties = httpHeaders.getChildren("property");
276 if (properties != null && properties.length > 0) {
277 headers = new HashMap<>();
278 for (PlexusConfiguration property : properties) {
279 headers.put(
280 property.getChild("name").getValue(),
281 property.getChild("value").getValue());
282 }
283 }
284 }
285
286 PlexusConfiguration connectTimeoutXml = config.getChild("connectTimeout", false);
287 if (connectTimeoutXml != null) {
288 connectTimeout = Integer.parseInt(connectTimeoutXml.getValue());
289 } else {
290
291 PlexusConfiguration httpConfiguration = config.getChild("httpConfiguration", false);
292 if (httpConfiguration != null) {
293 PlexusConfiguration httpConfigurationAll = httpConfiguration.getChild("all", false);
294 if (httpConfigurationAll != null) {
295 connectTimeoutXml = httpConfigurationAll.getChild("connectionTimeout", false);
296 if (connectTimeoutXml != null) {
297 connectTimeout = Integer.parseInt(connectTimeoutXml.getValue());
298 logger.warn("Settings for server {} uses legacy format", server.getId());
299 }
300 }
301 }
302 }
303
304 PlexusConfiguration requestTimeoutXml = config.getChild("requestTimeout", false);
305 if (requestTimeoutXml != null) {
306 requestTimeout = Integer.parseInt(requestTimeoutXml.getValue());
307 } else {
308
309 PlexusConfiguration httpConfiguration = config.getChild("httpConfiguration", false);
310 if (httpConfiguration != null) {
311 PlexusConfiguration httpConfigurationAll = httpConfiguration.getChild("all", false);
312 if (httpConfigurationAll != null) {
313 requestTimeoutXml = httpConfigurationAll.getChild("readTimeout", false);
314 if (requestTimeoutXml != null) {
315 requestTimeout = Integer.parseInt(requestTimeoutXml.getValue());
316 logger.warn("Settings for server {} uses legacy format", server.getId());
317 }
318 }
319 }
320 }
321
322
323 if (headers != null) {
324 configProps.put(ConfigurationProperties.HTTP_HEADERS + "." + server.getId(), headers);
325 }
326
327 if (connectTimeout != null) {
328 configProps.put(ConfigurationProperties.CONNECT_TIMEOUT + "." + server.getId(), connectTimeout);
329 }
330
331 if (requestTimeout != null) {
332 configProps.put(ConfigurationProperties.REQUEST_TIMEOUT + "." + server.getId(), requestTimeout);
333 }
334 }
335
336 configProps.put("aether.transport.wagon.perms.fileMode." + server.getId(), server.getFilePermissions());
337 configProps.put("aether.transport.wagon.perms.dirMode." + server.getId(), server.getDirectoryPermissions());
338 }
339 sessionBuilder.setAuthenticationSelector(authSelector);
340
341 Object transport =
342 mergedProps.getOrDefault(Constants.MAVEN_RESOLVER_TRANSPORT, MAVEN_RESOLVER_TRANSPORT_DEFAULT);
343 if (MAVEN_RESOLVER_TRANSPORT_DEFAULT.equals(transport)) {
344
345 } else if (MAVEN_RESOLVER_TRANSPORT_JDK.equals(transport)) {
346
347 configProps.put(FILE_TRANSPORTER_PRIORITY_KEY, RESOLVER_MAX_PRIORITY);
348 configProps.put(JDK_HTTP_TRANSPORTER_PRIORITY_KEY, RESOLVER_MAX_PRIORITY);
349 } else if (MAVEN_RESOLVER_TRANSPORT_APACHE.equals(transport)
350 || MAVEN_RESOLVER_TRANSPORT_NATIVE.equals(transport)) {
351 if (MAVEN_RESOLVER_TRANSPORT_NATIVE.equals(transport)) {
352 logger.warn(
353 "Transport name '{}' is DEPRECATED/RENAMED, use '{}' instead",
354 MAVEN_RESOLVER_TRANSPORT_NATIVE,
355 MAVEN_RESOLVER_TRANSPORT_APACHE);
356 }
357
358 configProps.put(FILE_TRANSPORTER_PRIORITY_KEY, RESOLVER_MAX_PRIORITY);
359 configProps.put(APACHE_HTTP_TRANSPORTER_PRIORITY_KEY, RESOLVER_MAX_PRIORITY);
360 } else if (MAVEN_RESOLVER_TRANSPORT_WAGON.equals(transport)) {
361
362 configProps.put(WAGON_TRANSPORTER_PRIORITY_KEY, RESOLVER_MAX_PRIORITY);
363 } else if (!MAVEN_RESOLVER_TRANSPORT_AUTO.equals(transport)) {
364 throw new IllegalArgumentException("Unknown resolver transport '" + transport
365 + "'. Supported transports are: " + MAVEN_RESOLVER_TRANSPORT_WAGON + ", "
366 + MAVEN_RESOLVER_TRANSPORT_APACHE + ", " + MAVEN_RESOLVER_TRANSPORT_JDK + ", "
367 + MAVEN_RESOLVER_TRANSPORT_AUTO);
368 }
369
370 sessionBuilder.setIgnoreArtifactDescriptorRepositories(request.isIgnoreTransitiveRepositories());
371
372 sessionBuilder.setTransferListener(request.getTransferListener());
373
374 RepositoryListener repositoryListener = eventSpyDispatcher.chainListener(new LoggingRepositoryListener(logger));
375
376 boolean recordReverseTree = Boolean.parseBoolean(
377 mergedProps.getOrDefault(Constants.MAVEN_REPO_LOCAL_RECORD_REVERSE_TREE, Boolean.FALSE.toString()));
378 if (recordReverseTree) {
379 repositoryListener = new ChainedRepositoryListener(repositoryListener, new ReverseTreeRepositoryListener());
380 }
381 sessionBuilder.setRepositoryListener(repositoryListener);
382
383
384 String resolverDependencyManagerTransitivity = mergedProps.getOrDefault(
385 Constants.MAVEN_RESOLVER_DEPENDENCY_MANAGER_TRANSITIVITY, Boolean.TRUE.toString());
386 sessionBuilder.setDependencyManager(
387 supplier.getDependencyManager(Boolean.parseBoolean(resolverDependencyManagerTransitivity)));
388
389 ArrayList<Path> paths = new ArrayList<>();
390 paths.add(Paths.get(request.getLocalRepository().getBasedir()));
391 String localRepoTail = mergedProps.get(Constants.MAVEN_REPO_LOCAL_TAIL);
392 if (localRepoTail != null) {
393 Arrays.stream(localRepoTail.split(","))
394 .filter(p -> p != null && !p.trim().isEmpty())
395 .map(Paths::get)
396 .forEach(paths::add);
397 }
398 sessionBuilder.withLocalRepositoryBaseDirectories(paths);
399
400 for (RepositorySystemSessionExtender extender : sessionExtenders.values()) {
401 extender.extend(request, configProps, mirrorSelector, proxySelector, authSelector);
402 }
403
404
405
406 HashMap<String, Object> finalConfigProperties = new HashMap<>();
407 finalConfigProperties.putAll(mergedProps);
408 finalConfigProperties.putAll(configProps);
409
410 sessionBuilder.setUserProperties(request.getUserProperties());
411 sessionBuilder.setSystemProperties(request.getSystemProperties());
412 sessionBuilder.setConfigProperties(finalConfigProperties);
413
414 return sessionBuilder;
415 }
416
417 private VersionFilter buildVersionFilter(String filterExpression) {
418 ArrayList<VersionFilter> filters = new ArrayList<>();
419 if (filterExpression != null) {
420 List<String> expressions = Arrays.stream(filterExpression.split(";"))
421 .filter(s -> s != null && !s.trim().isEmpty())
422 .toList();
423 for (String expression : expressions) {
424 if ("h".equals(expression)) {
425 filters.add(new HighestVersionFilter());
426 } else if (expression.startsWith("h(") && expression.endsWith(")")) {
427 int num = Integer.parseInt(expression.substring(2, expression.length() - 1));
428 filters.add(new HighestVersionFilter(num));
429 } else if ("l".equals(expression)) {
430 filters.add(new LowestVersionFilter());
431 } else if (expression.startsWith("l(") && expression.endsWith(")")) {
432 int num = Integer.parseInt(expression.substring(2, expression.length() - 1));
433 filters.add(new LowestVersionFilter(num));
434 } else if ("s".equals(expression)) {
435 filters.add(new ContextualSnapshotVersionFilter());
436 } else if (expression.startsWith("e(") && expression.endsWith(")")) {
437 Artifact artifact = new DefaultArtifact(expression.substring(2, expression.length() - 1));
438 VersionRange versionRange =
439 artifact.getVersion().contains(",") ? parseVersionRange(artifact.getVersion()) : null;
440 Predicate<Artifact> predicate = a -> {
441 if (artifact.getGroupId().equals(a.getGroupId())
442 && artifact.getArtifactId().equals(a.getArtifactId())) {
443 if (versionRange != null) {
444 Version v = parseVersion(a.getVersion());
445 return !versionRange.containsVersion(v);
446 } else {
447 return !artifact.getVersion().equals(a.getVersion());
448 }
449 }
450 return true;
451 };
452 filters.add(new PredicateVersionFilter(predicate));
453 } else {
454 throw new IllegalArgumentException("Unsupported filter expression: " + expression);
455 }
456 }
457 }
458 if (filters.isEmpty()) {
459 return null;
460 } else if (filters.size() == 1) {
461 return filters.get(0);
462 } else {
463 return ChainedVersionFilter.newInstance(filters);
464 }
465 }
466
467 private Version parseVersion(String spec) {
468 try {
469 return versionScheme.parseVersion(spec);
470 } catch (InvalidVersionSpecificationException e) {
471 throw new RuntimeException(e);
472 }
473 }
474
475 private VersionRange parseVersionRange(String spec) {
476 try {
477 return versionScheme.parseVersionRange(spec);
478 } catch (InvalidVersionSpecificationException e) {
479 throw new RuntimeException(e);
480 }
481 }
482
483 @SuppressWarnings({"unchecked", "rawtypes"})
484 private Map<String, String> createMergedProperties(MavenExecutionRequest request) {
485
486 Map<String, String> mergedProps = new HashMap<>();
487 mergedProps.putAll(getPropertiesFromRequestedProfiles(request));
488 mergedProps.putAll(new HashMap<String, String>((Map) request.getSystemProperties()));
489 mergedProps.putAll(new HashMap<String, String>((Map) request.getUserProperties()));
490 return mergedProps;
491 }
492
493 private Map<String, String> getPropertiesFromRequestedProfiles(MavenExecutionRequest request) {
494 HashSet<String> activeProfileId =
495 new HashSet<>(request.getProfileActivation().getRequiredActiveProfileIds());
496 activeProfileId.addAll(request.getProfileActivation().getOptionalActiveProfileIds());
497
498 return request.getProfiles().stream()
499 .filter(profile -> activeProfileId.contains(profile.getId()))
500 .map(ModelBase::getProperties)
501 .flatMap(properties -> properties.entrySet().stream())
502 .filter(e -> e.getValue() != null)
503 .collect(Collectors.toMap(
504 e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue()), (k1, k2) -> k2));
505 }
506
507 private String getUserAgent() {
508 String version = runtimeInformation.getMavenVersion();
509 version = version.isEmpty() ? version : "/" + version;
510 return "Apache-Maven" + version + " (Java " + System.getProperty("java.version") + "; "
511 + System.getProperty("os.name") + " " + System.getProperty("os.version") + ")";
512 }
513 }