Coverage Report - org.owasp.dependencycheck.utils.Downloader
 
Classes in this File Line Coverage Branch Coverage Complexity
Downloader
7%
7/88
3%
1/28
6.6
Downloader$1
0%
0/4
0%
0/2
6.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.Authenticator;
 26  
 import java.net.HttpURLConnection;
 27  
 import java.net.InetSocketAddress;
 28  
 import java.net.PasswordAuthentication;
 29  
 import java.net.Proxy;
 30  
 import java.net.SocketAddress;
 31  
 import java.net.URISyntaxException;
 32  
 import java.net.URL;
 33  
 import java.util.logging.Level;
 34  
 import java.util.logging.Logger;
 35  
 import java.util.zip.GZIPInputStream;
 36  
 import java.util.zip.InflaterInputStream;
 37  
 
 38  
 /**
 39  
  * A utility to download files from the Internet.
 40  
  *
 41  
  * @author Jeremy Long <jeremy.long@owasp.org>
 42  
  */
 43  
 public final class Downloader {
 44  
 
 45  
     /**
 46  
      * Private constructor for utility class.
 47  
      */
 48  0
     private Downloader() {
 49  0
     }
 50  
 
 51  
     /**
 52  
      * Retrieves a file from a given URL and saves it to the outputPath.
 53  
      *
 54  
      * @param url the URL of the file to download.
 55  
      * @param outputPath the path to the save the file to.
 56  
      * @throws DownloadFailedException is thrown if there is an error downloading the file.
 57  
      */
 58  
     public static void fetchFile(URL url, File outputPath) throws DownloadFailedException {
 59  0
         HttpURLConnection conn = null;
 60  
         try {
 61  0
             conn = Downloader.getConnection(url);
 62  0
             conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
 63  0
             conn.connect();
 64  0
         } catch (IOException ex) {
 65  
             try {
 66  0
                 if (conn != null) {
 67  0
                     conn.disconnect();
 68  
                 }
 69  
             } finally {
 70  0
                 conn = null;
 71  0
             }
 72  0
             throw new DownloadFailedException("Error downloading file.", ex);
 73  0
         }
 74  0
         final String encoding = conn.getContentEncoding();
 75  
 
 76  0
         BufferedOutputStream writer = null;
 77  0
         InputStream reader = null;
 78  
         try {
 79  0
             if (encoding != null && "gzip".equalsIgnoreCase(encoding)) {
 80  0
                 reader = new GZIPInputStream(conn.getInputStream());
 81  0
             } else if (encoding != null && "deflate".equalsIgnoreCase(encoding)) {
 82  0
                 reader = new InflaterInputStream(conn.getInputStream());
 83  
             } else {
 84  0
                 reader = conn.getInputStream();
 85  
             }
 86  
 
 87  0
             writer = new BufferedOutputStream(new FileOutputStream(outputPath));
 88  0
             final byte[] buffer = new byte[4096];
 89  
             int bytesRead;
 90  0
             while ((bytesRead = reader.read(buffer)) > 0) {
 91  0
                 writer.write(buffer, 0, bytesRead);
 92  
             }
 93  0
         } catch (Exception ex) {
 94  0
             throw new DownloadFailedException("Error saving downloaded file.", ex);
 95  
         } finally {
 96  0
             if (writer != null) {
 97  
                 try {
 98  0
                     writer.close();
 99  0
                 } catch (Exception ex) {
 100  0
                     Logger.getLogger(Downloader.class.getName()).log(Level.FINEST,
 101  
                             "Error closing the writer in Downloader.", ex);
 102  0
                 }
 103  
             }
 104  0
             if (reader != null) {
 105  
                 try {
 106  0
                     reader.close();
 107  0
                 } catch (Exception ex) {
 108  0
                     Logger.getLogger(Downloader.class.getName()).log(Level.FINEST,
 109  
                             "Error closing the reader in Downloader.", ex);
 110  0
                 }
 111  
             }
 112  
             try {
 113  0
                 conn.disconnect();
 114  
             } finally {
 115  0
                 conn = null;
 116  0
             }
 117  0
         }
 118  0
     }
 119  
 
 120  
     /**
 121  
      * Makes an HTTP Head request to retrieve the last modified date of the given URL. If the file:// protocol is
 122  
      * specified, then the lastTimestamp of the file is returned.
 123  
      *
 124  
      * @param url the URL to retrieve the timestamp from
 125  
      * @return an epoch timestamp
 126  
      * @throws DownloadFailedException is thrown if an exception occurs making the HTTP request
 127  
      */
 128  
     public static long getLastModified(URL url) throws DownloadFailedException {
 129  10
         long timestamp = 0;
 130  
         //TODO add the FPR protocol?
 131  10
         if ("file".equalsIgnoreCase(url.getProtocol())) {
 132  
             File lastModifiedFile;
 133  
             try {
 134  
 //                if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
 135  
 //                    String filePath = url.toString();
 136  
 //                    if (filePath.matches("file://[a-zA-Z]:.*")) {
 137  
 //                        f = new File(filePath.substring(7));
 138  
 //                    } else {
 139  
 //                        f = new File(url.toURI());
 140  
 //                    }
 141  
 //                } else {
 142  10
                 lastModifiedFile = new File(url.toURI());
 143  
 //                }
 144  0
             } catch (URISyntaxException ex) {
 145  0
                 final String msg = String.format("Unable to locate '%s'; is the cve.url-2.0.modified property set correctly?", url.toString());
 146  0
                 throw new DownloadFailedException(msg);
 147  10
             }
 148  10
             timestamp = lastModifiedFile.lastModified();
 149  10
         } else {
 150  0
             HttpURLConnection conn = null;
 151  
             try {
 152  0
                 conn = Downloader.getConnection(url);
 153  0
                 conn.setRequestMethod("HEAD");
 154  0
                 conn.connect();
 155  0
                 timestamp = conn.getLastModified();
 156  0
             } catch (Exception ex) {
 157  0
                 throw new DownloadFailedException("Error making HTTP HEAD request.", ex);
 158  
             } finally {
 159  0
                 if (conn != null) {
 160  
                     try {
 161  0
                         conn.disconnect();
 162  
                     } finally {
 163  0
                         conn = null;
 164  0
                     }
 165  
                 }
 166  
             }
 167  
         }
 168  10
         return timestamp;
 169  
     }
 170  
 
 171  
     /**
 172  
      * Utility method to get an HttpURLConnection. If the app is configured to use a proxy this method will retrieve the
 173  
      * proxy settings and use them when setting up the connection.
 174  
      *
 175  
      * @param url the url to connect to
 176  
      * @return an HttpURLConnection
 177  
      * @throws DownloadFailedException thrown if there is an exception
 178  
      */
 179  
     private static HttpURLConnection getConnection(URL url) throws DownloadFailedException {
 180  0
         HttpURLConnection conn = null;
 181  0
         Proxy proxy = null;
 182  0
         final String proxyUrl = Settings.getString(Settings.KEYS.PROXY_URL);
 183  
         try {
 184  0
             if (proxyUrl != null) {
 185  0
                 final int proxyPort = Settings.getInt(Settings.KEYS.PROXY_PORT);
 186  0
                 final SocketAddress addr = new InetSocketAddress(proxyUrl, proxyPort);
 187  
 
 188  0
                 final String username = Settings.getString(Settings.KEYS.PROXY_USERNAME);
 189  0
                 final String password = Settings.getString(Settings.KEYS.PROXY_PASSWORD);
 190  0
                 if (username != null && password != null) {
 191  0
                     final Authenticator auth = new Authenticator() {
 192  
                         @Override
 193  
                         public PasswordAuthentication getPasswordAuthentication() {
 194  0
                             if (getRequestorType().equals(RequestorType.PROXY)) {
 195  0
                                 return new PasswordAuthentication(username, password.toCharArray());
 196  
                             }
 197  0
                             return super.getPasswordAuthentication();
 198  
                         }
 199  
                     };
 200  0
                     Authenticator.setDefault(auth);
 201  
                 }
 202  
 
 203  0
                 proxy = new Proxy(Proxy.Type.HTTP, addr);
 204  0
                 conn = (HttpURLConnection) url.openConnection(proxy);
 205  0
             } else {
 206  0
                 conn = (HttpURLConnection) url.openConnection();
 207  
             }
 208  0
             final int timeout = Settings.getInt(Settings.KEYS.CONNECTION_TIMEOUT, 60000);
 209  0
             conn.setConnectTimeout(timeout);
 210  0
         } catch (IOException ex) {
 211  0
             if (conn != null) {
 212  
                 try {
 213  0
                     conn.disconnect();
 214  
                 } finally {
 215  0
                     conn = null;
 216  0
                 }
 217  
             }
 218  0
             throw new DownloadFailedException("Error getting connection.", ex);
 219  0
         }
 220  0
         return conn;
 221  
     }
 222  
 }