emul/mini/src/main/java/org/apidesign/bck2brwsr/emul/zip/ZipInputStream.java
branchemul
changeset 694 0d277415ed02
parent 611 9839e9a75bcf
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/emul/mini/src/main/java/org/apidesign/bck2brwsr/emul/zip/ZipInputStream.java	Thu Feb 07 12:58:12 2013 +0100
     1.3 @@ -0,0 +1,468 @@
     1.4 +/*
     1.5 + * Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved.
     1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.7 + *
     1.8 + * This code is free software; you can redistribute it and/or modify it
     1.9 + * under the terms of the GNU General Public License version 2 only, as
    1.10 + * published by the Free Software Foundation.  Oracle designates this
    1.11 + * particular file as subject to the "Classpath" exception as provided
    1.12 + * by Oracle in the LICENSE file that accompanied this code.
    1.13 + *
    1.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.17 + * version 2 for more details (a copy is included in the LICENSE file that
    1.18 + * accompanied this code).
    1.19 + *
    1.20 + * You should have received a copy of the GNU General Public License version
    1.21 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.23 + *
    1.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    1.25 + * or visit www.oracle.com if you need additional information or have any
    1.26 + * questions.
    1.27 + */
    1.28 +
    1.29 +package org.apidesign.bck2brwsr.emul.zip;
    1.30 +
    1.31 +import java.util.zip.*;
    1.32 +import java.io.InputStream;
    1.33 +import java.io.IOException;
    1.34 +import java.io.EOFException;
    1.35 +import java.io.PushbackInputStream;
    1.36 +import static org.apidesign.bck2brwsr.emul.zip.ZipConstants64.*;
    1.37 +import static java.util.zip.ZipInputStream.*;
    1.38 +
    1.39 +/**
    1.40 + * This class implements an input stream filter for reading files in the
    1.41 + * ZIP file format. Includes support for both compressed and uncompressed
    1.42 + * entries.
    1.43 + *
    1.44 + * @author      David Connelly
    1.45 + */
    1.46 +public
    1.47 +class ZipInputStream extends InflaterInputStream  {
    1.48 +    private ZipEntry entry;
    1.49 +    private int flag;
    1.50 +    private CRC32 crc = new CRC32();
    1.51 +    private long remaining;
    1.52 +    private byte[] tmpbuf = new byte[512];
    1.53 +
    1.54 +    private static final int STORED = ZipEntry.STORED;
    1.55 +    private static final int DEFLATED = ZipEntry.DEFLATED;
    1.56 +
    1.57 +    private boolean closed = false;
    1.58 +    // this flag is set to true after EOF has reached for
    1.59 +    // one entry
    1.60 +    private boolean entryEOF = false;
    1.61 +
    1.62 +    /**
    1.63 +     * Check to make sure that this stream has not been closed
    1.64 +     */
    1.65 +    private void ensureOpen() throws IOException {
    1.66 +        if (closed) {
    1.67 +            throw new IOException("Stream closed");
    1.68 +        }
    1.69 +    }
    1.70 +
    1.71 +    /**
    1.72 +     * Creates a new ZIP input stream.
    1.73 +     *
    1.74 +     * <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to
    1.75 +     * decode the entry names.
    1.76 +     *
    1.77 +     * @param in the actual input stream
    1.78 +     */
    1.79 +    public ZipInputStream(InputStream in) {
    1.80 +//        this(in, "UTF-8");
    1.81 +        super(new PushbackInputStream(in, 512), new Inflater(true), 512);
    1.82 +        //usesDefaultInflater = true;
    1.83 +        if(in == null) {
    1.84 +            throw new NullPointerException("in is null");
    1.85 +        }
    1.86 +    }
    1.87 +
    1.88 +    /**
    1.89 +     * Creates a new ZIP input stream.
    1.90 +     *
    1.91 +     * @param in the actual input stream
    1.92 +     *
    1.93 +     * @param charset
    1.94 +     *        The {@linkplain java.nio.charset.Charset charset} to be
    1.95 +     *        used to decode the ZIP entry name (ignored if the
    1.96 +     *        <a href="package-summary.html#lang_encoding"> language
    1.97 +     *        encoding bit</a> of the ZIP entry's general purpose bit
    1.98 +     *        flag is set).
    1.99 +     *
   1.100 +     * @since 1.7
   1.101 +     *
   1.102 +    public ZipInputStream(InputStream in, Charset charset) {
   1.103 +        super(new PushbackInputStream(in, 512), new Inflater(true), 512);
   1.104 +        usesDefaultInflater = true;
   1.105 +        if(in == null) {
   1.106 +            throw new NullPointerException("in is null");
   1.107 +        }
   1.108 +        if (charset == null)
   1.109 +            throw new NullPointerException("charset is null");
   1.110 +        this.zc = ZipCoder.get(charset);
   1.111 +    }
   1.112 +    */
   1.113 +
   1.114 +    /**
   1.115 +     * Reads the next ZIP file entry and positions the stream at the
   1.116 +     * beginning of the entry data.
   1.117 +     * @return the next ZIP file entry, or null if there are no more entries
   1.118 +     * @exception ZipException if a ZIP file error has occurred
   1.119 +     * @exception IOException if an I/O error has occurred
   1.120 +     */
   1.121 +    public ZipEntry getNextEntry() throws IOException {
   1.122 +        ensureOpen();
   1.123 +        if (entry != null) {
   1.124 +            closeEntry();
   1.125 +        }
   1.126 +        crc.reset();
   1.127 +        inf.reset();
   1.128 +        if ((entry = readLOC()) == null) {
   1.129 +            return null;
   1.130 +        }
   1.131 +        if (entry.getMethod() == STORED) {
   1.132 +            remaining = entry.getSize();
   1.133 +        }
   1.134 +        entryEOF = false;
   1.135 +        return entry;
   1.136 +    }
   1.137 +
   1.138 +    /**
   1.139 +     * Closes the current ZIP entry and positions the stream for reading the
   1.140 +     * next entry.
   1.141 +     * @exception ZipException if a ZIP file error has occurred
   1.142 +     * @exception IOException if an I/O error has occurred
   1.143 +     */
   1.144 +    public void closeEntry() throws IOException {
   1.145 +        ensureOpen();
   1.146 +        while (read(tmpbuf, 0, tmpbuf.length) != -1) ;
   1.147 +        entryEOF = true;
   1.148 +    }
   1.149 +
   1.150 +    /**
   1.151 +     * Returns 0 after EOF has reached for the current entry data,
   1.152 +     * otherwise always return 1.
   1.153 +     * <p>
   1.154 +     * Programs should not count on this method to return the actual number
   1.155 +     * of bytes that could be read without blocking.
   1.156 +     *
   1.157 +     * @return     1 before EOF and 0 after EOF has reached for current entry.
   1.158 +     * @exception  IOException  if an I/O error occurs.
   1.159 +     *
   1.160 +     */
   1.161 +    public int available() throws IOException {
   1.162 +        ensureOpen();
   1.163 +        if (entryEOF) {
   1.164 +            return 0;
   1.165 +        } else {
   1.166 +            return 1;
   1.167 +        }
   1.168 +    }
   1.169 +
   1.170 +    /**
   1.171 +     * Reads from the current ZIP entry into an array of bytes.
   1.172 +     * If <code>len</code> is not zero, the method
   1.173 +     * blocks until some input is available; otherwise, no
   1.174 +     * bytes are read and <code>0</code> is returned.
   1.175 +     * @param b the buffer into which the data is read
   1.176 +     * @param off the start offset in the destination array <code>b</code>
   1.177 +     * @param len the maximum number of bytes read
   1.178 +     * @return the actual number of bytes read, or -1 if the end of the
   1.179 +     *         entry is reached
   1.180 +     * @exception  NullPointerException if <code>b</code> is <code>null</code>.
   1.181 +     * @exception  IndexOutOfBoundsException if <code>off</code> is negative,
   1.182 +     * <code>len</code> is negative, or <code>len</code> is greater than
   1.183 +     * <code>b.length - off</code>
   1.184 +     * @exception ZipException if a ZIP file error has occurred
   1.185 +     * @exception IOException if an I/O error has occurred
   1.186 +     */
   1.187 +    public int read(byte[] b, int off, int len) throws IOException {
   1.188 +        ensureOpen();
   1.189 +        if (off < 0 || len < 0 || off > b.length - len) {
   1.190 +            throw new IndexOutOfBoundsException();
   1.191 +        } else if (len == 0) {
   1.192 +            return 0;
   1.193 +        }
   1.194 +
   1.195 +        if (entry == null) {
   1.196 +            return -1;
   1.197 +        }
   1.198 +        switch (entry.getMethod()) {
   1.199 +        case DEFLATED:
   1.200 +            len = super.read(b, off, len);
   1.201 +            if (len == -1) {
   1.202 +                readEnd(entry);
   1.203 +                entryEOF = true;
   1.204 +                entry = null;
   1.205 +            } else {
   1.206 +                crc.update(b, off, len);
   1.207 +            }
   1.208 +            return len;
   1.209 +        case STORED:
   1.210 +            if (remaining <= 0) {
   1.211 +                entryEOF = true;
   1.212 +                entry = null;
   1.213 +                return -1;
   1.214 +            }
   1.215 +            if (len > remaining) {
   1.216 +                len = (int)remaining;
   1.217 +            }
   1.218 +            len = in.read(b, off, len);
   1.219 +            if (len == -1) {
   1.220 +                throw new ZipException("unexpected EOF");
   1.221 +            }
   1.222 +            crc.update(b, off, len);
   1.223 +            remaining -= len;
   1.224 +            if (remaining == 0 && entry.getCrc() != crc.getValue()) {
   1.225 +                throw new ZipException(
   1.226 +                    "invalid entry CRC (expected 0x" + Long.toHexString(entry.getCrc()) +
   1.227 +                    " but got 0x" + Long.toHexString(crc.getValue()) + ")");
   1.228 +            }
   1.229 +            return len;
   1.230 +        default:
   1.231 +            throw new ZipException("invalid compression method");
   1.232 +        }
   1.233 +    }
   1.234 +
   1.235 +    /**
   1.236 +     * Skips specified number of bytes in the current ZIP entry.
   1.237 +     * @param n the number of bytes to skip
   1.238 +     * @return the actual number of bytes skipped
   1.239 +     * @exception ZipException if a ZIP file error has occurred
   1.240 +     * @exception IOException if an I/O error has occurred
   1.241 +     * @exception IllegalArgumentException if n < 0
   1.242 +     */
   1.243 +    public long skip(long n) throws IOException {
   1.244 +        if (n < 0) {
   1.245 +            throw new IllegalArgumentException("negative skip length");
   1.246 +        }
   1.247 +        ensureOpen();
   1.248 +        int max = (int)Math.min(n, Integer.MAX_VALUE);
   1.249 +        int total = 0;
   1.250 +        while (total < max) {
   1.251 +            int len = max - total;
   1.252 +            if (len > tmpbuf.length) {
   1.253 +                len = tmpbuf.length;
   1.254 +            }
   1.255 +            len = read(tmpbuf, 0, len);
   1.256 +            if (len == -1) {
   1.257 +                entryEOF = true;
   1.258 +                break;
   1.259 +            }
   1.260 +            total += len;
   1.261 +        }
   1.262 +        return total;
   1.263 +    }
   1.264 +
   1.265 +    /**
   1.266 +     * Closes this input stream and releases any system resources associated
   1.267 +     * with the stream.
   1.268 +     * @exception IOException if an I/O error has occurred
   1.269 +     */
   1.270 +    public void close() throws IOException {
   1.271 +        if (!closed) {
   1.272 +            super.close();
   1.273 +            closed = true;
   1.274 +        }
   1.275 +    }
   1.276 +
   1.277 +    private byte[] b = new byte[256];
   1.278 +
   1.279 +    /*
   1.280 +     * Reads local file (LOC) header for next entry.
   1.281 +     */
   1.282 +    private ZipEntry readLOC() throws IOException {
   1.283 +        try {
   1.284 +            readFully(tmpbuf, 0, LOCHDR);
   1.285 +        } catch (EOFException e) {
   1.286 +            return null;
   1.287 +        }
   1.288 +        if (get32(tmpbuf, 0) != LOCSIG) {
   1.289 +            return null;
   1.290 +        }
   1.291 +        // get flag first, we need check EFS.
   1.292 +        flag = get16(tmpbuf, LOCFLG);
   1.293 +        // get the entry name and create the ZipEntry first
   1.294 +        int len = get16(tmpbuf, LOCNAM);
   1.295 +        int blen = b.length;
   1.296 +        if (len > blen) {
   1.297 +            do
   1.298 +                blen = blen * 2;
   1.299 +            while (len > blen);
   1.300 +            b = new byte[blen];
   1.301 +        }
   1.302 +        readFully(b, 0, len);
   1.303 +        // Force to use UTF-8 if the EFS bit is ON, even the cs is NOT UTF-8
   1.304 +        ZipEntry e = createZipEntry(((flag & EFS) != 0)
   1.305 +                                    ? toStringUTF8(b, len)
   1.306 +                                    : toString(b, len));
   1.307 +        // now get the remaining fields for the entry
   1.308 +        if ((flag & 1) == 1) {
   1.309 +            throw new ZipException("encrypted ZIP entry not supported");
   1.310 +        }
   1.311 +        e.setMethod(get16(tmpbuf, LOCHOW));
   1.312 +        e.setTime(get32(tmpbuf, LOCTIM));
   1.313 +        if ((flag & 8) == 8) {
   1.314 +            /* "Data Descriptor" present */
   1.315 +            if (e.getMethod() != DEFLATED) {
   1.316 +                throw new ZipException(
   1.317 +                        "only DEFLATED entries can have EXT descriptor");
   1.318 +            }
   1.319 +        } else {
   1.320 +            e.setCrc(get32(tmpbuf, LOCCRC));
   1.321 +            e.setCompressedSize(get32(tmpbuf, LOCSIZ));
   1.322 +            e.setSize(get32(tmpbuf, LOCLEN));
   1.323 +        }
   1.324 +        len = get16(tmpbuf, LOCEXT);
   1.325 +        if (len > 0) {
   1.326 +            byte[] bb = new byte[len];
   1.327 +            readFully(bb, 0, len);
   1.328 +            e.setExtra(bb);
   1.329 +            // extra fields are in "HeaderID(2)DataSize(2)Data... format
   1.330 +            if (e.getCompressedSize() == ZIP64_MAGICVAL || e.getCompressedSize() == ZIP64_MAGICVAL) {
   1.331 +                int off = 0;
   1.332 +                while (off + 4 < len) {
   1.333 +                    int sz = get16(bb, off + 2);
   1.334 +                    if (get16(bb, off) == ZIP64_EXTID) {
   1.335 +                        off += 4;
   1.336 +                        // LOC extra zip64 entry MUST include BOTH original and
   1.337 +                        // compressed file size fields
   1.338 +                        if (sz < 16 || (off + sz) > len ) {
   1.339 +                            // Invalid zip64 extra fields, simply skip. Even it's
   1.340 +                            // rare, it's possible the entry size happens to be
   1.341 +                            // the magic value and it "accidnetly" has some bytes
   1.342 +                            // in extra match the id.
   1.343 +                            return e;
   1.344 +                        }
   1.345 +                        e.setSize(get64(bb, off));
   1.346 +                        e.setCompressedSize(get64(bb, off + 8));
   1.347 +                        break;
   1.348 +                    }
   1.349 +                    off += (sz + 4);
   1.350 +                }
   1.351 +            }
   1.352 +        }
   1.353 +        return e;
   1.354 +    }
   1.355 +
   1.356 +    /**
   1.357 +     * Creates a new <code>ZipEntry</code> object for the specified
   1.358 +     * entry name.
   1.359 +     *
   1.360 +     * @param name the ZIP file entry name
   1.361 +     * @return the ZipEntry just created
   1.362 +     */
   1.363 +    protected ZipEntry createZipEntry(String name) {
   1.364 +        return new ZipEntry(name);
   1.365 +    }
   1.366 +
   1.367 +    /*
   1.368 +     * Reads end of deflated entry as well as EXT descriptor if present.
   1.369 +     */
   1.370 +    private void readEnd(ZipEntry e) throws IOException {
   1.371 +        int n = inf.getRemaining();
   1.372 +        if (n > 0) {
   1.373 +            ((PushbackInputStream)in).unread(buf, len - n, n);
   1.374 +        }
   1.375 +        if ((flag & 8) == 8) {
   1.376 +            /* "Data Descriptor" present */
   1.377 +            if (inf.getBytesWritten() > ZIP64_MAGICVAL ||
   1.378 +                inf.getBytesRead() > ZIP64_MAGICVAL) {
   1.379 +                // ZIP64 format
   1.380 +                readFully(tmpbuf, 0, ZIP64_EXTHDR);
   1.381 +                long sig = get32(tmpbuf, 0);
   1.382 +                if (sig != EXTSIG) { // no EXTSIG present
   1.383 +                    e.setCrc(sig);
   1.384 +                    e.setCompressedSize(get64(tmpbuf, ZIP64_EXTSIZ - ZIP64_EXTCRC));
   1.385 +                    e.setSize(get64(tmpbuf, ZIP64_EXTLEN - ZIP64_EXTCRC));
   1.386 +                    ((PushbackInputStream)in).unread(
   1.387 +                        tmpbuf, ZIP64_EXTHDR - ZIP64_EXTCRC - 1, ZIP64_EXTCRC);
   1.388 +                } else {
   1.389 +                    e.setCrc(get32(tmpbuf, ZIP64_EXTCRC));
   1.390 +                    e.setCompressedSize(get64(tmpbuf, ZIP64_EXTSIZ));
   1.391 +                    e.setSize(get64(tmpbuf, ZIP64_EXTLEN));
   1.392 +                }
   1.393 +            } else {
   1.394 +                readFully(tmpbuf, 0, EXTHDR);
   1.395 +                long sig = get32(tmpbuf, 0);
   1.396 +                if (sig != EXTSIG) { // no EXTSIG present
   1.397 +                    e.setCrc(sig);
   1.398 +                    e.setCompressedSize(get32(tmpbuf, EXTSIZ - EXTCRC));
   1.399 +                    e.setSize(get32(tmpbuf, EXTLEN - EXTCRC));
   1.400 +                    ((PushbackInputStream)in).unread(
   1.401 +                                               tmpbuf, EXTHDR - EXTCRC - 1, EXTCRC);
   1.402 +                } else {
   1.403 +                    e.setCrc(get32(tmpbuf, EXTCRC));
   1.404 +                    e.setCompressedSize(get32(tmpbuf, EXTSIZ));
   1.405 +                    e.setSize(get32(tmpbuf, EXTLEN));
   1.406 +                }
   1.407 +            }
   1.408 +        }
   1.409 +        if (e.getSize() != inf.getBytesWritten()) {
   1.410 +            throw new ZipException(
   1.411 +                "invalid entry size (expected " + e.getSize() +
   1.412 +                " but got " + inf.getBytesWritten() + " bytes)");
   1.413 +        }
   1.414 +        if (e.getCompressedSize() != inf.getBytesRead()) {
   1.415 +            throw new ZipException(
   1.416 +                "invalid entry compressed size (expected " + e.getCompressedSize() +
   1.417 +                " but got " + inf.getBytesRead() + " bytes)");
   1.418 +        }
   1.419 +        if (e.getCrc() != crc.getValue()) {
   1.420 +            throw new ZipException(
   1.421 +                "invalid entry CRC (expected 0x" + Long.toHexString(e.getCrc()) +
   1.422 +                " but got 0x" + Long.toHexString(crc.getValue()) + ")");
   1.423 +        }
   1.424 +    }
   1.425 +
   1.426 +    /*
   1.427 +     * Reads bytes, blocking until all bytes are read.
   1.428 +     */
   1.429 +    private void readFully(byte[] b, int off, int len) throws IOException {
   1.430 +        while (len > 0) {
   1.431 +            int n = in.read(b, off, len);
   1.432 +            if (n == -1) {
   1.433 +                throw new EOFException();
   1.434 +            }
   1.435 +            off += n;
   1.436 +            len -= n;
   1.437 +        }
   1.438 +    }
   1.439 +
   1.440 +    /*
   1.441 +     * Fetches unsigned 16-bit value from byte array at specified offset.
   1.442 +     * The bytes are assumed to be in Intel (little-endian) byte order.
   1.443 +     */
   1.444 +    private static final int get16(byte b[], int off) {
   1.445 +        return (b[off] & 0xff) | ((b[off+1] & 0xff) << 8);
   1.446 +    }
   1.447 +
   1.448 +    /*
   1.449 +     * Fetches unsigned 32-bit value from byte array at specified offset.
   1.450 +     * The bytes are assumed to be in Intel (little-endian) byte order.
   1.451 +     */
   1.452 +    private static final long get32(byte b[], int off) {
   1.453 +        return (get16(b, off) | ((long)get16(b, off+2) << 16)) & 0xffffffffL;
   1.454 +    }
   1.455 +
   1.456 +    /*
   1.457 +     * Fetches signed 64-bit value from byte array at specified offset.
   1.458 +     * The bytes are assumed to be in Intel (little-endian) byte order.
   1.459 +     */
   1.460 +    private static final long get64(byte b[], int off) {
   1.461 +        return get32(b, off) | (get32(b, off+4) << 32);
   1.462 +    }
   1.463 +
   1.464 +    private static String toStringUTF8(byte[] arr, int len) {
   1.465 +        return new String(arr, 0, len);
   1.466 +    }
   1.467 +    
   1.468 +    private static String toString(byte[] b, int len) {
   1.469 +        return new String(b, 0, len);
   1.470 +    }
   1.471 +}