1 /* 2 * Copyright (c) 1996, 2015, 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 java.io.InputStream; 29 import java.io.IOException; 30 import java.io.EOFException; 31 import java.io.PushbackInputStream; 32 import java.nio.charset.Charset; 33 import java.nio.charset.StandardCharsets; 34 import static java.util.zip.ZipConstants64.*; 35 import static java.util.zip.ZipUtils.*; 36 37 /** 38 * This class implements an input stream filter for reading files in the 39 * ZIP file format. Includes support for both compressed and uncompressed 40 * entries. 41 * 42 * @author David Connelly 43 */ 44 public 45 class ZipInputStream extends InflaterInputStream implements ZipConstants { 46 private ZipEntry entry; 47 private int flag; 48 private CRC32 crc = new CRC32(); 49 private long remaining; 50 private byte[] tmpbuf = new byte[512]; 51 52 private static final int STORED = ZipEntry.STORED; 53 private static final int DEFLATED = ZipEntry.DEFLATED; 54 55 private boolean closed = false; 56 // this flag is set to true after EOF has reached for 57 // one entry 58 private boolean entryEOF = false; 59 60 private ZipCoder zc; 61 62 private ZipCryption zipCryption; 63 64 /** 65 * Check to make sure that this stream has not been closed 66 */ 67 private void ensureOpen() throws IOException { 68 if (closed) { 69 throw new IOException("Stream closed"); 70 } 71 } 72 73 /** 74 * Creates a new ZIP input stream. 75 * 76 * <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to 77 * decode the entry names. 78 * 79 * @param in the actual input stream 80 */ 81 public ZipInputStream(InputStream in) { 82 this(in, StandardCharsets.UTF_8); 83 } 84 85 /** 86 * Creates a new ZIP input stream. 87 * 88 * @param in the actual input stream 89 * 90 * @param charset 91 * The {@linkplain java.nio.charset.Charset charset} to be 92 * used to decode the ZIP entry name (ignored if the 93 * <a href="package-summary.html#lang_encoding"> language 94 * encoding bit</a> of the ZIP entry's general purpose bit 95 * flag is set). 96 * 97 * @since 1.7 98 */ 99 public ZipInputStream(InputStream in, Charset charset) { 100 super(new PushbackInputStream(in, 512), new Inflater(true), 512); 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 return getNextEntry(null); 119 } 120 121 /** 122 * Reads the next ZIP file entry and positions the stream at the 123 * beginning of the entry data. 124 * @param zipCryption instance of ZipCryption 125 * @return the next ZIP file entry, or null if there are no more entries 126 * @exception ZipException if a ZIP file error has occurred 127 * @exception IOException if an I/O error has occurred 128 */ 129 public ZipEntry getNextEntry(ZipCryption zipCryption) throws IOException { 130 ensureOpen(); 131 if (entry != null) { 132 closeEntry(); 133 } 134 crc.reset(); 135 inf.reset(); 136 if ((entry = readLOC(zipCryption)) == null) { 137 return null; 138 } 139 if (entry.method == STORED) { 140 remaining = entry.size; 141 } 142 entryEOF = false; 143 return entry; 144 } 145 146 /** 147 * Closes the current ZIP entry and positions the stream for reading the 148 * next entry. 149 * @exception ZipException if a ZIP file error has occurred 150 * @exception IOException if an I/O error has occurred 151 */ 152 public void closeEntry() throws IOException { 153 ensureOpen(); 154 while (read(tmpbuf, 0, tmpbuf.length) != -1) ; 155 entryEOF = true; 156 } 157 158 /** 159 * Returns 0 after EOF has reached for the current entry data, 160 * otherwise always return 1. 161 * <p> 162 * Programs should not count on this method to return the actual number 163 * of bytes that could be read without blocking. 164 * 165 * @return 1 before EOF and 0 after EOF has reached for current entry. 166 * @exception IOException if an I/O error occurs. 167 * 168 */ 169 public int available() throws IOException { 170 ensureOpen(); 171 if (entryEOF) { 172 return 0; 173 } else { 174 return 1; 175 } 176 } 177 178 /** 179 * Reads from the current ZIP entry into an array of bytes. 180 * If <code>len</code> is not zero, the method 181 * blocks until some input is available; otherwise, no 182 * bytes are read and <code>0</code> is returned. 183 * @param b the buffer into which the data is read 184 * @param off the start offset in the destination array <code>b</code> 185 * @param len the maximum number of bytes read 186 * @return the actual number of bytes read, or -1 if the end of the 187 * entry is reached 188 * @exception NullPointerException if <code>b</code> is <code>null</code>. 189 * @exception IndexOutOfBoundsException if <code>off</code> is negative, 190 * <code>len</code> is negative, or <code>len</code> is greater than 191 * <code>b.length - off</code> 192 * @exception ZipException if a ZIP file error has occurred 193 * @exception IOException if an I/O error has occurred 194 */ 195 public int read(byte[] b, int off, int len) throws IOException { 196 ensureOpen(); 197 if (off < 0 || len < 0 || off > b.length - len) { 198 throw new IndexOutOfBoundsException(); 199 } else if (len == 0) { 200 return 0; 201 } 202 203 if (entry == null) { 204 return -1; 205 } 206 switch (entry.method) { 207 case DEFLATED: 208 len = super.read(b, off, len); 209 if (len == -1) { 210 readEnd(entry); 211 entryEOF = true; 212 entry = null; 213 } else { 214 crc.update(b, off, len); 215 } 216 return len; 217 case STORED: 218 if (remaining <= 0) { 219 entryEOF = true; 220 entry = null; 221 return -1; 222 } 223 if (len > remaining) { 224 len = (int)remaining; 225 } 226 len = in.read(b, off, len); 227 if (len == -1) { 228 throw new ZipException("unexpected EOF"); 229 } 230 if (zipCryption != null) { 231 zipCryption.decryptBytes(b, off, len); 232 } 233 crc.update(b, off, len); 234 remaining -= len; 235 if (remaining == 0 && entry.crc != crc.getValue()) { 236 throw new ZipException( 237 "invalid entry CRC (expected 0x" + Long.toHexString(entry.crc) + 238 " but got 0x" + Long.toHexString(crc.getValue()) + ")"); 239 } 240 return len; 241 default: 242 throw new ZipException("invalid compression method"); 243 } 244 } 245 246 /** 247 * Skips specified number of bytes in the current ZIP entry. 248 * @param n the number of bytes to skip 249 * @return the actual number of bytes skipped 250 * @exception ZipException if a ZIP file error has occurred 251 * @exception IOException if an I/O error has occurred 252 * @exception IllegalArgumentException if {@code n < 0} 253 */ 254 public long skip(long n) throws IOException { 255 if (n < 0) { 256 throw new IllegalArgumentException("negative skip length"); 257 } 258 ensureOpen(); 259 int max = (int)Math.min(n, Integer.MAX_VALUE); 260 int total = 0; 261 while (total < max) { 262 int len = max - total; 263 if (len > tmpbuf.length) { 264 len = tmpbuf.length; 265 } 266 len = read(tmpbuf, 0, len); 267 if (len == -1) { 268 entryEOF = true; 269 break; 270 } 271 total += len; 272 } 273 return total; 274 } 275 276 /** 277 * Closes this input stream and releases any system resources associated 278 * with the stream. 279 * @exception IOException if an I/O error has occurred 280 */ 281 public void close() throws IOException { 282 if (!closed) { 283 super.close(); 284 closed = true; 285 } 286 } 287 288 private byte[] b = new byte[256]; 289 290 /* 291 * Reads local file (LOC) header for next entry. 292 */ 293 private ZipEntry readLOC(ZipCryption zipCryption) throws IOException { 294 this.zipCryption = zipCryption; 295 296 try { 297 readFully(tmpbuf, 0, LOCHDR); 298 } catch (EOFException e) { 299 return null; 300 } 301 if (get32(tmpbuf, 0) != LOCSIG) { 302 return null; 303 } 304 // get flag first, we need check EFS and encryption. 305 flag = get16(tmpbuf, LOCFLG); 306 // get the entry name and create the ZipEntry first 307 int len = get16(tmpbuf, LOCNAM); 308 int blen = b.length; 309 if (len > blen) { 310 do { 311 blen = blen * 2; 312 } while (len > blen); 313 b = new byte[blen]; 314 } 315 readFully(b, 0, len); 316 // Force to use UTF-8 if the EFS bit is ON, even the cs is NOT UTF-8 317 ZipEntry e = createZipEntry(((flag & EFS) != 0) 318 ? zc.toStringUTF8(b, len) 319 : zc.toString(b, len)); 320 e.flag = flag; 321 // now get the remaining fields for the entry 322 if (((flag & 1) == 1) && (zipCryption == null)) { 323 throw new ZipException("ZipCryption is required."); 324 } 325 e.method = get16(tmpbuf, LOCHOW); 326 e.xdostime = get32(tmpbuf, LOCTIM); 327 if ((flag & 8) == 8) { 328 /* "Data Descriptor" present */ 329 if (e.method != DEFLATED) { 330 throw new ZipException( 331 "only DEFLATED entries can have EXT descriptor"); 332 } 333 } else { 334 e.crc = get32(tmpbuf, LOCCRC); 335 e.csize = get32(tmpbuf, LOCSIZ); 336 e.size = get32(tmpbuf, LOCLEN); 337 } 338 len = get16(tmpbuf, LOCEXT); 339 if (len > 0) { 340 byte[] extra = new byte[len]; 341 readFully(extra, 0, len); 342 e.setExtra0(extra, 343 e.csize == ZIP64_MAGICVAL || e.size == ZIP64_MAGICVAL); 344 } 345 346 if (zipCryption != null) { 347 zipCryption.reset(); 348 super.setZipCryption(zipCryption); 349 350 byte[] encryptionHeader = 351 new byte[zipCryption.getEncryptionHeaderSize()]; 352 readFully(encryptionHeader, 0, encryptionHeader.length); 353 zipCryption.decryptBytes(encryptionHeader); 354 355 if (!zipCryption.isValid(e, encryptionHeader)) { 356 throw new ZipException("possibly incorrect passphrase"); 357 } 358 359 } 360 361 return e; 362 } 363 364 /** 365 * Creates a new <code>ZipEntry</code> object for the specified 366 * entry name. 367 * 368 * @param name the ZIP file entry name 369 * @return the ZipEntry just created 370 */ 371 protected ZipEntry createZipEntry(String name) { 372 return new ZipEntry(name); 373 } 374 375 /** 376 * Reads end of deflated entry as well as EXT descriptor if present. 377 * 378 * Local headers for DEFLATED entries may optionally be followed by a 379 * data descriptor, and that data descriptor may optionally contain a 380 * leading signature (EXTSIG). 381 * 382 * From the zip spec http://www.pkware.com/documents/casestudies/APPNOTE.TXT 383 * 384 * """Although not originally assigned a signature, the value 0x08074b50 385 * has commonly been adopted as a signature value for the data descriptor 386 * record. Implementers should be aware that ZIP files may be 387 * encountered with or without this signature marking data descriptors 388 * and should account for either case when reading ZIP files to ensure 389 * compatibility.""" 390 */ 391 private void readEnd(ZipEntry e) throws IOException { 392 int n = inf.getRemaining(); 393 if (n > 0) { 394 ((PushbackInputStream)in).unread( 395 (zipCryption == null) ? buf : originBuf, len - n, n); 396 } 397 if ((flag & 8) == 8) { 398 /* "Data Descriptor" present */ 399 if (inf.getBytesWritten() > ZIP64_MAGICVAL || 400 inf.getBytesRead() > ZIP64_MAGICVAL) { 401 // ZIP64 format 402 readFully(tmpbuf, 0, ZIP64_EXTHDR); 403 long sig = get32(tmpbuf, 0); 404 if (sig != EXTSIG) { // no EXTSIG present 405 e.crc = sig; 406 e.csize = get64(tmpbuf, ZIP64_EXTSIZ - ZIP64_EXTCRC); 407 e.size = get64(tmpbuf, ZIP64_EXTLEN - ZIP64_EXTCRC); 408 ((PushbackInputStream)in).unread( 409 tmpbuf, ZIP64_EXTHDR - ZIP64_EXTCRC, ZIP64_EXTCRC); 410 } else { 411 e.crc = get32(tmpbuf, ZIP64_EXTCRC); 412 e.csize = get64(tmpbuf, ZIP64_EXTSIZ); 413 e.size = get64(tmpbuf, ZIP64_EXTLEN); 414 } 415 } else { 416 readFully(tmpbuf, 0, EXTHDR); 417 long sig = get32(tmpbuf, 0); 418 if (sig != EXTSIG) { // no EXTSIG present 419 e.crc = sig; 420 e.csize = get32(tmpbuf, EXTSIZ - EXTCRC); 421 e.size = get32(tmpbuf, EXTLEN - EXTCRC); 422 ((PushbackInputStream)in).unread( 423 tmpbuf, EXTHDR - EXTCRC, EXTCRC); 424 } else { 425 e.crc = get32(tmpbuf, EXTCRC); 426 e.csize = get32(tmpbuf, EXTSIZ); 427 e.size = get32(tmpbuf, EXTLEN); 428 } 429 } 430 } 431 if (e.size != inf.getBytesWritten()) { 432 throw new ZipException( 433 "invalid entry size (expected " + e.size + 434 " but got " + inf.getBytesWritten() + " bytes)"); 435 } 436 if (zipCryption != null) { 437 e.csize -= zipCryption.getEncryptionHeaderSize(); 438 } 439 if (e.csize != inf.getBytesRead()) { 440 throw new ZipException( 441 "invalid entry compressed size (expected " + e.csize + 442 " but got " + inf.getBytesRead() + " bytes)"); 443 } 444 if (e.crc != crc.getValue()) { 445 throw new ZipException( 446 "invalid entry CRC (expected 0x" + Long.toHexString(e.crc) + 447 " but got 0x" + Long.toHexString(crc.getValue()) + ")"); 448 } 449 } 450 451 /* 452 * Reads bytes, blocking until all bytes are read. 453 */ 454 private void readFully(byte[] b, int off, int len) throws IOException { 455 while (len > 0) { 456 int n = in.read(b, off, len); 457 if (n == -1) { 458 throw new EOFException(); 459 } 460 off += n; 461 len -= n; 462 } 463 } 464 465 }