001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.eclipse.aether.internal.impl.checksum;
020
021import javax.inject.Inject;
022import javax.inject.Named;
023import javax.inject.Singleton;
024
025import java.io.IOException;
026import java.io.UncheckedIOException;
027import java.nio.file.Files;
028import java.nio.file.Path;
029import java.util.HashMap;
030import java.util.List;
031import java.util.Map;
032
033import org.eclipse.aether.RepositorySystemSession;
034import org.eclipse.aether.artifact.Artifact;
035import org.eclipse.aether.internal.impl.LocalPathComposer;
036import org.eclipse.aether.repository.ArtifactRepository;
037import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmFactory;
038import org.eclipse.aether.spi.io.FileProcessor;
039import org.eclipse.aether.util.ConfigUtils;
040import org.slf4j.Logger;
041import org.slf4j.LoggerFactory;
042
043import static java.util.Objects.requireNonNull;
044
045/**
046 * Sparse file {@link FileTrustedChecksumsSourceSupport} implementation that use specified directory as base
047 * directory, where it expects artifacts checksums on standard Maven2 "local" layout. This implementation uses Artifact
048 * coordinates solely to form path from basedir, pretty much as Maven local repository does.
049 * <p>
050 * The source by default is "origin aware", it will factor in origin repository ID as well into base directory name
051 * (for example ".checksums/central/...").
052 * <p>
053 * The checksums files are directly loaded from disk, so in-flight file changes during lifecycle of session are picked
054 * up. This implementation can be simultaneously used to lookup and also write checksums. The written checksums
055 * will become visible across all sessions right after the moment they were written.
056 * <p>
057 * The name of this implementation is "sparseDirectory".
058 *
059 * @see LocalPathComposer
060 * @since 1.9.0
061 */
062@Singleton
063@Named(SparseDirectoryTrustedChecksumsSource.NAME)
064public final class SparseDirectoryTrustedChecksumsSource extends FileTrustedChecksumsSourceSupport {
065    public static final String NAME = "sparseDirectory";
066
067    private static final String CONFIG_PROPS_PREFIX =
068            FileTrustedChecksumsSourceSupport.CONFIG_PROPS_PREFIX + NAME + ".";
069
070    /**
071     * Is checksum source enabled?
072     *
073     * @configurationSource {@link RepositorySystemSession#getConfigProperties()}
074     * @configurationType {@link java.lang.Boolean}
075     * @configurationDefaultValue false
076     */
077    public static final String CONFIG_PROP_ENABLED = FileTrustedChecksumsSourceSupport.CONFIG_PROPS_PREFIX + NAME;
078
079    /**
080     * The basedir where checksums are. If relative, is resolved from local repository root.
081     *
082     * @configurationSource {@link RepositorySystemSession#getConfigProperties()}
083     * @configurationType {@link java.lang.String}
084     * @configurationDefaultValue {@link #LOCAL_REPO_PREFIX_DIR}
085     */
086    public static final String CONFIG_PROP_BASEDIR = CONFIG_PROPS_PREFIX + "basedir";
087
088    public static final String LOCAL_REPO_PREFIX_DIR = ".checksums";
089
090    /**
091     * Is source origin aware?
092     *
093     * @configurationSource {@link RepositorySystemSession#getConfigProperties()}
094     * @configurationType {@link java.lang.Boolean}
095     * @configurationDefaultValue true
096     */
097    public static final String CONFIG_PROP_ORIGIN_AWARE = CONFIG_PROPS_PREFIX + "originAware";
098
099    private static final Logger LOGGER = LoggerFactory.getLogger(SparseDirectoryTrustedChecksumsSource.class);
100
101    private final FileProcessor fileProcessor;
102
103    private final LocalPathComposer localPathComposer;
104
105    @Inject
106    public SparseDirectoryTrustedChecksumsSource(FileProcessor fileProcessor, LocalPathComposer localPathComposer) {
107        this.fileProcessor = requireNonNull(fileProcessor);
108        this.localPathComposer = requireNonNull(localPathComposer);
109    }
110
111    @Override
112    protected boolean isEnabled(RepositorySystemSession session) {
113        return ConfigUtils.getBoolean(session, false, CONFIG_PROP_ENABLED);
114    }
115
116    private boolean isOriginAware(RepositorySystemSession session) {
117        return ConfigUtils.getBoolean(session, true, CONFIG_PROP_ORIGIN_AWARE);
118    }
119
120    @Override
121    protected Map<String, String> doGetTrustedArtifactChecksums(
122            RepositorySystemSession session,
123            Artifact artifact,
124            ArtifactRepository artifactRepository,
125            List<ChecksumAlgorithmFactory> checksumAlgorithmFactories) {
126        final boolean originAware = isOriginAware(session);
127        final HashMap<String, String> checksums = new HashMap<>();
128        Path basedir = getBasedir(session, LOCAL_REPO_PREFIX_DIR, CONFIG_PROP_BASEDIR, false);
129        if (Files.isDirectory(basedir)) {
130            for (ChecksumAlgorithmFactory checksumAlgorithmFactory : checksumAlgorithmFactories) {
131                Path checksumPath = basedir.resolve(
132                        calculateArtifactPath(originAware, artifact, artifactRepository, checksumAlgorithmFactory));
133
134                if (!Files.isRegularFile(checksumPath)) {
135                    LOGGER.debug(
136                            "Artifact '{}' trusted checksum '{}' not found on path '{}'",
137                            artifact,
138                            checksumAlgorithmFactory.getName(),
139                            checksumPath);
140                    continue;
141                }
142
143                try {
144                    String checksum = fileProcessor.readChecksum(checksumPath.toFile());
145                    if (checksum != null) {
146                        checksums.put(checksumAlgorithmFactory.getName(), checksum);
147                    }
148                } catch (IOException e) {
149                    // unexpected, log
150                    LOGGER.warn(
151                            "Could not read artifact '{}' trusted checksum on path '{}'", artifact, checksumPath, e);
152                    throw new UncheckedIOException(e);
153                }
154            }
155        }
156        return checksums;
157    }
158
159    @Override
160    protected Writer doGetTrustedArtifactChecksumsWriter(RepositorySystemSession session) {
161        return new SparseDirectoryWriter(
162                getBasedir(session, LOCAL_REPO_PREFIX_DIR, CONFIG_PROP_BASEDIR, true), isOriginAware(session));
163    }
164
165    private String calculateArtifactPath(
166            boolean originAware,
167            Artifact artifact,
168            ArtifactRepository artifactRepository,
169            ChecksumAlgorithmFactory checksumAlgorithmFactory) {
170        String path = localPathComposer.getPathForArtifact(artifact, false) + "."
171                + checksumAlgorithmFactory.getFileExtension();
172        if (originAware) {
173            path = artifactRepository.getId() + "/" + path;
174        }
175        return path;
176    }
177
178    private class SparseDirectoryWriter implements Writer {
179        private final Path basedir;
180
181        private final boolean originAware;
182
183        private SparseDirectoryWriter(Path basedir, boolean originAware) {
184            this.basedir = basedir;
185            this.originAware = originAware;
186        }
187
188        @Override
189        public void addTrustedArtifactChecksums(
190                Artifact artifact,
191                ArtifactRepository artifactRepository,
192                List<ChecksumAlgorithmFactory> checksumAlgorithmFactories,
193                Map<String, String> trustedArtifactChecksums)
194                throws IOException {
195            for (ChecksumAlgorithmFactory checksumAlgorithmFactory : checksumAlgorithmFactories) {
196                Path checksumPath = basedir.resolve(
197                        calculateArtifactPath(originAware, artifact, artifactRepository, checksumAlgorithmFactory));
198                String checksum = requireNonNull(trustedArtifactChecksums.get(checksumAlgorithmFactory.getName()));
199                fileProcessor.writeChecksum(checksumPath.toFile(), checksum);
200            }
201        }
202    }
203}