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.FileInputStream;
29 import java.io.IOException;
30 import java.util.ArrayList;
31 import java.util.List;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
40 * <dt>Checksum File</dt>
41 * <dd>The file that contains the previously calculated checksum value for the reference file.
42 * This is a text file with the extension ".sha1" or ".md5", and contains a single entry
43 * consisting of an optional reference filename, and a checksum string.
45 * <dt>Reference File</dt>
46 * <dd>The file that is being referenced in the checksum file.</dd>
51 public class ChecksummedFile
53 private Logger log = LoggerFactory.getLogger( ChecksummedFile.class );
55 private final File referenceFile;
58 * Construct a ChecksummedFile object.
60 * @param referenceFile
62 public ChecksummedFile( final File referenceFile )
64 this.referenceFile = referenceFile;
68 * Calculate the checksum based on a given checksum.
70 * @param checksumAlgorithm the algorithm to use.
71 * @return the checksum string for the file.
72 * @throws IOException if unable to calculate the checksum.
74 public String calculateChecksum( ChecksumAlgorithm checksumAlgorithm )
78 try (FileInputStream fis = new FileInputStream( referenceFile ))
80 Checksum checksum = new Checksum( checksumAlgorithm );
81 checksum.update( fis );
82 return checksum.getChecksum();
87 * Creates a checksum file of the provided referenceFile.
89 * @param checksumAlgorithm the hash to use.
90 * @return the checksum File that was created.
91 * @throws IOException if there was a problem either reading the referenceFile, or writing the checksum file.
93 public File createChecksum( ChecksumAlgorithm checksumAlgorithm )
96 File checksumFile = new File( referenceFile.getAbsolutePath() + "." + checksumAlgorithm.getExt() );
97 String checksum = calculateChecksum( checksumAlgorithm );
98 FileUtils.writeStringToFile( checksumFile, checksum + " " + referenceFile.getName() );
103 * Get the checksum file for the reference file and hash.
105 * @param checksumAlgorithm the hash that we are interested in.
106 * @return the checksum file to return
108 public File getChecksumFile( ChecksumAlgorithm checksumAlgorithm )
110 return new File( referenceFile.getAbsolutePath() + "." + checksumAlgorithm.getExt() );
115 * Given a checksum file, check to see if the file it represents is valid according to the checksum.
119 * NOTE: Only supports single file checksums of type MD5 or SHA1.
122 * @param algorithm the algorithms to check for.
123 * @return true if the checksum is valid for the file it represents. or if the checksum file does not exist.
124 * @throws IOException if the reading of the checksumFile or the file it refers to fails.
126 public boolean isValidChecksum( ChecksumAlgorithm algorithm )
129 return isValidChecksums( new ChecksumAlgorithm[]{ algorithm } );
133 * Of any checksum files present, validate that the reference file conforms
134 * the to the checksum.
136 * @param algorithms the algorithms to check for.
137 * @return true if the checksums report that the the reference file is valid, false if invalid.
139 public boolean isValidChecksums( ChecksumAlgorithm algorithms[] )
142 try (FileInputStream fis = new FileInputStream( referenceFile ))
144 List<Checksum> checksums = new ArrayList<>( algorithms.length );
145 // Create checksum object for each algorithm.
146 for ( ChecksumAlgorithm checksumAlgorithm : algorithms )
148 File checksumFile = getChecksumFile( checksumAlgorithm );
150 // Only add algorithm if checksum file exists.
151 if ( checksumFile.exists() )
153 checksums.add( new Checksum( checksumAlgorithm ) );
158 if ( checksums.isEmpty() )
160 // No checksum objects, no checksum files, default to is invalid.
164 // Parse file once, for all checksums.
167 Checksum.update( checksums, fis );
169 catch ( IOException e )
171 log.warn( "Unable to update checksum:{}", e.getMessage() );
175 boolean valid = true;
177 // check the checksum files
180 for ( Checksum checksum : checksums )
182 ChecksumAlgorithm checksumAlgorithm = checksum.getAlgorithm();
183 File checksumFile = getChecksumFile( checksumAlgorithm );
185 String rawChecksum = FileUtils.readFileToString( checksumFile );
186 String expectedChecksum = parseChecksum( rawChecksum, checksumAlgorithm, referenceFile.getName() );
188 if ( !StringUtils.equalsIgnoreCase( expectedChecksum, checksum.getChecksum() ) )
194 catch ( IOException e )
196 log.warn( "Unable to read / parse checksum: {}", e.getMessage() );
201 } catch ( IOException e )
203 log.warn( "Unable to read / parse checksum: {}", e.getMessage() );
209 * Fix or create checksum files for the reference file.
211 * @param algorithms the hashes to check for.
212 * @return true if checksums were created successfully.
214 public boolean fixChecksums( ChecksumAlgorithm[] algorithms )
216 List<Checksum> checksums = new ArrayList<>( algorithms.length );
217 // Create checksum object for each algorithm.
218 for ( ChecksumAlgorithm checksumAlgorithm : algorithms )
220 checksums.add( new Checksum( checksumAlgorithm ) );
224 if ( checksums.isEmpty() )
226 // No checksum objects, no checksum files, default to is valid.
231 try (FileInputStream fis = new FileInputStream( referenceFile ))
233 // Parse file once, for all checksums.
234 Checksum.update( checksums, fis );
236 catch ( IOException e )
238 log.warn( e.getMessage(), e );
242 boolean valid = true;
244 // check the hash files
245 for ( Checksum checksum : checksums )
247 ChecksumAlgorithm checksumAlgorithm = checksum.getAlgorithm();
250 File checksumFile = getChecksumFile( checksumAlgorithm );
251 String actualChecksum = checksum.getChecksum();
253 if ( checksumFile.exists() )
255 String rawChecksum = FileUtils.readFileToString( checksumFile );
256 String expectedChecksum = parseChecksum( rawChecksum, checksumAlgorithm, referenceFile.getName() );
258 if ( !StringUtils.equalsIgnoreCase( expectedChecksum, actualChecksum ) )
260 // create checksum (again)
261 FileUtils.writeStringToFile( checksumFile, actualChecksum + " " + referenceFile.getName() );
266 FileUtils.writeStringToFile( checksumFile, actualChecksum + " " + referenceFile.getName() );
269 catch ( IOException e )
271 log.warn( e.getMessage(), e );
280 private boolean isValidChecksumPattern( String filename, String path )
282 // check if it is a remote metadata file
283 Pattern pattern = Pattern.compile( "maven-metadata-\\S*.xml" );
284 Matcher m = pattern.matcher( path );
287 return filename.endsWith( path ) || ( "-".equals( filename ) ) || filename.endsWith( "maven-metadata.xml" );
290 return filename.endsWith( path ) || ( "-".equals( filename ) );
294 * Parse a checksum string.
296 * Validate the expected path, and expected checksum algorithm, then return
297 * the trimmed checksum hex string.
299 * @param rawChecksumString
300 * @param expectedHash
301 * @param expectedPath
303 * @throws IOException
305 public String parseChecksum( String rawChecksumString, ChecksumAlgorithm expectedHash, String expectedPath )
308 String trimmedChecksum = rawChecksumString.replace( '\n', ' ' ).trim();
310 // Free-BSD / openssl
311 String regex = expectedHash.getType() + "\\s*\\(([^)]*)\\)\\s*=\\s*([a-fA-F0-9]+)";
312 Matcher m = Pattern.compile( regex ).matcher( trimmedChecksum );
315 String filename = m.group( 1 );
316 if ( !isValidChecksumPattern( filename, expectedPath ) )
318 throw new IOException(
319 "Supplied checksum file '" + filename + "' does not match expected file: '" + expectedPath + "'" );
321 trimmedChecksum = m.group( 2 );
326 m = Pattern.compile( "([a-fA-F0-9]+)\\s+\\*?(.+)" ).matcher( trimmedChecksum );
329 String filename = m.group( 2 );
330 if ( !isValidChecksumPattern( filename, expectedPath ) )
332 throw new IOException(
333 "Supplied checksum file '" + filename + "' does not match expected file: '" + expectedPath
336 trimmedChecksum = m.group( 1 );
339 return trimmedChecksum;