1 /*
   2  * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.util.zip;
  27 
  28 import jdk.internal.ref.CleanerFactory;
  29 
  30 import java.io.EOFException;
  31 import java.io.FilterInputStream;
  32 import java.io.IOException;
  33 import java.io.InputStream;
  34 import java.lang.ref.Cleaner;
  35 import java.util.function.Consumer;
  36 import java.util.function.Supplier;
  37 
  38 /**
  39  * This class implements a stream filter for uncompressing data in the
  40  * "deflate" compression format. It is also used as the basis for other
  41  * decompression filters, such as GZIPInputStream.
  42  *
  43  * @see         Inflater
  44  * @author      David Connelly
  45  * @since 1.1
  46  */
  47 public
  48 class InflaterInputStream extends FilterInputStream {
  49     /**
  50      * Decompressor for this stream.
  51      */
  52     protected Inflater inf;
  53 
  54     /**
  55      * Input buffer for decompression.
  56      */
  57     protected byte[] buf;
  58 
  59     /**
  60      * Length of input buffer.
  61      */
  62     protected int len;
  63 
  64     private boolean closed = false;
  65     // this flag is set to true after EOF has reached
  66     private boolean reachEOF = false;
  67 
  68     // in case this stream manages own Inflater, else null
  69     private final Cleaner.CleanableResource<Inflater> infRes;
  70 
  71     /**
  72      * Check to make sure that this stream has not been closed
  73      */
  74     private void ensureOpen() throws IOException {
  75         if (closed) {
  76             throw new IOException("Stream closed");
  77         }
  78     }
  79 
  80 
  81     /**
  82      * Creates a new input stream with the specified decompressor and
  83      * buffer size.
  84      * @param in the input stream
  85      * @param inf the decompressor ("inflater")
  86      * @param size the input buffer size
  87      * @exception IllegalArgumentException if {@code size <= 0}
  88      */
  89     public InflaterInputStream(InputStream in, Inflater inf, int size) {
  90         super(in);
  91         if (in == null || inf == null) {
  92             throw new NullPointerException();
  93         } else if (size <= 0) {
  94             throw new IllegalArgumentException("buffer size <= 0");
  95         }
  96         this.buf = new byte[size];
  97         this.infRes = null; // uses specified/default decompressor
  98         this.inf = inf;
  99     }
 100 
 101     /**
 102      * Creates a new input stream with the specified decompressor and a
 103      * default buffer size.
 104      * @param in the input stream
 105      * @param inf the decompressor ("inflater")
 106      */
 107     public InflaterInputStream(InputStream in, Inflater inf) {
 108         this(in, inf, 512);
 109     }
 110 
 111     boolean usesDefaultInflater = false;
 112 
 113     /**
 114      * Creates a new input stream with a default decompressor and buffer size.
 115      * @param in the input stream
 116      */
 117     public InflaterInputStream(InputStream in) {
 118         this(in, new Inflater());
 119         usesDefaultInflater = true;
 120     }
 121 
 122     /**
 123      * Creates a new input stream with a decompressor allocated by inflaterAllocator
 124      * and deallocated by inflaterDeallocator and buffer size.
 125      * @param in the input stream
 126      * @param inflaterAllocator the inflater allocator function
 127      * @param inflaterDeallocator the inflater de-allocator function
 128      * @param size the input buffer size
 129      */
 130     InflaterInputStream(InputStream in,
 131                         Supplier<Inflater> inflaterAllocator,
 132                         Consumer<Inflater> inflaterDeallocator,
 133                         int size) {
 134         super(in);
 135         if (in == null) {
 136             throw new NullPointerException();
 137         } else if (size <= 0) {
 138             throw new IllegalArgumentException("buffer size <= 0");
 139         }
 140         this.buf = new byte[size];
 141         this.infRes = CleanerFactory
 142             .cleaner()
 143             .createResource(this, inflaterAllocator, inflaterDeallocator);
 144         this.inf = infRes.value();
 145     }
 146 
 147     private byte[] singleByteBuf = new byte[1];
 148 
 149     /**
 150      * Reads a byte of uncompressed data. This method will block until
 151      * enough input is available for decompression.
 152      * @return the byte read, or -1 if end of compressed input is reached
 153      * @exception IOException if an I/O error has occurred
 154      */
 155     public int read() throws IOException {
 156         ensureOpen();
 157         return read(singleByteBuf, 0, 1) == -1 ? -1 : Byte.toUnsignedInt(singleByteBuf[0]);
 158     }
 159 
 160     /**
 161      * Reads uncompressed data into an array of bytes. If <code>len</code> is not
 162      * zero, the method will block until some input can be decompressed; otherwise,
 163      * no bytes are read and <code>0</code> is returned.
 164      * @param b the buffer into which the data is read
 165      * @param off the start offset in the destination array <code>b</code>
 166      * @param len the maximum number of bytes read
 167      * @return the actual number of bytes read, or -1 if the end of the
 168      *         compressed input is reached or a preset dictionary is needed
 169      * @exception  NullPointerException If <code>b</code> is <code>null</code>.
 170      * @exception  IndexOutOfBoundsException If <code>off</code> is negative,
 171      * <code>len</code> is negative, or <code>len</code> is greater than
 172      * <code>b.length - off</code>
 173      * @exception ZipException if a ZIP format error has occurred
 174      * @exception IOException if an I/O error has occurred
 175      */
 176     public int read(byte[] b, int off, int len) throws IOException {
 177         ensureOpen();
 178         if (b == null) {
 179             throw new NullPointerException();
 180         } else if (off < 0 || len < 0 || len > b.length - off) {
 181             throw new IndexOutOfBoundsException();
 182         } else if (len == 0) {
 183             return 0;
 184         }
 185         try {
 186             int n;
 187             while ((n = inf.inflate(b, off, len)) == 0) {
 188                 if (inf.finished() || inf.needsDictionary()) {
 189                     reachEOF = true;
 190                     return -1;
 191                 }
 192                 if (inf.needsInput()) {
 193                     fill();
 194                 }
 195             }
 196             return n;
 197         } catch (DataFormatException e) {
 198             String s = e.getMessage();
 199             throw new ZipException(s != null ? s : "Invalid ZLIB data format");
 200         }
 201     }
 202 
 203     /**
 204      * Returns 0 after EOF has been reached, otherwise always return 1.
 205      * <p>
 206      * Programs should not count on this method to return the actual number
 207      * of bytes that could be read without blocking.
 208      *
 209      * @return     1 before EOF and 0 after EOF.
 210      * @exception  IOException  if an I/O error occurs.
 211      *
 212      */
 213     public int available() throws IOException {
 214         ensureOpen();
 215         if (reachEOF) {
 216             return 0;
 217         } else if (inf.finished()) {
 218             // the end of the compressed data stream has been reached
 219             reachEOF = true;
 220             return 0;
 221         } else {
 222             return 1;
 223         }
 224     }
 225 
 226     private byte[] b = new byte[512];
 227 
 228     /**
 229      * Skips specified number of bytes of uncompressed data.
 230      * @param n the number of bytes to skip
 231      * @return the actual number of bytes skipped.
 232      * @exception IOException if an I/O error has occurred
 233      * @exception IllegalArgumentException if {@code n < 0}
 234      */
 235     public long skip(long n) throws IOException {
 236         if (n < 0) {
 237             throw new IllegalArgumentException("negative skip length");
 238         }
 239         ensureOpen();
 240         int max = (int)Math.min(n, Integer.MAX_VALUE);
 241         int total = 0;
 242         while (total < max) {
 243             int len = max - total;
 244             if (len > b.length) {
 245                 len = b.length;
 246             }
 247             len = read(b, 0, len);
 248             if (len == -1) {
 249                 reachEOF = true;
 250                 break;
 251             }
 252             total += len;
 253         }
 254         return total;
 255     }
 256 
 257     /**
 258      * Closes this input stream and releases any system resources associated
 259      * with the stream.
 260      * @exception IOException if an I/O error has occurred
 261      */
 262     public void close() throws IOException {
 263         if (!closed) {
 264             if (infRes != null)
 265                 infRes.clean();
 266             else if (usesDefaultInflater)
 267                 inf.end();
 268             in.close();
 269             closed = true;
 270         }
 271     }
 272 
 273     /**
 274      * Fills input buffer with more data to decompress.
 275      * @exception IOException if an I/O error has occurred
 276      */
 277     protected void fill() throws IOException {
 278         ensureOpen();
 279         len = in.read(buf, 0, buf.length);
 280         if (len == -1) {
 281             throw new EOFException("Unexpected end of ZLIB input stream");
 282         }
 283         inf.setInput(buf, 0, len);
 284     }
 285 
 286     /**
 287      * Tests if this input stream supports the <code>mark</code> and
 288      * <code>reset</code> methods. The <code>markSupported</code>
 289      * method of <code>InflaterInputStream</code> returns
 290      * <code>false</code>.
 291      *
 292      * @return  a <code>boolean</code> indicating if this stream type supports
 293      *          the <code>mark</code> and <code>reset</code> methods.
 294      * @see     java.io.InputStream#mark(int)
 295      * @see     java.io.InputStream#reset()
 296      */
 297     public boolean markSupported() {
 298         return false;
 299     }
 300 
 301     /**
 302      * Marks the current position in this input stream.
 303      *
 304      * <p> The <code>mark</code> method of <code>InflaterInputStream</code>
 305      * does nothing.
 306      *
 307      * @param   readlimit   the maximum limit of bytes that can be read before
 308      *                      the mark position becomes invalid.
 309      * @see     java.io.InputStream#reset()
 310      */
 311     public synchronized void mark(int readlimit) {
 312     }
 313 
 314     /**
 315      * Repositions this stream to the position at the time the
 316      * <code>mark</code> method was last called on this input stream.
 317      *
 318      * <p> The method <code>reset</code> for class
 319      * <code>InflaterInputStream</code> does nothing except throw an
 320      * <code>IOException</code>.
 321      *
 322      * @exception  IOException  if this method is invoked.
 323      * @see     java.io.InputStream#mark(int)
 324      * @see     java.io.IOException
 325      */
 326     public synchronized void reset() throws IOException {
 327         throw new IOException("mark/reset not supported");
 328     }
 329 }