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.io.InputStream;
31 import java.nio.file.Files;
32 import java.util.ArrayList;
33 import java.util.List;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
42 * <dt>Checksum File</dt>
43 * <dd>The file that contains the previously calculated checksum value for the reference file.
44 * This is a text file with the extension ".sha1" or ".md5", and contains a single entry
45 * consisting of an optional reference filename, and a checksum string.
47 * <dt>Reference File</dt>
48 * <dd>The file that is being referenced in the checksum file.</dd>
53 public class ChecksummedFile
55 private Logger log = LoggerFactory.getLogger( ChecksummedFile.class );
57 private final File referenceFile;
60 * Construct a ChecksummedFile object.
62 * @param referenceFile
64 public ChecksummedFile( final File referenceFile )
66 this.referenceFile = referenceFile;
70 * Calculate the checksum based on a given checksum.
72 * @param checksumAlgorithm the algorithm to use.
73 * @return the checksum string for the file.
74 * @throws IOException if unable to calculate the checksum.
76 public String calculateChecksum( ChecksumAlgorithm checksumAlgorithm )
80 try (InputStream fis = Files.newInputStream( referenceFile.toPath() ) )
82 Checksum checksum = new Checksum( checksumAlgorithm );
83 checksum.update( fis );
84 return checksum.getChecksum();
89 * Creates a checksum file of the provided referenceFile.
91 * @param checksumAlgorithm the hash to use.
92 * @return the checksum File that was created.
93 * @throws IOException if there was a problem either reading the referenceFile, or writing the checksum file.
95 public File createChecksum( ChecksumAlgorithm checksumAlgorithm )
98 File checksumFile = new File( referenceFile.getAbsolutePath() + "." + checksumAlgorithm.getExt() );
99 String checksum = calculateChecksum( checksumAlgorithm );
100 FileUtils.writeStringToFile( checksumFile, checksum + " " + referenceFile.getName() );
105 * Get the checksum file for the reference file and hash.
107 * @param checksumAlgorithm the hash that we are interested in.
108 * @return the checksum file to return
110 public File getChecksumFile( ChecksumAlgorithm checksumAlgorithm )
112 return new File( referenceFile.getAbsolutePath() + "." + checksumAlgorithm.getExt() );
117 * Given a checksum file, check to see if the file it represents is valid according to the checksum.
121 * NOTE: Only supports single file checksums of type MD5 or SHA1.
124 * @param algorithm the algorithms to check for.
125 * @return true if the checksum is valid for the file it represents. or if the checksum file does not exist.
126 * @throws IOException if the reading of the checksumFile or the file it refers to fails.
128 public boolean isValidChecksum( ChecksumAlgorithm algorithm )
131 return isValidChecksums( new ChecksumAlgorithm[]{ algorithm } );
135 * Of any checksum files present, validate that the reference file conforms
136 * the to the checksum.
138 * @param algorithms the algorithms to check for.
139 * @return true if the checksums report that the the reference file is valid, false if invalid.
141 public boolean isValidChecksums( ChecksumAlgorithm algorithms[] )
144 try (InputStream fis = Files.newInputStream( referenceFile.toPath() ))
146 List<Checksum> checksums = new ArrayList<>( algorithms.length );
147 // Create checksum object for each algorithm.
148 for ( ChecksumAlgorithm checksumAlgorithm : algorithms )
150 File checksumFile = getChecksumFile( checksumAlgorithm );
152 // Only add algorithm if checksum file exists.
153 if ( checksumFile.exists() )
155 checksums.add( new Checksum( checksumAlgorithm ) );
160 if ( checksums.isEmpty() )
162 // No checksum objects, no checksum files, default to is invalid.
166 // Parse file once, for all checksums.
169 Checksum.update( checksums, fis );
171 catch ( IOException e )
173 log.warn( "Unable to update checksum:{}", e.getMessage() );
177 boolean valid = true;
179 // check the checksum files
182 for ( Checksum checksum : checksums )
184 ChecksumAlgorithm checksumAlgorithm = checksum.getAlgorithm();
185 File checksumFile = getChecksumFile( checksumAlgorithm );
187 String rawChecksum = FileUtils.readFileToString( checksumFile );
188 String expectedChecksum = parseChecksum( rawChecksum, checksumAlgorithm, referenceFile.getName() );
190 if ( !StringUtils.equalsIgnoreCase( expectedChecksum, checksum.getChecksum() ) )
196 catch ( IOException e )
198 log.warn( "Unable to read / parse checksum: {}", e.getMessage() );
203 } catch ( IOException e )
205 log.warn( "Unable to read / parse checksum: {}", e.getMessage() );
211 * Fix or create checksum files for the reference file.
213 * @param algorithms the hashes to check for.
214 * @return true if checksums were created successfully.
216 public boolean fixChecksums( ChecksumAlgorithm[] algorithms )
218 List<Checksum> checksums = new ArrayList<>( algorithms.length );
219 // Create checksum object for each algorithm.
220 for ( ChecksumAlgorithm checksumAlgorithm : algorithms )
222 checksums.add( new Checksum( checksumAlgorithm ) );
226 if ( checksums.isEmpty() )
228 // No checksum objects, no checksum files, default to is valid.
233 try (InputStream fis = Files.newInputStream( referenceFile.toPath() ))
235 // Parse file once, for all checksums.
236 Checksum.update( checksums, fis );
238 catch ( IOException e )
240 log.warn( e.getMessage(), e );
244 boolean valid = true;
246 // check the hash files
247 for ( Checksum checksum : checksums )
249 ChecksumAlgorithm checksumAlgorithm = checksum.getAlgorithm();
252 File checksumFile = getChecksumFile( checksumAlgorithm );
253 String actualChecksum = checksum.getChecksum();
255 if ( checksumFile.exists() )
257 String rawChecksum = FileUtils.readFileToString( checksumFile );
258 String expectedChecksum = parseChecksum( rawChecksum, checksumAlgorithm, referenceFile.getName() );
260 if ( !StringUtils.equalsIgnoreCase( expectedChecksum, actualChecksum ) )
262 // create checksum (again)
263 FileUtils.writeStringToFile( checksumFile, actualChecksum + " " + referenceFile.getName() );
268 FileUtils.writeStringToFile( checksumFile, actualChecksum + " " + referenceFile.getName() );
271 catch ( IOException e )
273 log.warn( e.getMessage(), e );
282 private boolean isValidChecksumPattern( String filename, String path )
284 // check if it is a remote metadata file
285 Pattern pattern = Pattern.compile( "maven-metadata-\\S*.xml" );
286 Matcher m = pattern.matcher( path );
289 return filename.endsWith( path ) || ( "-".equals( filename ) ) || filename.endsWith( "maven-metadata.xml" );
292 return filename.endsWith( path ) || ( "-".equals( filename ) );
296 * Parse a checksum string.
298 * Validate the expected path, and expected checksum algorithm, then return
299 * the trimmed checksum hex string.
301 * @param rawChecksumString
302 * @param expectedHash
303 * @param expectedPath
305 * @throws IOException
307 public String parseChecksum( String rawChecksumString, ChecksumAlgorithm expectedHash, String expectedPath )
310 String trimmedChecksum = rawChecksumString.replace( '\n', ' ' ).trim();
312 // Free-BSD / openssl
313 String regex = expectedHash.getType() + "\\s*\\(([^)]*)\\)\\s*=\\s*([a-fA-F0-9]+)";
314 Matcher m = Pattern.compile( regex ).matcher( trimmedChecksum );
317 String filename = m.group( 1 );
318 if ( !isValidChecksumPattern( filename, expectedPath ) )
320 throw new IOException(
321 "Supplied checksum file '" + filename + "' does not match expected file: '" + expectedPath + "'" );
323 trimmedChecksum = m.group( 2 );
328 m = Pattern.compile( "([a-fA-F0-9]+)\\s+\\*?(.+)" ).matcher( trimmedChecksum );
331 String filename = m.group( 2 );
332 if ( !isValidChecksumPattern( filename, expectedPath ) )
334 throw new IOException(
335 "Supplied checksum file '" + filename + "' does not match expected file: '" + expectedPath
338 trimmedChecksum = m.group( 1 );
341 return trimmedChecksum;