Coverage Report - org.owasp.dependencycheck.data.update.nvd.DownloadTask
 
Classes in this File Line Coverage Branch Coverage Complexity
DownloadTask
55%
61/110
31%
22/70
5.636
 
 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) 2013 Jeremy Long. All Rights Reserved.
 17  
  */
 18  
 package org.owasp.dependencycheck.data.update.nvd;
 19  
 
 20  
 import java.io.File;
 21  
 import java.io.FileInputStream;
 22  
 import java.io.FileNotFoundException;
 23  
 import java.io.FileOutputStream;
 24  
 import java.io.IOException;
 25  
 import java.io.InputStream;
 26  
 import java.net.URL;
 27  
 import java.util.concurrent.Callable;
 28  
 import java.util.concurrent.ExecutorService;
 29  
 import java.util.concurrent.Future;
 30  
 import java.util.zip.GZIPInputStream;
 31  
 import org.apache.commons.io.FileUtils;
 32  
 import org.owasp.dependencycheck.data.nvdcve.CveDB;
 33  
 import org.owasp.dependencycheck.data.update.exception.UpdateException;
 34  
 import org.owasp.dependencycheck.utils.DownloadFailedException;
 35  
 import org.owasp.dependencycheck.utils.Downloader;
 36  
 import org.owasp.dependencycheck.utils.Settings;
 37  
 import org.slf4j.Logger;
 38  
 import org.slf4j.LoggerFactory;
 39  
 
 40  
 /**
 41  
  * A callable object to download two files.
 42  
  *
 43  
  * @author Jeremy Long
 44  
  */
 45  0
 public class DownloadTask implements Callable<Future<ProcessTask>> {
 46  
 
 47  
     /**
 48  
      * The Logger.
 49  
      */
 50  2
     private static final Logger LOGGER = LoggerFactory.getLogger(DownloadTask.class);
 51  
 
 52  
     /**
 53  
      * Simple constructor for the callable download task.
 54  
      *
 55  
      * @param nvdCveInfo the NVD CVE info
 56  
      * @param processor the processor service to submit the downloaded files to
 57  
      * @param cveDB the CVE DB to use to store the vulnerability data
 58  
      * @param settings a reference to the global settings object; this is necessary so that when the thread is started the
 59  
      * dependencies have a correct reference to the global settings.
 60  
      * @throws UpdateException thrown if temporary files could not be created
 61  
      */
 62  2
     public DownloadTask(NvdCveInfo nvdCveInfo, ExecutorService processor, CveDB cveDB, Settings settings) throws UpdateException {
 63  2
         this.nvdCveInfo = nvdCveInfo;
 64  2
         this.processorService = processor;
 65  2
         this.cveDB = cveDB;
 66  2
         this.settings = settings;
 67  
 
 68  
         final File file1;
 69  
         final File file2;
 70  
 
 71  
         try {
 72  2
             file1 = File.createTempFile("cve" + nvdCveInfo.getId() + '_', ".xml", Settings.getTempDirectory());
 73  2
             file2 = File.createTempFile("cve_1_2_" + nvdCveInfo.getId() + '_', ".xml", Settings.getTempDirectory());
 74  0
         } catch (IOException ex) {
 75  0
             throw new UpdateException("Unable to create temporary files", ex);
 76  2
         }
 77  2
         this.first = file1;
 78  2
         this.second = file2;
 79  
 
 80  2
     }
 81  
     /**
 82  
      * The CVE DB to use when processing the files.
 83  
      */
 84  
     private final CveDB cveDB;
 85  
     /**
 86  
      * The processor service to pass the results of the download to.
 87  
      */
 88  
     private final ExecutorService processorService;
 89  
     /**
 90  
      * The NVD CVE Meta Data.
 91  
      */
 92  
     private NvdCveInfo nvdCveInfo;
 93  
     /**
 94  
      * A reference to the global settings object.
 95  
      */
 96  
     private final Settings settings;
 97  
 
 98  
     /**
 99  
      * Get the value of nvdCveInfo.
 100  
      *
 101  
      * @return the value of nvdCveInfo
 102  
      */
 103  
     public NvdCveInfo getNvdCveInfo() {
 104  0
         return nvdCveInfo;
 105  
     }
 106  
 
 107  
     /**
 108  
      * Set the value of nvdCveInfo.
 109  
      *
 110  
      * @param nvdCveInfo new value of nvdCveInfo
 111  
      */
 112  
     public void setNvdCveInfo(NvdCveInfo nvdCveInfo) {
 113  0
         this.nvdCveInfo = nvdCveInfo;
 114  0
     }
 115  
     /**
 116  
      * a file.
 117  
      */
 118  
     private File first;
 119  
 
 120  
     /**
 121  
      * Get the value of first.
 122  
      *
 123  
      * @return the value of first
 124  
      */
 125  
     public File getFirst() {
 126  0
         return first;
 127  
     }
 128  
 
 129  
     /**
 130  
      * Set the value of first.
 131  
      *
 132  
      * @param first new value of first
 133  
      */
 134  
     public void setFirst(File first) {
 135  0
         this.first = first;
 136  0
     }
 137  
     /**
 138  
      * a file.
 139  
      */
 140  
     private File second;
 141  
 
 142  
     /**
 143  
      * Get the value of second.
 144  
      *
 145  
      * @return the value of second
 146  
      */
 147  
     public File getSecond() {
 148  0
         return second;
 149  
     }
 150  
 
 151  
     /**
 152  
      * Set the value of second.
 153  
      *
 154  
      * @param second new value of second
 155  
      */
 156  
     public void setSecond(File second) {
 157  0
         this.second = second;
 158  0
     }
 159  
 
 160  
     @Override
 161  
     public Future<ProcessTask> call() throws Exception {
 162  
         try {
 163  2
             Settings.setInstance(settings);
 164  2
             final URL url1 = new URL(nvdCveInfo.getUrl());
 165  2
             final URL url2 = new URL(nvdCveInfo.getOldSchemaVersionUrl());
 166  2
             LOGGER.info("Download Started for NVD CVE - {}", nvdCveInfo.getId());
 167  2
             final long startDownload = System.currentTimeMillis();
 168  
             try {
 169  2
                 Downloader.fetchFile(url1, first);
 170  2
                 Downloader.fetchFile(url2, second);
 171  0
             } catch (DownloadFailedException ex) {
 172  0
                 LOGGER.warn("Download Failed for NVD CVE - {}\nSome CVEs may not be reported.", nvdCveInfo.getId());
 173  0
                 if (Settings.getString(Settings.KEYS.PROXY_SERVER) == null) {
 174  0
                     LOGGER.info(
 175  
                             "If you are behind a proxy you may need to configure dependency-check to use the proxy.");
 176  
                 }
 177  0
                 LOGGER.debug("", ex);
 178  0
                 return null;
 179  2
             }
 180  2
             if (url1.toExternalForm().endsWith(".xml.gz") && !isXml(first)) {
 181  2
                 extractGzip(first);
 182  
             }
 183  2
             if (url2.toExternalForm().endsWith(".xml.gz") && !isXml(second)) {
 184  2
                 extractGzip(second);
 185  
             }
 186  
 
 187  4
             LOGGER.info("Download Complete for NVD CVE - {}  ({} ms)", nvdCveInfo.getId(),
 188  2
                     System.currentTimeMillis() - startDownload);
 189  2
             if (this.processorService == null) {
 190  4
                 return null;
 191  
             }
 192  0
             final ProcessTask task = new ProcessTask(cveDB, this, settings);
 193  0
             return this.processorService.submit(task);
 194  
 
 195  0
         } catch (Throwable ex) {
 196  0
             LOGGER.warn("An exception occurred downloading NVD CVE - {}\nSome CVEs may not be reported.", nvdCveInfo.getId());
 197  0
             LOGGER.debug("Download Task Failed", ex);
 198  
         } finally {
 199  2
             Settings.cleanup(false);
 200  0
         }
 201  0
         return null;
 202  
     }
 203  
 
 204  
     /**
 205  
      * Attempts to delete the files that were downloaded.
 206  
      */
 207  
     public void cleanup() {
 208  0
         boolean deleted = false;
 209  
         try {
 210  0
             if (first != null && first.exists()) {
 211  0
                 deleted = first.delete();
 212  
             }
 213  
         } finally {
 214  0
             if (first != null && (first.exists() || !deleted)) {
 215  0
                 first.deleteOnExit();
 216  
             }
 217  
         }
 218  
         try {
 219  0
             deleted = false;
 220  0
             if (second != null && second.exists()) {
 221  0
                 deleted = second.delete();
 222  
             }
 223  
         } finally {
 224  0
             if (second != null && (second.exists() || !deleted)) {
 225  0
                 second.deleteOnExit();
 226  
             }
 227  
         }
 228  0
     }
 229  
 
 230  
     /**
 231  
      * Checks the file header to see if it is an XML file.
 232  
      *
 233  
      * @param file the file to check
 234  
      * @return true if the file is XML
 235  
      */
 236  
     public static boolean isXml(File file) {
 237  8
         if (file == null || !file.isFile()) {
 238  0
             return false;
 239  
         }
 240  8
         InputStream is = null;
 241  
         try {
 242  8
             is = new FileInputStream(file);
 243  
 
 244  8
             final byte[] buf = new byte[5];
 245  8
             int read = 0;
 246  
             try {
 247  8
                 read = is.read(buf);
 248  0
             } catch (IOException ex) {
 249  0
                 return false;
 250  8
             }
 251  16
             return read == 5
 252  
                     && buf[0] == '<'
 253  
                     && (buf[1] == '?')
 254  
                     && (buf[2] == 'x' || buf[2] == 'X')
 255  
                     && (buf[3] == 'm' || buf[3] == 'M')
 256  
                     && (buf[4] == 'l' || buf[4] == 'L');
 257  0
         } catch (FileNotFoundException ex) {
 258  0
             return false;
 259  
         } finally {
 260  8
             if (is != null) {
 261  
                 try {
 262  8
                     is.close();
 263  0
                 } catch (IOException ex) {
 264  0
                     LOGGER.debug("Error closing stream", ex);
 265  8
                 }
 266  
             }
 267  
         }
 268  
     }
 269  
 
 270  
     /**
 271  
      * Extracts the file contained in a gzip archive. The extracted file is placed in the exact same path as the file specified.
 272  
      *
 273  
      * @param file the archive file
 274  
      * @throws FileNotFoundException thrown if the file does not exist
 275  
      * @throws IOException thrown if there is an error extracting the file.
 276  
      */
 277  
     private void extractGzip(File file) throws FileNotFoundException, IOException {
 278  4
         final String originalPath = file.getPath();
 279  4
         final File gzip = new File(originalPath + ".gz");
 280  4
         if (gzip.isFile() && !gzip.delete()) {
 281  0
             gzip.deleteOnExit();
 282  
         }
 283  4
         if (!file.renameTo(gzip)) {
 284  0
             throw new IOException("Unable to rename '" + file.getPath() + "'");
 285  
         }
 286  4
         final File newfile = new File(originalPath);
 287  
 
 288  4
         final byte[] buffer = new byte[4096];
 289  
 
 290  4
         GZIPInputStream cin = null;
 291  4
         FileOutputStream out = null;
 292  
         try {
 293  4
             cin = new GZIPInputStream(new FileInputStream(gzip));
 294  4
             out = new FileOutputStream(newfile);
 295  
 
 296  
             int len;
 297  3366
             while ((len = cin.read(buffer)) > 0) {
 298  3362
                 out.write(buffer, 0, len);
 299  
             }
 300  
         } finally {
 301  4
             if (cin != null) {
 302  
                 try {
 303  4
                     cin.close();
 304  0
                 } catch (IOException ex) {
 305  0
                     LOGGER.trace("ignore", ex);
 306  4
                 }
 307  
             }
 308  4
             if (out != null) {
 309  
                 try {
 310  4
                     out.close();
 311  0
                 } catch (IOException ex) {
 312  0
                     LOGGER.trace("ignore", ex);
 313  4
                 }
 314  
             }
 315  4
             if (gzip.isFile()) {
 316  4
                 FileUtils.deleteQuietly(gzip);
 317  
             }
 318  
         }
 319  4
     }
 320  
 }