ZipInputStream.java revision 6975f84c2ed72e1e26d20190b6f318718c849008
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved.
4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 *
6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.  Oracle designates this
9 * particular file as subject to the "Classpath" exception as provided
10 * by Oracle in the LICENSE file that accompanied this code.
11 *
12 * This code is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 * version 2 for more details (a copy is included in the LICENSE file that
16 * accompanied this code).
17 *
18 * You should have received a copy of the GNU General Public License version
19 * 2 along with this work; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 *
22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23 * or visit www.oracle.com if you need additional information or have any
24 * questions.
25 */
26
27package java.util.zip;
28
29import java.io.InputStream;
30import java.io.IOException;
31import java.io.EOFException;
32import java.io.PushbackInputStream;
33import java.nio.charset.Charset;
34import java.nio.charset.StandardCharsets;
35import static java.util.zip.ZipConstants64.*;
36import static java.util.zip.ZipUtils.*;
37
38/**
39 * This class implements an input stream filter for reading files in the
40 * ZIP file format. Includes support for both compressed and uncompressed
41 * entries.
42 *
43 * @author      David Connelly
44 */
45public
46class ZipInputStream extends InflaterInputStream implements ZipConstants {
47    private ZipEntry entry;
48    private int flag;
49    private CRC32 crc = new CRC32();
50    private long remaining;
51    private byte[] tmpbuf = new byte[512];
52
53    private static final int STORED = ZipEntry.STORED;
54    private static final int DEFLATED = ZipEntry.DEFLATED;
55
56    private boolean closed = false;
57    // this flag is set to true after EOF has reached for
58    // one entry
59    private boolean entryEOF = false;
60
61    private ZipCoder zc;
62
63    /**
64     * Check to make sure that this stream has not been closed
65     */
66    private void ensureOpen() throws IOException {
67        if (closed) {
68            throw new IOException("Stream closed");
69        }
70    }
71
72    /**
73     * Creates a new ZIP input stream.
74     *
75     * <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to
76     * decode the entry names.
77     *
78     * @param in the actual input stream
79     */
80    public ZipInputStream(InputStream in) {
81        this(in, StandardCharsets.UTF_8);
82    }
83
84    /**
85     * Creates a new ZIP input stream.
86     *
87     * @param in the actual input stream
88     *
89     * @param charset
90     *        The {@linkplain java.nio.charset.Charset charset} to be
91     *        used to decode the ZIP entry name (ignored if the
92     *        <a href="package-summary.html#lang_encoding"> language
93     *        encoding bit</a> of the ZIP entry's general purpose bit
94     *        flag is set).
95     *
96     * @since 1.7
97     */
98    public ZipInputStream(InputStream in, Charset charset) {
99        super(new PushbackInputStream(in, 512), new Inflater(true), 512);
100        // Android-changed: Unconditionally close external inflaters (b/26462400)
101        // usesDefaultInflater = true;
102        if(in == null) {
103            throw new NullPointerException("in is null");
104        }
105        if (charset == null)
106            throw new NullPointerException("charset is null");
107        this.zc = ZipCoder.get(charset);
108    }
109
110    /**
111     * Reads the next ZIP file entry and positions the stream at the
112     * beginning of the entry data.
113     * @return the next ZIP file entry, or null if there are no more entries
114     * @exception ZipException if a ZIP file error has occurred
115     * @exception IOException if an I/O error has occurred
116     */
117    public ZipEntry getNextEntry() throws IOException {
118        ensureOpen();
119        if (entry != null) {
120            closeEntry();
121        }
122        crc.reset();
123        inf.reset();
124        if ((entry = readLOC()) == null) {
125            return null;
126        }
127        // BEGIN Android-changed
128        // if (entry.method == STORED) {
129        if (entry.method == STORED || entry.method == DEFLATED) {
130        // END Android-changed
131            remaining = entry.size;
132        }
133        entryEOF = false;
134        return entry;
135    }
136
137    /**
138     * Closes the current ZIP entry and positions the stream for reading the
139     * next entry.
140     * @exception ZipException if a ZIP file error has occurred
141     * @exception IOException if an I/O error has occurred
142     */
143    public void closeEntry() throws IOException {
144        ensureOpen();
145        while (read(tmpbuf, 0, tmpbuf.length) != -1) ;
146        entryEOF = true;
147    }
148
149    /**
150     * Returns 0 after EOF has reached for the current entry data,
151     * otherwise always return 1.
152     * <p>
153     * Programs should not count on this method to return the actual number
154     * of bytes that could be read without blocking.
155     *
156     * @return     1 before EOF and 0 after EOF has reached for current entry.
157     * @exception  IOException  if an I/O error occurs.
158     *
159     */
160    public int available() throws IOException {
161        ensureOpen();
162        // BEGIN Android-changed
163        // if (entryEOF) {
164        if (entryEOF || (entry != null && remaining == 0)) {
165        // END Android-changed
166            return 0;
167        } else {
168            return 1;
169        }
170    }
171
172    /**
173     * Reads from the current ZIP entry into an array of bytes.
174     * If <code>len</code> is not zero, the method
175     * blocks until some input is available; otherwise, no
176     * bytes are read and <code>0</code> is returned.
177     * @param b the buffer into which the data is read
178     * @param off the start offset in the destination array <code>b</code>
179     * @param len the maximum number of bytes read
180     * @return the actual number of bytes read, or -1 if the end of the
181     *         entry is reached
182     * @exception  NullPointerException if <code>b</code> is <code>null</code>.
183     * @exception  IndexOutOfBoundsException if <code>off</code> is negative,
184     * <code>len</code> is negative, or <code>len</code> is greater than
185     * <code>b.length - off</code>
186     * @exception ZipException if a ZIP file error has occurred
187     * @exception IOException if an I/O error has occurred
188     */
189    public int read(byte[] b, int off, int len) throws IOException {
190        ensureOpen();
191        if (off < 0 || len < 0 || off > b.length - len) {
192            throw new IndexOutOfBoundsException();
193        } else if (len == 0) {
194            return 0;
195        }
196
197        if (entry == null) {
198            return -1;
199        }
200        switch (entry.method) {
201        case DEFLATED:
202            len = super.read(b, off, len);
203            if (len == -1) {
204                readEnd(entry);
205                entryEOF = true;
206                entry = null;
207            } else {
208                crc.update(b, off, len);
209                // BEGIN Android-changed
210                remaining -= len;
211                // END Android-changed
212            }
213            return len;
214        case STORED:
215            if (remaining <= 0) {
216                entryEOF = true;
217                entry = null;
218                return -1;
219            }
220            if (len > remaining) {
221                len = (int)remaining;
222            }
223            len = in.read(b, off, len);
224            if (len == -1) {
225                throw new ZipException("unexpected EOF");
226            }
227            crc.update(b, off, len);
228            remaining -= len;
229            if (remaining == 0 && entry.crc != crc.getValue()) {
230                throw new ZipException(
231                    "invalid entry CRC (expected 0x" + Long.toHexString(entry.crc) +
232                    " but got 0x" + Long.toHexString(crc.getValue()) + ")");
233            }
234            return len;
235        default:
236            throw new ZipException("invalid compression method");
237        }
238    }
239
240    /**
241     * Skips specified number of bytes in the current ZIP entry.
242     * @param n the number of bytes to skip
243     * @return the actual number of bytes skipped
244     * @exception ZipException if a ZIP file error has occurred
245     * @exception IOException if an I/O error has occurred
246     * @exception IllegalArgumentException if {@code n < 0}
247     */
248    public long skip(long n) throws IOException {
249        if (n < 0) {
250            throw new IllegalArgumentException("negative skip length");
251        }
252        ensureOpen();
253        int max = (int)Math.min(n, Integer.MAX_VALUE);
254        int total = 0;
255        while (total < max) {
256            int len = max - total;
257            if (len > tmpbuf.length) {
258                len = tmpbuf.length;
259            }
260            len = read(tmpbuf, 0, len);
261            if (len == -1) {
262                entryEOF = true;
263                break;
264            }
265            total += len;
266        }
267        return total;
268    }
269
270    /**
271     * Closes this input stream and releases any system resources associated
272     * with the stream.
273     * @exception IOException if an I/O error has occurred
274     */
275    public void close() throws IOException {
276        if (!closed) {
277            super.close();
278            closed = true;
279        }
280    }
281
282    private byte[] b = new byte[256];
283
284    /*
285     * Reads local file (LOC) header for next entry.
286     */
287    private ZipEntry readLOC() throws IOException {
288        try {
289            readFully(tmpbuf, 0, LOCHDR);
290        } catch (EOFException e) {
291            return null;
292        }
293        if (get32(tmpbuf, 0) != LOCSIG) {
294            return null;
295        }
296        // get flag first, we need check EFS.
297        flag = get16(tmpbuf, LOCFLG);
298        // get the entry name and create the ZipEntry first
299        int len = get16(tmpbuf, LOCNAM);
300        int blen = b.length;
301        if (len > blen) {
302            do {
303                blen = blen * 2;
304            } while (len > blen);
305            b = new byte[blen];
306        }
307        readFully(b, 0, len);
308        // Force to use UTF-8 if the EFS bit is ON, even the cs is NOT UTF-8
309        ZipEntry e = createZipEntry(((flag & EFS) != 0)
310                                    ? zc.toStringUTF8(b, len)
311                                    : zc.toString(b, len));
312        // now get the remaining fields for the entry
313        if ((flag & 1) == 1) {
314            throw new ZipException("encrypted ZIP entry not supported");
315        }
316        e.method = get16(tmpbuf, LOCHOW);
317        e.xdostime = get32(tmpbuf, LOCTIM);
318        if ((flag & 8) == 8) {
319            /* "Data Descriptor" present */
320            if (e.method != DEFLATED) {
321                throw new ZipException(
322                        "only DEFLATED entries can have EXT descriptor");
323            }
324        } else {
325            e.crc = get32(tmpbuf, LOCCRC);
326            e.csize = get32(tmpbuf, LOCSIZ);
327            e.size = get32(tmpbuf, LOCLEN);
328        }
329        len = get16(tmpbuf, LOCEXT);
330        if (len > 0) {
331            byte[] extra = new byte[len];
332            readFully(extra, 0, len);
333            e.setExtra0(extra,
334                        e.csize == ZIP64_MAGICVAL || e.size == ZIP64_MAGICVAL);
335        }
336        return e;
337    }
338
339    /**
340     * Creates a new <code>ZipEntry</code> object for the specified
341     * entry name.
342     *
343     * @param name the ZIP file entry name
344     * @return the ZipEntry just created
345     */
346    protected ZipEntry createZipEntry(String name) {
347        return new ZipEntry(name);
348    }
349
350    /*
351     * Reads end of deflated entry as well as EXT descriptor if present.
352     */
353    private void readEnd(ZipEntry e) throws IOException {
354        int n = inf.getRemaining();
355        if (n > 0) {
356            ((PushbackInputStream)in).unread(buf, len - n, n);
357        }
358        if ((flag & 8) == 8) {
359            /* "Data Descriptor" present */
360            if (inf.getBytesWritten() > ZIP64_MAGICVAL ||
361                inf.getBytesRead() > ZIP64_MAGICVAL) {
362                // ZIP64 format
363                readFully(tmpbuf, 0, ZIP64_EXTHDR);
364                long sig = get32(tmpbuf, 0);
365                if (sig != EXTSIG) { // no EXTSIG present
366                    e.crc = sig;
367                    e.csize = get64(tmpbuf, ZIP64_EXTSIZ - ZIP64_EXTCRC);
368                    e.size = get64(tmpbuf, ZIP64_EXTLEN - ZIP64_EXTCRC);
369                    ((PushbackInputStream)in).unread(
370                        tmpbuf, ZIP64_EXTHDR - ZIP64_EXTCRC - 1, ZIP64_EXTCRC);
371                } else {
372                    e.crc = get32(tmpbuf, ZIP64_EXTCRC);
373                    e.csize = get64(tmpbuf, ZIP64_EXTSIZ);
374                    e.size = get64(tmpbuf, ZIP64_EXTLEN);
375                }
376            } else {
377                readFully(tmpbuf, 0, EXTHDR);
378                long sig = get32(tmpbuf, 0);
379                if (sig != EXTSIG) { // no EXTSIG present
380                    e.crc = sig;
381                    e.csize = get32(tmpbuf, EXTSIZ - EXTCRC);
382                    e.size = get32(tmpbuf, EXTLEN - EXTCRC);
383                    ((PushbackInputStream)in).unread(
384                                               tmpbuf, EXTHDR - EXTCRC - 1, EXTCRC);
385                } else {
386                    e.crc = get32(tmpbuf, EXTCRC);
387                    e.csize = get32(tmpbuf, EXTSIZ);
388                    e.size = get32(tmpbuf, EXTLEN);
389                }
390            }
391        }
392        if (e.size != inf.getBytesWritten()) {
393            throw new ZipException(
394                "invalid entry size (expected " + e.size +
395                " but got " + inf.getBytesWritten() + " bytes)");
396        }
397        if (e.csize != inf.getBytesRead()) {
398            throw new ZipException(
399                "invalid entry compressed size (expected " + e.csize +
400                " but got " + inf.getBytesRead() + " bytes)");
401        }
402        if (e.crc != crc.getValue()) {
403            throw new ZipException(
404                "invalid entry CRC (expected 0x" + Long.toHexString(e.crc) +
405                " but got 0x" + Long.toHexString(crc.getValue()) + ")");
406        }
407    }
408
409    /*
410     * Reads bytes, blocking until all bytes are read.
411     */
412    private void readFully(byte[] b, int off, int len) throws IOException {
413        while (len > 0) {
414            int n = in.read(b, off, len);
415            if (n == -1) {
416                throw new EOFException();
417            }
418            off += n;
419            len -= n;
420        }
421    }
422
423}
424