1 package org.apache.archiva.checksum;
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
22 import org.apache.commons.io.FileUtils;
23 import org.apache.commons.lang.StringUtils;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.nio.file.Files;
31 import java.nio.file.StandardOpenOption;
32 import java.util.ArrayList;
33 import java.util.List;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
41 * <dt>Checksum File</dt>
42 * <dd>The file that contains the previously calculated checksum value for the reference file.
43 * This is a text file with the extension ".sha1" or ".md5", and contains a single entry
44 * consisting of an optional reference filename, and a checksum string.
46 * <dt>Reference File</dt>
47 * <dd>The file that is being referenced in the checksum file.</dd>
50 public class ChecksummedFile
52 private final Logger log = LoggerFactory.getLogger( ChecksummedFile.class );
54 private static final Pattern METADATA_PATTERN = Pattern.compile( "maven-metadata-\\S*.xml" );
56 private final File referenceFile;
59 * Construct a ChecksummedFile object.
61 * @param referenceFile
63 public ChecksummedFile( final File referenceFile )
65 this.referenceFile = referenceFile;
69 * Calculate the checksum based on a given checksum.
71 * @param checksumAlgorithm the algorithm to use.
72 * @return the checksum string for the file.
73 * @throws IOException if unable to calculate the checksum.
75 public String calculateChecksum( ChecksumAlgorithm checksumAlgorithm )
79 try (InputStream fis = Files.newInputStream( referenceFile.toPath() ))
81 Checksum checksum = new Checksum( checksumAlgorithm );
82 checksum.update( fis );
83 return checksum.getChecksum();
88 * Creates a checksum file of the provided referenceFile.
90 * @param checksumAlgorithm the hash to use.
91 * @return the checksum File that was created.
92 * @throws IOException if there was a problem either reading the referenceFile, or writing the checksum file.
94 public File createChecksum( ChecksumAlgorithm checksumAlgorithm )
97 File checksumFile = new File( referenceFile.getAbsolutePath() + "." + checksumAlgorithm.getExt() );
98 Files.deleteIfExists( checksumFile.toPath() );
99 String checksum = calculateChecksum( checksumAlgorithm );
100 Files.write( checksumFile.toPath(), //
101 ( checksum + " " + referenceFile.getName() ).getBytes(), //
102 StandardOpenOption.CREATE_NEW );
107 * Get the checksum file for the reference file and hash.
109 * @param checksumAlgorithm the hash that we are interested in.
110 * @return the checksum file to return
112 public File getChecksumFile( ChecksumAlgorithm checksumAlgorithm )
114 return new File( referenceFile.getAbsolutePath() + "." + checksumAlgorithm.getExt() );
119 * Given a checksum file, check to see if the file it represents is valid according to the checksum.
122 * NOTE: Only supports single file checksums of type MD5 or SHA1.
125 * @param algorithm the algorithms to check for.
126 * @return true if the checksum is valid for the file it represents. or if the checksum file does not exist.
127 * @throws IOException if the reading of the checksumFile or the file it refers to fails.
129 public boolean isValidChecksum( ChecksumAlgorithm algorithm )
132 return isValidChecksums( new ChecksumAlgorithm[]{ algorithm } );
136 * Of any checksum files present, validate that the reference file conforms
137 * the to the checksum.
139 * @param algorithms the algorithms to check for.
140 * @return true if the checksums report that the the reference file is valid, false if invalid.
142 public boolean isValidChecksums( ChecksumAlgorithm algorithms[] )
145 try (InputStream fis = Files.newInputStream( referenceFile.toPath() ))
147 List<Checksum> checksums = new ArrayList<>( algorithms.length );
148 // Create checksum object for each algorithm.
149 for ( ChecksumAlgorithm checksumAlgorithm : algorithms )
151 File checksumFile = getChecksumFile( checksumAlgorithm );
153 // Only add algorithm if checksum file exists.
154 if ( checksumFile.exists() )
156 checksums.add( new Checksum( checksumAlgorithm ) );
161 if ( checksums.isEmpty() )
163 // No checksum objects, no checksum files, default to is invalid.
167 // Parse file once, for all checksums.
170 Checksum.update( checksums, fis );
172 catch ( IOException e )
174 log.warn( "Unable to update checksum:{}", e.getMessage() );
178 boolean valid = true;
180 // check the checksum files
183 for ( Checksum checksum : checksums )
185 ChecksumAlgorithm checksumAlgorithm = checksum.getAlgorithm();
186 File checksumFile = getChecksumFile( checksumAlgorithm );
188 String rawChecksum = FileUtils.readFileToString( checksumFile );
189 String expectedChecksum = parseChecksum( rawChecksum, checksumAlgorithm, referenceFile.getName() );
191 if ( !StringUtils.equalsIgnoreCase( expectedChecksum, checksum.getChecksum() ) )
197 catch ( IOException e )
199 log.warn( "Unable to read / parse checksum: {}", e.getMessage() );
205 catch ( IOException e )
207 log.warn( "Unable to read / parse checksum: {}", e.getMessage() );
213 * Fix or create checksum files for the reference file.
215 * @param algorithms the hashes to check for.
216 * @return true if checksums were created successfully.
218 public boolean fixChecksums( ChecksumAlgorithm[] algorithms )
220 List<Checksum> checksums = new ArrayList<>( algorithms.length );
221 // Create checksum object for each algorithm.
222 for ( ChecksumAlgorithm checksumAlgorithm : algorithms )
224 checksums.add( new Checksum( checksumAlgorithm ) );
228 if ( checksums.isEmpty() )
230 // No checksum objects, no checksum files, default to is valid.
234 try (InputStream fis = Files.newInputStream( referenceFile.toPath() ))
236 // Parse file once, for all checksums.
237 Checksum.update( checksums, fis );
239 catch ( IOException e )
241 log.warn( e.getMessage(), e );
245 boolean valid = true;
247 // check the hash files
248 for ( Checksum checksum : checksums )
250 ChecksumAlgorithm checksumAlgorithm = checksum.getAlgorithm();
253 File checksumFile = getChecksumFile( checksumAlgorithm );
254 String actualChecksum = checksum.getChecksum();
256 if ( checksumFile.exists() )
258 String rawChecksum = FileUtils.readFileToString( checksumFile );
259 String expectedChecksum = parseChecksum( rawChecksum, checksumAlgorithm, referenceFile.getName() );
261 if ( !StringUtils.equalsIgnoreCase( expectedChecksum, actualChecksum ) )
263 // create checksum (again)
264 FileUtils.writeStringToFile( checksumFile, actualChecksum + " " + referenceFile.getName() );
269 FileUtils.writeStringToFile( checksumFile, actualChecksum + " " + referenceFile.getName() );
272 catch ( IOException e )
274 log.warn( e.getMessage(), e );
283 private boolean isValidChecksumPattern( String filename, String path )
285 // check if it is a remote metadata file
287 Matcher m = METADATA_PATTERN.matcher( path );
290 return filename.endsWith( path ) || ( "-".equals( filename ) ) || filename.endsWith( "maven-metadata.xml" );
293 return filename.endsWith( path ) || ( "-".equals( filename ) );
297 * Parse a checksum string.
299 * Validate the expected path, and expected checksum algorithm, then return
300 * the trimmed checksum hex string.
303 * @param rawChecksumString
304 * @param expectedHash
305 * @param expectedPath
307 * @throws IOException
309 public String parseChecksum( String rawChecksumString, ChecksumAlgorithm expectedHash, String expectedPath )
312 String trimmedChecksum = rawChecksumString.replace( '\n', ' ' ).trim();
314 // Free-BSD / openssl
315 String regex = expectedHash.getType() + "\\s*\\(([^)]*)\\)\\s*=\\s*([a-fA-F0-9]+)";
316 Matcher m = Pattern.compile( regex ).matcher( trimmedChecksum );
319 String filename = m.group( 1 );
320 if ( !isValidChecksumPattern( filename, expectedPath ) )
322 throw new IOException(
323 "Supplied checksum file '" + filename + "' does not match expected file: '" + expectedPath + "'" );
325 trimmedChecksum = m.group( 2 );
330 m = Pattern.compile( "([a-fA-F0-9]+)\\s+\\*?(.+)" ).matcher( trimmedChecksum );
333 String filename = m.group( 2 );
334 if ( !isValidChecksumPattern( filename, expectedPath ) )
336 throw new IOException(
337 "Supplied checksum file '" + filename + "' does not match expected file: '" + expectedPath
340 trimmedChecksum = m.group( 1 );
343 return trimmedChecksum;