1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19 package org.eclipse.aether.internal.impl;
20
21 import java.io.IOException;
22 import java.nio.file.Files;
23 import java.nio.file.Path;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.Map;
29 import java.util.Objects;
30 import java.util.Properties;
31 import java.util.concurrent.ConcurrentHashMap;
32 import java.util.regex.Pattern;
33
34 import org.eclipse.aether.RepositorySystemSession;
35 import org.eclipse.aether.artifact.Artifact;
36 import org.eclipse.aether.metadata.Metadata;
37 import org.eclipse.aether.repository.LocalArtifactRegistration;
38 import org.eclipse.aether.repository.LocalArtifactRequest;
39 import org.eclipse.aether.repository.LocalArtifactResult;
40 import org.eclipse.aether.repository.RemoteRepository;
41 import org.eclipse.aether.repository.RepositoryKeyFunction;
42 import org.eclipse.aether.util.ConfigUtils;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 import static java.util.Objects.requireNonNull;
47
48 /**
49 * These are implementation details for enhanced local repository manager, subject to change without prior notice.
50 * Repositories from which a cached artifact was resolved are tracked in a properties file named
51 * <code>_remote.repositories</code>, with content key as filename>repo_id and value as empty string. If a file has
52 * been installed in the repository, but not downloaded from a remote repository, it is tracked as empty repository id
53 * and always resolved. For example:
54 *
55 * <pre>
56 * artifact-1.0.pom>=
57 * artifact-1.0.jar>=
58 * artifact-1.0.pom>central=
59 * artifact-1.0.jar>central=
60 * artifact-1.0.zip>central=
61 * artifact-1.0-classifier.zip>central=
62 * artifact-1.0.pom>my_repo_id=
63 * </pre>
64 *
65 * The repository id component of a tracking key is produced by the tracking-scoped repository key function, which
66 * is URL-qualified by default: two repositories that merely share an id but point at different URLs are tracked as
67 * different origins (see
68 * {@link org.eclipse.aether.ConfigurationProperties#REPOSITORY_TRACKING_REPOSITORY_KEY_FUNCTION}). This does not hold
69 * unconditionally when {@link EnhancedLocalRepositoryManagerFactory#CONFIG_PROP_LEGACY_LOCAL_REPOSITORY} is enabled
70 * (the default): for backward compatibility with Maven 3.9 and older, a same-id fallback then also accepts an
71 * artifact tracked under a different URL as long as the repository id matches (see {@link #applyTracking}).
72 *
73 * @see EnhancedLocalRepositoryManagerFactory
74 */
75 class EnhancedLocalRepositoryManager extends SimpleLocalRepositoryManager {
76
77 private static final Logger LOGGER = LoggerFactory.getLogger(EnhancedLocalRepositoryManager.class);
78
79 private static final String LOCAL_REPO_ID = "";
80
81 private static final Pattern SHA1_HEX = Pattern.compile("[0-9a-f]{40}");
82
83 /**
84 * Shared sentinel for "no tracking data". Mutation is forbidden: the instance is shared
85 * across threads via {@link #trackingFileCache} and returned directly from {@link #readRepos}.
86 */
87 private static final Properties EMPTY_PROPERTIES = new Properties() {
88 @Override
89 public synchronized Object put(Object key, Object value) {
90 throw new UnsupportedOperationException("EMPTY_PROPERTIES is read-only");
91 }
92
93 @Override
94 public synchronized Object remove(Object key) {
95 throw new UnsupportedOperationException("EMPTY_PROPERTIES is read-only");
96 }
97
98 @Override
99 public synchronized void clear() {
100 throw new UnsupportedOperationException("EMPTY_PROPERTIES is read-only");
101 }
102 };
103
104 private final String trackingFilename;
105
106 private final boolean legacyLocalRepository;
107
108 private final TrackingFileManager trackingFileManager;
109
110 private final LocalPathPrefixComposer localPathPrefixComposer;
111
112 /**
113 * Repository key function used solely for the provenance tracking entries (the repository component of the
114 * keys in the tracking file); path composition keeps using the (system-wide) key function held by the
115 * superclass. URL-qualified by default, so two repositories merely sharing an id are not treated as the same
116 * origin - see {@link org.eclipse.aether.ConfigurationProperties#REPOSITORY_TRACKING_REPOSITORY_KEY_FUNCTION}.
117 * Lookups of entries written under a different key function miss and fail safe: the artifact stays tracked
118 * (so the untracked inter-op fallback in {@link #checkFind} does not accept it) but unavailable, forcing a
119 * checksum-validated re-fetch.
120 */
121 private final RepositoryKeyFunction trackingRepositoryKeyFunction;
122
123 /**
124 * Cache of tracking file contents, keyed by tracking file path. Eliminates redundant disk I/O
125 * when multiple artifacts in the same directory are resolved — they all share the same
126 * {@code _remote.repositories} tracking file. Invalidated on writes via {@link #addRepo}.
127 * <p>
128 * Cached {@link Properties} instances are shared across threads and must be treated as
129 * read-only by callers of {@link #readRepos}. The cache is scoped to this manager instance
130 * (one per session), so concurrent builds in separate JVMs each maintain independent caches.
131 * If another process updates a tracking file after it has been cached here, a stale entry is
132 * NOT always harmless: for a tracked artifact it merely causes a redundant download, but in the
133 * untracked inter-op branch of {@link #checkFind} staleness would be trust-increasing (the file
134 * would be accepted as locally installed although its recorded origin says otherwise). That
135 * branch therefore re-reads the tracking file from disk before accepting, see
136 * {@link #readReposFresh}.
137 */
138 private final ConcurrentHashMap<Path, Properties> trackingFileCache = new ConcurrentHashMap<>();
139
140 EnhancedLocalRepositoryManager(
141 Path basedir,
142 LocalPathComposer localPathComposer,
143 RepositoryKeyFunction trackingRepositoryKeyFunction,
144 String trackingFilename,
145 boolean legacyLocalRepository,
146 TrackingFileManager trackingFileManager,
147 LocalPathPrefixComposer localPathPrefixComposer) {
148 super(basedir, "enhanced", localPathComposer);
149 this.trackingRepositoryKeyFunction = requireNonNull(trackingRepositoryKeyFunction);
150 this.trackingFilename = requireNonNull(trackingFilename);
151 this.legacyLocalRepository = legacyLocalRepository;
152 this.trackingFileManager = requireNonNull(trackingFileManager);
153 this.localPathPrefixComposer = requireNonNull(localPathPrefixComposer);
154 }
155
156 private String concatPaths(String prefix, String artifactPath) {
157 if (prefix == null || prefix.isEmpty()) {
158 return artifactPath;
159 }
160 return prefix + '/' + artifactPath;
161 }
162
163 @Deprecated
164 @Override
165 public String getPathForLocalArtifact(Artifact artifact) {
166 return concatPaths(
167 localPathPrefixComposer.getPathPrefixForLocalArtifact(artifact),
168 super.getPathForLocalArtifact(artifact));
169 }
170
171 @Deprecated
172 @Override
173 public String getPathForRemoteArtifact(Artifact artifact, RemoteRepository repository, String context) {
174 return concatPaths(
175 localPathPrefixComposer.getPathPrefixForRemoteArtifact(artifact, repository),
176 super.getPathForRemoteArtifact(artifact, repository, context));
177 }
178
179 @Deprecated
180 @Override
181 public String getPathForLocalMetadata(Metadata metadata) {
182 return concatPaths(
183 localPathPrefixComposer.getPathPrefixForLocalMetadata(metadata),
184 super.getPathForLocalMetadata(metadata));
185 }
186
187 @Deprecated
188 @Override
189 public String getPathForRemoteMetadata(Metadata metadata, RemoteRepository repository, String context) {
190 requireNonNull(metadata, "metadata cannot be null");
191 requireNonNull(repository, "repository cannot be null");
192 if (legacyLocalRepository) {
193 return concatPaths(
194 localPathPrefixComposer.getPathPrefixForRemoteMetadata(metadata, repository),
195 super.getPathForRemoteMetadata(metadata, repository, context));
196 } else {
197 return concatPaths(
198 localPathPrefixComposer.getPathPrefixForRemoteMetadata(metadata, repository),
199 localPathComposer.getPathForMetadata(metadata, getTrackingRepositoryKey(repository, context)));
200 }
201 }
202
203 @Override
204 public LocalArtifactResult find(RepositorySystemSession session, LocalArtifactRequest request) {
205 Artifact artifact = request.getArtifact();
206 LocalArtifactResult result = new LocalArtifactResult(request);
207
208 boolean verifyRealPath = ConfigUtils.getBoolean(
209 session,
210 EnhancedLocalRepositoryManagerFactory.DEFAULT_VERIFY_REAL_PATH,
211 EnhancedLocalRepositoryManagerFactory.CONFIG_PROP_VERIFY_REAL_PATH);
212
213 Path filePath;
214
215 // Local repository CANNOT have timestamped installed, they are created only during deploy
216 if (Objects.equals(artifact.getVersion(), artifact.getBaseVersion())) {
217 filePath = getAbsolutePathForLocalArtifact(artifact);
218 checkFind(
219 getPrefixDirectory(localPathPrefixComposer.getPathPrefixForLocalArtifact(artifact)),
220 filePath,
221 result,
222 verifyRealPath);
223 }
224
225 if (!result.isAvailable()) {
226 for (RemoteRepository repository : request.getRepositories()) {
227 filePath = getAbsolutePathForRemoteArtifact(artifact, repository, request.getContext());
228
229 checkFind(
230 getPrefixDirectory(
231 localPathPrefixComposer.getPathPrefixForRemoteArtifact(artifact, repository)),
232 filePath,
233 result,
234 verifyRealPath);
235
236 if (result.isAvailable()) {
237 break;
238 }
239 }
240 }
241
242 return result;
243 }
244
245 private Path getPrefixDirectory(String prefix) {
246 Path basePath = getRepository().getBasePath();
247 return prefix == null || prefix.isEmpty() ? basePath : basePath.resolve(prefix);
248 }
249
250 /**
251 * Verifies that the real (on-disk) spelling of the given artifact path matches the requested spelling,
252 * relative to the directory of its local path prefix. On case-insensitive or normalization-preserving
253 * filesystems (the macOS and Windows defaults) a cached file whose stored name differs from the requested one
254 * - for example one cached for case-colliding coordinates - still passes the file-existence check, while the
255 * tracking data in the tracking file is compared exactly: the aliased file would then be treated as
256 * present-but-untracked and accepted with no download and no checksum verification. Such aliases are treated
257 * as "not present" instead (fail closed), forcing a proper download for the requested coordinates. Only the
258 * coordinate-derived part of the path is compared, as a suffix of the real path: the base directory and the
259 * prefix directories are configuration, not coordinates, so they may be symbolic links - see
260 * {@link EnhancedLocalRepositoryManagerFactory#CONFIG_PROP_VERIFY_REAL_PATH} to opt out.
261 */
262 private boolean hasFaithfulRealPath(Path prefixDirectory, Path path) {
263 try {
264 String requested = prefixDirectory.relativize(path).toString();
265 String real = path.toRealPath().toString();
266 // compare strings: Path comparison ignores case on Windows
267 if (!real.endsWith(path.getFileSystem().getSeparator() + requested)) {
268 LOGGER.warn(
269 "Rejecting locally cached artifact {}: its on-disk path {} does not match the requested"
270 + " coordinates (filesystem case/normalization alias); treating it as not present",
271 path,
272 real);
273 return false;
274 }
275 return true;
276 } catch (IOException | IllegalArgumentException e) {
277 // the real identity of the file cannot be established: fail closed, forcing a re-download
278 return false;
279 }
280 }
281
282 private void checkFind(Path prefixDirectory, Path path, LocalArtifactResult result, boolean verifyRealPath) {
283 if (Files.isRegularFile(path) && (!verifyRealPath || hasFaithfulRealPath(prefixDirectory, path))) {
284 result.setPath(path);
285
286 Properties props = readRepos(path);
287
288 if (!applyTracking(path, result, props) && !isTracked(props, path)) {
289 /*
290 * The (possibly cached) state claims the artifact is untracked, and the untracked inter-op
291 * branch below is trust-increasing: it accepts the file as locally installed. That decision
292 * must never rest on tracking state that may be older than the file it judges (another process
293 * sharing this local repository may have recorded the true origin of the file after our cache
294 * entry was populated), so re-read the tracking file from disk before concluding untracked.
295 */
296 props = readReposFresh(path);
297 if (!applyTracking(path, result, props) && !isTracked(props, path)) {
298 /*
299 * NOTE: The artifact is present but not tracked at all, for inter-op with simple local repo, assume
300 * the artifact was locally installed.
301 */
302 result.setAvailable(true);
303 }
304 }
305 }
306 }
307
308 /**
309 * Applies the tracking-state based acceptance rules to given result: an artifact installed into the local
310 * repository is always accepted, an artifact downloaded from a remote repository is accepted only if
311 * downloaded from one of the request repositories.
312 *
313 * @return {@code true} if the result was made available, {@code false} otherwise.
314 */
315 private boolean applyTracking(Path path, LocalArtifactResult result, Properties props) {
316 if (props.get(getKey(path, LOCAL_REPO_ID)) != null) {
317 // artifact installed into the local repo is always accepted
318 result.setAvailable(true);
319 return true;
320 }
321 String context = result.getRequest().getContext();
322 for (RemoteRepository repository : result.getRequest().getRepositories()) {
323 String trackingKey = getTrackingRepositoryKey(repository, context);
324 if (props.get(getKey(path, trackingKey)) != null) {
325 // artifact downloaded from remote repository is accepted only downloaded from request
326 // repositories
327 result.setAvailable(true);
328 result.setRepository(repository);
329 return true;
330 }
331 if (legacyLocalRepository) {
332 // Backward compatibility fallback: if the tracking key function is URL-qualified (e.g. nid_hurl)
333 // but the tracking file was written by an older resolver using the system-wide key function
334 // (e.g. nid, producing ID-only entries like "artifact>central="), the URL-qualified lookup above
335 // misses. Try the system-wide key function as a fallback: if it matches, the artifact was genuinely
336 // downloaded from this repository under the old key scheme. Accept it and log a migration notice.
337 String legacyKey = simpleRepositoryKeyFunction.apply(repository, context);
338 if (!legacyKey.equals(trackingKey) && props.get(getKey(path, legacyKey)) != null) {
339 LOGGER.debug(
340 "Accepting locally cached artifact {} via legacy tracking key '{}'"
341 + " (current key function would produce '{}'); the entry will be"
342 + " upgraded on next download",
343 path.getFileName(),
344 legacyKey,
345 trackingKey);
346 result.setAvailable(true);
347 result.setRepository(repository);
348 return true;
349 }
350 // Same-ID-different-URL fallback: if the tracking file contains a URL-qualified entry for the
351 // same repository ID but with a different URL hash (e.g. real Central tracked as
352 // "central-<sha1(realUrl)>=" but the current build overrides central to "file:target/null"),
353 // the exact lookup misses because sha1(realUrl) != sha1(file:target/null). Match by repo-ID
354 // prefix: any entry starting with "filename>repoId-" is accepted as originating from the same
355 // logical repository. The remainder must be exactly one SHA-1 hash, otherwise a different repository
356 // whose ID merely starts with "repoId-" (e.g. "central-snapshots") would be accepted as well.
357 String repoIdPrefix = getKey(path, legacyKey + "-");
358 for (Object key : props.keySet()) {
359 String k = key.toString();
360 if (k.startsWith(repoIdPrefix) && isSha1(k.substring(repoIdPrefix.length()))) {
361 LOGGER.debug(
362 "Accepting locally cached artifact {} via same-id tracking entry '{}'"
363 + " (current URL-qualified key would be '{}')",
364 path.getFileName(),
365 k,
366 getKey(path, trackingKey));
367 result.setAvailable(true);
368 result.setRepository(repository);
369 return true;
370 }
371 }
372 }
373 }
374 return false;
375 }
376
377 private static boolean isSha1(String s) {
378 return SHA1_HEX.matcher(s).matches();
379 }
380
381 @Override
382 public void add(RepositorySystemSession session, LocalArtifactRegistration request) {
383 Collection<String> repositories;
384 // no contexts would record nothing, leaving the artifact untracked, hence later accepted as locally installed
385 Collection<String> contexts =
386 request.getContexts().isEmpty() ? Collections.singleton("") : request.getContexts();
387 if (request.getRepository() == null) {
388 repositories = Collections.singleton(LOCAL_REPO_ID);
389 } else {
390 repositories = getRepositoryKeys(request.getRepository(), contexts);
391 }
392 if (request.getRepository() == null) {
393 addArtifact(request.getArtifact(), repositories, null, null);
394 } else {
395 for (String context : contexts) {
396 addArtifact(request.getArtifact(), repositories, request.getRepository(), context);
397 }
398 }
399 }
400
401 private Collection<String> getRepositoryKeys(RemoteRepository repository, Collection<String> contexts) {
402 Collection<String> keys = new HashSet<>();
403
404 if (contexts != null) {
405 for (String context : contexts) {
406 keys.add(getTrackingRepositoryKey(repository, context));
407 }
408 }
409
410 return keys;
411 }
412
413 private void addArtifact(
414 Artifact artifact, Collection<String> repositories, RemoteRepository repository, String context) {
415 requireNonNull(artifact, "artifact cannot be null");
416 Path file = repository == null
417 ? getAbsolutePathForLocalArtifact(artifact)
418 : getAbsolutePathForRemoteArtifact(artifact, repository, context);
419 addRepo(file, repositories);
420 }
421
422 private Properties readRepos(Path artifactPath) {
423 Path trackingFile = getTrackingFile(artifactPath);
424 return trackingFileCache.computeIfAbsent(trackingFile, tf -> {
425 Properties props = trackingFileManager.read(tf);
426 return (props != null) ? props : EMPTY_PROPERTIES;
427 });
428 }
429
430 /**
431 * Reads the tracking file for given artifact directly from disk, bypassing (and deliberately not populating)
432 * {@link #trackingFileCache}: callers use the result for a trust-increasing decision, which must not be taken
433 * on — nor allowed to re-cache — possibly stale state.
434 */
435 private Properties readReposFresh(Path artifactPath) {
436 Properties props = trackingFileManager.read(getTrackingFile(artifactPath));
437 return (props != null) ? props : EMPTY_PROPERTIES;
438 }
439
440 private void addRepo(Path artifactPath, Collection<String> repositories) {
441 Map<String, String> updates = new HashMap<>();
442 for (String repository : repositories) {
443 updates.put(getKey(artifactPath, repository), "");
444 }
445
446 Path trackingPath = getTrackingFile(artifactPath);
447
448 // Invalidate cache before AND after the write. Before: using put() with the returned Properties
449 // would be racy — two concurrent addRepo() calls could reorder their puts, leaving stale data.
450 // After: a reader may re-populate the cache with the pre-write contents between the first
451 // invalidation and the write completing; without a post-write invalidation that stale entry —
452 // which is trust-affecting, see checkFind — would survive for the whole session.
453 trackingFileCache.remove(trackingPath);
454 try {
455 trackingFileManager.update(trackingPath, updates);
456 } finally {
457 trackingFileCache.remove(trackingPath);
458 }
459 }
460
461 private Path getTrackingFile(Path artifactPath) {
462 return artifactPath.getParent().resolve(trackingFilename);
463 }
464
465 private String getKey(Path path, String repository) {
466 return path.getFileName() + ">" + repository;
467 }
468
469 /**
470 * Returns the tracking key of given repository, derived with the tracking-scoped key function (URL-qualified
471 * by default). Deliberately distinct from {@link #simpleRepositoryKeyFunction}, which follows
472 * the Maven 3.9 (Resolver 1.x) key function and is used for path composition: tracking must bind an artifact to the full
473 * identity of its origin, while on-disk layout and repository aggregation identity stay unchanged.
474 */
475 private String getTrackingRepositoryKey(RemoteRepository repository, String context) {
476 return trackingRepositoryKeyFunction.apply(repository, context);
477 }
478
479 private boolean isTracked(Properties props, Path path) {
480 if (props != null) {
481 String keyPrefix = path.getFileName() + ">";
482 for (Object key : props.keySet()) {
483 if (key.toString().startsWith(keyPrefix)) {
484 return true;
485 }
486 }
487 }
488 return false;
489 }
490 }