Coverage Report - org.owasp.dependencycheck.utils.Downloader
 
Classes in this File Line Coverage Branch Coverage Complexity
Downloader
6%
8/123
2%
1/42
9.6
 
 1  
 /*
 2  
  * This file is part of dependency-check-core.
 3  
  *
 4  
  * Licensed under the Apache License, Version 2.0 (the "License");
 5  
  * you may not use this file except in compliance with the License.
 6  
  * You may obtain a copy of the License at
 7  
  *
 8  
  *     http://www.apache.org/licenses/LICENSE-2.0
 9  
  *
 10  
  * Unless required by applicable law or agreed to in writing, software
 11  
  * distributed under the License is distributed on an "AS IS" BASIS,
 12  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  
  * See the License for the specific language governing permissions and
 14  
  * limitations under the License.
 15  
  *
 16  
  * Copyright (c) 2012 Jeremy Long. All Rights Reserved.
 17  
  */
 18  
 package org.owasp.dependencycheck.utils;
 19  
 
 20  
 import java.io.BufferedOutputStream;
 21  
 import java.io.File;
 22  
 import java.io.FileOutputStream;
 23  
 import java.io.IOException;
 24  
 import java.io.InputStream;
 25  
 import java.net.HttpURLConnection;
 26  
 import java.net.URISyntaxException;
 27  
 import java.net.URL;
 28  
 import java.security.InvalidAlgorithmParameterException;
 29  
 import java.util.logging.Level;
 30  
 import java.util.logging.Logger;
 31  
 import java.util.zip.GZIPInputStream;
 32  
 import java.util.zip.InflaterInputStream;
 33  
 
 34  
 /**
 35  
  * A utility to download files from the Internet.
 36  
  *
 37  
  * @author Jeremy Long <jeremy.long@owasp.org>
 38  
  */
 39  
 public final class Downloader {
 40  
 
 41  
     /**
 42  
      * The logger.
 43  
      */
 44  1
     private static final Logger LOGGER = Logger.getLogger(Downloader.class.getName());
 45  
 
 46  
     /**
 47  
      * Private constructor for utility class.
 48  
      */
 49  0
     private Downloader() {
 50  0
     }
 51  
 
 52  
     /**
 53  
      * Retrieves a file from a given URL and saves it to the outputPath.
 54  
      *
 55  
      * @param url the URL of the file to download
 56  
      * @param outputPath the path to the save the file to
 57  
      * @throws DownloadFailedException is thrown if there is an error downloading the file
 58  
      */
 59  
     public static void fetchFile(URL url, File outputPath) throws DownloadFailedException {
 60  0
         fetchFile(url, outputPath, true);
 61  0
     }
 62  
 
 63  
     /**
 64  
      * Retrieves a file from a given URL and saves it to the outputPath.
 65  
      *
 66  
      * @param url the URL of the file to download
 67  
      * @param outputPath the path to the save the file to
 68  
      * @param useProxy whether to use the configured proxy when downloading files
 69  
      * @throws DownloadFailedException is thrown if there is an error downloading the file
 70  
      */
 71  
     public static void fetchFile(URL url, File outputPath, boolean useProxy) throws DownloadFailedException {
 72  0
         if ("file".equalsIgnoreCase(url.getProtocol())) {
 73  
             File file;
 74  
             try {
 75  0
                 file = new File(url.toURI());
 76  0
             } catch (URISyntaxException ex) {
 77  0
                 final String msg = String.format("Download failed, unable to locate '%s'", url.toString());
 78  0
                 throw new DownloadFailedException(msg);
 79  0
             }
 80  0
             if (file.exists()) {
 81  
                 try {
 82  0
                     org.apache.commons.io.FileUtils.copyFile(file, outputPath);
 83  0
                 } catch (IOException ex) {
 84  0
                     final String msg = String.format("Download failed, unable to copy '%s' to '%s'", url.toString(), outputPath.getAbsolutePath());
 85  0
                     throw new DownloadFailedException(msg);
 86  0
                 }
 87  
             } else {
 88  0
                 final String msg = String.format("Download failed, file ('%s') does not exist", url.toString());
 89  0
                 throw new DownloadFailedException(msg);
 90  
             }
 91  0
         } else {
 92  0
             HttpURLConnection conn = null;
 93  
             try {
 94  0
                 conn = URLConnectionFactory.createHttpURLConnection(url, useProxy);
 95  0
                 conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
 96  0
                 conn.connect();
 97  0
                 int status = conn.getResponseCode();
 98  0
                 if (status != HttpURLConnection.HTTP_OK) {
 99  0
                     if (status == HttpURLConnection.HTTP_MOVED_TEMP
 100  
                             || status == HttpURLConnection.HTTP_MOVED_PERM
 101  
                             || status == HttpURLConnection.HTTP_SEE_OTHER) {
 102  0
                         final String location = conn.getHeaderField("Location");
 103  
                         try {
 104  0
                             conn.disconnect();
 105  
                         } finally {
 106  0
                             conn = null;
 107  0
                         }
 108  0
                         LOGGER.fine(String.format("Download is being redirected from %s to %s", url.toString(), location));
 109  0
                         conn = URLConnectionFactory.createHttpURLConnection(new URL(location), useProxy);
 110  0
                         conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
 111  0
                         conn.connect();
 112  0
                         status = conn.getResponseCode();
 113  
                     }
 114  
                 }
 115  0
                 if (status != 200) {
 116  
                     try {
 117  0
                         conn.disconnect();
 118  
                     } finally {
 119  0
                         conn = null;
 120  0
                     }
 121  0
                     final String msg = String.format("Error downloading file %s; received response code %s.", url.toString(), status);
 122  0
                     throw new DownloadFailedException(msg);
 123  
 
 124  
                 }
 125  0
             } catch (IOException ex) {
 126  
                 try {
 127  0
                     if (conn != null) {
 128  0
                         conn.disconnect();
 129  
                     }
 130  
                 } finally {
 131  0
                     conn = null;
 132  0
                 }
 133  0
                 final String msg = String.format("Error downloading file %s; unable to connect.", url.toString());
 134  0
                 throw new DownloadFailedException(msg, ex);
 135  0
             }
 136  
 
 137  0
             final String encoding = conn.getContentEncoding();
 138  0
             BufferedOutputStream writer = null;
 139  0
             InputStream reader = null;
 140  
             try {
 141  0
                 if (encoding != null && "gzip".equalsIgnoreCase(encoding)) {
 142  0
                     reader = new GZIPInputStream(conn.getInputStream());
 143  0
                 } else if (encoding != null && "deflate".equalsIgnoreCase(encoding)) {
 144  0
                     reader = new InflaterInputStream(conn.getInputStream());
 145  
                 } else {
 146  0
                     reader = conn.getInputStream();
 147  
                 }
 148  
 
 149  0
                 writer = new BufferedOutputStream(new FileOutputStream(outputPath));
 150  0
                 final byte[] buffer = new byte[4096];
 151  
                 int bytesRead;
 152  0
                 while ((bytesRead = reader.read(buffer)) > 0) {
 153  0
                     writer.write(buffer, 0, bytesRead);
 154  
                 }
 155  0
             } catch (IOException ex) {
 156  0
                 analyzeException(ex);
 157  0
                 final String msg = String.format("Error saving '%s' to file '%s'%nConnection Timeout: %d%nEncoding: %s%n",
 158  
                         url.toString(), outputPath.getAbsolutePath(), conn.getConnectTimeout(), encoding);
 159  0
                 throw new DownloadFailedException(msg, ex);
 160  0
             } catch (Throwable ex) {
 161  0
                 final String msg = String.format("Unexpected exception saving '%s' to file '%s'%nConnection Timeout: %d%nEncoding: %s%n",
 162  
                         url.toString(), outputPath.getAbsolutePath(), conn.getConnectTimeout(), encoding);
 163  0
                 throw new DownloadFailedException(msg, ex);
 164  
             } finally {
 165  0
                 if (writer != null) {
 166  
                     try {
 167  0
                         writer.close();
 168  0
                     } catch (IOException ex) {
 169  0
                         LOGGER.log(Level.FINEST, "Error closing the writer in Downloader.", ex);
 170  0
                     }
 171  
                 }
 172  0
                 if (reader != null) {
 173  
                     try {
 174  0
                         reader.close();
 175  0
                     } catch (IOException ex) {
 176  0
                         LOGGER.log(Level.FINEST, "Error closing the reader in Downloader.", ex);
 177  0
                     }
 178  
                 }
 179  
                 try {
 180  0
                     conn.disconnect();
 181  
                 } finally {
 182  0
                     conn = null;
 183  0
                 }
 184  0
             }
 185  
         }
 186  0
     }
 187  
 
 188  
     /**
 189  
      * Makes an HTTP Head request to retrieve the last modified date of the given URL. If the file:// protocol is specified, then
 190  
      * the lastTimestamp of the file is returned.
 191  
      *
 192  
      * @param url the URL to retrieve the timestamp from
 193  
      * @return an epoch timestamp
 194  
      * @throws DownloadFailedException is thrown if an exception occurs making the HTTP request
 195  
      */
 196  
     public static long getLastModified(URL url) throws DownloadFailedException {
 197  1
         long timestamp = 0;
 198  
         //TODO add the FTP protocol?
 199  1
         if ("file".equalsIgnoreCase(url.getProtocol())) {
 200  
             File lastModifiedFile;
 201  
             try {
 202  1
                 lastModifiedFile = new File(url.toURI());
 203  0
             } catch (URISyntaxException ex) {
 204  0
                 final String msg = String.format("Unable to locate '%s'", url.toString());
 205  0
                 throw new DownloadFailedException(msg);
 206  1
             }
 207  1
             timestamp = lastModifiedFile.lastModified();
 208  1
         } else {
 209  0
             HttpURLConnection conn = null;
 210  
             try {
 211  0
                 conn = URLConnectionFactory.createHttpURLConnection(url);
 212  0
                 conn.setRequestMethod("HEAD");
 213  0
                 conn.connect();
 214  0
                 final int t = conn.getResponseCode();
 215  0
                 if (t >= 200 && t < 300) {
 216  0
                     timestamp = conn.getLastModified();
 217  
                 } else {
 218  0
                     throw new DownloadFailedException("HEAD request returned a non-200 status code");
 219  
                 }
 220  0
             } catch (URLConnectionFailureException ex) {
 221  0
                 throw new DownloadFailedException("Error creating URL Connection for HTTP HEAD request.", ex);
 222  0
             } catch (IOException ex) {
 223  0
                 analyzeException(ex);
 224  0
                 throw new DownloadFailedException("Error making HTTP HEAD request.", ex);
 225  
             } finally {
 226  0
                 if (conn != null) {
 227  
                     try {
 228  0
                         conn.disconnect();
 229  
                     } finally {
 230  0
                         conn = null;
 231  0
                     }
 232  
                 }
 233  
             }
 234  
         }
 235  1
         return timestamp;
 236  
     }
 237  
 
 238  
     /**
 239  
      * Analyzes the IOException, logs the appropriate information for debugging purposes, and then throws a
 240  
      * DownloadFailedException that wraps the IO Exception.
 241  
      *
 242  
      * @param ex the original exception
 243  
      * @throws DownloadFailedException a wrapper exception that contains the original exception as the cause
 244  
      */
 245  
     protected static void analyzeException(IOException ex) throws DownloadFailedException {
 246  0
         Throwable cause = ex;
 247  0
         while (cause != null) {
 248  0
             if (cause instanceof InvalidAlgorithmParameterException) {
 249  0
                 final String keystore = System.getProperty("javax.net.ssl.keyStore");
 250  0
                 final String version = System.getProperty("java.version");
 251  0
                 final String vendor = System.getProperty("java.vendor");
 252  0
                 LOGGER.info("Error making HTTPS request - InvalidAlgorithmParameterException");
 253  0
                 LOGGER.info("There appears to be an issue with the installation of Java and the cacerts."
 254  
                         + "See closed issue #177 here: https://github.com/jeremylong/DependencyCheck/issues/177");
 255  0
                 LOGGER.info(String.format("Java Info:%njavax.net.ssl.keyStore='%s'%njava.version='%s'%njava.vendor='%s'",
 256  
                         keystore, version, vendor));
 257  0
                 throw new DownloadFailedException("Error making HTTPS request. Please see the log for more details.");
 258  
             }
 259  0
             cause = cause.getCause();
 260  
         }
 261  0
     }
 262  
 }